@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
@@ -81,10 +81,23 @@ function publicDecisionResponse(value) {
81
81
  return replace(projected);
82
82
  }
83
83
 
84
+ // src/lib/cloud-env.ts
85
+ function isClaudeCloudSession(env = process.env) {
86
+ return env.CLAUDE_CODE_REMOTE === "true";
87
+ }
88
+ 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';
89
+ 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';
90
+ 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}.`;
91
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
92
+ function cloudSetupPointer(message, env = process.env) {
93
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
94
+ }
95
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
96
+
84
97
  // src/client.ts
85
- import { createHash as createHash5 } from "crypto";
86
- import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
87
- import { dirname as dirname5 } from "path";
98
+ import { createHash as createHash7 } from "crypto";
99
+ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
100
+ import { dirname as dirname6 } from "path";
88
101
 
89
102
  // src/lib/atomic-file.ts
90
103
  import { randomUUID } from "crypto";
@@ -166,16 +179,25 @@ function atomicWriteFile(target, content, options = {}) {
166
179
  }
167
180
 
168
181
  // src/lib/credentials.ts
169
- import { createHash as createHash4 } from "crypto";
170
- import { readFileSync as readFileSync6 } from "fs";
171
- import { join as join7 } from "path";
182
+ import { createHash as createHash6 } from "crypto";
183
+ import { readFileSync as readFileSync7 } from "fs";
184
+ import { join as join9 } from "path";
172
185
 
173
186
  // src/lib/machine-credentials.ts
174
- import { execFileSync } from "child_process";
175
- import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
176
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
187
+ import { execFileSync as execFileSync2 } from "child_process";
188
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
189
+ import {
190
+ chmodSync,
191
+ existsSync as existsSync3,
192
+ linkSync,
193
+ lstatSync as lstatSync4,
194
+ mkdirSync as mkdirSync3,
195
+ readFileSync as readFileSync6,
196
+ rmSync as rmSync6,
197
+ writeFileSync as writeFileSync3
198
+ } from "fs";
177
199
  import { createRequire } from "module";
178
- import { dirname as dirname4, join as join6 } from "path";
200
+ import { dirname as dirname5, join as join8 } from "path";
179
201
  import { fileURLToPath as fileURLToPath3 } from "url";
180
202
 
181
203
  // src/lib/file-lock.ts
@@ -381,6 +403,36 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
381
403
  "fi; fi; "
382
404
  ].join("");
383
405
 
406
+ // src/lib/loopback-fetch.ts
407
+ import { request } from "http";
408
+ import { Readable } from "stream";
409
+ function loopbackFetch(url, init = {}) {
410
+ const target = new URL(url);
411
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
412
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
413
+ return new Promise((resolve3, reject) => {
414
+ const outgoing = request(
415
+ target,
416
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
417
+ (incoming) => {
418
+ try {
419
+ const headers = new Headers();
420
+ for (const [name, value] of Object.entries(incoming.headers))
421
+ if (typeof value === "string") headers.set(name, value);
422
+ const status = incoming.statusCode ?? 502;
423
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
424
+ resolve3(new Response(body, { status, headers }));
425
+ } catch (error) {
426
+ incoming.destroy();
427
+ reject(error);
428
+ }
429
+ }
430
+ );
431
+ outgoing.once("error", reject);
432
+ outgoing.end(init.body);
433
+ });
434
+ }
435
+
384
436
  // src/lib/workos-connect.ts
385
437
  var TOKEN_PATH = "/oauth2/token";
386
438
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -517,10 +569,10 @@ function parseWorkosConnectTokens(value, options = {}) {
517
569
  "access_token",
518
570
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
519
571
  );
520
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
572
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
521
573
  return {
522
574
  accessToken,
523
- refreshToken: refreshToken2,
575
+ refreshToken: refreshToken3,
524
576
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
525
577
  };
526
578
  }
@@ -576,9 +628,19 @@ function parseMachineConfiguration(value) {
576
628
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
577
629
  };
578
630
  }
631
+ function rejectedCredentialsMessage(message, env = process.env) {
632
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
633
+ }
579
634
  function machineSignal(signal) {
580
635
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
581
636
  }
637
+ function hostOf(url) {
638
+ try {
639
+ return new URL(url).hostname;
640
+ } catch {
641
+ return "Primitive";
642
+ }
643
+ }
582
644
  async function fetchMachine(url, options, fetchImpl) {
583
645
  try {
584
646
  return await fetchImpl(url, options);
@@ -586,7 +648,9 @@ async function fetchMachine(url, options, fetchImpl) {
586
648
  options.signal?.throwIfAborted();
587
649
  throw new MachineAuthError(
588
650
  "authentication_unavailable",
589
- "Machine authentication is temporarily unavailable. Check the connection and retry."
651
+ // A cloud VM reaches only the hosts its environment allows, and both of
652
+ // Primitive's are blocked by default: name the one that failed.
653
+ 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."
590
654
  );
591
655
  }
592
656
  }
@@ -613,8 +677,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
613
677
  );
614
678
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
615
679
  }
616
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
617
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
680
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
681
+ const network = options.secretInjection === "network";
682
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
618
683
  throw new MachineAuthError(
619
684
  "invalid_credentials",
620
685
  "A machine client ID and secret are required.",
@@ -628,11 +693,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
628
693
  redirect: "error",
629
694
  signal: machineSignal(signal),
630
695
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
631
- body: new URLSearchParams({
632
- grant_type: "client_credentials",
633
- client_id: clientId,
634
- client_secret: clientSecret
635
- })
696
+ // With a network secret the agent proxy authenticates the client with
697
+ // HTTP Basic (client_secret_basic); the body carries no credential.
698
+ body: new URLSearchParams(
699
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
700
+ )
636
701
  },
637
702
  fetchImpl
638
703
  );
@@ -640,7 +705,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
640
705
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
641
706
  throw new MachineAuthError(
642
707
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
643
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
708
+ 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(
709
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
710
+ ) : "The machine token service is temporarily unavailable.",
644
711
  terminal,
645
712
  terminal ? void 0 : machineRetryAt(response)
646
713
  );
@@ -660,6 +727,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
660
727
  } catch {
661
728
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
662
729
  }
730
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
731
+ throw new MachineAuthError(
732
+ "token_client_mismatch",
733
+ "The token service issued a token for another machine client."
734
+ );
663
735
  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()) {
664
736
  throw new MachineAuthError(
665
737
  "token_identity_mismatch",
@@ -705,12 +777,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
705
777
  const terminal = response.status === 401 || response.status === 403;
706
778
  throw new MachineAuthError(
707
779
  terminal ? "machine_access_rejected" : "verification_unavailable",
708
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
780
+ terminal ? rejectedCredentialsMessage(
781
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
782
+ ) : "Machine verification is temporarily unavailable.",
709
783
  terminal
710
784
  );
711
785
  }
712
786
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
713
787
  }
788
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
789
+ const rejected = () => new MachineAuthError(
790
+ "network_token_rejected",
791
+ `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.`,
792
+ true
793
+ );
794
+ if (status === 401 || status === 403) throw rejected();
795
+ if (status < 200 || status > 299)
796
+ throw new MachineAuthError(
797
+ "verification_unavailable",
798
+ "Machine verification is temporarily unavailable."
799
+ );
800
+ let data;
801
+ try {
802
+ data = machineRecord(value);
803
+ } catch {
804
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
805
+ }
806
+ if (data.authenticated !== true) throw rejected();
807
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
808
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
809
+ throw new MachineAuthError(
810
+ "network_secret_mismatch",
811
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
812
+ true
813
+ );
814
+ return parseMachineIdentity(data, clientId);
815
+ }
816
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
817
+ const response = await fetchMachine(
818
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
819
+ { redirect: "error", signal: machineSignal(signal) },
820
+ fetchImpl
821
+ );
822
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
823
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
824
+ }
714
825
 
715
826
  // src/lib/paths.ts
716
827
  import { homedir } from "os";
@@ -742,6 +853,11 @@ function primConfigDirectory(options = {}) {
742
853
 
743
854
  // src/lib/machine-broker.ts
744
855
  var MAX_RESPONSE_BYTES = 96 * 1024;
856
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
857
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
858
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
859
+ var FORWARD_REQUEST_PROOF = "forward-request";
860
+ var FORWARD_ANSWER_PROOF = "forward-answer";
745
861
  var IDLE_MS = 5 * 6e4;
746
862
  function descriptorPath(directory, generation) {
747
863
  return join4(directory, `machine_broker_${generation}.json`);
@@ -757,8 +873,8 @@ function readDescriptor(path) {
757
873
  return void 0;
758
874
  }
759
875
  }
760
- function signature(secret, nonce, body) {
761
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
876
+ function signature(secret, nonce, body, purpose) {
877
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
762
878
  }
763
879
  function matches(left, right) {
764
880
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -773,10 +889,9 @@ async function brokerRequest(descriptor, environment, options) {
773
889
  observedTokenHash: tokenHash(options.observedToken),
774
890
  timestamp: Date.now()
775
891
  });
776
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
892
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
777
893
  method: "POST",
778
894
  body,
779
- redirect: "error",
780
895
  signal: options.signal,
781
896
  headers: {
782
897
  "Content-Type": "application/json",
@@ -807,6 +922,15 @@ async function brokerRequest(descriptor, environment, options) {
807
922
  );
808
923
  return credential;
809
924
  }
925
+ function brokerEnvironment(options) {
926
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
927
+ return {
928
+ ...options.env,
929
+ PRIM_API_URL: options.apiUrl,
930
+ PRIM_CONFIG_DIR: options.directory,
931
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
932
+ };
933
+ }
810
934
  async function acquireBrokerCredential(options) {
811
935
  const path = descriptorPath(options.directory, options.environment.generation);
812
936
  const existing = readDescriptor(path);
@@ -818,15 +942,28 @@ async function acquireBrokerCredential(options) {
818
942
  if (error instanceof MachineAuthError) throw error;
819
943
  }
820
944
  }
821
- const descriptor = await withFileLock(
945
+ const descriptor = await ensureBroker(options);
946
+ try {
947
+ return await brokerRequest(descriptor, options.environment, options);
948
+ } catch (error) {
949
+ options.signal.throwIfAborted();
950
+ if (error instanceof MachineAuthError) throw error;
951
+ throw new MachineAuthError(
952
+ "broker_unavailable",
953
+ "Machine credential broker is unavailable. Retry the command."
954
+ );
955
+ }
956
+ }
957
+ async function ensureBroker(options) {
958
+ const path = descriptorPath(options.directory, options.environment.generation);
959
+ return withFileLock(
822
960
  join4(options.directory, "machine-broker.lock"),
823
961
  async () => {
824
962
  const current = readDescriptor(path);
825
963
  if (current) {
826
964
  try {
827
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
828
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
829
- redirect: "error"
965
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
966
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
830
967
  });
831
968
  if (response.ok && await response.text() === current.nonce) return current;
832
969
  } catch {
@@ -845,7 +982,7 @@ async function acquireBrokerCredential(options) {
845
982
  detached: true,
846
983
  stdio: ["ignore", "ignore", "ignore", "ipc"],
847
984
  windowsHide: true,
848
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
985
+ env: brokerEnvironment(options)
849
986
  });
850
987
  let settled = false;
851
988
  const finish = (error) => {
@@ -897,27 +1034,93 @@ async function acquireBrokerCredential(options) {
897
1034
  },
898
1035
  { signal: options.signal }
899
1036
  );
1037
+ }
1038
+ async function forwardOnce(descriptor, environment, request3, signal) {
1039
+ const body = JSON.stringify({
1040
+ generation: environment.generation,
1041
+ timestamp: Date.now(),
1042
+ method: request3.method,
1043
+ path: request3.path,
1044
+ headers: request3.headers ?? {},
1045
+ ...request3.body === void 0 ? {} : { body: request3.body }
1046
+ });
1047
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
1048
+ method: "POST",
1049
+ body,
1050
+ signal,
1051
+ headers: {
1052
+ "Content-Type": "application/json",
1053
+ "X-Prim-Proof": signature(
1054
+ environment.clientSecret,
1055
+ descriptor.nonce,
1056
+ body,
1057
+ FORWARD_REQUEST_PROOF
1058
+ )
1059
+ }
1060
+ });
1061
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
1062
+ if (typeof envelope.body !== "string" || !matches(
1063
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
1064
+ envelope.proof
1065
+ ))
1066
+ throw new MachineAuthError(
1067
+ "broker_unavailable",
1068
+ "Machine credential broker could not be authenticated. Retry the command."
1069
+ );
1070
+ const data = machineRecord(JSON.parse(envelope.body));
1071
+ if (data.error) {
1072
+ const error = machineRecord(data.error);
1073
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
1074
+ }
1075
+ const status = data.status;
1076
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
1077
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
1078
+ const headers = new Headers();
1079
+ for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
1080
+ if (typeof value === "string") headers.set(name, value);
1081
+ const text = typeof data.body === "string" ? data.body : "";
1082
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
1083
+ }
1084
+ async function forwardBrokerRequest(options) {
1085
+ const path = descriptorPath(options.directory, options.environment.generation);
1086
+ const unavailable = () => new MachineAuthError(
1087
+ "broker_unavailable",
1088
+ "Machine credential broker is unavailable. Retry the command."
1089
+ );
1090
+ const existing = readDescriptor(path);
1091
+ if (existing) {
1092
+ try {
1093
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
1094
+ } catch (error) {
1095
+ options.signal.throwIfAborted();
1096
+ if (error instanceof MachineAuthError) throw error;
1097
+ if (error.code !== "ECONNREFUSED") throw unavailable();
1098
+ }
1099
+ }
1100
+ const descriptor = await ensureBroker(options);
900
1101
  try {
901
- return await brokerRequest(descriptor, options.environment, options);
1102
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
902
1103
  } catch (error) {
903
1104
  options.signal.throwIfAborted();
904
1105
  if (error instanceof MachineAuthError) throw error;
905
- throw new MachineAuthError(
906
- "broker_unavailable",
907
- "Machine credential broker is unavailable. Retry the command."
908
- );
1106
+ throw unavailable();
909
1107
  }
910
1108
  }
911
1109
 
912
1110
  // src/lib/machine-retry.ts
913
1111
  import { createHash as createHash2 } from "crypto";
914
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
1112
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
915
1113
  import { join as join5 } from "path";
916
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
1114
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
1115
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
1116
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
917
1117
  signal?.throwIfAborted();
918
1118
  const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
919
1119
  const path = join5(directory, `machine_retry_${key}.json`);
920
- let state = { failures: 0, retryAt: 0 };
1120
+ let state = {
1121
+ failures: 0,
1122
+ retryAt: 0
1123
+ };
921
1124
  try {
922
1125
  const stat = lstatSync2(path);
923
1126
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
@@ -932,12 +1135,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
932
1135
  if (state.retryAt > Date.now())
933
1136
  throw new MachineAuthError(
934
1137
  "token_service_unavailable",
935
- "Machine authentication is cooling down after a temporary failure. Retry later.",
1138
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
1139
+ // Cloud setup keeps this wait too, so pointing at it would loop.
1140
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
1141
+ ) : (
1142
+ // The cooldown hides the failure that started it; cloud setup
1143
+ // retries at once and names the cause.
1144
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
1145
+ ),
936
1146
  false,
937
1147
  state.retryAt
938
1148
  );
939
1149
  try {
940
- const result = await request2();
1150
+ const result = await request3();
941
1151
  rmSync4(path, { force: true });
942
1152
  return result;
943
1153
  } catch (error) {
@@ -949,40 +1159,1212 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
949
1159
  ].includes(error.code)) {
950
1160
  const failures = Math.min(16, state.failures + 1);
951
1161
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
952
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
953
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
1162
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
1163
+ atomicWriteFile(
1164
+ path,
1165
+ JSON.stringify({
1166
+ failures,
1167
+ retryAt,
1168
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
1169
+ }),
1170
+ { mode: 384 }
1171
+ );
954
1172
  throw new MachineAuthError(error.code, error.message, false, retryAt);
955
1173
  }
956
1174
  throw error;
957
1175
  }
958
1176
  }
959
1177
 
1178
+ // src/lib/session-identity.ts
1179
+ import { execFile } from "child_process";
1180
+ import { createHash as createHash4 } from "crypto";
1181
+ import { rmSync as rmSync5 } from "fs";
1182
+ import { join as join7 } from "path";
1183
+ import { promisify } from "util";
1184
+
1185
+ // src/lib/git.ts
1186
+ import { execFileSync } from "child_process";
1187
+ import { createHash as createHash3 } from "crypto";
1188
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
1189
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
1190
+ var GIT_TIMEOUT_MS = 1e3;
1191
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1192
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1193
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1194
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1195
+ function gitChildEnvironment(env = process.env) {
1196
+ return Object.fromEntries(
1197
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
1198
+ );
1199
+ }
1200
+ function gitToplevel(cwd) {
1201
+ try {
1202
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1203
+ cwd,
1204
+ encoding: "utf-8",
1205
+ stdio: ["ignore", "pipe", "ignore"],
1206
+ timeout: GIT_TIMEOUT_MS,
1207
+ env: gitChildEnvironment()
1208
+ }).trim();
1209
+ } catch {
1210
+ return null;
1211
+ }
1212
+ }
1213
+ function gitValue(cwd, args) {
1214
+ try {
1215
+ const value = execFileSync("git", args, {
1216
+ cwd,
1217
+ encoding: "utf-8",
1218
+ stdio: ["ignore", "pipe", "ignore"],
1219
+ timeout: GIT_TIMEOUT_MS,
1220
+ env: gitChildEnvironment()
1221
+ }).trim();
1222
+ return value || void 0;
1223
+ } catch {
1224
+ return void 0;
1225
+ }
1226
+ }
1227
+ function currentBranch(cwd) {
1228
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1229
+ }
1230
+ function parseGithubRepositoryName(path) {
1231
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1232
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1233
+ return null;
1234
+ }
1235
+ return `${parts[0]}/${parts[1]}`;
1236
+ }
1237
+ function githubRepositoryFromRemote(remote) {
1238
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1239
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1240
+ remote
1241
+ );
1242
+ const path = match?.[1] ?? match?.[2];
1243
+ return path ? parseGithubRepositoryName(path) : null;
1244
+ }
1245
+ function checkoutSettingsText(repoRoot) {
1246
+ const path = join6(repoRoot, ".claude", "settings.json");
1247
+ try {
1248
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
1249
+ const stat = lstatSync3(path);
1250
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1251
+ return readFileSync5(path, "utf8");
1252
+ } catch {
1253
+ return null;
1254
+ }
1255
+ }
1256
+ function checkoutDeclaration(repoRoot, name) {
1257
+ const text = checkoutSettingsText(repoRoot);
1258
+ if (text === null) return null;
1259
+ let parsed;
1260
+ try {
1261
+ parsed = JSON.parse(text);
1262
+ } catch {
1263
+ return null;
1264
+ }
1265
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1266
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
1267
+ return typeof value === "string" ? value : null;
1268
+ }
1269
+ function declaredGithubRepository(repoRoot) {
1270
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1271
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1272
+ }
1273
+ function githubRepositoryFullName(cwd) {
1274
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1275
+ if (remote) {
1276
+ const fromOrigin = githubRepositoryFromRemote(remote);
1277
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1278
+ }
1279
+ const root = gitToplevel(cwd);
1280
+ return root ? declaredGithubRepository(root) : null;
1281
+ }
1282
+ function canonicalGitRoot(cwd) {
1283
+ try {
1284
+ const top = gitToplevel(cwd);
1285
+ return top ? realpathSync.native(top) : null;
1286
+ } catch {
1287
+ return null;
1288
+ }
1289
+ }
1290
+ function normalizeOriginRemote(remote) {
1291
+ const value = remote.trim();
1292
+ if (!value) return void 0;
1293
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1294
+ if (scp?.host && scp.path) {
1295
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1296
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1297
+ }
1298
+ try {
1299
+ const url = new URL(value);
1300
+ url.username = "";
1301
+ url.password = "";
1302
+ url.search = "";
1303
+ url.hash = "";
1304
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1305
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1306
+ return void 0;
1307
+ } catch {
1308
+ return void 0;
1309
+ }
1310
+ }
1311
+ function nearestExistingAncestor(path) {
1312
+ const suffix = [];
1313
+ let cursor = path;
1314
+ while (true) {
1315
+ try {
1316
+ lstatSync3(cursor);
1317
+ break;
1318
+ } catch (error) {
1319
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1320
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1321
+ const parent = dirname4(cursor);
1322
+ if (parent === cursor) return null;
1323
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1324
+ cursor = parent;
1325
+ }
1326
+ }
1327
+ try {
1328
+ return { real: realpathSync.native(cursor), suffix };
1329
+ } catch {
1330
+ return null;
1331
+ }
1332
+ }
1333
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1334
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1335
+ return { ok: false, reason: "invalid_path" };
1336
+ }
1337
+ const absolute = resolve(baseDir, filePath);
1338
+ const resolved = nearestExistingAncestor(absolute);
1339
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1340
+ const target = resolve(resolved.real, ...resolved.suffix);
1341
+ const rel = relative(context.repoRoot, target);
1342
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1343
+ if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1344
+ return { ok: false, reason: "outside_repository" };
1345
+ }
1346
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1347
+ }
1348
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1349
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1350
+ return null;
1351
+ const absolute = resolve(cwd, filePath);
1352
+ let target;
1353
+ try {
1354
+ const stat = lstatSync3(absolute);
1355
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1356
+ target = realpathSync.native(absolute);
1357
+ } catch (error) {
1358
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1359
+ return null;
1360
+ }
1361
+ try {
1362
+ const parent = realpathSync.native(dirname4(absolute));
1363
+ if (!lstatSync3(parent).isDirectory()) return null;
1364
+ target = resolve(parent, basename2(absolute));
1365
+ } catch {
1366
+ return null;
1367
+ }
1368
+ }
1369
+ const rel = relative(repositoryRoot, target);
1370
+ if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1371
+ return null;
1372
+ }
1373
+ return sep === "/" ? rel : rel.split(sep).join("/");
1374
+ }
1375
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1376
+ if (typeof contextOrCwd === "string") {
1377
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1378
+ }
1379
+ return canonicalRepositoryPathScoped(
1380
+ filePath,
1381
+ contextOrCwd,
1382
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1383
+ );
1384
+ }
1385
+
1386
+ // src/lib/terminal-safe.ts
1387
+ function replaceIsolatedSurrogates(value) {
1388
+ let out = "";
1389
+ for (let index = 0; index < value.length; index += 1) {
1390
+ const unit = value.charCodeAt(index);
1391
+ if (unit >= 55296 && unit <= 56319) {
1392
+ const next = value.charCodeAt(index + 1);
1393
+ if (next >= 56320 && next <= 57343) {
1394
+ out += value[index] + value[index + 1];
1395
+ index += 1;
1396
+ } else {
1397
+ out += "\uFFFD";
1398
+ }
1399
+ } else if (unit >= 56320 && unit <= 57343) {
1400
+ out += "\uFFFD";
1401
+ } else {
1402
+ out += value[index];
1403
+ }
1404
+ }
1405
+ return out;
1406
+ }
1407
+ function isUnsafeTerminalCodePoint(point) {
1408
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1409
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1410
+ point === 1564 || // Arabic letter mark
1411
+ point === 6158 || // Mongolian vowel separator
1412
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1413
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1414
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1415
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1416
+ point === 65279 || // zero-width no-break space / BOM
1417
+ point >= 917504 && point <= 917631;
1418
+ return c0OrC1 || bidiOrZeroWidth;
1419
+ }
1420
+ function terminalSafeText(value) {
1421
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1422
+ }
1423
+ function terminalSafeLine(value) {
1424
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1425
+ }
1426
+
1427
+ // src/lib/session-identity.ts
1428
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1429
+ var SESSION_IDENTITY_VALUE = "session";
1430
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1431
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1432
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1433
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1434
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1435
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1436
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1437
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1438
+ var SESSION_IDENTITY_ROUTES = {
1439
+ challenge: "/api/cli/session-identity/challenge",
1440
+ token: "/api/cli/session-identity/token",
1441
+ refresh: "/api/cli/session-identity/token/refresh",
1442
+ link: "/api/cli/session-identity/link"
1443
+ };
1444
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1445
+ var RENEW_BEFORE_MS = 6e4;
1446
+ var GIT_TIMEOUT_MS2 = 1e4;
1447
+ var POLL_BUDGET_MS = 15e3;
1448
+ var POLL_FIRST_DELAY_MS = 500;
1449
+ var POLL_MAX_DELAY_MS = 3e3;
1450
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1451
+ var LOCK_TIMEOUT_MS = 6e4;
1452
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1453
+ function sessionIdentityRequested(env = process.env) {
1454
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1455
+ }
1456
+ function sessionIdentityMode(deps = {}) {
1457
+ const env = deps.env ?? process.env;
1458
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1459
+ }
1460
+ function failure(code, cause, remedy) {
1461
+ return { status: "failed", code, cause, remedy };
1462
+ }
1463
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1464
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1465
+ 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';
1466
+ var SESSION_REVOKED = failure(
1467
+ "session_revoked",
1468
+ "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",
1469
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1470
+ );
1471
+ var CHALLENGE_WINDOW_PASSED = failure(
1472
+ "challenge_expired",
1473
+ "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)",
1474
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1475
+ );
1476
+ var CHALLENGE_GONE = failure(
1477
+ "challenge_not_found",
1478
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1479
+ NEW_SESSION_REMEDY
1480
+ );
1481
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1482
+ function rejectionFailure(reason, repository) {
1483
+ switch (reason) {
1484
+ case "identity_mismatch":
1485
+ return failure(
1486
+ "identity_mismatch",
1487
+ "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",
1488
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1489
+ );
1490
+ case "push_after_expiry":
1491
+ return failure(
1492
+ "push_after_expiry",
1493
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1494
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1495
+ );
1496
+ case "repository_mismatch":
1497
+ return failure(
1498
+ "repository_mismatch",
1499
+ `Primitive received the identity push from a different repository than ${repository}`,
1500
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1501
+ );
1502
+ case "conflicting_push":
1503
+ return failure(
1504
+ "conflicting_push",
1505
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1506
+ NEW_SESSION_REMEDY
1507
+ );
1508
+ case "unsupported_sender":
1509
+ return failure(
1510
+ "unsupported_sender",
1511
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1512
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1513
+ );
1514
+ default:
1515
+ return failure(
1516
+ "challenge_rejected",
1517
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1518
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1519
+ );
1520
+ }
1521
+ }
1522
+ function sessionIdentityMessage(outcome) {
1523
+ if (outcome.status === "link_required")
1524
+ 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.`;
1525
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1526
+ }
1527
+ function hash(value) {
1528
+ return createHash4("sha256").update(value).digest("hex");
1529
+ }
1530
+ function sessionContext(deps) {
1531
+ const env = deps.env ?? process.env;
1532
+ const environment = environmentCredentials(deps);
1533
+ if (!environment)
1534
+ return failure(
1535
+ "environment_credential_missing",
1536
+ "the cloud environment has no environment credential",
1537
+ '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'
1538
+ );
1539
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1540
+ if (!sessionId || !SESSION_ID.test(sessionId))
1541
+ return failure(
1542
+ "session_id_missing",
1543
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1544
+ NEW_SESSION_REMEDY
1545
+ );
1546
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1547
+ const directory = deps.directory ?? primConfigDirectory({ env });
1548
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1549
+ return {
1550
+ directory,
1551
+ apiUrl,
1552
+ clientId: environment.clientId,
1553
+ generation: environment.generation,
1554
+ sessionId,
1555
+ tokenPath: join7(directory, `session_identity_${key}.json`),
1556
+ statePath: join7(directory, `session_identity_${key}.state.json`),
1557
+ lockPath: join7(directory, "session-identity.lock")
1558
+ };
1559
+ }
1560
+ function readRecord(path) {
1561
+ try {
1562
+ const value = readMachineMetadata(path);
1563
+ return value === void 0 ? void 0 : machineRecord(value);
1564
+ } catch {
1565
+ return void 0;
1566
+ }
1567
+ }
1568
+ function finiteNumber(value) {
1569
+ return typeof value === "number" && Number.isFinite(value);
1570
+ }
1571
+ function readToken(context) {
1572
+ const data = readRecord(context.tokenPath);
1573
+ 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))
1574
+ return void 0;
1575
+ const identity = data.identity;
1576
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1577
+ return void 0;
1578
+ return data;
1579
+ }
1580
+ function readState(context) {
1581
+ const data = readRecord(context.statePath);
1582
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1583
+ return void 0;
1584
+ return data;
1585
+ }
1586
+ function writeToken(context, record) {
1587
+ prepareMachineMetadataDirectory(context.directory);
1588
+ writeMachineMetadata(context.tokenPath, record);
1589
+ rmSync5(context.statePath, { force: true });
1590
+ }
1591
+ function writeState(context, state) {
1592
+ try {
1593
+ prepareMachineMetadataDirectory(context.directory);
1594
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1595
+ } catch {
1596
+ }
1597
+ }
1598
+ function tokenValid(record, now = Date.now()) {
1599
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1600
+ }
1601
+ function tokenFresh(record, now = Date.now()) {
1602
+ return tokenValid(record, now) && now < record.refreshAfter;
1603
+ }
1604
+ function toCredential(record) {
1605
+ return {
1606
+ issuer: record.issuer,
1607
+ audience: record.audience,
1608
+ ...record.identity,
1609
+ accessToken: record.accessToken,
1610
+ expiresAt: record.expiresAt,
1611
+ apiUrl: record.apiUrl,
1612
+ generation: record.generation,
1613
+ storage: "environment",
1614
+ session: {
1615
+ userId: record.userId,
1616
+ displayName: record.displayName,
1617
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1618
+ refreshAfter: record.refreshAfter
1619
+ }
1620
+ };
1621
+ }
1622
+ function identified(record, reused) {
1623
+ return {
1624
+ status: "ok",
1625
+ credential: toCredential(record),
1626
+ displayName: record.displayName,
1627
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1628
+ reused
1629
+ };
1630
+ }
1631
+ function cachedSessionCredential(deps = {}) {
1632
+ if (!sessionIdentityMode(deps)) return void 0;
1633
+ let context;
1634
+ try {
1635
+ context = sessionContext(deps);
1636
+ } catch {
1637
+ return void 0;
1638
+ }
1639
+ if ("status" in context) return void 0;
1640
+ const record = readToken(context);
1641
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1642
+ }
1643
+ function outcomeFromState(state) {
1644
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1645
+ return {
1646
+ status: "link_required",
1647
+ githubLogin: state.githubLogin,
1648
+ challengeId: state.challengeId,
1649
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1650
+ };
1651
+ return failure(
1652
+ state.code,
1653
+ state.cause ?? "the last identity check failed",
1654
+ state.remedy ?? RETRY_REMEDY
1655
+ );
1656
+ }
1657
+ function parseInstant(value) {
1658
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1659
+ if (typeof value === "string" && value.length <= 64) {
1660
+ const parsed = Date.parse(value);
1661
+ return Number.isFinite(parsed) ? parsed : void 0;
1662
+ }
1663
+ return void 0;
1664
+ }
1665
+ async function sendJson(url, init, fetchImpl) {
1666
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1667
+ let value;
1668
+ try {
1669
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1670
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1671
+ } catch {
1672
+ value = void 0;
1673
+ }
1674
+ return { status: response.status, value };
1675
+ }
1676
+ function environmentOnly(deps) {
1677
+ return { ...deps, environmentOnly: true };
1678
+ }
1679
+ async function environmentRequest(method, path, body, deps, signal) {
1680
+ const send = async (credential2) => {
1681
+ const headers = { "Content-Type": "application/json" };
1682
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1683
+ if (credential2.tokenInjection) {
1684
+ const response = await forwardMachineRequest(
1685
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1686
+ signal,
1687
+ environmentOnly(deps)
1688
+ );
1689
+ const parsed = await response.json().catch(() => void 0);
1690
+ return {
1691
+ status: response.status,
1692
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1693
+ };
1694
+ }
1695
+ return sendJson(
1696
+ `${credential2.apiUrl}${path}`,
1697
+ {
1698
+ method,
1699
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1700
+ ...text === void 0 ? {} : { body: text },
1701
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1702
+ },
1703
+ deps.fetch ?? fetch
1704
+ );
1705
+ };
1706
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1707
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1708
+ let answer = await send(credential);
1709
+ if (answer.status === 401) {
1710
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1711
+ if (!credential)
1712
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1713
+ answer = await send(credential);
1714
+ }
1715
+ return answer;
1716
+ }
1717
+ function environmentFailure(error, apiUrl) {
1718
+ if (error instanceof MachineAuthError && error.terminal)
1719
+ return failure(
1720
+ "environment_credential_rejected",
1721
+ "Primitive rejected the cloud environment's credential",
1722
+ ENVIRONMENT_CREDENTIAL_REMEDY
1723
+ );
1724
+ const host = (() => {
1725
+ try {
1726
+ return new URL(apiUrl).hostname;
1727
+ } catch {
1728
+ return "Primitive";
1729
+ }
1730
+ })();
1731
+ return failure(
1732
+ "identity_unavailable",
1733
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1734
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1735
+ );
1736
+ }
1737
+ function answerError(answer) {
1738
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1739
+ }
1740
+ async function git(root, args, signal) {
1741
+ try {
1742
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1743
+ cwd: root,
1744
+ encoding: "utf8",
1745
+ timeout: GIT_TIMEOUT_MS2,
1746
+ signal,
1747
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1748
+ maxBuffer: 1024 * 1024
1749
+ });
1750
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1751
+ } catch (error) {
1752
+ const failed = error;
1753
+ return {
1754
+ ok: false,
1755
+ code: typeof failed.code === "number" ? failed.code : void 0,
1756
+ stdout: failed.stdout ?? "",
1757
+ stderr: failed.stderr ?? "",
1758
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1759
+ };
1760
+ }
1761
+ }
1762
+ function gitDetail(stderr) {
1763
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1764
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1765
+ }
1766
+ async function defaultSleep2(milliseconds, signal) {
1767
+ await new Promise((resolve3, reject) => {
1768
+ const timer = setTimeout(resolve3, milliseconds);
1769
+ signal?.addEventListener(
1770
+ "abort",
1771
+ () => {
1772
+ clearTimeout(timer);
1773
+ reject(signal.reason);
1774
+ },
1775
+ { once: true }
1776
+ );
1777
+ });
1778
+ }
1779
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1780
+ const sleep = deps.sleep ?? defaultSleep2;
1781
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1782
+ let delay = POLL_FIRST_DELAY_MS;
1783
+ let unreachable;
1784
+ for (; ; ) {
1785
+ const remaining = deadline - Date.now();
1786
+ if (remaining <= 0) break;
1787
+ await sleep(Math.min(delay, remaining), signal);
1788
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1789
+ let answer;
1790
+ try {
1791
+ answer = await environmentRequest(
1792
+ "GET",
1793
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1794
+ void 0,
1795
+ deps,
1796
+ signal
1797
+ );
1798
+ } catch (error) {
1799
+ signal?.throwIfAborted();
1800
+ unreachable = error;
1801
+ continue;
1802
+ }
1803
+ if (answer.status === 404) return CHALLENGE_GONE;
1804
+ if (answer.status === 401 || answer.status === 403)
1805
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1806
+ if (answer.status < 200 || answer.status > 299) {
1807
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1808
+ continue;
1809
+ }
1810
+ unreachable = void 0;
1811
+ const status = answer.value;
1812
+ if (status?.status === "verified")
1813
+ return {
1814
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1815
+ };
1816
+ if (status?.status === "expired")
1817
+ return failure(
1818
+ "challenge_expired",
1819
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1820
+ NEW_SESSION_REMEDY
1821
+ );
1822
+ if (status?.status === "rejected")
1823
+ return rejectionFailure(status.reason, repository);
1824
+ }
1825
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1826
+ return failure(
1827
+ "webhook_timeout",
1828
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1829
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1830
+ );
1831
+ }
1832
+ function parseTokenAnswer(value) {
1833
+ if (!value) return void 0;
1834
+ const user = value.user;
1835
+ const expiresAt = parseInstant(value.expiresAt);
1836
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1837
+ 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))
1838
+ return void 0;
1839
+ return {
1840
+ accessToken: value.accessToken,
1841
+ expiresAt,
1842
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1843
+ userId: user.id,
1844
+ displayName: user.displayName,
1845
+ organizationId: value.organizationId
1846
+ };
1847
+ }
1848
+ var SERVER_CONTRACT_FAILURE = failure(
1849
+ "server_contract",
1850
+ "Primitive's answer did not identify the linked member",
1851
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1852
+ );
1853
+ async function recordFor(context, answer, extra, deps, signal) {
1854
+ let identity;
1855
+ let environment;
1856
+ try {
1857
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1858
+ identity = await verifyMachineIdentity(
1859
+ context.apiUrl,
1860
+ answer.accessToken,
1861
+ context.clientId,
1862
+ signal,
1863
+ deps.fetch
1864
+ );
1865
+ } catch (error) {
1866
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1867
+ return SERVER_CONTRACT_FAILURE;
1868
+ return environmentFailure(error, context.apiUrl);
1869
+ }
1870
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1871
+ return SERVER_CONTRACT_FAILURE;
1872
+ return {
1873
+ version: 1,
1874
+ apiUrl: context.apiUrl,
1875
+ clientId: context.clientId,
1876
+ generation: context.generation,
1877
+ sessionId: context.sessionId,
1878
+ issuer: environment.issuer,
1879
+ audience: environment.audience,
1880
+ accessToken: answer.accessToken,
1881
+ expiresAt: answer.expiresAt,
1882
+ refreshAfter: answer.refreshAfter,
1883
+ userId: answer.userId,
1884
+ displayName: answer.displayName,
1885
+ organizationId: answer.organizationId,
1886
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1887
+ identity,
1888
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1889
+ };
1890
+ }
1891
+ async function refreshToken(context, record, deps, signal) {
1892
+ let answer;
1893
+ try {
1894
+ answer = await environmentRequest(
1895
+ "POST",
1896
+ SESSION_IDENTITY_ROUTES.refresh,
1897
+ { accessToken: record.accessToken },
1898
+ deps,
1899
+ signal
1900
+ );
1901
+ } catch (error) {
1902
+ signal?.throwIfAborted();
1903
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
1904
+ }
1905
+ const code = answerError(answer);
1906
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
1907
+ return { status: "refused", failure: SESSION_REVOKED };
1908
+ if (answer.status === 401 || answer.status === 403)
1909
+ return {
1910
+ status: "refused",
1911
+ failure: environmentFailure(
1912
+ new MachineAuthError("rejected", "rejected", true),
1913
+ context.apiUrl
1914
+ )
1915
+ };
1916
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1917
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
1918
+ return { status: "unavailable" };
1919
+ return {
1920
+ status: "ok",
1921
+ record: {
1922
+ ...record,
1923
+ accessToken: token.accessToken,
1924
+ expiresAt: token.expiresAt,
1925
+ refreshAfter: token.refreshAfter,
1926
+ displayName: token.displayName
1927
+ }
1928
+ };
1929
+ }
1930
+ function exchangeRefusal(answer, repository) {
1931
+ if (answer.status === 404) return CHALLENGE_GONE;
1932
+ if (answer.status !== 409) return void 0;
1933
+ switch (answerError(answer)) {
1934
+ case "identity_mismatch":
1935
+ return rejectionFailure("identity_mismatch", repository);
1936
+ case "challenge_rejected":
1937
+ return rejectionFailure(answer.value?.reason, repository);
1938
+ case "challenge_expired":
1939
+ return CHALLENGE_WINDOW_PASSED;
1940
+ case "challenge_already_exchanged":
1941
+ return failure(
1942
+ "challenge_already_exchanged",
1943
+ "this session's identity check was already exchanged for a token this VM does not hold",
1944
+ NEW_SESSION_REMEDY
1945
+ );
1946
+ case "challenge_pending":
1947
+ return failure(
1948
+ "webhook_timeout",
1949
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
1950
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1951
+ );
1952
+ default:
1953
+ return void 0;
1954
+ }
1955
+ }
1956
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
1957
+ let answer;
1958
+ try {
1959
+ answer = await environmentRequest(
1960
+ "POST",
1961
+ SESSION_IDENTITY_ROUTES.token,
1962
+ { challengeId: challenge.challengeId },
1963
+ deps,
1964
+ signal
1965
+ );
1966
+ } catch (error) {
1967
+ signal?.throwIfAborted();
1968
+ return environmentFailure(error, context.apiUrl);
1969
+ }
1970
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
1971
+ const login = answer.value?.githubLogin;
1972
+ return {
1973
+ status: "link_required",
1974
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
1975
+ challengeId: challenge.challengeId,
1976
+ challengeExpiresAt: challenge.challengeExpiresAt
1977
+ };
1978
+ }
1979
+ const refused = exchangeRefusal(
1980
+ answer,
1981
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
1982
+ );
1983
+ if (refused) return refused;
1984
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1985
+ if (!token) {
1986
+ if (answer.status === 401 || answer.status === 403)
1987
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1988
+ return answer.status >= 500 ? environmentFailure(
1989
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1990
+ context.apiUrl
1991
+ ) : SERVER_CONTRACT_FAILURE;
1992
+ }
1993
+ return recordFor(
1994
+ context,
1995
+ token,
1996
+ { githubLogin: challenge.githubLogin, repositoryRoot },
1997
+ deps,
1998
+ signal
1999
+ );
2000
+ }
2001
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
2002
+ const env = deps.env ?? process.env;
2003
+ const repository = githubRepositoryFullName(root);
2004
+ if (!repository)
2005
+ return failure(
2006
+ "repository_unidentified",
2007
+ "this checkout does not name its GitHub repository",
2008
+ "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"
2009
+ );
2010
+ const branch = currentBranch(root);
2011
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
2012
+ return failure(
2013
+ "not_session_branch",
2014
+ `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`,
2015
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
2016
+ );
2017
+ attempt.branch = branch;
2018
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
2019
+ if (!baseSha) {
2020
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
2021
+ baseSha = head.stdout.trim();
2022
+ if (!head.ok || !SHA.test(baseSha))
2023
+ return failure(
2024
+ "no_commit",
2025
+ "this checkout has no commit to create the session branch at",
2026
+ NEW_SESSION_REMEDY
2027
+ );
2028
+ }
2029
+ const published = await git(
2030
+ root,
2031
+ [
2032
+ "for-each-ref",
2033
+ "--count=1",
2034
+ "--format=%(refname)",
2035
+ "--contains",
2036
+ baseSha,
2037
+ "refs/remotes/origin/"
2038
+ ],
2039
+ signal
2040
+ );
2041
+ if (!published.ok || published.stdout.trim() === "")
2042
+ return failure(
2043
+ "unpublished_commits",
2044
+ `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`,
2045
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
2046
+ );
2047
+ attempt.baseSha = baseSha;
2048
+ const remote = await git(
2049
+ root,
2050
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2051
+ signal
2052
+ );
2053
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2054
+ if (remote.ok && recorded) {
2055
+ Object.assign(attempt, recorded);
2056
+ return { ...recorded, repository };
2057
+ }
2058
+ if (remote.ok)
2059
+ return failure(
2060
+ "branch_exists",
2061
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2062
+ NEW_SESSION_REMEDY
2063
+ );
2064
+ if (remote.code !== 2)
2065
+ return failure(
2066
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2067
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2068
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2069
+ );
2070
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2071
+ Object.assign(attempt, recorded);
2072
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2073
+ }
2074
+ let answer;
2075
+ try {
2076
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2077
+ answer = await environmentRequest(
2078
+ "POST",
2079
+ SESSION_IDENTITY_ROUTES.challenge,
2080
+ {
2081
+ repositoryFullName: repository,
2082
+ claudeSessionId: context.sessionId,
2083
+ branch,
2084
+ baseSha,
2085
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2086
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2087
+ },
2088
+ deps,
2089
+ signal
2090
+ );
2091
+ } catch (error) {
2092
+ signal?.throwIfAborted();
2093
+ return environmentFailure(error, context.apiUrl);
2094
+ }
2095
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2096
+ return failure(
2097
+ "repository_not_connected",
2098
+ `${repository} is not connected to Primitive`,
2099
+ CLOUD_GITHUB_CONNECT_REMEDY
2100
+ );
2101
+ if (answer.status === 401 || answer.status === 403)
2102
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2103
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2104
+ return failure(
2105
+ "challenge_open",
2106
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2107
+ `wait five minutes, then ${RETRY_REMEDY}`
2108
+ );
2109
+ if (answer.status === 429)
2110
+ return failure(
2111
+ "too_many_challenges",
2112
+ "too many sessions of this cloud environment are being identified at once",
2113
+ `wait a few minutes, then ${RETRY_REMEDY}`
2114
+ );
2115
+ const challengeId = answer.value?.challengeId;
2116
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2117
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2118
+ return answer.status >= 500 ? environmentFailure(
2119
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2120
+ context.apiUrl
2121
+ ) : SERVER_CONTRACT_FAILURE;
2122
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2123
+ attempt.challengeId = challengeId;
2124
+ attempt.challengeExpiresAt = challengeExpiresAt;
2125
+ return pushSessionBranch(
2126
+ root,
2127
+ repository,
2128
+ branch,
2129
+ baseSha,
2130
+ { challengeId, challengeExpiresAt },
2131
+ signal
2132
+ );
2133
+ }
2134
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2135
+ const push = await git(
2136
+ root,
2137
+ [
2138
+ "-c",
2139
+ "core.hooksPath=/dev/null",
2140
+ "-c",
2141
+ "push.followTags=false",
2142
+ "-c",
2143
+ "push.recurseSubmodules=no",
2144
+ "-c",
2145
+ "push.gpgSign=false",
2146
+ "-c",
2147
+ "push.pushOption=",
2148
+ "push",
2149
+ "--no-verify",
2150
+ "--no-follow-tags",
2151
+ "--no-recurse-submodules",
2152
+ "--no-signed",
2153
+ "--quiet",
2154
+ "origin",
2155
+ `${baseSha}:refs/heads/${branch}`
2156
+ ],
2157
+ signal
2158
+ );
2159
+ if (!push.ok)
2160
+ return push.timedOut ? failure(
2161
+ "push_timeout",
2162
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2163
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2164
+ ) : failure(
2165
+ "push_refused",
2166
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2167
+ `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}`
2168
+ );
2169
+ return { ...challenge, repository };
2170
+ }
2171
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2172
+ let context;
2173
+ try {
2174
+ context = sessionContext(deps);
2175
+ } catch (error) {
2176
+ return failure(
2177
+ "environment_credential_invalid",
2178
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2179
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2180
+ );
2181
+ }
2182
+ if ("status" in context) return context;
2183
+ const ctx = context;
2184
+ const startedAt = Date.now();
2185
+ prepareMachineMetadataDirectory(ctx.directory);
2186
+ return withFileLock(
2187
+ ctx.lockPath,
2188
+ async () => {
2189
+ const record = readToken(ctx);
2190
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2191
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2192
+ if (record) {
2193
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2194
+ if (refreshed.status === "ok") {
2195
+ writeToken(ctx, refreshed.record);
2196
+ return identified(refreshed.record, true);
2197
+ }
2198
+ if (refreshed.status === "refused") {
2199
+ rmSync5(ctx.tokenPath, { force: true });
2200
+ writeState(ctx, {
2201
+ sessionId: ctx.sessionId,
2202
+ status: "failed",
2203
+ code: refreshed.failure.code,
2204
+ cause: refreshed.failure.cause,
2205
+ remedy: refreshed.failure.remedy,
2206
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2207
+ at: Date.now()
2208
+ });
2209
+ return refreshed.failure;
2210
+ }
2211
+ if (!forced && tokenValid(record)) return identified(record, true);
2212
+ }
2213
+ const state = readState(ctx);
2214
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2215
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2216
+ if (!options.explicit) {
2217
+ if (!root || !(record || state))
2218
+ return failure(
2219
+ "not_identified",
2220
+ "this session has not identified who started it yet",
2221
+ RETRY_REMEDY
2222
+ );
2223
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2224
+ } else if (state && state.at >= startedAt) {
2225
+ return outcomeFromState(state);
2226
+ }
2227
+ if (!root)
2228
+ return failure(
2229
+ "repository_missing",
2230
+ "this is not a git repository",
2231
+ "run it in the repository the session cloned"
2232
+ );
2233
+ const attempt = { root };
2234
+ const remember = (outcome) => {
2235
+ writeState(ctx, {
2236
+ sessionId: ctx.sessionId,
2237
+ status: outcome.status,
2238
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2239
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2240
+ githubLogin: outcome.githubLogin
2241
+ },
2242
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2243
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2244
+ repositoryRoot: root,
2245
+ branch: attempt.branch ?? state?.branch,
2246
+ baseSha: attempt.baseSha ?? state?.baseSha,
2247
+ at: Date.now()
2248
+ });
2249
+ return outcome;
2250
+ };
2251
+ let challenge;
2252
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2253
+ attempt.challengeId = state.challengeId;
2254
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2255
+ attempt.branch = state.branch;
2256
+ attempt.baseSha = state.baseSha;
2257
+ challenge = {
2258
+ challengeId: state.challengeId,
2259
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2260
+ repository: githubRepositoryFullName(root) ?? "the repository"
2261
+ };
2262
+ } else if (state?.status === "link_required" && state.challengeId) {
2263
+ attempt.challengeId = state.challengeId;
2264
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2265
+ const exchanged2 = await exchangeChallenge(
2266
+ ctx,
2267
+ {
2268
+ challengeId: state.challengeId,
2269
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2270
+ githubLogin: state.githubLogin
2271
+ },
2272
+ root,
2273
+ deps,
2274
+ options.signal
2275
+ );
2276
+ if ("status" in exchanged2) return remember(exchanged2);
2277
+ writeToken(ctx, exchanged2);
2278
+ return identified(exchanged2, false);
2279
+ } else if (!options.explicit) {
2280
+ return state ? outcomeFromState(state) : failure(
2281
+ "not_identified",
2282
+ "this session has not identified who started it yet",
2283
+ RETRY_REMEDY
2284
+ );
2285
+ } else {
2286
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2287
+ if ("status" in pushed) return remember(pushed);
2288
+ challenge = pushed;
2289
+ }
2290
+ const verified = await pollChallenge(
2291
+ ctx.apiUrl,
2292
+ challenge.challengeId,
2293
+ challenge.repository,
2294
+ // A hook process waits only briefly for a late notice.
2295
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2296
+ options.signal
2297
+ );
2298
+ if ("status" in verified) return remember(verified);
2299
+ const exchanged = await exchangeChallenge(
2300
+ ctx,
2301
+ { ...challenge, githubLogin: verified.githubLogin },
2302
+ root,
2303
+ deps,
2304
+ options.signal
2305
+ );
2306
+ if ("status" in exchanged) return remember(exchanged);
2307
+ writeToken(ctx, exchanged);
2308
+ return identified(exchanged, false);
2309
+ },
2310
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2311
+ );
2312
+ }
2313
+ async function acquireSessionCredential(options = {}, deps = {}) {
2314
+ const cached2 = cachedSessionCredential(deps);
2315
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2316
+ if (cached2 && fresh && !options.force) return cached2;
2317
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2318
+ let outcome;
2319
+ try {
2320
+ outcome = await ensureSessionIdentity(
2321
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2322
+ deps
2323
+ );
2324
+ } catch (error) {
2325
+ options.signal?.throwIfAborted();
2326
+ if (error instanceof MachineAuthError) throw error;
2327
+ throw new MachineAuthError(
2328
+ "identity_unavailable",
2329
+ "Identifying who started this cloud session is still in progress; retry shortly."
2330
+ );
2331
+ }
2332
+ if (outcome.status === "ok") return outcome.credential;
2333
+ throw new MachineAuthError(
2334
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2335
+ sessionIdentityMessage(outcome)
2336
+ );
2337
+ }
2338
+
960
2339
  // src/lib/machine-credentials.ts
