@primitive.ai/prim 0.1.0-alpha.125 → 0.1.0-alpha.127

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 +140 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
  4. package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
  5. package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
  6. package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
  7. package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
  8. package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
  9. package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
  10. package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
  11. package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
  12. package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
  13. package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
  14. package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
  15. package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
  16. package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
  17. package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
  18. package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
  19. package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
  20. package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
  21. package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
  22. package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
  23. package/dist/daemon/server.js +805 -218
  24. package/dist/hook-runtime/daemon/server.js +805 -218
  25. package/dist/hook-runtime/hooks/post-commit.js +286 -59
  26. package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
  27. package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
  28. package/dist/hook-runtime/hooks/pre-commit.js +536 -88
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
  30. package/dist/hook-runtime/hooks/prim-hook.js +642 -167
  31. package/dist/hook-runtime/hooks/session-end.js +263 -47
  32. package/dist/hook-runtime/hooks/session-start.js +1103 -476
  33. package/dist/hook-runtime/index.js +3645 -2120
  34. package/dist/hook-runtime/statusline-main.js +257 -29
  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 +15 -15
  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 +49 -18
  43. package/dist/index.js +1014 -271
  44. package/dist/statusline-main.js +257 -29
  45. package/package.json +1 -1
@@ -54,8 +54,8 @@ 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 join27 } from "path";
59
59
  import { fileURLToPath as fileURLToPath5 } from "url";
60
60
 
61
61
  // src/binding.ts
@@ -69,8 +69,17 @@ import { join as join7 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
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";
72
+ import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
73
+ import {
74
+ chmodSync,
75
+ existsSync as existsSync3,
76
+ linkSync,
77
+ lstatSync as lstatSync3,
78
+ mkdirSync as mkdirSync3,
79
+ readFileSync as readFileSync5,
80
+ rmSync as rmSync5,
81
+ writeFileSync as writeFileSync3
82
+ } from "fs";
74
83
  import { createRequire } from "module";
75
84
  import { dirname as dirname4, join as join6 } from "path";
76
85
  import { fileURLToPath as fileURLToPath3 } from "url";
@@ -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,47 @@ 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
+ function cloudSetupPointer(message, env = process.env) {
459
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
460
+ }
461
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
462
+
412
463
  // src/lib/workos-connect.ts
413
464
  var TOKEN_PATH = "/oauth2/token";
414
465
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -604,9 +655,19 @@ function parseMachineConfiguration(value) {
604
655
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
605
656
  };
606
657
  }
658
+ function rejectedCredentialsMessage(message, env = process.env) {
659
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
660
+ }
607
661
  function machineSignal(signal) {
608
662
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
609
663
  }
664
+ function hostOf(url) {
665
+ try {
666
+ return new URL(url).hostname;
667
+ } catch {
668
+ return "Primitive";
669
+ }
670
+ }
610
671
  async function fetchMachine(url, options, fetchImpl) {
611
672
  try {
612
673
  return await fetchImpl(url, options);
@@ -614,7 +675,9 @@ async function fetchMachine(url, options, fetchImpl) {
614
675
  options.signal?.throwIfAborted();
615
676
  throw new MachineAuthError(
616
677
  "authentication_unavailable",
617
- "Machine authentication is temporarily unavailable. Check the connection and retry."
678
+ // A cloud VM reaches only the hosts its environment allows, and both of
679
+ // Primitive's are blocked by default: name the one that failed.
680
+ 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
681
  );
619
682
  }
620
683
  }
@@ -641,8 +704,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
641
704
  );
642
705
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
643
706
  }
644
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
645
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
707
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
708
+ const network = options.secretInjection === "network";
709
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
646
710
  throw new MachineAuthError(
647
711
  "invalid_credentials",
648
712
  "A machine client ID and secret are required.",
@@ -656,11 +720,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
656
720
  redirect: "error",
657
721
  signal: machineSignal(signal),
658
722
  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
- })
723
+ // With a network secret the agent proxy authenticates the client with
724
+ // HTTP Basic (client_secret_basic); the body carries no credential.
725
+ body: new URLSearchParams(
726
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
727
+ )
664
728
  },
665
729
  fetchImpl
666
730
  );
@@ -668,7 +732,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
668
732
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
669
733
  throw new MachineAuthError(
670
734
  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.",
735
+ 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(
736
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
737
+ ) : "The machine token service is temporarily unavailable.",
672
738
  terminal,
673
739
  terminal ? void 0 : machineRetryAt(response)
674
740
  );
@@ -688,6 +754,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
688
754
  } catch {
689
755
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
690
756
  }
757
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
758
+ throw new MachineAuthError(
759
+ "token_client_mismatch",
760
+ "The token service issued a token for another machine client."
761
+ );
691
762
  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
763
  throw new MachineAuthError(
693
764
  "token_identity_mismatch",
@@ -733,12 +804,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
733
804
  const terminal = response.status === 401 || response.status === 403;
734
805
  throw new MachineAuthError(
735
806
  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.",
807
+ terminal ? rejectedCredentialsMessage(
808
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
809
+ ) : "Machine verification is temporarily unavailable.",
737
810
  terminal
738
811
  );
739
812
  }
740
813
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
741
814
  }
815
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
816
+ const rejected = () => new MachineAuthError(
817
+ "network_token_rejected",
818
+ `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.`,
819
+ true
820
+ );
821
+ if (status === 401 || status === 403) throw rejected();
822
+ if (status < 200 || status > 299)
823
+ throw new MachineAuthError(
824
+ "verification_unavailable",
825
+ "Machine verification is temporarily unavailable."
826
+ );
827
+ let data;
828
+ try {
829
+ data = machineRecord(value);
830
+ } catch {
831
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
832
+ }
833
+ if (data.authenticated !== true) throw rejected();
834
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
835
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
836
+ throw new MachineAuthError(
837
+ "network_secret_mismatch",
838
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
839
+ true
840
+ );
841
+ return parseMachineIdentity(data, clientId);
842
+ }
843
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
844
+ const response = await fetchMachine(
845
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
846
+ { redirect: "error", signal: machineSignal(signal) },
847
+ fetchImpl
848
+ );
849
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
850
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
851
+ }
742
852
 
743
853
  // src/lib/paths.ts
744
854
  import { homedir } from "os";