2340
+ function sessionScoped(deps) {
2341
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2342
+ }
961
2343
  var require2 = createRequire(import.meta.url);
962
2344
  var SERVICE = "ai.primitive.prim.machine";
963
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2345
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
964
2346
  var PROFILE_FILE = "machine_profile.json";
965
- var RENEW_BEFORE_MS = 6e4;
2347
+ var RENEW_BEFORE_MS2 = 6e4;
966
2348
  var cached;
967
2349
  function configurationDirectory(deps) {
968
2350
  return deps.directory ?? primConfigDirectory({ env: deps.env });
969
2351
  }
970
2352
  function apiUrlFor(deps) {
971
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2353
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
972
2354
  }
973
- function hash(value) {
974
- return createHash3("sha256").update(value).digest("hex");
2355
+ function hash2(value) {
2356
+ return createHash5("sha256").update(value).digest("hex");
975
2357
  }
976
2358
  function recordPath(directory, generation) {
977
- return join6(directory, `machine_${generation}.json`);
2359
+ return join8(directory, `machine_${generation}.json`);
978
2360
  }
979
2361
  function storageKey(directory, generation) {
980
- return `${hash(directory)}:${generation}`;
2362
+ return `${hash2(directory)}:${generation}`;
981
2363
  }
982
2364
  function environmentContextPath(deps, clientId) {
983
- return join6(
2365
+ return join8(
984
2366
  configurationDirectory(deps),
985
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2367
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
986
2368
  );
987
2369
  }
988
2370
  function writeEnvironmentContext(credential, deps) {
@@ -1041,14 +2423,14 @@ function readEnvironmentContext(environment, deps) {
1041
2423
  }
1042
2424
  }
1043
2425
  function keyringEntry(key) {
1044
- let directory = dirname4(fileURLToPath3(import.meta.url));
2426
+ let directory = dirname5(fileURLToPath3(import.meta.url));
1045
2427
  for (let depth = 0; depth < 5; depth++) {
1046
- const loader = join6(directory, "native", "keyring.cjs");
2428
+ const loader = join8(directory, "native", "keyring.cjs");
1047
2429
  if (existsSync3(loader)) {
1048
2430
  const module2 = require2(loader);
1049
2431
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1050
2432
  }
1051
- directory = dirname4(directory);
2433
+ directory = dirname5(directory);
1052
2434
  }
1053
2435
  const module = require2("@napi-rs/keyring");
1054
2436
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -1060,7 +2442,7 @@ function protectPath(path, directory) {
1060
2442
  }
1061
2443
  const encodedPath = Buffer.from(path).toString("base64");
1062
2444
  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)`;
1063
- execFileSync(
2445
+ execFileSync2(
1064
2446
  "powershell.exe",
1065
2447
  [
1066
2448
  "-NoProfile",
@@ -1073,7 +2455,7 @@ function protectPath(path, directory) {
1073
2455
  }
1074
2456
  function ensureDirectory(directory) {
1075
2457
  mkdirSync3(directory, { recursive: true, mode: 448 });
1076
- if (lstatSync3(directory).isSymbolicLink())
2458
+ if (lstatSync4(directory).isSymbolicLink())
1077
2459
  throw new MachineAuthError(
1078
2460
  "unsafe_storage",
1079
2461
  "Credential directory must not be a symbolic link."
@@ -1085,17 +2467,20 @@ function writePrivate(path, value) {
1085
2467
  `, { mode: 384 });
1086
2468
  protectPath(path, false);
1087
2469
  }
2470
+ function readMachineMetadata(path) {
2471
+ return readPrivate(path);
2472
+ }
1088
2473
  function readPrivate(path) {
1089
2474
  let raw;
1090
2475
  try {
1091
- const stat = lstatSync3(path);
2476
+ const stat = lstatSync4(path);
1092
2477
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1093
2478
  throw new MachineAuthError(
1094
2479
  "unsafe_storage",
1095
2480
  "Machine credential files must be owner-only regular files."
1096
2481
  );
1097
2482
  }
1098
- raw = readFileSync5(path, "utf8");
2483
+ raw = readFileSync6(path, "utf8");
1099
2484
  } catch (error) {
1100
2485
  if (error.code === "ENOENT") return void 0;
1101
2486
  throw error;
@@ -1140,13 +2525,101 @@ function parseProfile(value) {
1140
2525
  };
1141
2526
  }
1142
2527
  function readMachineProfile(deps = {}) {
1143
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
2528
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
1144
2529
  return value === void 0 ? void 0 : parseProfile(value);
1145
2530
  }
2531
+ var NETWORK_SECRET_AUTH = "network-secret";
2532
+ var NETWORK_TOKEN_AUTH = "network-token";
2533
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2534
+ var brokerKeys = /* @__PURE__ */ new Map();
2535
+ function networkSecretBrokerKey(deps, clientId) {
2536
+ const directory = configurationDirectory(deps);
2537
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2538
+ const known = brokerKeys.get(path);
2539
+ if (known) return known;
2540
+ ensureDirectory(directory);
2541
+ const read = () => {
2542
+ try {
2543
+ const stat = lstatSync4(path);
2544
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2545
+ throw new MachineAuthError(
2546
+ "unsafe_storage",
2547
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2548
+ true
2549
+ );
2550
+ const value = readFileSync6(path, "utf8").trim();
2551
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2552
+ } catch (error) {
2553
+ if (error.code === "ENOENT") return void 0;
2554
+ throw error;
2555
+ }
2556
+ };
2557
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2558
+ const existing = read();
2559
+ if (existing?.key) {
2560
+ brokerKeys.set(path, existing.key);
2561
+ return existing.key;
2562
+ }
2563
+ if (existing)
2564
+ throw new MachineAuthError(
2565
+ "unsafe_storage",
2566
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2567
+ true
2568
+ );
2569
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
2570
+ try {
2571
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
2572
+ `, { mode: 384, flag: "wx" });
2573
+ protectPath(staged, false);
2574
+ linkSync(staged, path);
2575
+ } catch (error) {
2576
+ if (error.code !== "EEXIST") throw error;
2577
+ } finally {
2578
+ rmSync6(staged, { force: true });
2579
+ }
2580
+ }
2581
+ const key = read()?.key;
2582
+ if (!key)
2583
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2584
+ brokerKeys.set(path, key);
2585
+ return key;
2586
+ }
1146
2587
  function environmentCredentials(deps) {
1147
2588
  const env = deps.env ?? process.env;
1148
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
1149
- if (clientId === void 0 && clientSecret === void 0) return void 0;
2589
+ const {
2590
+ PRIM_M2M_CLIENT_ID: clientId,
2591
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2592
+ PRIM_M2M_CLIENT_AUTH: auth
2593
+ } = env;
2594
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2595
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2596
+ throw new MachineAuthError(
2597
+ "incomplete_machine_credentials",
2598
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2599
+ );
2600
+ if (auth !== void 0) {
2601
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2602
+ throw new MachineAuthError(
2603
+ "incomplete_machine_credentials",
2604
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2605
+ );
2606
+ if (clientSecret !== void 0)
2607
+ throw new MachineAuthError(
2608
+ "conflicting_credentials",
2609
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2610
+ );
2611
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2612
+ const credentials = {
2613
+ clientId,
2614
+ generation,
2615
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2616
+ };
2617
+ Object.defineProperty(credentials, "clientSecret", {
2618
+ enumerable: true,
2619
+ get: () => networkSecretBrokerKey(deps, clientId)
2620
+ });
2621
+ return credentials;
2622
+ }
1150
2623
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1151
2624
  throw new MachineAuthError(
1152
2625
  "incomplete_machine_credentials",
@@ -1156,12 +2629,12 @@ function environmentCredentials(deps) {
1156
2629
  return {
1157
2630
  clientId,
1158
2631
  clientSecret,
1159
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2632
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1160
2633
  };
1161
2634
  }
1162
2635
  function hasMachineConfiguration(deps = {}) {
1163
2636
  const env = deps.env ?? process.env;
1164
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
2637
+ 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));
1165
2638
  if (configured && env.PRIM_TOKEN?.trim()) {
1166
2639
  throw new MachineAuthError(
1167
2640
  "conflicting_credentials",
@@ -1173,6 +2646,7 @@ function hasMachineConfiguration(deps = {}) {
1173
2646
  }
1174
2647
  function machineContext(deps = {}) {
1175
2648
  if (!hasMachineConfiguration(deps)) return void 0;
2649
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1176
2650
  const environment = environmentCredentials(deps);
1177
2651
  if (environment) {
1178
2652
  if (environmentTerminal === environment.generation) return void 0;
@@ -1187,6 +2661,7 @@ function machineContext(deps = {}) {
1187
2661
  return profile;
1188
2662
  }
1189
2663
  function cachedMachineCredential(deps = {}) {
2664
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1190
2665
  const context = machineContext(deps);
1191
2666
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1192
2667
  }
@@ -1195,9 +2670,11 @@ function machineSessionEnded(deps = {}) {
1195
2670
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1196
2671
  if (!generation) return false;
1197
2672
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1198
- return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
2673
+ return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
1199
2674
  }
1200
2675
  var environmentTerminal;
2676
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2677
+ var networkRejection;
1201
2678
  async function loadRecord(profile, deps, signal) {
1202
2679
  const directory = configurationDirectory(deps);
1203
2680
  let value;
@@ -1257,10 +2734,12 @@ async function persistRecord(record, deps, signal) {
1257
2734
  }
1258
2735
  async function acquireMachineCredential(options = {}, deps = {}) {
1259
2736
  if (!hasMachineConfiguration(deps)) return void 0;
2737
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1260
2738
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1261
2739
  const apiUrl = apiUrlFor(deps);
1262
2740
  const environment = environmentCredentials(deps);
1263
2741
  if (environment) {
2742
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
1264
2743
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
1265
2744
  const directory2 = configurationDirectory(deps);
1266
2745
  ensureDirectory(directory2);
@@ -1278,22 +2757,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1278
2757
  writeEnvironmentContext(cached, deps);
1279
2758
  return cached;
1280
2759
  } catch (error) {
1281
- if (error instanceof MachineAuthError && error.terminal)
2760
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
1282
2761
  environmentTerminal = environment.generation;
1283
2762
  throw error;
1284
2763
  }
1285
2764
  }
1286
2765
  return withFileLock(
1287
- join6(directory2, "credentials.lock"),
2766
+ join8(directory2, "credentials.lock"),
1288
2767
  async () => {
1289
2768
  if (machineSessionEnded(deps))
1290
2769
  throw new MachineAuthError(
1291
2770
  "machine_credentials_rejected",
1292
- "Rotate the injected machine credentials.",
2771
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1293
2772
  true
1294
2773
  );
1295
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2774
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1296
2775
  return cached;
2776
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2777
+ throw networkRejection.error;
1297
2778
  try {
1298
2779
  const { configuration, tokens, identity } = await withMachineCooldown(
1299
2780
  directory2,
@@ -1302,13 +2783,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1302
2783
  signal,
1303
2784
  async () => {
1304
2785
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2786
+ if (environment.tokenInjection) {
2787
+ const identity3 = await verifyInjectedMachineIdentity(
2788
+ apiUrl,
2789
+ environment.clientId,
2790
+ signal,
2791
+ deps.fetch
2792
+ );
2793
+ const tokens3 = {
2794
+ accessToken: "",
2795
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2796
+ };
2797
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2798
+ }
1305
2799
  const tokens2 = await exchangeMachineCredentials(
1306
2800
  configuration2,
1307
2801
  environment.clientId,
1308
- environment.clientSecret,
2802
+ // The broker key is not a client secret; the proxy supplies that.
2803
+ environment.secretInjection ? "" : environment.clientSecret,
1309
2804
  signal,
1310
- deps.fetch
1311
- );
2805
+ deps.fetch,
2806
+ { secretInjection: environment.secretInjection }
2807
+ ).catch((error) => {
2808
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2809
+ throw new MachineAuthError(
2810
+ "network_secret_mismatch",
2811
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2812
+ true
2813
+ );
2814
+ throw error;
2815
+ });
1312
2816
  const identity2 = await verifyMachineIdentity(
1313
2817
  apiUrl,
1314
2818
  tokens2.accessToken,
@@ -1325,17 +2829,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1325
2829
  ...identity,
1326
2830
  apiUrl,
1327
2831
  generation: environment.generation,
1328
- storage: "environment"
2832
+ storage: "environment",
2833
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
1329
2834
  };
1330
2835
  writeEnvironmentContext(cached, deps);
1331
2836
  return cached;
1332
2837
  } catch (error) {
2838
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2839
+ networkRejection = {
2840
+ generation: environment.generation,
2841
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2842
+ error
2843
+ };
2844
+ if (cached?.generation === environment.generation) cached = void 0;
2845
+ const contextPath = environmentContextPath(deps, environment.clientId);
2846
+ try {
2847
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2848
+ rmSync6(contextPath, { force: true });
2849
+ } catch {
2850
+ }
2851
+ throw error;
2852
+ }
1333
2853
  if (error instanceof MachineAuthError && error.terminal) {
1334
2854
  environmentTerminal = environment.generation;
1335
2855
  const contextPath = environmentContextPath(deps, environment.clientId);
1336
2856
  try {
1337
2857
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1338
- rmSync5(contextPath, { force: true });
2858
+ rmSync6(contextPath, { force: true });
1339
2859
  } catch {
1340
2860
  }
1341
2861
  }
@@ -1349,7 +2869,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1349
2869
  const expected = machineContext(deps);
1350
2870
  const directory = configurationDirectory(deps);
1351
2871
  return withFileLock(
1352
- join6(directory, "credentials.lock"),
2872
+ join8(directory, "credentials.lock"),
1353
2873
  async () => {
1354
2874
  const profile = readMachineProfile(deps);
1355
2875
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1364,7 +2884,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1364
2884
  true
1365
2885
  );
1366
2886
  let record = await loadRecord(profile, deps, signal);
1367
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2887
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1368
2888
  try {
1369
2889
  const { tokens, identity } = await withMachineCooldown(
1370
2890
  directory,
@@ -1399,7 +2919,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1399
2919
  await persistRecord(record, deps, signal);
1400
2920
  } catch (error) {
1401
2921
  if (error instanceof MachineAuthError && error.terminal)
1402
- writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
2922
+ writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
1403
2923
  throw error;
1404
2924
  }
1405
2925
  }
@@ -1410,23 +2930,47 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1410
2930
  { signal }
1411
2931
  );
1412
2932
  }
2933
+ async function forwardMachineRequest(request3, signal, deps = {}) {
2934
+ const environment = environmentCredentials(deps);
2935
+ if (!environment?.tokenInjection)
2936
+ throw new MachineAuthError(
2937
+ "identity_changed",
2938
+ "Machine identity changed; restart the operation."
2939
+ );
2940
+ const directory = configurationDirectory(deps);
2941
+ ensureDirectory(directory);
2942
+ return forwardBrokerRequest({
2943
+ directory,
2944
+ apiUrl: apiUrlFor(deps),
2945
+ environment,
2946
+ env: deps.env ?? process.env,
2947
+ request: request3,
2948
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2949
+ });
2950
+ }
2951
+ function prepareMachineMetadataDirectory(directory) {
2952
+ ensureDirectory(directory);
2953
+ }
2954
+ function writeMachineMetadata(path, value) {
2955
+ writePrivate(path, value);
2956
+ }
1413
2957
 
1414
2958
  // src/lib/credentials.ts
1415
2959
  var CONFIG_DIRECTORY = primConfigDirectory();
1416
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1417
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1418
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1419
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1420
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1421
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1422
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1423
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
2960
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
2961
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
2962
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
2963
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
2964
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
2965
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
2966
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
2967
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1424
2968
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1425
2969
  var CREDENTIAL_MIGRATION_VERSION = 1;
1426
2970
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1427
2971
  function readTrimmed(path) {
1428
2972
  try {
1429
- const value = readFileSync6(path, "utf8").trim();
2973
+ const value = readFileSync7(path, "utf8").trim();
1430
2974
  return value || void 0;
1431
2975
  } catch {
1432
2976
  return void 0;
@@ -1435,7 +2979,7 @@ function readTrimmed(path) {
1435
2979
  function resolveAuthCredential(options = {}) {
1436
2980
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
1437
2981
  const machine = cachedMachineCredential({ env: options.env });
1438
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
2982
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
1439
2983
  }
1440
2984
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
1441
2985
  if (envToken) return { token: envToken, source: "environment" };
@@ -1448,22 +2992,22 @@ function resolveAuthCredential(options = {}) {
1448
2992
  );
1449
2993
  if (metadata.state === "legacy_broker") {
1450
2994
  if (metadata.metadata) {
1451
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1452
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
2995
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2996
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1453
2997
  return void 0;
1454
2998
  }
1455
2999
  }
1456
3000
  return { token: stored, source: "token_file" };
1457
3001
  }
1458
3002
  if (metadata.state === "invalid") return void 0;
1459
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1460
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3003
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3004
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1461
3005
  return void 0;
1462
3006
  }
1463
3007
  return { token: stored, source: "token_file" };
1464
3008
  }
1465
3009
  function credentialFingerprint(value) {
1466
- return createHash4("sha256").update(value).digest("hex");
3010
+ return createHash6("sha256").update(value).digest("hex");
1467
3011
  }
1468
3012
  function parseLegacyBrokerCredentialMetadata(value) {
1469
3013
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1483,7 +3027,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1483
3027
  function readBoundedCredentialJson(path) {
1484
3028
  let raw;
1485
3029
  try {
1486
- raw = readFileSync6(path, "utf8");
3030
+ raw = readFileSync7(path, "utf8");
1487
3031
  } catch (error) {
1488
3032
  return error.code === "ENOENT" ? void 0 : null;
1489
3033
  }
@@ -1555,9 +3099,9 @@ function jwtExpiresAt(token) {
1555
3099
  }
1556
3100
 
1557
3101
  // src/daemon/client-instance-id.ts
1558
- import { randomBytes as randomBytes3 } from "crypto";
1559
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
1560
- import { join as join8 } from "path";
3102
+ import { randomBytes as randomBytes4 } from "crypto";
3103
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
3104
+ import { join as join10 } from "path";
1561
3105
  var CONFIG_DIRECTORY_MODE = 448;
1562
3106
  var INSTANCE_FILE_MODE = 384;
1563
3107
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -1570,7 +3114,7 @@ function isClientInstanceId(value) {
1570
3114
  }
1571
3115
  function ensurePrivateConfigDirectory(configDir) {
1572
3116
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
1573
- const metadata = lstatSync4(configDir);
3117
+ const metadata = lstatSync5(configDir);
1574
3118
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
1575
3119
  throw new Error("prim config path must be a private directory");
1576
3120
  }
@@ -1580,7 +3124,7 @@ function ensurePrivateConfigDirectory(configDir) {
1580
3124
  function readExisting(path) {
1581
3125
  let metadata;
1582
3126
  try {
1583
- metadata = lstatSync4(path);
3127
+ metadata = lstatSync5(path);
1584
3128
  } catch (error) {
1585
3129
  if (error.code === "ENOENT") {
1586
3130
  return;
@@ -1594,7 +3138,7 @@ function readExisting(path) {
1594
3138
  if (metadata.size > MAX_STORED_BYTES) {
1595
3139
  throw new Error("stored client instance identity is invalid");
1596
3140
  }
1597
- const raw = readFileSync7(path, "utf8");
3141
+ const raw = readFileSync8(path, "utf8");
1598
3142
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
1599
3143
  if (raw !== value && raw !== `${value}
1600
3144
  ` || !isClientInstanceId(value)) {
@@ -1608,8 +3152,8 @@ function atomicWrite(path, value) {
1608
3152
  }
1609
3153
  async function getOrCreateClientInstanceId(options) {
1610
3154
  const configDir = options.configDir;
1611
- const path = join8(configDir, "client_instance_id");
1612
- const lockPath = join8(configDir, "client-instance.lock");
3155
+ const path = join10(configDir, "client_instance_id");
3156
+ const lockPath = join10(configDir, "client-instance.lock");
1613
3157
  ensurePrivateConfigDirectory(configDir);
1614
3158
  return withFileLock(
1615
3159
  lockPath,
@@ -1618,7 +3162,7 @@ async function getOrCreateClientInstanceId(options) {
1618
3162
  if (existing !== void 0) {
1619
3163
  return existing;
1620
3164
  }
1621
- const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
3165
+ const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
1622
3166
  "base64url"
1623
3167
  )}`;
1624
3168
  if (!isClientInstanceId(generated)) {
@@ -1653,56 +3197,18 @@ async function ingestUploaderHeaders() {
1653
3197
  return headers;
1654
3198
  }
1655
3199
 
1656
- // src/lib/terminal-safe.ts
1657
- function replaceIsolatedSurrogates(value) {
1658
- let out = "";
1659
- for (let index = 0; index < value.length; index += 1) {
1660
- const unit = value.charCodeAt(index);
1661
- if (unit >= 55296 && unit <= 56319) {
1662
- const next = value.charCodeAt(index + 1);
1663
- if (next >= 56320 && next <= 57343) {
1664
- out += value[index] + value[index + 1];
1665
- index += 1;
1666
- } else {
1667
- out += "\uFFFD";
1668
- }
1669
- } else if (unit >= 56320 && unit <= 57343) {
1670
- out += "\uFFFD";
1671
- } else {
1672
- out += value[index];
1673
- }
1674
- }
1675
- return out;
1676
- }
1677
- function isUnsafeTerminalCodePoint(point) {
1678
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1679
- const bidiOrZeroWidth = point === 173 || // soft hyphen
1680
- point === 1564 || // Arabic letter mark
1681
- point === 6158 || // Mongolian vowel separator
1682
- point >= 8203 && point <= 8207 || // zero-width + directional marks
1683
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1684
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1685
- point >= 65529 && point <= 65531 || // interlinear annotation controls
1686
- point === 65279 || // zero-width no-break space / BOM
1687
- point >= 917504 && point <= 917631;
1688
- return c0OrC1 || bidiOrZeroWidth;
1689
- }
1690
- function terminalSafeText(value) {
1691
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1692
- }
1693
- function terminalSafeLine(value) {
1694
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1695
- }
1696
-
1697
3200
  // src/client.ts
1698
3201
  var CONFIG_DIR_MODE = 448;
1699
3202
  var CREDENTIAL_FILE_MODE = 384;
1700
3203
  var REFRESH_THRESHOLD_MS = 6e4;
1701
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3204
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
1702
3205
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
3206
+ function authExpiredMessage() {
3207
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
3208
+ }
1703
3209
  function readTrimmed2(path) {
1704
3210
  try {
1705
- const value = readFileSync8(path, "utf8").trim();
3211
+ const value = readFileSync9(path, "utf8").trim();
1706
3212
  return value || void 0;
1707
3213
  } catch {
1708
3214
  return void 0;
@@ -1712,13 +3218,13 @@ function getSiteUrl() {
1712
3218
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
1713
3219
  }
1714
3220
  function getSiteUrlForEnvironment(primApiUrl) {
1715
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3221
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
1716
3222
  }
1717
3223
  function expiresAtFor(token, expiresIn) {
1718
3224
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
1719
3225
  }
1720
3226
  function ensureConfigDirectory() {
1721
- const directory = dirname5(TOKEN_FILE_PATH);
3227
+ const directory = dirname6(TOKEN_FILE_PATH);
1722
3228
  mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
1723
3229
  chmodSync3(directory, CONFIG_DIR_MODE);
1724
3230
  }
@@ -1728,7 +3234,7 @@ function atomicWrite2(path, content) {
1728
3234
  }
1729
3235
  function removeCredentialFile(path) {
1730
3236
  if (!existsSync4(path)) return false;
1731
- rmSync6(path, { force: true });
3237
+ rmSync7(path, { force: true });
1732
3238
  return true;
1733
3239
  }
1734
3240
  function getTokenExpiresAt() {
@@ -1743,23 +3249,23 @@ function isTokenExpiringSoon(credential) {
1743
3249
  const expiresAt = getTokenExpiresAt();
1744
3250
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
1745
3251
  }
1746
- function refreshFingerprint(refreshToken2) {
1747
- return createHash5("sha256").update(refreshToken2).digest("hex");
3252
+ function refreshFingerprint(refreshToken3) {
3253
+ return createHash7("sha256").update(refreshToken3).digest("hex");
1748
3254
  }
1749
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3255
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
1750
3256
  return {
1751
3257
  version: 1,
1752
3258
  family: "legacy_broker",
1753
3259
  accessTokenHash: refreshFingerprint(accessToken),
1754
- refreshTokenHash: refreshFingerprint(refreshToken2)
3260
+ refreshTokenHash: refreshFingerprint(refreshToken3)
1755
3261
  };
1756
3262
  }
1757
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3263
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
1758
3264
  const hashes = {
1759
3265
  accessTokenHash: refreshFingerprint(accessToken),
1760
- refreshTokenHash: refreshFingerprint(refreshToken2)
3266
+ refreshTokenHash: refreshFingerprint(refreshToken3)
1761
3267
  };
1762
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3268
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
1763
3269
  }
1764
3270
  function writeCredentialMigrationSentinel() {
1765
3271
  atomicWrite2(
@@ -1771,11 +3277,11 @@ function writeCredentialMigrationSentinel() {
1771
3277
  `
1772
3278
  );
1773
3279
  }
1774
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
1775
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3280
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3281
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
1776
3282
  return { state: "invalid" };
1777
3283
  }
1778
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3284
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
1779
3285
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
1780
3286
  return { state: "invalid" };
1781
3287
  }
@@ -1792,17 +3298,17 @@ function preserveMarkerlessLegacyGeneration() {
1792
3298
  const metadata = readStoredCredentialMetadata();
1793
3299
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
1794
3300
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
1795
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
1796
- if (!(accessToken && refreshToken2)) return;
1797
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3301
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3302
+ if (!(accessToken && refreshToken3)) return;
3303
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
1798
3304
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
1799
3305
  `);
1800
3306
  }
1801
3307
  function terminalFingerprint() {
1802
3308
  return readTrimmed2(TERMINAL_REFRESH_PATH);
1803
3309
  }
1804
- function writeTerminalFingerprint(refreshToken2) {
1805
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3310
+ function writeTerminalFingerprint(refreshToken3) {
3311
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
1806
3312
  `);
1807
3313
  }
1808
3314
  function clearTerminalFingerprint() {
@@ -1811,20 +3317,20 @@ function clearTerminalFingerprint() {
1811
3317
  function isSessionEnded() {
1812
3318
  if (hasMachineConfiguration()) return machineSessionEnded();
1813
3319
  if (resolveAuthCredential()?.source !== "token_file") return false;
1814
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3320
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
1815
3321
  const ended = terminalFingerprint();
1816
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3322
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
1817
3323
  }
1818
3324
  function withCredentialLock(operation, options = {}) {
1819
3325
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
1820
3326
  }
1821
3327
  function commitCredentialsUnlocked(credentials) {
1822
3328
  const accessToken = credentials.accessToken.trim();
1823
- const refreshToken2 = credentials.refreshToken.trim();
1824
- if (!accessToken || !refreshToken2) {
3329
+ const refreshToken3 = credentials.refreshToken.trim();
3330
+ if (!accessToken || !refreshToken3) {
1825
3331
  throw new Error("OAuth credentials require both access and refresh tokens");
1826
3332
  }
1827
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3333
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
1828
3334
  if (credentials.metadata !== void 0) {
1829
3335
  preserveMarkerlessLegacyGeneration();
1830
3336
  writeCredentialMigrationSentinel();
@@ -1832,10 +3338,10 @@ function commitCredentialsUnlocked(credentials) {
1832
3338
  `);
1833
3339
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
1834
3340
  `);
1835
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3341
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
1836
3342
  `);
1837
3343
  } else {
1838
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3344
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
1839
3345
  `);
1840
3346
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
1841
3347
  `);
@@ -1872,15 +3378,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
1872
3378
  `
1873
3379
  );
1874
3380
  }
1875
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3381
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
1876
3382
  const current = readStoredCredentialMetadata();
1877
3383
  if (expected.state === "legacy_broker") {
1878
3384
  if (current.state !== "legacy_broker") return false;
1879
3385
  if (!expected.metadata) return current.metadata === void 0;
1880
- 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;
3386
+ 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;
1881
3387
  }
1882
3388
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
1883
- 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;
3389
+ 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;
1884
3390
  }
1885
3391
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
1886
3392
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2049,7 +3555,7 @@ async function performTokenRefresh(options = {}) {
2049
3555
  );
2050
3556
  }
2051
3557
  var _refreshInFlight;
2052
- function refreshToken(options = {}) {
3558
+ function refreshToken2(options = {}) {
2053
3559
  if (hasMachineConfiguration())
2054
3560
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2055
3561
  if (_refreshInFlight) return _refreshInFlight;
@@ -2081,7 +3587,7 @@ var CliManagementResponseError = class extends Error {
2081
3587
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
2082
3588
  async function managementResponseValue(response) {
2083
3589
  if (response.status === 401) {
2084
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3590
+ throw new HttpError(401, authExpiredMessage());
2085
3591
  }
2086
3592
  let value;
2087
3593
  try {
@@ -2103,23 +3609,50 @@ function selectedCredential() {
2103
3609
  }
2104
3610
  return _cachedCredential;
2105
3611
  }
3612
+ async function requestHeaders(method, path) {
3613
+ return {
3614
+ "Content-Type": "application/json",
3615
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
3616
+ };
3617
+ }
2106
3618
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
2107
3619
  return fetch(`${siteUrl}${path}`, {
2108
3620
  method,
2109
- headers: {
2110
- Authorization: `Bearer ${token}`,
2111
- "Content-Type": "application/json",
2112
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2113
- },
3621
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
2114
3622
  body: body === void 0 ? void 0 : JSON.stringify(body),
2115
3623
  signal: options?.signal,
2116
3624
  redirect: options?.redirect
2117
3625
  });
2118
3626
  }
3627
+ async function fetchAsMachine(credential, method, path, body, options) {
3628
+ if (!credential.tokenInjection)
3629
+ return fetchWithToken(
3630
+ method,
3631
+ path,
3632
+ body,
3633
+ { ...options, redirect: "error" },
3634
+ credential.accessToken,
3635
+ credential.apiUrl
3636
+ );
3637
+ try {
3638
+ return await forwardMachineRequest(
3639
+ {
3640
+ method,
3641
+ path,
3642
+ headers: await requestHeaders(method, path),
3643
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
3644
+ },
3645
+ options.signal
3646
+ );
3647
+ } catch (error) {
3648
+ if (!(error instanceof MachineAuthError)) throw error;
3649
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
3650
+ }
3651
+ }
2119
3652
  async function responseValue(response) {
2120
3653
  if (!response.ok) {
2121
3654
  if (response.status === 401) {
2122
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3655
+ throw new HttpError(401, authExpiredMessage());
2123
3656
  }
2124
3657
  const errorBody = await response.json().catch(() => null);
2125
3658
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -2146,14 +3679,7 @@ async function machineClient(options = {}, management = false) {
2146
3679
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
2147
3680
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
2148
3681
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2149
- let response = await fetchWithToken(
2150
- method,
2151
- path,
2152
- body,
2153
- { ...requestOptions, redirect: "error" },
2154
- current.accessToken,
2155
- selected.apiUrl
2156
- );
3682
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
2157
3683
  if (response.status === 401) {
2158
3684
  const renewed = await acquireMachineCredential({
2159
3685
  force: true,
@@ -2162,19 +3688,14 @@ async function machineClient(options = {}, management = false) {
2162
3688
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
2163
3689
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2164
3690
  }
2165
- response = await fetchWithToken(
2166
- method,
2167
- path,
2168
- body,
2169
- { ...requestOptions, redirect: "error" },
2170
- renewed.accessToken,
2171
- renewed.apiUrl
2172
- );
3691
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
2173
3692
  }
2174
3693
  if (response.status === 401)
2175
3694
  throw new HttpError(
2176
3695
  401,
2177
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3696
+ 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(
3697
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3698
+ )
2178
3699
  );
2179
3700
  return parse(response);
2180
3701
  };
@@ -2184,7 +3705,7 @@ async function machineClient(options = {}, management = false) {
2184
3705
  delete: (path, body, opts) => send("DELETE", path, body, opts)
2185
3706
  };
2186
3707
  }
2187
- async function request(method, path, body, options) {
3708
+ async function request2(method, path, body, options) {
2188
3709
  const machine = await machineClient(options);
2189
3710
  if (machine)
2190
3711
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -2193,17 +3714,17 @@ async function request(method, path, body, options) {
2193
3714
  let refreshAttempted = false;
2194
3715
  if (credential && isTokenExpiringSoon(credential)) {
2195
3716
  refreshAttempted = true;
2196
- const token = await refreshToken({
3717
+ const token = await refreshToken2({
2197
3718
  signal: options?.signal,
2198
3719
  quiet: options?.quietRefresh
2199
3720
  });
2200
3721
  if (token) credential = { token, source: "token_file" };
2201
3722
  }
2202
3723
  if (!credential) {
2203
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3724
+ throw new HttpError(401, authExpiredMessage());
2204
3725
  }
2205
3726
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
2206
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3727
+ throw new HttpError(401, authExpiredMessage());
2207
3728
  }
2208
3729
  const tokenUsed = credential.token;
2209
3730
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -2212,7 +3733,7 @@ async function request(method, path, body, options) {
2212
3733
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2213
3734
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2214
3735
  refreshAttempted = true;
2215
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
3736
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2216
3737
  }
2217
3738
  if (retryToken) {
2218
3739
  _cachedCredential = {
@@ -2226,19 +3747,19 @@ async function request(method, path, body, options) {
2226
3747
  }
2227
3748
  function getClient() {
2228
3749
  return {
2229
- get: (path, options) => request("GET", path, void 0, options),
2230
- post: (path, body, options) => request("POST", path, body, options)
3750
+ get: (path, options) => request2("GET", path, void 0, options),
3751
+ post: (path, body, options) => request2("POST", path, body, options)
2231
3752
  };
2232
3753
  }
2233
3754
 
2234
3755
  // src/daemon/principal.ts
2235
- import { createHash as createHash6 } from "crypto";
3756
+ import { createHash as createHash8 } from "crypto";
2236
3757
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
2237
3758
  function boundedClaim(value) {
2238
3759
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
2239
3760
  }
2240
3761
  function sha256(value) {
2241
- return createHash6("sha256").update(value).digest("hex");
3762
+ return createHash8("sha256").update(value).digest("hex");
2242
3763
  }
2243
3764
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
2244
3765
  if (hasMachineConfiguration()) {
@@ -2289,14 +3810,14 @@ function parseDaemonResponseEnvelope(value) {
2289
3810
 
2290
3811
  // src/daemon/client.ts
2291
3812
  import { createConnection } from "net";
2292
- import { join as join10 } from "path";
2293
- var SOCK_PATH = join10(primConfigDirectory(), "sock");
3813
+ import { join as join12 } from "path";
3814
+ var SOCK_PATH = join12(primConfigDirectory(), "sock");
2294
3815
  var DEFAULT_TIMEOUT_MS2 = 250;
2295
3816
  var nextRequestId = 1;
2296
3817
  function daemonRequest(method, params = {}, opts = {}) {
2297
3818
  const id = nextRequestId++;
2298
3819
  const caller = resolveDaemonPrincipal();
2299
- const request2 = {
3820
+ const request3 = {
2300
3821
  id,
2301
3822
  method,
2302
3823
  params,
@@ -2335,7 +3856,7 @@ function daemonRequest(method, params = {}, opts = {}) {
2335
3856
  });
2336
3857
  socket.on("connect", () => {
2337
3858
  try {
2338
- socket?.write(`${JSON.stringify(request2)}
3859
+ socket?.write(`${JSON.stringify(request3)}
2339
3860
  `);
2340
3861
  } catch {
2341
3862
  clearTimeout(timer);
@@ -2405,151 +3926,22 @@ async function daemonOrDirectGet(method, path, client, timeoutMs = DAEMON_HTTP_T
2405
3926
 
2406
3927
  // src/lib/activation.ts
2407
3928
  import { execFileSync as execFileSync4 } from "child_process";
2408
- import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
3929
+ import { existsSync as existsSync6, readFileSync as readFileSync11 } from "fs";
2409
3930
  import { homedir as homedir2 } from "os";
2410
- import { join as join11 } from "path";
3931
+ import { join as join14 } from "path";
2411
3932
 
2412
- // src/lib/demo-pause.ts
2413
- import { execFileSync as execFileSync2 } from "child_process";
2414
- var DEMO_PAUSE_MS = 30 * 6e4;
3933
+ // src/lib/cloud-prepared.ts
3934
+ import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8, writeFileSync as writeFileSync4 } from "fs";
3935
+ import { join as join13 } from "path";
2415
3936
 
2416
- // src/lib/git.ts
3937
+ // src/lib/demo-pause.ts
2417
3938
  import { execFileSync as execFileSync3 } from "child_process";
2418
- import { createHash as createHash7 } from "crypto";
2419
- import { lstatSync as lstatSync5, realpathSync } from "fs";
2420
- import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
2421
- var GIT_TIMEOUT_MS = 1e3;
2422
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
2423
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
2424
- function gitToplevel(cwd) {
2425
- try {
2426
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
2427
- cwd,
2428
- encoding: "utf-8",
2429
- stdio: ["ignore", "pipe", "ignore"],
2430
- timeout: GIT_TIMEOUT_MS
2431
- }).trim();
2432
- } catch {
2433
- return null;
2434
- }
2435
- }
2436
- function gitValue(cwd, args) {
2437
- try {
2438
- const value = execFileSync3("git", args, {
2439
- cwd,
2440
- encoding: "utf-8",
2441
- stdio: ["ignore", "pipe", "ignore"],
2442
- timeout: GIT_TIMEOUT_MS
2443
- }).trim();
2444
- return value || void 0;
2445
- } catch {
2446
- return void 0;
2447
- }
2448
- }
2449
- function currentBranch(cwd) {
2450
- return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
2451
- }
2452
- function githubRepositoryFullName(cwd) {
2453
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
2454
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
2455
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
2456
- remote
2457
- );
2458
- const path = match?.[1] ?? match?.[2];
2459
- if (!path) return null;
2460
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
2461
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
2462
- return null;
2463
- }
2464
- return `${parts[0]}/${parts[1]}`;
2465
- }
2466
- function canonicalGitRoot(cwd) {
2467
- try {
2468
- const top = gitToplevel(cwd);
2469
- return top ? realpathSync.native(top) : null;
2470
- } catch {
2471
- return null;
2472
- }
2473
- }
2474
- function nearestExistingAncestor(path) {
2475
- const suffix = [];
2476
- let cursor = path;
2477
- while (true) {
2478
- try {
2479
- lstatSync5(cursor);
2480
- break;
2481
- } catch (error) {
2482
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
2483
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
2484
- const parent = dirname6(cursor);
2485
- if (parent === cursor) return null;
2486
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
2487
- cursor = parent;
2488
- }
2489
- }
2490
- try {
2491
- return { real: realpathSync.native(cursor), suffix };
2492
- } catch {
2493
- return null;
2494
- }
2495
- }
2496
- function canonicalRepositoryPathScoped(filePath, context, baseDir) {
2497
- if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
2498
- return { ok: false, reason: "invalid_path" };
2499
- }
2500
- const absolute = resolve2(baseDir, filePath);
2501
- const resolved = nearestExistingAncestor(absolute);
2502
- if (!resolved) return { ok: false, reason: "invalid_path" };
2503
- const target = resolve2(resolved.real, ...resolved.suffix);
2504
- const rel = relative(context.repoRoot, target);
2505
- if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
2506
- if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
2507
- return { ok: false, reason: "outside_repository" };
2508
- }
2509
- return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
2510
- }
2511
- function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
2512
- if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
2513
- return null;
2514
- const absolute = resolve2(cwd, filePath);
2515
- let target;
2516
- try {
2517
- const stat = lstatSync5(absolute);
2518
- if (!stat.isFile() || stat.isSymbolicLink()) return null;
2519
- target = realpathSync.native(absolute);
2520
- } catch (error) {
2521
- if (!(error instanceof Error) || error.code !== "ENOENT") {
2522
- return null;
2523
- }
2524
- try {
2525
- const parent = realpathSync.native(dirname6(absolute));
2526
- if (!lstatSync5(parent).isDirectory()) return null;
2527
- target = resolve2(parent, basename2(absolute));
2528
- } catch {
2529
- return null;
2530
- }
2531
- }
2532
- const rel = relative(repositoryRoot, target);
2533
- if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
2534
- return null;
2535
- }
2536
- return sep === "/" ? rel : rel.split(sep).join("/");
2537
- }
2538
- function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
2539
- if (typeof contextOrCwd === "string") {
2540
- return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
2541
- }
2542
- return canonicalRepositoryPathScoped(
2543
- filePath,
2544
- contextOrCwd,
2545
- baseDirOrRoot ?? contextOrCwd.repoRoot
2546
- );
2547
- }
3939
+ var DEMO_PAUSE_MS = 30 * 6e4;
2548
3940
 