@@ -770,6 +880,11 @@ function primConfigDirectory(options = {}) {
770
880
 
771
881
  // src/lib/machine-broker.ts
772
882
  var MAX_RESPONSE_BYTES = 96 * 1024;
883
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
884
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
885
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
886
+ var FORWARD_REQUEST_PROOF = "forward-request";
887
+ var FORWARD_ANSWER_PROOF = "forward-answer";
773
888
  var IDLE_MS = 5 * 6e4;
774
889
  function descriptorPath(directory, generation) {
775
890
  return join4(directory, `machine_broker_${generation}.json`);
@@ -785,8 +900,8 @@ function readDescriptor(path) {
785
900
  return void 0;
786
901
  }
787
902
  }
788
- function signature(secret, nonce, body) {
789
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
903
+ function signature(secret, nonce, body, purpose) {
904
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
790
905
  }
791
906
  function matches(left, right) {
792
907
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -801,10 +916,9 @@ async function brokerRequest(descriptor, environment, options) {
801
916
  observedTokenHash: tokenHash(options.observedToken),
802
917
  timestamp: Date.now()
803
918
  });
804
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
919
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
805
920
  method: "POST",
806
921
  body,
807
- redirect: "error",
808
922
  signal: options.signal,
809
923
  headers: {
810
924
  "Content-Type": "application/json",
@@ -835,6 +949,15 @@ async function brokerRequest(descriptor, environment, options) {
835
949
  );
836
950
  return credential;
837
951
  }
952
+ function brokerEnvironment(options) {
953
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
954
+ return {
955
+ ...options.env,
956
+ PRIM_API_URL: options.apiUrl,
957
+ PRIM_CONFIG_DIR: options.directory,
958
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
959
+ };
960
+ }
838
961
  async function acquireBrokerCredential(options) {
839
962
  const path = descriptorPath(options.directory, options.environment.generation);
840
963
  const existing = readDescriptor(path);
@@ -846,15 +969,28 @@ async function acquireBrokerCredential(options) {
846
969
  if (error instanceof MachineAuthError) throw error;
847
970
  }
848
971
  }
849
- const descriptor = await withFileLock(
972
+ const descriptor = await ensureBroker(options);
973
+ try {
974
+ return await brokerRequest(descriptor, options.environment, options);
975
+ } catch (error) {
976
+ options.signal.throwIfAborted();
977
+ if (error instanceof MachineAuthError) throw error;
978
+ throw new MachineAuthError(
979
+ "broker_unavailable",
980
+ "Machine credential broker is unavailable. Retry the command."
981
+ );
982
+ }
983
+ }
984
+ async function ensureBroker(options) {
985
+ const path = descriptorPath(options.directory, options.environment.generation);
986
+ return withFileLock(
850
987
  join4(options.directory, "machine-broker.lock"),
851
988
  async () => {
852
989
  const current = readDescriptor(path);
853
990
  if (current) {
854
991
  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"
992
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
993
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
858
994
  });
859
995
  if (response.ok && await response.text() === current.nonce) return current;
860
996
  } catch {
@@ -873,7 +1009,7 @@ async function acquireBrokerCredential(options) {
873
1009
  detached: true,
874
1010
  stdio: ["ignore", "ignore", "ignore", "ipc"],
875
1011
  windowsHide: true,
876
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
1012
+ env: brokerEnvironment(options)
877
1013
  });
878
1014
  let settled = false;
879
1015
  const finish = (error) => {
@@ -925,27 +1061,93 @@ async function acquireBrokerCredential(options) {
925
1061
  },
926
1062
  { signal: options.signal }
927
1063
  );
1064
+ }
1065
+ async function forwardOnce(descriptor, environment, request3, signal) {
1066
+ const body = JSON.stringify({
1067
+ generation: environment.generation,
1068
+ timestamp: Date.now(),
1069
+ method: request3.method,
1070
+ path: request3.path,
1071
+ headers: request3.headers ?? {},
1072
+ ...request3.body === void 0 ? {} : { body: request3.body }
1073
+ });
1074
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
1075
+ method: "POST",
1076
+ body,
1077
+ signal,
1078
+ headers: {
1079
+ "Content-Type": "application/json",
1080
+ "X-Prim-Proof": signature(
1081
+ environment.clientSecret,
1082
+ descriptor.nonce,
1083
+ body,
1084
+ FORWARD_REQUEST_PROOF
1085
+ )
1086
+ }
1087
+ });
1088
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
1089
+ if (typeof envelope.body !== "string" || !matches(
1090
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
1091
+ envelope.proof
1092
+ ))
1093
+ throw new MachineAuthError(
1094
+ "broker_unavailable",
1095
+ "Machine credential broker could not be authenticated. Retry the command."
1096
+ );
1097
+ const data = machineRecord(JSON.parse(envelope.body));
1098
+ if (data.error) {
1099
+ const error = machineRecord(data.error);
1100
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
1101
+ }
1102
+ const status = data.status;
1103
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
1104
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
1105
+ const headers = new Headers();
1106
+ for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
1107
+ if (typeof value === "string") headers.set(name2, value);
1108
+ const text = typeof data.body === "string" ? data.body : "";
1109
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
1110
+ }
1111
+ async function forwardBrokerRequest(options) {
1112
+ const path = descriptorPath(options.directory, options.environment.generation);
1113
+ const unavailable = () => new MachineAuthError(
1114
+ "broker_unavailable",
1115
+ "Machine credential broker is unavailable. Retry the command."
1116
+ );
1117
+ const existing = readDescriptor(path);
1118
+ if (existing) {
1119
+ try {
1120
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
1121
+ } catch (error) {
1122
+ options.signal.throwIfAborted();
1123
+ if (error instanceof MachineAuthError) throw error;
1124
+ if (error.code !== "ECONNREFUSED") throw unavailable();
1125
+ }
1126
+ }
1127
+ const descriptor = await ensureBroker(options);
928
1128
  try {
929
- return await brokerRequest(descriptor, options.environment, options);
1129
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
930
1130
  } catch (error) {
931
1131
  options.signal.throwIfAborted();
932
1132
  if (error instanceof MachineAuthError) throw error;
933
- throw new MachineAuthError(
934
- "broker_unavailable",
935
- "Machine credential broker is unavailable. Retry the command."
936
- );
1133
+ throw unavailable();
937
1134
  }
938
1135
  }
939
1136
 
940
1137
  // src/lib/machine-retry.ts
941
1138
  import { createHash as createHash2 } from "crypto";
942
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
1139
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
943
1140
  import { join as join5 } from "path";
944
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
1141
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
1142
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
1143
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
945
1144
  signal?.throwIfAborted();
946
1145
  const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
947
1146
  const path = join5(directory, `machine_retry_${key}.json`);
948
- let state = { failures: 0, retryAt: 0 };
1147
+ let state = {
1148
+ failures: 0,
1149
+ retryAt: 0
1150
+ };
949
1151
  try {
950
1152
  const stat = lstatSync2(path);
951
1153
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
@@ -960,12 +1162,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
960
1162
  if (state.retryAt > Date.now())
961
1163
  throw new MachineAuthError(
962
1164
  "token_service_unavailable",
963
- "Machine authentication is cooling down after a temporary failure. Retry later.",
1165
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
1166
+ // Cloud setup keeps this wait too, so pointing at it would loop.
1167
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
1168
+ ) : (
1169
+ // The cooldown hides the failure that started it; cloud setup
1170
+ // retries at once and names the cause.
1171
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
1172
+ ),
964
1173
  false,
965
1174
  state.retryAt
966
1175
  );
967
1176
  try {
968
- const result = await request2();
1177
+ const result = await request3();
969
1178
  rmSync4(path, { force: true });
970
1179
  return result;
971
1180
  } catch (error) {
@@ -977,8 +1186,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
977
1186
  ].includes(error.code)) {
978
1187
  const failures = Math.min(16, state.failures + 1);
979
1188
  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 });
1189
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
1190
+ atomicWriteFile(
1191
+ path,
1192
+ JSON.stringify({
1193
+ failures,
1194
+ retryAt,
1195
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
1196
+ }),
1197
+ { mode: 384 }
1198
+ );
982
1199
  throw new MachineAuthError(error.code, error.message, false, retryAt);
983
1200
  }
984
1201
  throw error;
@@ -1171,10 +1388,98 @@ function readMachineProfile(deps = {}) {
1171
1388
  const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
1172
1389
  return value === void 0 ? void 0 : parseProfile(value);
1173
1390
  }