2549
3941
  // src/lib/activation.ts
2550
3942
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
2551
3943
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
2552
- var GIT_TIMEOUT_MS2 = 1e3;
3944
+ var GIT_TIMEOUT_MS3 = 1e3;
2553
3945
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
2554
3946
  function isValidRepoSyncId(value) {
2555
3947
  return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
@@ -2560,7 +3952,7 @@ function localGitConfigValue(cwd, key) {
2560
3952
  cwd,
2561
3953
  encoding: "utf-8",
2562
3954
  stdio: ["ignore", "pipe", "ignore"],
2563
- timeout: GIT_TIMEOUT_MS2
3955
+ timeout: GIT_TIMEOUT_MS3
2564
3956
  }).trim();
2565
3957
  return value || void 0;
2566
3958
  } catch {
@@ -2623,7 +4015,7 @@ async function checkAffectedDecisions(filePaths, deps = defaultDeps) {
2623
4015
  return {
2624
4016
  decisions: [],
2625
4017
  truncated: false,
2626
- unavailable: "this checkout has no current Primitive repository binding; run prim enable"
4018
+ unavailable: isClaudeCloudSession() ? cloudSetupPointer("this checkout has no current Primitive repository binding") : "this checkout has no current Primitive repository binding; run prim enable"
2627
4019
  };
2628
4020
  }
2629
4021
  const canonical = filePaths.map(