1391
+ var NETWORK_SECRET_AUTH = "network-secret";
1392
+ var NETWORK_TOKEN_AUTH = "network-token";
1393
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
1394
+ var brokerKeys = /* @__PURE__ */ new Map();
1395
+ function networkSecretBrokerKey(deps, clientId) {
1396
+ const directory = configurationDirectory(deps);
1397
+ const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
1398
+ const known = brokerKeys.get(path);
1399
+ if (known) return known;
1400
+ ensureDirectory(directory);
1401
+ const read = () => {
1402
+ try {
1403
+ const stat = lstatSync3(path);
1404
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
1405
+ throw new MachineAuthError(
1406
+ "unsafe_storage",
1407
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
1408
+ true
1409
+ );
1410
+ const value = readFileSync5(path, "utf8").trim();
1411
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
1412
+ } catch (error) {
1413
+ if (error.code === "ENOENT") return void 0;
1414
+ throw error;
1415
+ }
1416
+ };
1417
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1418
+ const existing = read();
1419
+ if (existing?.key) {
1420
+ brokerKeys.set(path, existing.key);
1421
+ return existing.key;
1422
+ }
1423
+ if (existing)
1424
+ throw new MachineAuthError(
1425
+ "unsafe_storage",
1426
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
1427
+ true
1428
+ );
1429
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
1430
+ try {
1431
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
1432
+ `, { mode: 384, flag: "wx" });
1433
+ protectPath(staged, false);
1434
+ linkSync(staged, path);
1435
+ } catch (error) {
1436
+ if (error.code !== "EEXIST") throw error;
1437
+ } finally {
1438
+ rmSync5(staged, { force: true });
1439
+ }
1440
+ }
1441
+ const key = read()?.key;
1442
+ if (!key)
1443
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
1444
+ brokerKeys.set(path, key);
1445
+ return key;
1446
+ }
1174
1447
  function environmentCredentials(deps) {
1175
1448
  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;
1449
+ const {
1450
+ PRIM_M2M_CLIENT_ID: clientId,
1451
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
1452
+ PRIM_M2M_CLIENT_AUTH: auth
1453
+ } = env;
1454
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
1455
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
1456
+ throw new MachineAuthError(
1457
+ "incomplete_machine_credentials",
1458
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
1459
+ );
1460
+ if (auth !== void 0) {
1461
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
1462
+ throw new MachineAuthError(
1463
+ "incomplete_machine_credentials",
1464
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
1465
+ );
1466
+ if (clientSecret !== void 0)
1467
+ throw new MachineAuthError(
1468
+ "conflicting_credentials",
1469
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
1470
+ );
1471
+ const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1472
+ const credentials = {
1473
+ clientId,
1474
+ generation,
1475
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
1476
+ };
1477
+ Object.defineProperty(credentials, "clientSecret", {
1478
+ enumerable: true,
1479
+ get: () => networkSecretBrokerKey(deps, clientId)
1480
+ });
1481
+ return credentials;
1482
+ }
1178
1483
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1179
1484
  throw new MachineAuthError(
1180
1485
  "incomplete_machine_credentials",
@@ -1189,7 +1494,7 @@ function environmentCredentials(deps) {
1189
1494
  }
1190
1495
  function hasMachineConfiguration(deps = {}) {
1191
1496
  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));
1497
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
1193
1498
  if (configured && env.PRIM_TOKEN?.trim()) {
1194
1499
  throw new MachineAuthError(
1195
1500
  "conflicting_credentials",
@@ -1226,6 +1531,8 @@ function machineSessionEnded(deps = {}) {
1226
1531
  return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
1227
1532
  }
1228
1533
  var environmentTerminal;
1534
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
1535
+ var networkRejection;
1229
1536
  async function loadRecord(profile, deps, signal) {
1230
1537
  const directory = configurationDirectory(deps);
1231
1538
  let value;
@@ -1289,6 +1596,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1289
1596
  const apiUrl = apiUrlFor(deps);
1290
1597
  const environment = environmentCredentials(deps);
1291
1598
  if (environment) {
1599
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
1292
1600
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
1293
1601
  const directory2 = configurationDirectory(deps);
1294
1602
  ensureDirectory(directory2);
@@ -1306,7 +1614,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1306
1614
  writeEnvironmentContext(cached, deps);
1307
1615
  return cached;
1308
1616
  } catch (error) {
1309
- if (error instanceof MachineAuthError && error.terminal)
1617
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
1310
1618
  environmentTerminal = environment.generation;
1311
1619
  throw error;
1312
1620
  }
@@ -1317,11 +1625,13 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1317
1625
  if (machineSessionEnded(deps))
1318
1626
  throw new MachineAuthError(
1319
1627
  "machine_credentials_rejected",
1320
- "Rotate the injected machine credentials.",
1628
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1321
1629
  true
1322
1630
  );
1323
1631
  if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
1324
1632
  return cached;
1633
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
1634
+ throw networkRejection.error;
1325
1635
  try {
1326
1636
  const { configuration, tokens, identity } = await withMachineCooldown(
1327
1637
  directory2,
@@ -1330,13 +1640,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1330
1640
  signal,
1331
1641
  async () => {
1332
1642
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
1643
+ if (environment.tokenInjection) {
1644
+ const identity3 = await verifyInjectedMachineIdentity(
1645
+ apiUrl,
1646
+ environment.clientId,
1647
+ signal,
1648
+ deps.fetch
1649
+ );
1650
+ const tokens3 = {
1651
+ accessToken: "",
1652
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
1653
+ };
1654
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
1655
+ }
1333
1656
  const tokens2 = await exchangeMachineCredentials(
1334
1657
  configuration2,
1335
1658
  environment.clientId,
1336
- environment.clientSecret,
1659
+ // The broker key is not a client secret; the proxy supplies that.
1660
+ environment.secretInjection ? "" : environment.clientSecret,
1337
1661
  signal,
1338
- deps.fetch
1339
- );
1662
+ deps.fetch,
1663
+ { secretInjection: environment.secretInjection }
1664
+ ).catch((error) => {
1665
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
1666
+ throw new MachineAuthError(
1667
+ "network_secret_mismatch",
1668
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
1669
+ true
1670
+ );
1671
+ throw error;
1672
+ });
1340
1673
  const identity2 = await verifyMachineIdentity(
1341
1674
  apiUrl,
1342
1675
  tokens2.accessToken,
@@ -1353,11 +1686,27 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1353
1686
  ...identity,
1354
1687
  apiUrl,
1355
1688
  generation: environment.generation,
1356
- storage: "environment"
1689
+ storage: "environment",
1690
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
1357
1691
  };
1358
1692
  writeEnvironmentContext(cached, deps);
1359
1693
  return cached;
1360
1694
  } catch (error) {
1695
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
1696
+ networkRejection = {
1697
+ generation: environment.generation,
1698
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
1699
+ error
1700
+ };
1701
+ if (cached?.generation === environment.generation) cached = void 0;
1702
+ const contextPath = environmentContextPath(deps, environment.clientId);
1703
+ try {
1704
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1705
+ rmSync5(contextPath, { force: true });
1706
+ } catch {
1707
+ }
1708
+ throw error;
1709
+ }
1361
1710
  if (error instanceof MachineAuthError && error.terminal) {
1362
1711
  environmentTerminal = environment.generation;
1363
1712
  const contextPath = environmentContextPath(deps, environment.clientId);
@@ -1438,6 +1787,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1438
1787
  { signal }
1439
1788
  );
1440
1789
  }
1790
+ async function forwardMachineRequest(request3, signal, deps = {}) {
1791
+ const environment = environmentCredentials(deps);
1792
+ if (!environment?.tokenInjection)
1793
+ throw new MachineAuthError(
1794
+ "identity_changed",
1795
+ "Machine identity changed; restart the operation."
1796
+ );
1797
+ const directory = configurationDirectory(deps);
1798
+ ensureDirectory(directory);
1799
+ return forwardBrokerRequest({
1800
+ directory,
1801
+ apiUrl: apiUrlFor(deps),
1802
+ environment,
1803
+ env: deps.env ?? process.env,
1804
+ request: request3,
1805
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
1806
+ });
1807
+ }
1441
1808
  function machineCaptureActor(deps = {}) {
1442
1809
  if (!hasMachineConfiguration(deps)) return void 0;
1443
1810
  const context = machineContext(deps);
@@ -1457,6 +1824,12 @@ function machineCaptureActor(deps = {}) {
1457
1824
  function machineJournalBucket(identity) {
1458
1825
  return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1459
1826
  }
1827
+ function identityPending(actor) {
1828
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1829
+ }
1830
+ function machinePendingBucket(identity) {
1831
+ return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
1832
+ }
1460
1833
 
1461
1834
  // src/lib/credentials.ts
1462
1835
  var CONFIG_DIRECTORY = primConfigDirectory();
@@ -1482,7 +1855,7 @@ function readTrimmed(path) {
1482
1855
  function resolveAuthCredential(options = {}) {
1483
1856
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
1484
1857
  const machine = cachedMachineCredential({ env: options.env });
1485
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
1858
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
1486
1859
  }
1487
1860
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
1488
1861
  if (envToken) return { token: envToken, source: "environment" };
@@ -1748,7 +2121,7 @@ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirS
1748
2121
  import { dirname as dirname6 } from "path";
1749
2122
 
1750
2123
  // src/daemon/client-instance-id.ts
1751
- import { randomBytes as randomBytes3 } from "crypto";
2124
+ import { randomBytes as randomBytes4 } from "crypto";
1752
2125
  import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
1753
2126
  import { join as join9 } from "path";
1754
2127
  var CONFIG_DIRECTORY_MODE = 448;
@@ -1811,7 +2184,7 @@ async function getOrCreateClientInstanceId(options) {
1811
2184
  if (existing !== void 0) {
1812
2185
  return existing;
1813
2186
  }
1814
- const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
2187
+ const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
1815
2188
  "base64url"
1816
2189
  )}`;
1817
2190
  if (!isClientInstanceId(generated)) {
@@ -1897,6 +2270,9 @@ var CREDENTIAL_FILE_MODE = 384;
1897
2270
  var REFRESH_THRESHOLD_MS = 6e4;
1898
2271
  var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1899
2272
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
2273
+ function authExpiredMessage() {
2274
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
2275
+ }
1900
2276
  function readTrimmed2(path) {
1901
2277
  try {
1902
2278
  const value = readFileSync9(path, "utf8").trim();
@@ -2278,7 +2654,7 @@ var CliManagementResponseError = class extends Error {
2278
2654
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
2279
2655
  async function managementResponseValue(response) {
2280
2656
  if (response.status === 401) {
2281
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
2657
+ throw new HttpError(401, authExpiredMessage());
2282
2658
  }
2283
2659
  let value;
2284
2660
  try {
@@ -2300,23 +2676,50 @@ function selectedCredential() {
2300
2676
  }
2301
2677
  return _cachedCredential;
2302
2678
  }
2679
+ async function requestHeaders(method, path) {
2680
+ return {
2681
+ "Content-Type": "application/json",
2682
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2683
+ };
2684
+ }
2303
2685
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
2304
2686
  return fetch(`${siteUrl}${path}`, {
2305
2687
  method,
2306
- headers: {
2307
- Authorization: `Bearer ${token}`,
2308
- "Content-Type": "application/json",
2309
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2310
- },
2688
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
2311
2689
  body: body === void 0 ? void 0 : JSON.stringify(body),
2312
2690
  signal: options?.signal,
2313
2691
  redirect: options?.redirect
2314
2692
  });
2315
2693
  }
2694
+ async function fetchAsMachine(credential, method, path, body, options) {
2695
+ if (!credential.tokenInjection)
2696
+ return fetchWithToken(
2697
+ method,
2698
+ path,
2699
+ body,
2700
+ { ...options, redirect: "error" },
2701
+ credential.accessToken,
2702
+ credential.apiUrl
2703
+ );
2704
+ try {
2705
+ return await forwardMachineRequest(
2706
+ {
2707
+ method,
2708
+ path,
2709
+ headers: await requestHeaders(method, path),
2710
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
2711
+ },
2712
+ options.signal
2713
+ );
2714
+ } catch (error) {
2715
+ if (!(error instanceof MachineAuthError)) throw error;
2716
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
2717
+ }
2718
+ }
2316
2719
  async function responseValue(response) {
2317
2720
  if (!response.ok) {
2318
2721
  if (response.status === 401) {
2319
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
2722
+ throw new HttpError(401, authExpiredMessage());
2320
2723
  }
2321
2724
  const errorBody = await response.json().catch(() => null);
2322
2725
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -2343,14 +2746,7 @@ async function machineClient(options = {}, management = false) {
2343
2746
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
2344
2747
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
2345
2748
  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
- );
2749
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
2354
2750
  if (response.status === 401) {
2355
2751
  const renewed = await acquireMachineCredential({
2356
2752
  force: true,
@@ -2359,19 +2755,14 @@ async function machineClient(options = {}, management = false) {
2359
2755
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
2360
2756
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2361
2757
  }
2362
- response = await fetchWithToken(
2363
- method,
2364
- path,
2365
- body,
2366
- { ...requestOptions, redirect: "error" },
2367
- renewed.accessToken,
2368
- renewed.apiUrl
2369
- );
2758
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
2370
2759
  }
2371
2760
  if (response.status === 401)
2372
2761
  throw new HttpError(
2373
2762
  401,
2374
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
2763
+ 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(
2764
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
2765
+ )
2375
2766
  );
2376
2767
  return parse2(response);
2377
2768
  };
@@ -2381,7 +2772,7 @@ async function machineClient(options = {}, management = false) {
2381
2772
  delete: (path, body, opts) => send("DELETE", path, body, opts)
2382
2773
  };
2383
2774
  }
2384
- async function request(method, path, body, options) {
2775
+ async function request2(method, path, body, options) {
2385
2776
  const machine = await machineClient(options);
2386
2777
  if (machine)
2387
2778
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -2397,10 +2788,10 @@ async function request(method, path, body, options) {
2397
2788
  if (token) credential = { token, source: "token_file" };
2398
2789
  }
2399
2790
  if (!credential) {
2400
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
2791
+ throw new HttpError(401, authExpiredMessage());
2401
2792
  }
2402
2793
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
2403
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
2794
+ throw new HttpError(401, authExpiredMessage());
2404
2795
  }
2405
2796
  const tokenUsed = credential.token;
2406
2797
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -2423,8 +2814,8 @@ async function request(method, path, body, options) {
2423
2814
  }
2424
2815
  function getClient() {
2425
2816
  return {
2426
- get: (path, options) => request("GET", path, void 0, options),
2427
- post: (path, body, options) => request("POST", path, body, options)
2817
+ get: (path, options) => request2("GET", path, void 0, options),
2818
+ post: (path, body, options) => request2("POST", path, body, options)
2428
2819
  };
2429
2820
  }
2430
2821
 
@@ -2617,7 +3008,7 @@ import { existsSync as existsSync9 } from "fs";
2617
3008
  import { join as join14 } from "path";
2618
3009
 
2619
3010
  // src/lib/hook-runtime.ts
2620
- import { createHash as createHash6, randomBytes as randomBytes4 } from "crypto";
3011
+ import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
2621
3012
  import {
2622
3013
  constants as constants2,
2623
3014
  accessSync,
@@ -2628,13 +3019,13 @@ import {
2628
3019
  mkdirSync as mkdirSync5,
2629
3020
  mkdtempSync,
2630
3021
  readFileSync as readFileSync10,
2631
- readdirSync,
3022
+ readdirSync as readdirSync2,
2632
3023
  realpathSync,
2633
3024
  renameSync as renameSync2,
2634
3025
  rmSync as rmSync7,
2635
3026
  statSync as statSync2,
2636
3027
  utimesSync,
2637
- writeFileSync as writeFileSync3
3028
+ writeFileSync as writeFileSync4
2638
3029
  } from "fs";
2639
3030
  import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join12, resolve as resolve2 } from "path";
2640
3031
 
@@ -2738,7 +3129,7 @@ exec "$prim_node" "$prim_entry" "$@"
2738
3129
 
2739
3130
  // src/demo/state.ts
2740
3131
  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";
3132
+ import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
2742
3133
  import { join as join13, resolve as resolve3 } from "path";
2743
3134
 
2744
3135
  // src/generated/cli-http-v1.validators.js
@@ -29609,7 +30000,7 @@ import {
29609
30000
  opendirSync,
29610
30001
  readFileSync as readFileSync13,
29611
30002
  readSync,
29612
- readdirSync as readdirSync4
30003
+ readdirSync as readdirSync5
29613
30004
  } from "fs";
29614
30005
  import { dirname as dirname10, join as join16 } from "path";
29615
30006
 
@@ -29618,7 +30009,7 @@ import {
29618
30009
  chmodSync as chmodSync5,
29619
30010
  existsSync as existsSync11,
29620
30011
  readFileSync as readFileSync12,
29621
- readdirSync as readdirSync3,
30012
+ readdirSync as readdirSync4,
29622
30013
  rmSync as rmSync8,
29623
30014
  rmdirSync
29624
30015
  } from "fs";
@@ -29661,16 +30052,33 @@ function journalPath(orgId) {
29661
30052
  function appendMove(move, orgId) {
29662
30053
  const actor = machineCaptureActor();
29663
30054
  const captured = actor ? { ...move, captureActor: actor } : move;
29664
- appendMoveToPath(journalPath(actor ? machineJournalBucket(actor) : orgId), captured);
30055
+ const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
30056
+ appendMoveToPath(journalPath(bucket), captured);
29665
30057
  return captured;
29666
30058
  }
29667
30059
  var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
29668
30060
 
29669
30061
  // src/lib/activation.ts
29670
30062
  import { execFileSync as execFileSync4 } from "child_process";
29671
- import { existsSync as existsSync13, readFileSync as readFileSync14 } from "fs";
30063
+ import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
29672
30064
  import { homedir as homedir2 } from "os";
30065
+ import { join as join19 } from "path";
30066
+
30067
+ // src/lib/cloud-prepared.ts
30068
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync14, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
29673
30069
  import { join as join17 } from "path";
30070
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
30071
+ function cloudPreparedPath(env = process.env) {
30072
+ return join17(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30073
+ }
30074
+ function isPreparedCloudSession(env = process.env) {
30075
+ if (!isClaudeCloudSession(env)) return false;
30076
+ try {
30077
+ return existsSync13(cloudPreparedPath(env));
30078
+ } catch {
30079
+ return false;
30080
+ }
30081
+ }
29674
30082
 
29675
30083
  // src/lib/demo-pause.ts
29676
30084
  import { execFileSync as execFileSync2 } from "child_process";
@@ -29736,11 +30144,12 @@ function healDemoPause(cwd, pause, options = {}) {
29736
30144
  // src/lib/git.ts
29737
30145
  import { execFileSync as execFileSync3 } from "child_process";
29738
30146
  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";
30147
+ import { lstatSync as lstatSync7, readFileSync as readFileSync15, realpathSync as realpathSync2 } from "fs";
30148
+ import { basename as basename3, dirname as dirname11, isAbsolute as isAbsolute4, join as join18, relative, resolve as resolve4, sep } from "path";
29741
30149
  var GIT_TIMEOUT_MS2 = 1e3;
30150
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
29742
30151
  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;
30152
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
29744
30153
  function gitToplevel(cwd) {
29745
30154
  try {
29746
30155
  return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
@@ -29769,19 +30178,57 @@ function gitValue(cwd, args) {
29769
30178
  function currentBranch(cwd) {
29770
30179
  return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
29771
30180
  }
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;
30181
+ function parseGithubRepositoryName(path) {
30182
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
30183
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
30184
+ return null;
30185
+ }
30186
+ return `${parts[0]}/${parts[1]}`;
30187
+ }
30188
+ function githubRepositoryFromRemote(remote) {
30189
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
29775
30190
  const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29776
30191
  remote
29777
30192
  );
29778
30193
  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] ?? "")) {
30194
+ return path ? parseGithubRepositoryName(path) : null;
30195
+ }
30196
+ function checkoutSettingsText(repoRoot) {
30197
+ const path = join18(repoRoot, ".claude", "settings.json");
30198
+ try {
30199
+ if (!lstatSync7(join18(repoRoot, ".claude")).isDirectory()) return null;
30200
+ const stat = lstatSync7(path);
30201
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
30202
+ return readFileSync15(path, "utf8");
30203
+ } catch {
29782
30204
  return null;
29783
30205
  }
29784
- return `${parts[0]}/${parts[1]}`;
30206
+ }
30207
+ function checkoutDeclaration(repoRoot, name2) {
30208
+ const text = checkoutSettingsText(repoRoot);
30209
+ if (text === null) return null;
30210
+ let parsed;
30211
+ try {
30212
+ parsed = JSON.parse(text);
30213
+ } catch {
30214
+ return null;
30215
+ }
30216
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
30217
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
30218
+ return typeof value === "string" ? value : null;
30219
+ }
30220
+ function declaredGithubRepository(repoRoot) {
30221
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
30222
+ return value === null ? null : parseGithubRepositoryName(value.trim());
30223
+ }
30224
+ function githubRepositoryFullName(cwd) {
30225
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
30226
+ if (remote) {
30227
+ const fromOrigin = githubRepositoryFromRemote(remote);
30228
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
30229
+ }
30230
+ const root = gitToplevel(cwd);
30231
+ return root ? declaredGithubRepository(root) : null;
29785
30232
  }
29786
30233
  function canonicalGitRoot(cwd) {
29787
30234
  try {
@@ -29860,6 +30307,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
29860
30307
  repoFullName
29861
30308
  };
29862
30309
  }
30310
+ if (repoFullName) {
30311
+ return {
30312
+ repoRoot,
30313
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
30314
+ identitySource: "declared",
30315
+ repoFullName
30316
+ };
30317
+ }
29863
30318
  const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
29864
30319
  if (roots && roots.length > 0) {
29865
30320
  return {
@@ -29948,6 +30403,7 @@ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
29948
30403
 
29949
30404
  // src/lib/activation.ts
29950
30405
  var PRIM_ACTIVE_KEY = "prim.active";
30406
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
29951
30407
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
29952
30408
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
29953
30409
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
@@ -30004,14 +30460,13 @@ function repositoryBindingState(cwd) {
30004
30460
  if (marker !== void 0) return "invalid";
30005
30461
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
30006
30462
  }
30007
- function hasProjectPrimInstall(cwd) {
30008
- const root = gitToplevel(cwd);
30463
+ function projectPrimInstallAt(root) {
30009
30464
  if (root === null || root === homedir2()) return false;
30010
30465
  for (const rel of PROJECT_INSTALL_FILES) {
30011
- const path = join17(root, rel);
30012
- if (existsSync13(path)) {
30466
+ const path = join19(root, rel);
30467
+ if (existsSync14(path)) {
30013
30468
  try {
30014
- const content2 = readFileSync14(path, "utf-8");
30469
+ const content2 = readFileSync16(path, "utf-8");
30015
30470
  if (PRIM_HOOK_BINS.some((bin) => content2.includes(bin))) return true;
30016
30471
  } catch {
30017
30472
  }
@@ -30019,12 +30474,27 @@ function hasProjectPrimInstall(cwd) {
30019
30474
  }
30020
30475
  return false;
30021
30476
  }
30477
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
30478
+ function declaresInactiveAt(root) {
30479
+ if (root === null || root === homedir2()) return false;
30480
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
30481
+ const text = checkoutSettingsText(root);
30482
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
30483
+ try {
30484
+ JSON.parse(text);
30485
+ return false;
30486
+ } catch {
30487
+ return true;
30488
+ }
30489
+ }
30022
30490
  function isRepoActiveForCapture(cwd, options = {}) {
30023
30491
  let { active: flag, pause } = readCaptureConfig(cwd);
30024
30492
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
30025
30493
  if (flag === "true") return true;
30026
30494
  if (flag === "false") return false;
30027
- return hasProjectPrimInstall(cwd);
30495
+ const root = gitToplevel(cwd);
30496
+ if (declaresInactiveAt(root)) return false;
30497
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
30028
30498
  }
30029
30499
  function decisionIngestionStatus(cwd) {
30030
30500
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -30319,8 +30789,8 @@ function cachedCollectScopeAdmits(cwd, facts) {
30319
30789
 
30320
30790
  // src/lib/commit-heartbeat.ts
30321
30791
  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";
30792
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync17, readdirSync as readdirSync6, unlinkSync } from "fs";
30793
+ import { dirname as dirname12, join as join20, resolve as resolve5 } from "path";
30324
30794
  var GIT_TIMEOUT_MS4 = 1e3;
30325
30795
  function gitPath(cwd, relative3) {
30326
30796
  const value = execFileSync5("git", ["rev-parse", "--git-path", relative3], {
@@ -30333,8 +30803,8 @@ function gitPath(cwd, relative3) {
30333
30803
  return resolve5(cwd, value);
30334
30804
  }
30335
30805
  function ensurePrivateParent(path) {
30336
- mkdirSync7(dirname12(dirname12(path)), { recursive: true, mode: 448 });
30337
- mkdirSync7(dirname12(path), { recursive: true, mode: 448 });
30806
+ mkdirSync8(dirname12(dirname12(path)), { recursive: true, mode: 448 });
30807
+ mkdirSync8(dirname12(path), { recursive: true, mode: 448 });
30338
30808
  }
30339
30809
  function writeStamp(path, at) {
30340
30810
  ensurePrivateParent(path);
@@ -30363,17 +30833,17 @@ import {
30363
30833
  closeSync as closeSync3,
30364
30834
  fchmodSync as fchmodSync2,
30365
30835
  fsyncSync as fsyncSync2,
30366
- linkSync,
30836
+ linkSync as linkSync2,
30367
30837
  lstatSync as lstatSync8,
30368
- mkdirSync as mkdirSync8,
30838
+ mkdirSync as mkdirSync9,
30369
30839
  openSync as openSync3,
30370
- readFileSync as readFileSync16,
30840
+ readFileSync as readFileSync18,
30371
30841
  statSync as statSync3,
30372
30842
  unlinkSync as unlinkSync2,
30373
- writeFileSync as writeFileSync4
30843
+ writeFileSync as writeFileSync6
30374
30844
  } 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");
30845
+ import { dirname as dirname13, isAbsolute as isAbsolute5, join as join21, resolve as resolve6 } from "path";
30846
+ var WORKSPACE_ID_RELATIVE_PATH = join21("prim", "workspace-id");
30377
30847
  var MAX_ANCESTORS = 64;
30378
30848
  var MAX_GIT_FILE_BYTES = 4096;
30379
30849
  var MAX_ID_FILE_BYTES = 128;
@@ -30432,19 +30902,19 @@ function resolveWorkspaceIdPath(cwd) {
30432
30902
  function resolveFromFilesystem(cwd) {
30433
30903
  let current = resolve6(cwd);
30434
30904
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
30435
- const dotGit = join19(current, ".git");
30905
+ const dotGit = join21(current, ".git");
30436
30906
  try {
30437
30907
  const stat = lstatSync8(dotGit);
30438
30908
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
30439
- return join19(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30909
+ return join21(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30440
30910
  }
30441
30911
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
30442
- const contents = readFileSync16(dotGit, "utf8");
30912
+ const contents = readFileSync18(dotGit, "utf8");
30443
30913
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
30444
30914
  if (match?.[1]) {
30445
30915
  const gitDirectory = isAbsolute5(match[1]) ? resolve6(match[1]) : resolve6(current, match[1]);
30446
30916
  if (isGitDirectory(gitDirectory)) {
30447
- return join19(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30917
+ return join21(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30448
30918
  }
30449
30919
  }
30450
30920
  }
@@ -30463,7 +30933,7 @@ function resolveFromFilesystem(cwd) {
30463
30933
  }
30464
30934
  function isGitDirectory(path) {
30465
30935
  try {
30466
- return statSync3(join19(path, "HEAD")).isFile();
30936
+ return statSync3(join21(path, "HEAD")).isFile();
30467
30937
  } catch {
30468
30938
  return false;
30469
30939
  }
@@ -30482,7 +30952,7 @@ function inspectPath(path) {
30482
30952
  return { status: "corrupt", path, reason: "invalid_content" };
30483
30953
  }
30484
30954
  try {
30485
- const contents = readFileSync16(path, "utf8");
30955
+ const contents = readFileSync18(path, "utf8");
30486
30956
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
30487
30957
  if ((contents === workspaceId || contents === `${workspaceId}
30488
30958
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -30501,11 +30971,11 @@ function inspectPath(path) {
30501
30971
  function createWorkspaceId(path) {
30502
30972
  const parent = dirname13(path);
30503
30973
  const workspaceId = randomUUID4();
30504
- const temporaryPath = join19(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30974
+ const temporaryPath = join21(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30505
30975
  let temporaryCreated = false;
30506
30976
  let publishing = false;
30507
30977
  try {
30508
- mkdirSync8(parent, { recursive: true, mode: 448 });
30978
+ mkdirSync9(parent, { recursive: true, mode: 448 });
30509
30979
  chmodSync6(parent, 448);
30510
30980
  const fd = openSync3(
30511
30981
  temporaryPath,
@@ -30514,7 +30984,7 @@ function createWorkspaceId(path) {
30514
30984
  );
30515
30985
  temporaryCreated = true;
30516
30986
  try {
30517
- writeFileSync4(fd, `${workspaceId}
30987
+ writeFileSync6(fd, `${workspaceId}
30518
30988
  `, "utf8");
30519
30989
  fchmodSync2(fd, 384);
30520
30990
  fsyncSync2(fd);
@@ -30522,7 +30992,7 @@ function createWorkspaceId(path) {
30522
30992
  closeSync3(fd);
30523
30993
  }
30524
30994
  publishing = true;
30525
- linkSync(temporaryPath, path);
30995
+ linkSync2(temporaryPath, path);
30526
30996
  return { status: "ready", workspaceId, path, created: true };
30527
30997
  } catch (error) {
30528
30998
  if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
@@ -30571,20 +31041,20 @@ function parseAgent(argv) {
30571
31041
  }
30572
31042
 
30573
31043
  // src/hooks/codex-context.ts
30574
- import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
31044
+ import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
30575
31045
  import {
30576
31046
  chmodSync as chmodSync7,
30577
- existsSync as existsSync14,
30578
- mkdirSync as mkdirSync9,
30579
- readFileSync as readFileSync17,
30580
- readdirSync as readdirSync6,
31047
+ existsSync as existsSync15,
31048
+ mkdirSync as mkdirSync10,
31049
+ readFileSync as readFileSync19,
31050
+ readdirSync as readdirSync7,
30581
31051
  renameSync as renameSync3,
30582
- rmSync as rmSync9,
31052
+ rmSync as rmSync10,
30583
31053
  statSync as statSync4,
30584
31054
  unlinkSync as unlinkSync3,
30585
- writeFileSync as writeFileSync5
31055
+ writeFileSync as writeFileSync7
30586
31056
  } from "fs";
30587
- import { join as join21 } from "path";
31057
+ import { join as join23 } from "path";
30588
31058
 
30589
31059
  // src/daemon/principal.ts
30590
31060
  import { createHash as createHash9 } from "crypto";
@@ -30647,14 +31117,14 @@ function parseDaemonResponseEnvelope(value) {
30647
31117
 
30648
31118
  // src/daemon/client.ts
30649
31119
  import { createConnection } from "net";
30650
- import { join as join20 } from "path";
30651
- var SOCK_PATH = join20(primConfigDirectory(), "sock");
31120
+ import { join as join22 } from "path";
31121
+ var SOCK_PATH = join22(primConfigDirectory(), "sock");
30652
31122
  var DEFAULT_TIMEOUT_MS2 = 250;
30653
31123
  var nextRequestId = 1;
30654
31124
  function daemonRequest(method, params = {}, opts = {}) {
30655
31125
  const id2 = nextRequestId++;
30656
31126
  const caller = resolveDaemonPrincipal();
30657
- const request2 = {
31127
+ const request3 = {
30658
31128
  id: id2,
30659
31129
  method,
30660
31130
  params,
@@ -30693,7 +31163,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30693
31163
  });
30694
31164
  socket.on("connect", () => {
30695
31165
  try {
30696
- socket?.write(`${JSON.stringify(request2)}
31166
+ socket?.write(`${JSON.stringify(request3)}
30697
31167
  `);
30698
31168
  } catch {
30699
31169
  clearTimeout(timer);
@@ -30738,7 +31208,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30738
31208
  }
30739
31209
 
30740
31210
  // src/daemon/decision-digest-cache.ts
30741
- import { randomBytes as randomBytes5 } from "crypto";
31211
+ import { randomBytes as randomBytes6 } from "crypto";
30742
31212
  var DECISION_DIGEST_CACHE_LIMIT = 100;
30743
31213
  var DECISION_DIGEST_CACHE_WINDOW = "24h";
30744
31214
  var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
@@ -30897,10 +31367,10 @@ var STATE_VERSION = 1;
30897
31367
  var DRAFT_STATE_VERSION = 2;
30898
31368
  var NO_CURSOR = -1;
30899
31369
  function stateRoot(namespace) {
30900
- return join21(primConfigDirectory(), namespace, "decision-digests");
31370
+ return join23(primConfigDirectory(), namespace, "decision-digests");
30901
31371
  }
30902
31372
  function draftStateRoot(namespace) {
30903
- return join21(primConfigDirectory(), namespace, "decision-draft-deliveries");
31373
+ return join23(primConfigDirectory(), namespace, "decision-draft-deliveries");
30904
31374
  }
30905
31375
  function workspaceFor(cwd) {
30906
31376
  try {
@@ -30912,12 +31382,12 @@ function workspaceFor(cwd) {
30912
31382
  function statePath(args) {
30913
31383
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
30914
31384
  const key = createHash10("sha256").update(identity).digest("hex");
30915
- return join21(stateRoot(args.namespace), `${key}.json`);
31385
+ return join23(stateRoot(args.namespace), `${key}.json`);
30916
31386
  }
30917
31387
  function draftStatePath(args) {
30918
31388
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
30919
31389
  const key = createHash10("sha256").update(identity).digest("hex");
30920
- return join21(draftStateRoot(args.namespace), `${key}.json`);
31390
+ return join23(draftStateRoot(args.namespace), `${key}.json`);
30921
31391
  }
30922
31392
  function parseState(value) {
30923
31393
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -30956,30 +31426,30 @@ function parseDraftState(value) {
30956
31426
  };
30957
31427
  }
30958
31428
  function readState(path) {
30959
- if (!existsSync14(path)) return void 0;
31429
+ if (!existsSync15(path)) return void 0;
30960
31430
  try {
30961
- return parseState(JSON.parse(readFileSync17(path, "utf8")));
31431
+ return parseState(JSON.parse(readFileSync19(path, "utf8")));
30962
31432
  } catch {
30963
31433
  return void 0;
30964
31434
  }
30965
31435
  }
30966
31436
  function readDraftState(path) {
30967
- if (!existsSync14(path)) return void 0;
31437
+ if (!existsSync15(path)) return void 0;
30968
31438
  try {
30969
- return parseDraftState(JSON.parse(readFileSync17(path, "utf8")));
31439
+ return parseDraftState(JSON.parse(readFileSync19(path, "utf8")));
30970
31440
  } catch {
30971
31441
  return void 0;
30972
31442
  }
30973
31443
  }
30974
31444
  function writeStateFile(path, directory, state) {
30975
- mkdirSync9(directory, { recursive: true, mode: 448 });
31445
+ mkdirSync10(directory, { recursive: true, mode: 448 });
30976
31446
  chmodSync7(directory, 448);
30977
- const temporary = join21(
31447
+ const temporary = join23(
30978
31448
  directory,
30979
- `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes6(8).toString("hex")}`
31449
+ `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
30980
31450
  );
30981
31451
  try {
30982
- writeFileSync5(temporary, `${JSON.stringify(state)}
31452
+ writeFileSync7(temporary, `${JSON.stringify(state)}
30983
31453
  `, {
30984
31454
  encoding: "utf8",
30985
31455
  mode: 384,
@@ -30995,17 +31465,17 @@ function writeStateFile(path, directory, state) {
30995
31465
  }
30996
31466
  }
30997
31467
  function cleanupStateFiles(directory, now) {
30998
- if (!existsSync14(directory)) return;
31468
+ if (!existsSync15(directory)) return;
30999
31469
  let names;
31000
31470
  try {
31001
- names = readdirSync6(directory);
31471
+ names = readdirSync7(directory);
31002
31472
  } catch {
31003
31473
  return;
31004
31474
  }
31005
31475
  const files = [];
31006
31476
  const residue = [];
31007
31477
  for (const name2 of names) {
31008
- const path = join21(directory, name2);
31478
+ const path = join23(directory, name2);
31009
31479
  try {
31010
31480
  const mtimeMs = statSync4(path).mtimeMs;
31011
31481
  if (name2.endsWith(".json")) {
@@ -31027,7 +31497,7 @@ function cleanupStateFiles(directory, now) {
31027
31497
  for (const path of residue) {
31028
31498
  try {
31029
31499
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
31030
- rmSync9(path, { recursive: true, force: true });
31500
+ rmSync10(path, { recursive: true, force: true });
31031
31501
  }
31032
31502
  } catch {
31033
31503
  }
@@ -31343,17 +31813,17 @@ async function processCodexMessageContext(envelope, deps = defaultDeps) {
31343
31813
  }
31344
31814
 
31345
31815
  // src/commands/cursor-install.ts
31346
- import { existsSync as existsSync16, readFileSync as readFileSync19 } from "fs";
31816
+ import { existsSync as existsSync17, readFileSync as readFileSync21 } from "fs";
31347
31817
  import { homedir as homedir4 } from "os";
31348
- import { isAbsolute as isAbsolute6, join as join23 } from "path";
31818
+ import { isAbsolute as isAbsolute6, join as join25 } from "path";
31349
31819
 
31350
31820
  // src/lib/preflight-host.ts
31351
31821
  import { execFileSync as execFileSync7 } from "child_process";
31352
31822
 
31353
31823
  // src/commands/claude-install.ts
31354
- import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
31824
+ import { existsSync as existsSync16, lstatSync as lstatSync9, readFileSync as readFileSync20 } from "fs";
31355
31825
  import { homedir as homedir3 } from "os";
31356
- import { join as join22 } from "path";
31826
+ import { join as join24 } from "path";
31357
31827
  var CAPTURE_BIN = "prim-hook";
31358
31828
  var GATE_BIN = "prim-pre-tool-use";
31359
31829
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -31362,7 +31832,7 @@ var SESSION_END_BIN = "prim-session-end";
31362
31832
  var STATUSLINE_BIN = "prim-statusline";
31363
31833
  var STATUSLINE_ARGS = "";
31364
31834
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
31365
- var USER_SCOPE_PATH = join22(homedir3(), ".claude", "settings.json");
31835
+ var USER_SCOPE_PATH = join24(homedir3(), ".claude", "settings.json");
31366
31836
  function projectRoot() {
31367
31837
  return gitToplevel() ?? process.cwd();
31368
31838
  }
@@ -31442,20 +31912,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
31442
31912
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
31443
31913
  if (explicit && isAbsolute6(explicit)) return explicit;
31444
31914
  const xdg = env.XDG_CONFIG_HOME?.trim();
31445
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join23(xdg, "cursor");
31446
- return join23(home, ".cursor");
31915
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join25(xdg, "cursor");
31916
+ return join25(home, ".cursor");
31447
31917
  }
31448
31918
  function cursorHooksPath(scope, root = projectRoot()) {
31449
- return scope === "user" ? join23(cursorConfigDirectory(), "hooks.json") : join23(root, ".cursor", "hooks.json");
31919
+ return scope === "user" ? join25(cursorConfigDirectory(), "hooks.json") : join25(root, ".cursor", "hooks.json");
31450
31920
  }
31451
31921
  function plainObject(value) {
31452
31922
  return typeof value === "object" && value !== null && !Array.isArray(value);
31453
31923
  }
31454
31924
  function readCursorHooks(path) {
31455
- if (!existsSync16(path)) return {};
31925
+ if (!existsSync17(path)) return {};
31456
31926
  let parsed;
31457
31927
  try {
31458
- parsed = JSON.parse(readFileSync19(path, "utf8"));
31928
+ parsed = JSON.parse(readFileSync21(path, "utf8"));
31459
31929
  } catch {
31460
31930
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
31461
31931
  }
@@ -31727,8 +32197,8 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
31727
32197
  }
31728
32198
 
31729
32199
  // src/hooks/redact.ts
31730
- import { existsSync as existsSync17, readFileSync as readFileSync20, statSync as statSync5 } from "fs";
31731
- import { join as join24 } from "path";
32200
+ import { existsSync as existsSync18, readFileSync as readFileSync22, statSync as statSync5 } from "fs";
32201
+ import { join as join26 } from "path";
31732
32202
  import { Worker } from "worker_threads";
31733
32203
  var USER_HOME_RULES = [
31734
32204
  {
@@ -31772,6 +32242,11 @@ var DEFAULT_RULES = [
31772
32242
  pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
31773
32243
  reason: "aws-secret"
31774
32244
  },
32245
+ {
32246
+ // `prim auth enroll --print-env` output an agent may write into a file.
32247
+ pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
32248
+ reason: "prim-m2m-secret"
32249
+ },
31775
32250
  { pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
31776
32251
  {
31777
32252
  pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
@@ -31804,15 +32279,15 @@ function normalizedWorkspaceFlags(value) {
31804
32279
  return [...new Set(`g${requested}`)].sort().join("");
31805
32280
  }
31806
32281
  function loadWorkspaceRules(cwd) {
31807
- const path = join24(cwd, WORKSPACE_FILE2);
31808
- if (!existsSync17(path)) return [];
32282
+ const path = join26(cwd, WORKSPACE_FILE2);
32283
+ if (!existsSync18(path)) return [];
31809
32284
  let cfg;
31810
32285
  try {
31811
32286
  if (statSync5(path).size > MAX_WORKSPACE_CONFIG_BYTES) {
31812
32287
  debugRedaction(`ignoring oversized ${WORKSPACE_FILE2}`);
31813
32288
  return [];
31814
32289
  }
31815
- cfg = JSON.parse(readFileSync20(path, "utf-8"));
32290
+ cfg = JSON.parse(readFileSync22(path, "utf-8"));
31816
32291
  } catch {
31817
32292
  debugRedaction(`ignoring unparseable ${WORKSPACE_FILE2}`);
31818
32293
  return [];
@@ -41670,14 +42145,14 @@ function emitOutput(output, acknowledge) {
41670
42145
  }
41671
42146
  function resolveCliVersion() {
41672
42147
  try {
41673
- const pkg = JSON.parse(readFileSync21(join25(here, "..", "..", "package.json"), "utf-8"));
42148
+ const pkg = JSON.parse(readFileSync23(join27(here, "..", "..", "package.json"), "utf-8"));
41674
42149
  return pkg.version ?? "unknown";
41675
42150
  } catch {
41676
42151
  return "unknown";
41677
42152
  }
41678
42153
  }
41679
42154
  function spawnBackgroundFlush() {
41680
- const entry = join25(here, "..", "index.js");
42155
+ const entry = join27(here, "..", "index.js");
41681
42156
  spawn2(process.execPath, [entry, "moves", "flush"], {
41682
42157
  detached: true,
41683
42158
  stdio: "ignore",