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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
@@ -54,10 +54,10 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/lib/machine-broker.ts
56
56
  import { spawn } from "child_process";
57
- import { createHash as createHash3, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
58
- import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
57
+ import { createHash as createHash5, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
58
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, rmSync as rmSync6 } from "fs";
59
59
  import { createServer } from "http";
60
- import { basename, join as join6 } from "path";
60
+ import { basename as basename2, join as join8 } from "path";
61
61
  import { fileURLToPath as fileURLToPath3 } from "url";
62
62
 
63
63
  // src/lib/atomic-file.ts
@@ -334,14 +334,66 @@ async function withFileLock(lockDir, operation, options = {}) {
334
334
  }
335
335
  }
336
336
 
337
+ // src/lib/loopback-fetch.ts
338
+ import { request } from "http";
339
+ import { Readable } from "stream";
340
+ function loopbackFetch(url, init = {}) {
341
+ const target = new URL(url);
342
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
343
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
344
+ return new Promise((resolve3, reject) => {
345
+ const outgoing = request(
346
+ target,
347
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
348
+ (incoming) => {
349
+ try {
350
+ const headers = new Headers();
351
+ for (const [name, value] of Object.entries(incoming.headers))
352
+ if (typeof value === "string") headers.set(name, value);
353
+ const status = incoming.statusCode ?? 502;
354
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
355
+ resolve3(new Response(body, { status, headers }));
356
+ } catch (error) {
357
+ incoming.destroy();
358
+ reject(error);
359
+ }
360
+ }
361
+ );
362
+ outgoing.once("error", reject);
363
+ outgoing.end(init.body);
364
+ });
365
+ }
366
+
337
367
  // src/lib/machine-credentials.ts
338
- import { execFileSync } from "child_process";
339
- import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
340
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
368
+ import { execFileSync as execFileSync2 } from "child_process";
369
+ import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
370
+ import {
371
+ chmodSync,
372
+ existsSync as existsSync3,
373
+ linkSync,
374
+ lstatSync as lstatSync3,
375
+ mkdirSync as mkdirSync3,
376
+ readFileSync as readFileSync5,
377
+ rmSync as rmSync5,
378
+ writeFileSync as writeFileSync3
379
+ } from "fs";
341
380
  import { createRequire } from "module";
342
- import { dirname as dirname4, join as join5 } from "path";
381
+ import { dirname as dirname5, join as join7 } from "path";
343
382
  import { fileURLToPath as fileURLToPath2 } from "url";
344
383
 
384
+ // src/lib/cloud-env.ts
385
+ function isClaudeCloudSession(env = process.env) {
386
+ return env.CLAUDE_CODE_REMOTE === "true";
387
+ }
388
+ 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';
389
+ 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';
390
+ 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}.`;
391
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
392
+ function cloudSetupPointer(message, env = process.env) {
393
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
394
+ }
395
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
396
+
345
397
  // src/lib/workos-connect.ts
346
398
  var TOKEN_PATH = "/oauth2/token";
347
399
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -478,10 +530,10 @@ function parseWorkosConnectTokens(value, options = {}) {
478
530
  "access_token",
479
531
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
480
532
  );
481
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
533
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
482
534
  return {
483
535
  accessToken,
484
- refreshToken: refreshToken2,
536
+ refreshToken: refreshToken3,
485
537
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
486
538
  };
487
539
  }
@@ -537,9 +589,19 @@ function parseMachineConfiguration(value) {
537
589
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
538
590
  };
539
591
  }
592
+ function rejectedCredentialsMessage(message, env = process.env) {
593
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
594
+ }
540
595
  function machineSignal(signal) {
541
596
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
542
597
  }
598
+ function hostOf(url) {
599
+ try {
600
+ return new URL(url).hostname;
601
+ } catch {
602
+ return "Primitive";
603
+ }
604
+ }
543
605
  async function fetchMachine(url, options, fetchImpl) {
544
606
  try {
545
607
  return await fetchImpl(url, options);
@@ -547,7 +609,9 @@ async function fetchMachine(url, options, fetchImpl) {
547
609
  options.signal?.throwIfAborted();
548
610
  throw new MachineAuthError(
549
611
  "authentication_unavailable",
550
- "Machine authentication is temporarily unavailable. Check the connection and retry."
612
+ // A cloud VM reaches only the hosts its environment allows, and both of
613
+ // Primitive's are blocked by default: name the one that failed.
614
+ 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."
551
615
  );
552
616
  }
553
617
  }
@@ -574,8 +638,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
574
638
  );
575
639
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
576
640
  }
577
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
578
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
641
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
642
+ const network = options.secretInjection === "network";
643
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
579
644
  throw new MachineAuthError(
580
645
  "invalid_credentials",
581
646
  "A machine client ID and secret are required.",
@@ -589,11 +654,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
589
654
  redirect: "error",
590
655
  signal: machineSignal(signal),
591
656
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
592
- body: new URLSearchParams({
593
- grant_type: "client_credentials",
594
- client_id: clientId,
595
- client_secret: clientSecret
596
- })
657
+ // With a network secret the agent proxy authenticates the client with
658
+ // HTTP Basic (client_secret_basic); the body carries no credential.
659
+ body: new URLSearchParams(
660
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
661
+ )
597
662
  },
598
663
  fetchImpl
599
664
  );
@@ -601,7 +666,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
601
666
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
602
667
  throw new MachineAuthError(
603
668
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
604
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
669
+ 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(
670
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
671
+ ) : "The machine token service is temporarily unavailable.",
605
672
  terminal,
606
673
  terminal ? void 0 : machineRetryAt(response)
607
674
  );
@@ -621,6 +688,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
621
688
  } catch {
622
689
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
623
690
  }
691
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
692
+ throw new MachineAuthError(
693
+ "token_client_mismatch",
694
+ "The token service issued a token for another machine client."
695
+ );
624
696
  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()) {
625
697
  throw new MachineAuthError(
626
698
  "token_identity_mismatch",
@@ -666,22 +738,66 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
666
738
  const terminal = response.status === 401 || response.status === 403;
667
739
  throw new MachineAuthError(
668
740
  terminal ? "machine_access_rejected" : "verification_unavailable",
669
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
741
+ terminal ? rejectedCredentialsMessage(
742
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
743
+ ) : "Machine verification is temporarily unavailable.",
670
744
  terminal
671
745
  );
672
746
  }
673
747
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
674
748
  }
749
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
750
+ const rejected = () => new MachineAuthError(
751
+ "network_token_rejected",
752
+ `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.`,
753
+ true
754
+ );
755
+ if (status === 401 || status === 403) throw rejected();
756
+ if (status < 200 || status > 299)
757
+ throw new MachineAuthError(
758
+ "verification_unavailable",
759
+ "Machine verification is temporarily unavailable."
760
+ );
761
+ let data;
762
+ try {
763
+ data = machineRecord(value);
764
+ } catch {
765
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
766
+ }
767
+ if (data.authenticated !== true) throw rejected();
768
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
769
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
770
+ throw new MachineAuthError(
771
+ "network_secret_mismatch",
772
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
773
+ true
774
+ );
775
+ return parseMachineIdentity(data, clientId);
776
+ }
777
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
778
+ const response = await fetchMachine(
779
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
780
+ { redirect: "error", signal: machineSignal(signal) },
781
+ fetchImpl
782
+ );
783
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
784
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
785
+ }
675
786
 
676
787
  // src/lib/machine-retry.ts
677
788
  import { createHash } from "crypto";
678
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
789
+ import { lstatSync, readFileSync as readFileSync3, readdirSync, rmSync as rmSync3 } from "fs";
679
790
  import { join as join3 } from "path";
680
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
791
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
792
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
793
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
681
794
  signal?.throwIfAborted();
682
795
  const key = createHash("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
683
796
  const path = join3(directory, `machine_retry_${key}.json`);
684
- let state = { failures: 0, retryAt: 0 };
797
+ let state = {
798
+ failures: 0,
799
+ retryAt: 0
800
+ };
685
801
  try {
686
802
  const stat = lstatSync(path);
687
803
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
@@ -696,12 +812,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
696
812
  if (state.retryAt > Date.now())
697
813
  throw new MachineAuthError(
698
814
  "token_service_unavailable",
699
- "Machine authentication is cooling down after a temporary failure. Retry later.",
815
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
816
+ // Cloud setup keeps this wait too, so pointing at it would loop.
817
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
818
+ ) : (
819
+ // The cooldown hides the failure that started it; cloud setup
820
+ // retries at once and names the cause.
821
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
822
+ ),
700
823
  false,
701
824
  state.retryAt
702
825
  );
703
826
  try {
704
- const result = await request2();
827
+ const result = await request3();
705
828
  rmSync3(path, { force: true });
706
829
  return result;
707
830
  } catch (error) {
@@ -713,8 +836,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
713
836
  ].includes(error.code)) {
714
837
  const failures = Math.min(16, state.failures + 1);
715
838
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
716
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
717
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
839
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
840
+ atomicWriteFile(
841
+ path,
842
+ JSON.stringify({
843
+ failures,
844
+ retryAt,
845
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
846
+ }),
847
+ { mode: 384 }
848
+ );
718
849
  throw new MachineAuthError(error.code, error.message, false, retryAt);
719
850
  }
720
851
  throw error;
@@ -749,32 +880,1115 @@ function primConfigDirectory(options = {}) {
749
880
  return resolvePrimConfigDirectory(options).path;
750
881
  }
751
882
 
883
+ // src/lib/session-identity.ts
884
+ import { execFile } from "child_process";
885
+ import { createHash as createHash3 } from "crypto";
886
+ import { rmSync as rmSync4 } from "fs";
887
+ import { join as join6 } from "path";
888
+ import { promisify } from "util";
889
+
890
+ // src/lib/git.ts
891
+ import { execFileSync } from "child_process";
892
+ import { createHash as createHash2 } from "crypto";
893
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync } from "fs";
894
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute3, join as join5, relative, resolve, sep } from "path";
895
+ var GIT_TIMEOUT_MS = 1e3;
896
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
897
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
898
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
899
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
900
+ function gitChildEnvironment(env = process.env) {
901
+ return Object.fromEntries(
902
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
903
+ );
904
+ }
905
+ function gitToplevel(cwd) {
906
+ try {
907
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
908
+ cwd,
909
+ encoding: "utf-8",
910
+ stdio: ["ignore", "pipe", "ignore"],
911
+ timeout: GIT_TIMEOUT_MS,
912
+ env: gitChildEnvironment()
913
+ }).trim();
914
+ } catch {
915
+ return null;
916
+ }
917
+ }
918
+ function gitValue(cwd, args) {
919
+ try {
920
+ const value = execFileSync("git", args, {
921
+ cwd,
922
+ encoding: "utf-8",
923
+ stdio: ["ignore", "pipe", "ignore"],
924
+ timeout: GIT_TIMEOUT_MS,
925
+ env: gitChildEnvironment()
926
+ }).trim();
927
+ return value || void 0;
928
+ } catch {
929
+ return void 0;
930
+ }
931
+ }
932
+ function currentBranch(cwd) {
933
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
934
+ }
935
+ function parseGithubRepositoryName(path) {
936
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
937
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
938
+ return null;
939
+ }
940
+ return `${parts[0]}/${parts[1]}`;
941
+ }
942
+ function githubRepositoryFromRemote(remote) {
943
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
944
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
945
+ remote
946
+ );
947
+ const path = match?.[1] ?? match?.[2];
948
+ return path ? parseGithubRepositoryName(path) : null;
949
+ }
950
+ function checkoutSettingsText(repoRoot) {
951
+ const path = join5(repoRoot, ".claude", "settings.json");
952
+ try {
953
+ if (!lstatSync2(join5(repoRoot, ".claude")).isDirectory()) return null;
954
+ const stat = lstatSync2(path);
955
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
956
+ return readFileSync4(path, "utf8");
957
+ } catch {
958
+ return null;
959
+ }
960
+ }
961
+ function checkoutDeclaration(repoRoot, name) {
962
+ const text = checkoutSettingsText(repoRoot);
963
+ if (text === null) return null;
964
+ let parsed;
965
+ try {
966
+ parsed = JSON.parse(text);
967
+ } catch {
968
+ return null;
969
+ }
970
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
971
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
972
+ return typeof value === "string" ? value : null;
973
+ }
974
+ function declaredGithubRepository(repoRoot) {
975
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
976
+ return value === null ? null : parseGithubRepositoryName(value.trim());
977
+ }
978
+ function githubRepositoryFullName(cwd) {
979
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
980
+ if (remote) {
981
+ const fromOrigin = githubRepositoryFromRemote(remote);
982
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
983
+ }
984
+ const root = gitToplevel(cwd);
985
+ return root ? declaredGithubRepository(root) : null;
986
+ }
987
+ function normalizeOriginRemote(remote) {
988
+ const value = remote.trim();
989
+ if (!value) return void 0;
990
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
991
+ if (scp?.host && scp.path) {
992
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
993
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
994
+ }
995
+ try {
996
+ const url = new URL(value);
997
+ url.username = "";
998
+ url.password = "";
999
+ url.search = "";
1000
+ url.hash = "";
1001
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1002
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1003
+ return void 0;
1004
+ } catch {
1005
+ return void 0;
1006
+ }
1007
+ }
1008
+
1009
+ // src/lib/terminal-safe.ts
1010
+ function replaceIsolatedSurrogates(value) {
1011
+ let out = "";
1012
+ for (let index = 0; index < value.length; index += 1) {
1013
+ const unit = value.charCodeAt(index);
1014
+ if (unit >= 55296 && unit <= 56319) {
1015
+ const next = value.charCodeAt(index + 1);
1016
+ if (next >= 56320 && next <= 57343) {
1017
+ out += value[index] + value[index + 1];
1018
+ index += 1;
1019
+ } else {
1020
+ out += "\uFFFD";
1021
+ }
1022
+ } else if (unit >= 56320 && unit <= 57343) {
1023
+ out += "\uFFFD";
1024
+ } else {
1025
+ out += value[index];
1026
+ }
1027
+ }
1028
+ return out;
1029
+ }
1030
+ function isUnsafeTerminalCodePoint(point) {
1031
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1032
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1033
+ point === 1564 || // Arabic letter mark
1034
+ point === 6158 || // Mongolian vowel separator
1035
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1036
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1037
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1038
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1039
+ point === 65279 || // zero-width no-break space / BOM
1040
+ point >= 917504 && point <= 917631;
1041
+ return c0OrC1 || bidiOrZeroWidth;
1042
+ }
1043
+ function terminalSafeText(value) {
1044
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1045
+ }
1046
+ function terminalSafeLine(value) {
1047
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1048
+ }
1049
+ var stripControlChars = terminalSafeText;
1050
+
1051
+ // src/lib/session-identity.ts
1052
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1053
+ var SESSION_IDENTITY_VALUE = "session";
1054
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1055
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1056
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1057
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1058
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1059
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1060
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1061
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1062
+ var SESSION_IDENTITY_ROUTES = {
1063
+ challenge: "/api/cli/session-identity/challenge",
1064
+ token: "/api/cli/session-identity/token",
1065
+ refresh: "/api/cli/session-identity/token/refresh",
1066
+ link: "/api/cli/session-identity/link"
1067
+ };
1068
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1069
+ var RENEW_BEFORE_MS = 6e4;
1070
+ var GIT_TIMEOUT_MS2 = 1e4;
1071
+ var POLL_BUDGET_MS = 15e3;
1072
+ var POLL_FIRST_DELAY_MS = 500;
1073
+ var POLL_MAX_DELAY_MS = 3e3;
1074
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1075
+ var LOCK_TIMEOUT_MS = 6e4;
1076
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1077
+ function sessionIdentityRequested(env = process.env) {
1078
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1079
+ }
1080
+ function sessionIdentityMode(deps = {}) {
1081
+ const env = deps.env ?? process.env;
1082
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1083
+ }
1084
+ function failure(code, cause, remedy) {
1085
+ return { status: "failed", code, cause, remedy };
1086
+ }
1087
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1088
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1089
+ 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';
1090
+ var SESSION_REVOKED = failure(
1091
+ "session_revoked",
1092
+ "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",
1093
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1094
+ );
1095
+ var CHALLENGE_WINDOW_PASSED = failure(
1096
+ "challenge_expired",
1097
+ "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)",
1098
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1099
+ );
1100
+ var CHALLENGE_GONE = failure(
1101
+ "challenge_not_found",
1102
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1103
+ NEW_SESSION_REMEDY
1104
+ );
1105
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1106
+ function rejectionFailure(reason, repository) {
1107
+ switch (reason) {
1108
+ case "identity_mismatch":
1109
+ return failure(
1110
+ "identity_mismatch",
1111
+ "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",
1112
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1113
+ );
1114
+ case "push_after_expiry":
1115
+ return failure(
1116
+ "push_after_expiry",
1117
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1118
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1119
+ );
1120
+ case "repository_mismatch":
1121
+ return failure(
1122
+ "repository_mismatch",
1123
+ `Primitive received the identity push from a different repository than ${repository}`,
1124
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1125
+ );
1126
+ case "conflicting_push":
1127
+ return failure(
1128
+ "conflicting_push",
1129
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1130
+ NEW_SESSION_REMEDY
1131
+ );
1132
+ case "unsupported_sender":
1133
+ return failure(
1134
+ "unsupported_sender",
1135
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1136
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1137
+ );
1138
+ default:
1139
+ return failure(
1140
+ "challenge_rejected",
1141
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1142
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1143
+ );
1144
+ }
1145
+ }
1146
+ function sessionIdentityMessage(outcome) {
1147
+ if (outcome.status === "link_required")
1148
+ 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.`;
1149
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1150
+ }
1151
+ function hash(value) {
1152
+ return createHash3("sha256").update(value).digest("hex");
1153
+ }
1154
+ function sessionContext(deps) {
1155
+ const env = deps.env ?? process.env;
1156
+ const environment = environmentCredentials(deps);
1157
+ if (!environment)
1158
+ return failure(
1159
+ "environment_credential_missing",
1160
+ "the cloud environment has no environment credential",
1161
+ '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'
1162
+ );
1163
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1164
+ if (!sessionId || !SESSION_ID.test(sessionId))
1165
+ return failure(
1166
+ "session_id_missing",
1167
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1168
+ NEW_SESSION_REMEDY
1169
+ );
1170
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1171
+ const directory = deps.directory ?? primConfigDirectory({ env });
1172
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1173
+ return {
1174
+ directory,
1175
+ apiUrl,
1176
+ clientId: environment.clientId,
1177
+ generation: environment.generation,
1178
+ sessionId,
1179
+ tokenPath: join6(directory, `session_identity_${key}.json`),
1180
+ statePath: join6(directory, `session_identity_${key}.state.json`),
1181
+ lockPath: join6(directory, "session-identity.lock")
1182
+ };
1183
+ }
1184
+ function readRecord(path) {
1185
+ try {
1186
+ const value = readMachineMetadata(path);
1187
+ return value === void 0 ? void 0 : machineRecord(value);
1188
+ } catch {
1189
+ return void 0;
1190
+ }
1191
+ }
1192
+ function finiteNumber(value) {
1193
+ return typeof value === "number" && Number.isFinite(value);
1194
+ }
1195
+ function readToken(context) {
1196
+ const data = readRecord(context.tokenPath);
1197
+ 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))
1198
+ return void 0;
1199
+ const identity = data.identity;
1200
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1201
+ return void 0;
1202
+ return data;
1203
+ }
1204
+ function readState(context) {
1205
+ const data = readRecord(context.statePath);
1206
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1207
+ return void 0;
1208
+ return data;
1209
+ }
1210
+ function writeToken(context, record) {
1211
+ prepareMachineMetadataDirectory(context.directory);
1212
+ writeMachineMetadata(context.tokenPath, record);
1213
+ rmSync4(context.statePath, { force: true });
1214
+ }
1215
+ function writeState(context, state) {
1216
+ try {
1217
+ prepareMachineMetadataDirectory(context.directory);
1218
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1219
+ } catch {
1220
+ }
1221
+ }
1222
+ function tokenValid(record, now = Date.now()) {
1223
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1224
+ }
1225
+ function tokenFresh(record, now = Date.now()) {
1226
+ return tokenValid(record, now) && now < record.refreshAfter;
1227
+ }
1228
+ function toCredential(record) {
1229
+ return {
1230
+ issuer: record.issuer,
1231
+ audience: record.audience,
1232
+ ...record.identity,
1233
+ accessToken: record.accessToken,
1234
+ expiresAt: record.expiresAt,
1235
+ apiUrl: record.apiUrl,
1236
+ generation: record.generation,
1237
+ storage: "environment",
1238
+ session: {
1239
+ userId: record.userId,
1240
+ displayName: record.displayName,
1241
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1242
+ refreshAfter: record.refreshAfter
1243
+ }
1244
+ };
1245
+ }
1246
+ function identified(record, reused) {
1247
+ return {
1248
+ status: "ok",
1249
+ credential: toCredential(record),
1250
+ displayName: record.displayName,
1251
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1252
+ reused
1253
+ };
1254
+ }
1255
+ function cachedSessionCredential(deps = {}) {
1256
+ if (!sessionIdentityMode(deps)) return void 0;
1257
+ let context;
1258
+ try {
1259
+ context = sessionContext(deps);
1260
+ } catch {
1261
+ return void 0;
1262
+ }
1263
+ if ("status" in context) return void 0;
1264
+ const record = readToken(context);
1265
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1266
+ }
1267
+ function outcomeFromState(state) {
1268
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1269
+ return {
1270
+ status: "link_required",
1271
+ githubLogin: state.githubLogin,
1272
+ challengeId: state.challengeId,
1273
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1274
+ };
1275
+ return failure(
1276
+ state.code,
1277
+ state.cause ?? "the last identity check failed",
1278
+ state.remedy ?? RETRY_REMEDY
1279
+ );
1280
+ }
1281
+ function parseInstant(value) {
1282
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1283
+ if (typeof value === "string" && value.length <= 64) {
1284
+ const parsed = Date.parse(value);
1285
+ return Number.isFinite(parsed) ? parsed : void 0;
1286
+ }
1287
+ return void 0;
1288
+ }
1289
+ async function sendJson(url, init, fetchImpl) {
1290
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1291
+ let value;
1292
+ try {
1293
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1294
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1295
+ } catch {
1296
+ value = void 0;
1297
+ }
1298
+ return { status: response.status, value };
1299
+ }
1300
+ function environmentOnly(deps) {
1301
+ return { ...deps, environmentOnly: true };
1302
+ }
1303
+ async function environmentRequest(method, path, body, deps, signal) {
1304
+ const send = async (credential2) => {
1305
+ const headers = { "Content-Type": "application/json" };
1306
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1307
+ if (credential2.tokenInjection) {
1308
+ const response = await forwardMachineRequest(
1309
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1310
+ signal,
1311
+ environmentOnly(deps)
1312
+ );
1313
+ const parsed = await response.json().catch(() => void 0);
1314
+ return {
1315
+ status: response.status,
1316
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1317
+ };
1318
+ }
1319
+ return sendJson(
1320
+ `${credential2.apiUrl}${path}`,
1321
+ {
1322
+ method,
1323
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1324
+ ...text === void 0 ? {} : { body: text },
1325
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1326
+ },
1327
+ deps.fetch ?? fetch
1328
+ );
1329
+ };
1330
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1331
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1332
+ let answer = await send(credential);
1333
+ if (answer.status === 401) {
1334
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1335
+ if (!credential)
1336
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1337
+ answer = await send(credential);
1338
+ }
1339
+ return answer;
1340
+ }
1341
+ function environmentFailure(error, apiUrl) {
1342
+ if (error instanceof MachineAuthError && error.terminal)
1343
+ return failure(
1344
+ "environment_credential_rejected",
1345
+ "Primitive rejected the cloud environment's credential",
1346
+ ENVIRONMENT_CREDENTIAL_REMEDY
1347
+ );
1348
+ const host = (() => {
1349
+ try {
1350
+ return new URL(apiUrl).hostname;
1351
+ } catch {
1352
+ return "Primitive";
1353
+ }
1354
+ })();
1355
+ return failure(
1356
+ "identity_unavailable",
1357
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1358
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1359
+ );
1360
+ }
1361
+ function answerError(answer) {
1362
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1363
+ }
1364
+ async function git(root, args, signal) {
1365
+ try {
1366
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1367
+ cwd: root,
1368
+ encoding: "utf8",
1369
+ timeout: GIT_TIMEOUT_MS2,
1370
+ signal,
1371
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1372
+ maxBuffer: 1024 * 1024
1373
+ });
1374
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1375
+ } catch (error) {
1376
+ const failed = error;
1377
+ return {
1378
+ ok: false,
1379
+ code: typeof failed.code === "number" ? failed.code : void 0,
1380
+ stdout: failed.stdout ?? "",
1381
+ stderr: failed.stderr ?? "",
1382
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1383
+ };
1384
+ }
1385
+ }
1386
+ function gitDetail(stderr) {
1387
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1388
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1389
+ }
1390
+ async function defaultSleep2(milliseconds, signal) {
1391
+ await new Promise((resolve3, reject) => {
1392
+ const timer = setTimeout(resolve3, milliseconds);
1393
+ signal?.addEventListener(
1394
+ "abort",
1395
+ () => {
1396
+ clearTimeout(timer);
1397
+ reject(signal.reason);
1398
+ },
1399
+ { once: true }
1400
+ );
1401
+ });
1402
+ }
1403
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1404
+ const sleep = deps.sleep ?? defaultSleep2;
1405
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1406
+ let delay = POLL_FIRST_DELAY_MS;
1407
+ let unreachable;
1408
+ for (; ; ) {
1409
+ const remaining = deadline - Date.now();
1410
+ if (remaining <= 0) break;
1411
+ await sleep(Math.min(delay, remaining), signal);
1412
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1413
+ let answer;
1414
+ try {
1415
+ answer = await environmentRequest(
1416
+ "GET",
1417
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1418
+ void 0,
1419
+ deps,
1420
+ signal
1421
+ );
1422
+ } catch (error) {
1423
+ signal?.throwIfAborted();
1424
+ unreachable = error;
1425
+ continue;
1426
+ }
1427
+ if (answer.status === 404) return CHALLENGE_GONE;
1428
+ if (answer.status === 401 || answer.status === 403)
1429
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1430
+ if (answer.status < 200 || answer.status > 299) {
1431
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1432
+ continue;
1433
+ }
1434
+ unreachable = void 0;
1435
+ const status = answer.value;
1436
+ if (status?.status === "verified")
1437
+ return {
1438
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1439
+ };
1440
+ if (status?.status === "expired")
1441
+ return failure(
1442
+ "challenge_expired",
1443
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1444
+ NEW_SESSION_REMEDY
1445
+ );
1446
+ if (status?.status === "rejected")
1447
+ return rejectionFailure(status.reason, repository);
1448
+ }
1449
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1450
+ return failure(
1451
+ "webhook_timeout",
1452
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1453
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1454
+ );
1455
+ }
1456
+ function parseTokenAnswer(value) {
1457
+ if (!value) return void 0;
1458
+ const user = value.user;
1459
+ const expiresAt = parseInstant(value.expiresAt);
1460
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1461
+ 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))
1462
+ return void 0;
1463
+ return {
1464
+ accessToken: value.accessToken,
1465
+ expiresAt,
1466
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1467
+ userId: user.id,
1468
+ displayName: user.displayName,
1469
+ organizationId: value.organizationId
1470
+ };
1471
+ }
1472
+ var SERVER_CONTRACT_FAILURE = failure(
1473
+ "server_contract",
1474
+ "Primitive's answer did not identify the linked member",
1475
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1476
+ );
1477
+ async function recordFor(context, answer, extra, deps, signal) {
1478
+ let identity;
1479
+ let environment;
1480
+ try {
1481
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1482
+ identity = await verifyMachineIdentity(
1483
+ context.apiUrl,
1484
+ answer.accessToken,
1485
+ context.clientId,
1486
+ signal,
1487
+ deps.fetch
1488
+ );
1489
+ } catch (error) {
1490
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1491
+ return SERVER_CONTRACT_FAILURE;
1492
+ return environmentFailure(error, context.apiUrl);
1493
+ }
1494
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1495
+ return SERVER_CONTRACT_FAILURE;
1496
+ return {
1497
+ version: 1,
1498
+ apiUrl: context.apiUrl,
1499
+ clientId: context.clientId,
1500
+ generation: context.generation,
1501
+ sessionId: context.sessionId,
1502
+ issuer: environment.issuer,
1503
+ audience: environment.audience,
1504
+ accessToken: answer.accessToken,
1505
+ expiresAt: answer.expiresAt,
1506
+ refreshAfter: answer.refreshAfter,
1507
+ userId: answer.userId,
1508
+ displayName: answer.displayName,
1509
+ organizationId: answer.organizationId,
1510
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1511
+ identity,
1512
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1513
+ };
1514
+ }
1515
+ async function refreshToken(context, record, deps, signal) {
1516
+ let answer;
1517
+ try {
1518
+ answer = await environmentRequest(
1519
+ "POST",
1520
+ SESSION_IDENTITY_ROUTES.refresh,
1521
+ { accessToken: record.accessToken },
1522
+ deps,
1523
+ signal
1524
+ );
1525
+ } catch (error) {
1526
+ signal?.throwIfAborted();
1527
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
1528
+ }
1529
+ const code = answerError(answer);
1530
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
1531
+ return { status: "refused", failure: SESSION_REVOKED };
1532
+ if (answer.status === 401 || answer.status === 403)
1533
+ return {
1534
+ status: "refused",
1535
+ failure: environmentFailure(
1536
+ new MachineAuthError("rejected", "rejected", true),
1537
+ context.apiUrl
1538
+ )
1539
+ };
1540
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1541
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
1542
+ return { status: "unavailable" };
1543
+ return {
1544
+ status: "ok",
1545
+ record: {
1546
+ ...record,
1547
+ accessToken: token.accessToken,
1548
+ expiresAt: token.expiresAt,
1549
+ refreshAfter: token.refreshAfter,
1550
+ displayName: token.displayName
1551
+ }
1552
+ };
1553
+ }
1554
+ function exchangeRefusal(answer, repository) {
1555
+ if (answer.status === 404) return CHALLENGE_GONE;
1556
+ if (answer.status !== 409) return void 0;
1557
+ switch (answerError(answer)) {
1558
+ case "identity_mismatch":
1559
+ return rejectionFailure("identity_mismatch", repository);
1560
+ case "challenge_rejected":
1561
+ return rejectionFailure(answer.value?.reason, repository);
1562
+ case "challenge_expired":
1563
+ return CHALLENGE_WINDOW_PASSED;
1564
+ case "challenge_already_exchanged":
1565
+ return failure(
1566
+ "challenge_already_exchanged",
1567
+ "this session's identity check was already exchanged for a token this VM does not hold",
1568
+ NEW_SESSION_REMEDY
1569
+ );
1570
+ case "challenge_pending":
1571
+ return failure(
1572
+ "webhook_timeout",
1573
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
1574
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1575
+ );
1576
+ default:
1577
+ return void 0;
1578
+ }
1579
+ }
1580
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
1581
+ let answer;
1582
+ try {
1583
+ answer = await environmentRequest(
1584
+ "POST",
1585
+ SESSION_IDENTITY_ROUTES.token,
1586
+ { challengeId: challenge.challengeId },
1587
+ deps,
1588
+ signal
1589
+ );
1590
+ } catch (error) {
1591
+ signal?.throwIfAborted();
1592
+ return environmentFailure(error, context.apiUrl);
1593
+ }
1594
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
1595
+ const login = answer.value?.githubLogin;
1596
+ return {
1597
+ status: "link_required",
1598
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
1599
+ challengeId: challenge.challengeId,
1600
+ challengeExpiresAt: challenge.challengeExpiresAt
1601
+ };
1602
+ }
1603
+ const refused = exchangeRefusal(
1604
+ answer,
1605
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
1606
+ );
1607
+ if (refused) return refused;
1608
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1609
+ if (!token) {
1610
+ if (answer.status === 401 || answer.status === 403)
1611
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1612
+ return answer.status >= 500 ? environmentFailure(
1613
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1614
+ context.apiUrl
1615
+ ) : SERVER_CONTRACT_FAILURE;
1616
+ }
1617
+ return recordFor(
1618
+ context,
1619
+ token,
1620
+ { githubLogin: challenge.githubLogin, repositoryRoot },
1621
+ deps,
1622
+ signal
1623
+ );
1624
+ }
1625
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
1626
+ const env = deps.env ?? process.env;
1627
+ const repository = githubRepositoryFullName(root);
1628
+ if (!repository)
1629
+ return failure(
1630
+ "repository_unidentified",
1631
+ "this checkout does not name its GitHub repository",
1632
+ "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"
1633
+ );
1634
+ const branch = currentBranch(root);
1635
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
1636
+ return failure(
1637
+ "not_session_branch",
1638
+ `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`,
1639
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
1640
+ );
1641
+ attempt.branch = branch;
1642
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
1643
+ if (!baseSha) {
1644
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
1645
+ baseSha = head.stdout.trim();
1646
+ if (!head.ok || !SHA.test(baseSha))
1647
+ return failure(
1648
+ "no_commit",
1649
+ "this checkout has no commit to create the session branch at",
1650
+ NEW_SESSION_REMEDY
1651
+ );
1652
+ }
1653
+ const published = await git(
1654
+ root,
1655
+ [
1656
+ "for-each-ref",
1657
+ "--count=1",
1658
+ "--format=%(refname)",
1659
+ "--contains",
1660
+ baseSha,
1661
+ "refs/remotes/origin/"
1662
+ ],
1663
+ signal
1664
+ );
1665
+ if (!published.ok || published.stdout.trim() === "")
1666
+ return failure(
1667
+ "unpublished_commits",
1668
+ `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`,
1669
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
1670
+ );
1671
+ attempt.baseSha = baseSha;
1672
+ const remote = await git(
1673
+ root,
1674
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
1675
+ signal
1676
+ );
1677
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
1678
+ if (remote.ok && recorded) {
1679
+ Object.assign(attempt, recorded);
1680
+ return { ...recorded, repository };
1681
+ }
1682
+ if (remote.ok)
1683
+ return failure(
1684
+ "branch_exists",
1685
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
1686
+ NEW_SESSION_REMEDY
1687
+ );
1688
+ if (remote.code !== 2)
1689
+ return failure(
1690
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
1691
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
1692
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
1693
+ );
1694
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
1695
+ Object.assign(attempt, recorded);
1696
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
1697
+ }
1698
+ let answer;
1699
+ try {
1700
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
1701
+ answer = await environmentRequest(
1702
+ "POST",
1703
+ SESSION_IDENTITY_ROUTES.challenge,
1704
+ {
1705
+ repositoryFullName: repository,
1706
+ claudeSessionId: context.sessionId,
1707
+ branch,
1708
+ baseSha,
1709
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
1710
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
1711
+ },
1712
+ deps,
1713
+ signal
1714
+ );
1715
+ } catch (error) {
1716
+ signal?.throwIfAborted();
1717
+ return environmentFailure(error, context.apiUrl);
1718
+ }
1719
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
1720
+ return failure(
1721
+ "repository_not_connected",
1722
+ `${repository} is not connected to Primitive`,
1723
+ CLOUD_GITHUB_CONNECT_REMEDY
1724
+ );
1725
+ if (answer.status === 401 || answer.status === 403)
1726
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1727
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
1728
+ return failure(
1729
+ "challenge_open",
1730
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
1731
+ `wait five minutes, then ${RETRY_REMEDY}`
1732
+ );
1733
+ if (answer.status === 429)
1734
+ return failure(
1735
+ "too_many_challenges",
1736
+ "too many sessions of this cloud environment are being identified at once",
1737
+ `wait a few minutes, then ${RETRY_REMEDY}`
1738
+ );
1739
+ const challengeId = answer.value?.challengeId;
1740
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
1741
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
1742
+ return answer.status >= 500 ? environmentFailure(
1743
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1744
+ context.apiUrl
1745
+ ) : SERVER_CONTRACT_FAILURE;
1746
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
1747
+ attempt.challengeId = challengeId;
1748
+ attempt.challengeExpiresAt = challengeExpiresAt;
1749
+ return pushSessionBranch(
1750
+ root,
1751
+ repository,
1752
+ branch,
1753
+ baseSha,
1754
+ { challengeId, challengeExpiresAt },
1755
+ signal
1756
+ );
1757
+ }
1758
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
1759
+ const push = await git(
1760
+ root,
1761
+ [
1762
+ "-c",
1763
+ "core.hooksPath=/dev/null",
1764
+ "-c",
1765
+ "push.followTags=false",
1766
+ "-c",
1767
+ "push.recurseSubmodules=no",
1768
+ "-c",
1769
+ "push.gpgSign=false",
1770
+ "-c",
1771
+ "push.pushOption=",
1772
+ "push",
1773
+ "--no-verify",
1774
+ "--no-follow-tags",
1775
+ "--no-recurse-submodules",
1776
+ "--no-signed",
1777
+ "--quiet",
1778
+ "origin",
1779
+ `${baseSha}:refs/heads/${branch}`
1780
+ ],
1781
+ signal
1782
+ );
1783
+ if (!push.ok)
1784
+ return push.timedOut ? failure(
1785
+ "push_timeout",
1786
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
1787
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
1788
+ ) : failure(
1789
+ "push_refused",
1790
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
1791
+ `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}`
1792
+ );
1793
+ return { ...challenge, repository };
1794
+ }
1795
+ async function ensureSessionIdentity(options = {}, deps = {}) {
1796
+ let context;
1797
+ try {
1798
+ context = sessionContext(deps);
1799
+ } catch (error) {
1800
+ return failure(
1801
+ "environment_credential_invalid",
1802
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
1803
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
1804
+ );
1805
+ }
1806
+ if ("status" in context) return context;
1807
+ const ctx = context;
1808
+ const startedAt2 = Date.now();
1809
+ prepareMachineMetadataDirectory(ctx.directory);
1810
+ return withFileLock(
1811
+ ctx.lockPath,
1812
+ async () => {
1813
+ const record = readToken(ctx);
1814
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
1815
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
1816
+ if (record) {
1817
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
1818
+ if (refreshed.status === "ok") {
1819
+ writeToken(ctx, refreshed.record);
1820
+ return identified(refreshed.record, true);
1821
+ }
1822
+ if (refreshed.status === "refused") {
1823
+ rmSync4(ctx.tokenPath, { force: true });
1824
+ writeState(ctx, {
1825
+ sessionId: ctx.sessionId,
1826
+ status: "failed",
1827
+ code: refreshed.failure.code,
1828
+ cause: refreshed.failure.cause,
1829
+ remedy: refreshed.failure.remedy,
1830
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
1831
+ at: Date.now()
1832
+ });
1833
+ return refreshed.failure;
1834
+ }
1835
+ if (!forced && tokenValid(record)) return identified(record, true);
1836
+ }
1837
+ const state = readState(ctx);
1838
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
1839
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
1840
+ if (!options.explicit) {
1841
+ if (!root || !(record || state))
1842
+ return failure(
1843
+ "not_identified",
1844
+ "this session has not identified who started it yet",
1845
+ RETRY_REMEDY
1846
+ );
1847
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
1848
+ } else if (state && state.at >= startedAt2) {
1849
+ return outcomeFromState(state);
1850
+ }
1851
+ if (!root)
1852
+ return failure(
1853
+ "repository_missing",
1854
+ "this is not a git repository",
1855
+ "run it in the repository the session cloned"
1856
+ );
1857
+ const attempt = { root };
1858
+ const remember = (outcome) => {
1859
+ writeState(ctx, {
1860
+ sessionId: ctx.sessionId,
1861
+ status: outcome.status,
1862
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
1863
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
1864
+ githubLogin: outcome.githubLogin
1865
+ },
1866
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
1867
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
1868
+ repositoryRoot: root,
1869
+ branch: attempt.branch ?? state?.branch,
1870
+ baseSha: attempt.baseSha ?? state?.baseSha,
1871
+ at: Date.now()
1872
+ });
1873
+ return outcome;
1874
+ };
1875
+ let challenge;
1876
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
1877
+ attempt.challengeId = state.challengeId;
1878
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
1879
+ attempt.branch = state.branch;
1880
+ attempt.baseSha = state.baseSha;
1881
+ challenge = {
1882
+ challengeId: state.challengeId,
1883
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
1884
+ repository: githubRepositoryFullName(root) ?? "the repository"
1885
+ };
1886
+ } else if (state?.status === "link_required" && state.challengeId) {
1887
+ attempt.challengeId = state.challengeId;
1888
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
1889
+ const exchanged2 = await exchangeChallenge(
1890
+ ctx,
1891
+ {
1892
+ challengeId: state.challengeId,
1893
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
1894
+ githubLogin: state.githubLogin
1895
+ },
1896
+ root,
1897
+ deps,
1898
+ options.signal
1899
+ );
1900
+ if ("status" in exchanged2) return remember(exchanged2);
1901
+ writeToken(ctx, exchanged2);
1902
+ return identified(exchanged2, false);
1903
+ } else if (!options.explicit) {
1904
+ return state ? outcomeFromState(state) : failure(
1905
+ "not_identified",
1906
+ "this session has not identified who started it yet",
1907
+ RETRY_REMEDY
1908
+ );
1909
+ } else {
1910
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
1911
+ if ("status" in pushed) return remember(pushed);
1912
+ challenge = pushed;
1913
+ }
1914
+ const verified = await pollChallenge(
1915
+ ctx.apiUrl,
1916
+ challenge.challengeId,
1917
+ challenge.repository,
1918
+ // A hook process waits only briefly for a late notice.
1919
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
1920
+ options.signal
1921
+ );
1922
+ if ("status" in verified) return remember(verified);
1923
+ const exchanged = await exchangeChallenge(
1924
+ ctx,
1925
+ { ...challenge, githubLogin: verified.githubLogin },
1926
+ root,
1927
+ deps,
1928
+ options.signal
1929
+ );
1930
+ if ("status" in exchanged) return remember(exchanged);
1931
+ writeToken(ctx, exchanged);
1932
+ return identified(exchanged, false);
1933
+ },
1934
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
1935
+ );
1936
+ }
1937
+ async function acquireSessionCredential(options = {}, deps = {}) {
1938
+ const cached2 = cachedSessionCredential(deps);
1939
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
1940
+ if (cached2 && fresh && !options.force) return cached2;
1941
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1942
+ let outcome;
1943
+ try {
1944
+ outcome = await ensureSessionIdentity(
1945
+ { force: options.force, observedToken: cached2?.accessToken, signal },
1946
+ deps
1947
+ );
1948
+ } catch (error) {
1949
+ options.signal?.throwIfAborted();
1950
+ if (error instanceof MachineAuthError) throw error;
1951
+ throw new MachineAuthError(
1952
+ "identity_unavailable",
1953
+ "Identifying who started this cloud session is still in progress; retry shortly."
1954
+ );
1955
+ }
1956
+ if (outcome.status === "ok") return outcome.credential;
1957
+ throw new MachineAuthError(
1958
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
1959
+ sessionIdentityMessage(outcome)
1960
+ );
1961
+ }
1962
+
752
1963
  // src/lib/machine-credentials.ts
1964
+ function sessionScoped(deps) {
1965
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
1966
+ }
753
1967
  var require2 = createRequire(import.meta.url);
754
1968
  var SERVICE = "ai.primitive.prim.machine";
755
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
1969
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
756
1970
  var PROFILE_FILE = "machine_profile.json";
757
- var RENEW_BEFORE_MS = 6e4;
1971
+ var RENEW_BEFORE_MS2 = 6e4;
758
1972
  var cached;
759
1973
  function configurationDirectory(deps) {
760
1974
  return deps.directory ?? primConfigDirectory({ env: deps.env });
761
1975
  }
762
1976
  function apiUrlFor(deps) {
763
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
1977
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
764
1978
  }
765
- function hash(value) {
766
- return createHash2("sha256").update(value).digest("hex");
1979
+ function hash2(value) {
1980
+ return createHash4("sha256").update(value).digest("hex");
767
1981
  }
768
1982
  function recordPath(directory, generation) {
769
- return join5(directory, `machine_${generation}.json`);
1983
+ return join7(directory, `machine_${generation}.json`);
770
1984
  }
771
1985
  function storageKey(directory, generation) {
772
- return `${hash(directory)}:${generation}`;
1986
+ return `${hash2(directory)}:${generation}`;
773
1987
  }
774
1988
  function environmentContextPath(deps, clientId) {
775
- return join5(
1989
+ return join7(
776
1990
  configurationDirectory(deps),
777
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1991
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
778
1992
  );
779
1993
  }
780
1994
  function writeEnvironmentContext(credential, deps) {
@@ -833,14 +2047,14 @@ function readEnvironmentContext(environment, deps) {
833
2047
  }
834
2048
  }
835
2049
  function keyringEntry(key) {
836
- let directory = dirname4(fileURLToPath2(import.meta.url));
2050
+ let directory = dirname5(fileURLToPath2(import.meta.url));
837
2051
  for (let depth = 0; depth < 5; depth++) {
838
- const loader = join5(directory, "native", "keyring.cjs");
2052
+ const loader = join7(directory, "native", "keyring.cjs");
839
2053
  if (existsSync3(loader)) {
840
2054
  const module2 = require2(loader);
841
2055
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
842
2056
  }
843
- directory = dirname4(directory);
2057
+ directory = dirname5(directory);
844
2058
  }
845
2059
  const module = require2("@napi-rs/keyring");
846
2060
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -852,7 +2066,7 @@ function protectPath(path, directory) {
852
2066
  }
853
2067
  const encodedPath = Buffer.from(path).toString("base64");
854
2068
  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)`;
855
- execFileSync(
2069
+ execFileSync2(
856
2070
  "powershell.exe",
857
2071
  [
858
2072
  "-NoProfile",
@@ -865,7 +2079,7 @@ function protectPath(path, directory) {
865
2079
  }
866
2080
  function ensureDirectory(directory) {
867
2081
  mkdirSync3(directory, { recursive: true, mode: 448 });
868
- if (lstatSync2(directory).isSymbolicLink())
2082
+ if (lstatSync3(directory).isSymbolicLink())
869
2083
  throw new MachineAuthError(
870
2084
  "unsafe_storage",
871
2085
  "Credential directory must not be a symbolic link."
@@ -877,17 +2091,20 @@ function writePrivate(path, value) {
877
2091
  `, { mode: 384 });
878
2092
  protectPath(path, false);
879
2093
  }
2094
+ function readMachineMetadata(path) {
2095
+ return readPrivate(path);
2096
+ }
880
2097
  function readPrivate(path) {
881
2098
  let raw;
882
2099
  try {
883
- const stat = lstatSync2(path);
2100
+ const stat = lstatSync3(path);
884
2101
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
885
2102
  throw new MachineAuthError(
886
2103
  "unsafe_storage",
887
2104
  "Machine credential files must be owner-only regular files."
888
2105
  );
889
2106
  }
890
- raw = readFileSync4(path, "utf8");
2107
+ raw = readFileSync5(path, "utf8");
891
2108
  } catch (error) {
892
2109
  if (error.code === "ENOENT") return void 0;
893
2110
  throw error;
@@ -932,13 +2149,101 @@ function parseProfile(value) {
932
2149
  };
933
2150
  }
934
2151
  function readMachineProfile(deps = {}) {
935
- const value = readPrivate(join5(configurationDirectory(deps), PROFILE_FILE));
2152
+ const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
936
2153
  return value === void 0 ? void 0 : parseProfile(value);
937
2154
  }
2155
+ var NETWORK_SECRET_AUTH = "network-secret";
2156
+ var NETWORK_TOKEN_AUTH = "network-token";
2157
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2158
+ var brokerKeys = /* @__PURE__ */ new Map();
2159
+ function networkSecretBrokerKey(deps, clientId) {
2160
+ const directory = configurationDirectory(deps);
2161
+ const path = join7(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2162
+ const known = brokerKeys.get(path);
2163
+ if (known) return known;
2164
+ ensureDirectory(directory);
2165
+ const read = () => {
2166
+ try {
2167
+ const stat = lstatSync3(path);
2168
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2169
+ throw new MachineAuthError(
2170
+ "unsafe_storage",
2171
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2172
+ true
2173
+ );
2174
+ const value = readFileSync5(path, "utf8").trim();
2175
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2176
+ } catch (error) {
2177
+ if (error.code === "ENOENT") return void 0;
2178
+ throw error;
2179
+ }
2180
+ };
2181
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2182
+ const existing = read();
2183
+ if (existing?.key) {
2184
+ brokerKeys.set(path, existing.key);
2185
+ return existing.key;
2186
+ }
2187
+ if (existing)
2188
+ throw new MachineAuthError(
2189
+ "unsafe_storage",
2190
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2191
+ true
2192
+ );
2193
+ const staged = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}`;
2194
+ try {
2195
+ writeFileSync3(staged, `${randomBytes2(32).toString("hex")}
2196
+ `, { mode: 384, flag: "wx" });
2197
+ protectPath(staged, false);
2198
+ linkSync(staged, path);
2199
+ } catch (error) {
2200
+ if (error.code !== "EEXIST") throw error;
2201
+ } finally {
2202
+ rmSync5(staged, { force: true });
2203
+ }
2204
+ }
2205
+ const key = read()?.key;
2206
+ if (!key)
2207
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2208
+ brokerKeys.set(path, key);
2209
+ return key;
2210
+ }
938
2211
  function environmentCredentials(deps) {
939
2212
  const env = deps.env ?? process.env;
940
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
941
- if (clientId === void 0 && clientSecret === void 0) return void 0;
2213
+ const {
2214
+ PRIM_M2M_CLIENT_ID: clientId,
2215
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2216
+ PRIM_M2M_CLIENT_AUTH: auth
2217
+ } = env;
2218
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2219
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2220
+ throw new MachineAuthError(
2221
+ "incomplete_machine_credentials",
2222
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2223
+ );
2224
+ if (auth !== void 0) {
2225
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2226
+ throw new MachineAuthError(
2227
+ "incomplete_machine_credentials",
2228
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2229
+ );
2230
+ if (clientSecret !== void 0)
2231
+ throw new MachineAuthError(
2232
+ "conflicting_credentials",
2233
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2234
+ );
2235
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2236
+ const credentials = {
2237
+ clientId,
2238
+ generation,
2239
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2240
+ };
2241
+ Object.defineProperty(credentials, "clientSecret", {
2242
+ enumerable: true,
2243
+ get: () => networkSecretBrokerKey(deps, clientId)
2244
+ });
2245
+ return credentials;
2246
+ }
942
2247
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
943
2248
  throw new MachineAuthError(
944
2249
  "incomplete_machine_credentials",
@@ -948,12 +2253,12 @@ function environmentCredentials(deps) {
948
2253
  return {
949
2254
  clientId,
950
2255
  clientSecret,
951
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2256
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
952
2257
  };
953
2258
  }
954
2259
  function hasMachineConfiguration(deps = {}) {
955
2260
  const env = deps.env ?? process.env;
956
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join5(configurationDirectory(deps), PROFILE_FILE));
2261
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join7(configurationDirectory(deps), PROFILE_FILE));
957
2262
  if (configured && env.PRIM_TOKEN?.trim()) {
958
2263
  throw new MachineAuthError(
959
2264
  "conflicting_credentials",
@@ -965,6 +2270,7 @@ function hasMachineConfiguration(deps = {}) {
965
2270
  }
966
2271
  function machineContext(deps = {}) {
967
2272
  if (!hasMachineConfiguration(deps)) return void 0;
2273
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
968
2274
  const environment = environmentCredentials(deps);
969
2275
  if (environment) {
970
2276
  if (environmentTerminal === environment.generation) return void 0;
@@ -979,6 +2285,7 @@ function machineContext(deps = {}) {
979
2285
  return profile;
980
2286
  }
981
2287
  function cachedMachineCredential(deps = {}) {
2288
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
982
2289
  const context = machineContext(deps);
983
2290
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
984
2291
  }
@@ -987,9 +2294,11 @@ function machineSessionEnded(deps = {}) {
987
2294
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
988
2295
  if (!generation) return false;
989
2296
  if (environmentCredentials(deps)) return environmentTerminal === generation;
990
- return readPrivate(join5(configurationDirectory(deps), "machine_terminal.json")) === generation;
2297
+ return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
991
2298
  }
992
2299
  var environmentTerminal;
2300
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2301
+ var networkRejection;
993
2302
  async function loadRecord(profile, deps, signal) {
994
2303
  const directory = configurationDirectory(deps);
995
2304
  let value;
@@ -1049,10 +2358,12 @@ async function persistRecord(record, deps, signal) {
1049
2358
  }
1050
2359
  async function acquireMachineCredential(options = {}, deps = {}) {
1051
2360
  if (!hasMachineConfiguration(deps)) return void 0;
2361
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1052
2362
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1053
2363
  const apiUrl = apiUrlFor(deps);
1054
2364
  const environment = environmentCredentials(deps);
1055
2365
  if (environment) {
2366
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
1056
2367
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
1057
2368
  const directory2 = configurationDirectory(deps);
1058
2369
  ensureDirectory(directory2);
@@ -1070,22 +2381,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1070
2381
  writeEnvironmentContext(cached, deps);
1071
2382
  return cached;
1072
2383
  } catch (error) {
1073
- if (error instanceof MachineAuthError && error.terminal)
2384
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
1074
2385
  environmentTerminal = environment.generation;
1075
2386
  throw error;
1076
2387
  }
1077
2388
  }
1078
2389
  return withFileLock(
1079
- join5(directory2, "credentials.lock"),
2390
+ join7(directory2, "credentials.lock"),
1080
2391
  async () => {
1081
2392
  if (machineSessionEnded(deps))
1082
2393
  throw new MachineAuthError(
1083
2394
  "machine_credentials_rejected",
1084
- "Rotate the injected machine credentials.",
2395
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1085
2396
  true
1086
2397
  );
1087
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2398
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1088
2399
  return cached;
2400
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2401
+ throw networkRejection.error;
1089
2402
  try {
1090
2403
  const { configuration, tokens, identity } = await withMachineCooldown(
1091
2404
  directory2,
@@ -1094,13 +2407,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1094
2407
  signal,
1095
2408
  async () => {
1096
2409
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2410
+ if (environment.tokenInjection) {
2411
+ const identity3 = await verifyInjectedMachineIdentity(
2412
+ apiUrl,
2413
+ environment.clientId,
2414
+ signal,
2415
+ deps.fetch
2416
+ );
2417
+ const tokens3 = {
2418
+ accessToken: "",
2419
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2420
+ };
2421
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2422
+ }
1097
2423
  const tokens2 = await exchangeMachineCredentials(
1098
2424
  configuration2,
1099
2425
  environment.clientId,
1100
- environment.clientSecret,
2426
+ // The broker key is not a client secret; the proxy supplies that.
2427
+ environment.secretInjection ? "" : environment.clientSecret,
1101
2428
  signal,
1102
- deps.fetch
1103
- );
2429
+ deps.fetch,
2430
+ { secretInjection: environment.secretInjection }
2431
+ ).catch((error) => {
2432
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2433
+ throw new MachineAuthError(
2434
+ "network_secret_mismatch",
2435
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2436
+ true
2437
+ );
2438
+ throw error;
2439
+ });
1104
2440
  const identity2 = await verifyMachineIdentity(
1105
2441
  apiUrl,
1106
2442
  tokens2.accessToken,
@@ -1117,17 +2453,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1117
2453
  ...identity,
1118
2454
  apiUrl,
1119
2455
  generation: environment.generation,
1120
- storage: "environment"
2456
+ storage: "environment",
2457
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
1121
2458
  };
1122
2459
  writeEnvironmentContext(cached, deps);
1123
2460
  return cached;
1124
2461
  } catch (error) {
2462
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2463
+ networkRejection = {
2464
+ generation: environment.generation,
2465
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2466
+ error
2467
+ };
2468
+ if (cached?.generation === environment.generation) cached = void 0;
2469
+ const contextPath = environmentContextPath(deps, environment.clientId);
2470
+ try {
2471
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2472
+ rmSync5(contextPath, { force: true });
2473
+ } catch {
2474
+ }
2475
+ throw error;
2476
+ }
1125
2477
  if (error instanceof MachineAuthError && error.terminal) {
1126
2478
  environmentTerminal = environment.generation;
1127
2479
  const contextPath = environmentContextPath(deps, environment.clientId);
1128
2480
  try {
1129
2481
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1130
- rmSync4(contextPath, { force: true });
2482
+ rmSync5(contextPath, { force: true });
1131
2483
  } catch {
1132
2484
  }
1133
2485
  }
@@ -1141,7 +2493,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1141
2493
  const expected = machineContext(deps);
1142
2494
  const directory = configurationDirectory(deps);
1143
2495
  return withFileLock(
1144
- join5(directory, "credentials.lock"),
2496
+ join7(directory, "credentials.lock"),
1145
2497
  async () => {
1146
2498
  const profile = readMachineProfile(deps);
1147
2499
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1156,7 +2508,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1156
2508
  true
1157
2509
  );
1158
2510
  let record = await loadRecord(profile, deps, signal);
1159
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2511
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1160
2512
  try {
1161
2513
  const { tokens, identity } = await withMachineCooldown(
1162
2514
  directory,
@@ -1191,7 +2543,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1191
2543
  await persistRecord(record, deps, signal);
1192
2544
  } catch (error) {
1193
2545
  if (error instanceof MachineAuthError && error.terminal)
1194
- writePrivate(join5(directory, "machine_terminal.json"), profile.generation);
2546
+ writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
1195
2547
  throw error;
1196
2548
  }
1197
2549
  }
@@ -1202,35 +2554,73 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1202
2554
  { signal }
1203
2555
  );
1204
2556
  }
2557
+ async function forwardMachineRequest(request3, signal, deps = {}) {
2558
+ const environment = environmentCredentials(deps);
2559
+ if (!environment?.tokenInjection)
2560
+ throw new MachineAuthError(
2561
+ "identity_changed",
2562
+ "Machine identity changed; restart the operation."
2563
+ );
2564
+ const directory = configurationDirectory(deps);
2565
+ ensureDirectory(directory);
2566
+ return forwardBrokerRequest({
2567
+ directory,
2568
+ apiUrl: apiUrlFor(deps),
2569
+ environment,
2570
+ env: deps.env ?? process.env,
2571
+ request: request3,
2572
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2573
+ });
2574
+ }
1205
2575
  function machineJournalBucket(identity) {
1206
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2576
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2577
+ }
2578
+ function identityPending(actor) {
2579
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
2580
+ }
2581
+ function machinePendingBucket(identity) {
2582
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
2583
+ }
2584
+ function prepareMachineMetadataDirectory(directory) {
2585
+ ensureDirectory(directory);
2586
+ }
2587
+ function writeMachineMetadata(path, value) {
2588
+ writePrivate(path, value);
1207
2589
  }
1208
2590
 
1209
2591
  // src/lib/machine-broker.ts
1210
2592
  var MAX_RESPONSE_BYTES = 96 * 1024;
2593
+ var MAX_CREDENTIAL_REQUEST_BYTES = 2048;
2594
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
2595
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
2596
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
2597
+ var FORWARD_REQUEST_PROOF = "forward-request";
2598
+ var FORWARD_ANSWER_PROOF = "forward-answer";
2599
+ var FORWARD_TIMEOUT_MS = 3e4;
2600
+ var FORWARD_METHODS = ["GET", "POST", "DELETE"];
1211
2601
  var IDLE_MS = 5 * 6e4;
1212
2602
  function descriptorPath(directory, generation) {
1213
- return join6(directory, `machine_broker_${generation}.json`);
2603
+ return join8(directory, `machine_broker_${generation}.json`);
1214
2604
  }
1215
2605
  function readDescriptor(path) {
1216
2606
  try {
1217
- const stat = lstatSync3(path);
2607
+ const stat = lstatSync4(path);
1218
2608
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1219
2609
  return void 0;
1220
- const data = JSON.parse(readFileSync5(path, "utf8"));
2610
+ const data = JSON.parse(readFileSync6(path, "utf8"));
1221
2611
  return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
1222
2612
  } catch {
1223
2613
  return void 0;
1224
2614
  }
1225
2615
  }
1226
- function signature(secret, nonce, body) {
1227
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
2616
+ function signature(secret, nonce, body, purpose) {
2617
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
1228
2618
  }
1229
2619
  function matches(left, right) {
1230
2620
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
1231
2621
  }
1232
2622
  function tokenHash(token) {
1233
- return token ? createHash3("sha256").update(token).digest("hex") : void 0;
2623
+ return token ? createHash5("sha256").update(token).digest("hex") : void 0;
1234
2624
  }
1235
2625
  async function brokerRequest(descriptor, environment, options) {
1236
2626
  const body = JSON.stringify({
@@ -1239,10 +2629,9 @@ async function brokerRequest(descriptor, environment, options) {
1239
2629
  observedTokenHash: tokenHash(options.observedToken),
1240
2630
  timestamp: Date.now()
1241
2631
  });
1242
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
2632
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1243
2633
  method: "POST",
1244
2634
  body,
1245
- redirect: "error",
1246
2635
  signal: options.signal,
1247
2636
  headers: {
1248
2637
  "Content-Type": "application/json",
@@ -1273,6 +2662,15 @@ async function brokerRequest(descriptor, environment, options) {
1273
2662
  );
1274
2663
  return credential;
1275
2664
  }
2665
+ function brokerEnvironment(options) {
2666
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
2667
+ return {
2668
+ ...options.env,
2669
+ PRIM_API_URL: options.apiUrl,
2670
+ PRIM_CONFIG_DIR: options.directory,
2671
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
2672
+ };
2673
+ }
1276
2674
  async function acquireBrokerCredential(options) {
1277
2675
  const path = descriptorPath(options.directory, options.environment.generation);
1278
2676
  const existing = readDescriptor(path);
@@ -1284,15 +2682,28 @@ async function acquireBrokerCredential(options) {
1284
2682
  if (error instanceof MachineAuthError) throw error;
1285
2683
  }
1286
2684
  }
1287
- const descriptor = await withFileLock(
1288
- join6(options.directory, "machine-broker.lock"),
2685
+ const descriptor = await ensureBroker(options);
2686
+ try {
2687
+ return await brokerRequest(descriptor, options.environment, options);
2688
+ } catch (error) {
2689
+ options.signal.throwIfAborted();
2690
+ if (error instanceof MachineAuthError) throw error;
2691
+ throw new MachineAuthError(
2692
+ "broker_unavailable",
2693
+ "Machine credential broker is unavailable. Retry the command."
2694
+ );
2695
+ }
2696
+ }
2697
+ async function ensureBroker(options) {
2698
+ const path = descriptorPath(options.directory, options.environment.generation);
2699
+ return withFileLock(
2700
+ join8(options.directory, "machine-broker.lock"),
1289
2701
  async () => {
1290
2702
  const current = readDescriptor(path);
1291
2703
  if (current) {
1292
2704
  try {
1293
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
1294
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
1295
- redirect: "error"
2705
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
2706
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
1296
2707
  });
1297
2708
  if (response.ok && await response.text() === current.nonce) return current;
1298
2709
  } catch {
@@ -1300,7 +2711,7 @@ async function acquireBrokerCredential(options) {
1300
2711
  }
1301
2712
  }
1302
2713
  const bundled = fileURLToPath3(import.meta.url);
1303
- const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
2714
+ const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
1304
2715
  if (!entry)
1305
2716
  throw new MachineAuthError(
1306
2717
  "broker_unavailable",
@@ -1311,7 +2722,7 @@ async function acquireBrokerCredential(options) {
1311
2722
  detached: true,
1312
2723
  stdio: ["ignore", "ignore", "ignore", "ipc"],
1313
2724
  windowsHide: true,
1314
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
2725
+ env: brokerEnvironment(options)
1315
2726
  });
1316
2727
  let settled = false;
1317
2728
  const finish = (error) => {
@@ -1363,44 +2774,202 @@ async function acquireBrokerCredential(options) {
1363
2774
  },
1364
2775
  { signal: options.signal }
1365
2776
  );
2777
+ }
2778
+ async function forwardOnce(descriptor, environment, request3, signal) {
2779
+ const body = JSON.stringify({
2780
+ generation: environment.generation,
2781
+ timestamp: Date.now(),
2782
+ method: request3.method,
2783
+ path: request3.path,
2784
+ headers: request3.headers ?? {},
2785
+ ...request3.body === void 0 ? {} : { body: request3.body }
2786
+ });
2787
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
2788
+ method: "POST",
2789
+ body,
2790
+ signal,
2791
+ headers: {
2792
+ "Content-Type": "application/json",
2793
+ "X-Prim-Proof": signature(
2794
+ environment.clientSecret,
2795
+ descriptor.nonce,
2796
+ body,
2797
+ FORWARD_REQUEST_PROOF
2798
+ )
2799
+ }
2800
+ });
2801
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
2802
+ if (typeof envelope.body !== "string" || !matches(
2803
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
2804
+ envelope.proof
2805
+ ))
2806
+ throw new MachineAuthError(
2807
+ "broker_unavailable",
2808
+ "Machine credential broker could not be authenticated. Retry the command."
2809
+ );
2810
+ const data = machineRecord(JSON.parse(envelope.body));
2811
+ if (data.error) {
2812
+ const error = machineRecord(data.error);
2813
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
2814
+ }
2815
+ const status = data.status;
2816
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
2817
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
2818
+ const headers = new Headers();
2819
+ for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
2820
+ if (typeof value === "string") headers.set(name, value);
2821
+ const text = typeof data.body === "string" ? data.body : "";
2822
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
2823
+ }
2824
+ async function forwardBrokerRequest(options) {
2825
+ const path = descriptorPath(options.directory, options.environment.generation);
2826
+ const unavailable = () => new MachineAuthError(
2827
+ "broker_unavailable",
2828
+ "Machine credential broker is unavailable. Retry the command."
2829
+ );
2830
+ const existing = readDescriptor(path);
2831
+ if (existing) {
2832
+ try {
2833
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
2834
+ } catch (error) {
2835
+ options.signal.throwIfAborted();
2836
+ if (error instanceof MachineAuthError) throw error;
2837
+ if (error.code !== "ECONNREFUSED") throw unavailable();
2838
+ }
2839
+ }
2840
+ const descriptor = await ensureBroker(options);
1366
2841
  try {
1367
- return await brokerRequest(descriptor, options.environment, options);
2842
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
1368
2843
  } catch (error) {
1369
2844
  options.signal.throwIfAborted();
1370
2845
  if (error instanceof MachineAuthError) throw error;
1371
- throw new MachineAuthError(
1372
- "broker_unavailable",
1373
- "Machine credential broker is unavailable. Retry the command."
2846
+ throw unavailable();
2847
+ }
2848
+ }
2849
+ function forwardableHeaders(value) {
2850
+ const headers = {};
2851
+ if (!value || typeof value !== "object" || Array.isArray(value)) return headers;
2852
+ for (const [name, content] of Object.entries(value)) {
2853
+ const lower = name.toLowerCase();
2854
+ if (typeof content === "string" && content.length <= 256 && !/[\p{Cc}]/u.test(content) && (lower === "content-type" || /^x-prim-[a-z0-9-]+$/u.test(lower)))
2855
+ headers[name] = content;
2856
+ }
2857
+ return headers;
2858
+ }
2859
+ async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
2860
+ const refuse = (message) => ({
2861
+ error: { code: "invalid_request", message, terminal: false }
2862
+ });
2863
+ if (typeof data.method !== "string" || !FORWARD_METHODS.includes(data.method))
2864
+ return refuse("The forwarded request's method is not allowed.");
2865
+ if (data.body !== void 0 && typeof data.body !== "string")
2866
+ return refuse("The forwarded request's body is not text.");
2867
+ let target;
2868
+ try {
2869
+ if (typeof data.path !== "string" || !data.path.startsWith("/")) throw new Error("path");
2870
+ target = new URL(data.path, `${apiUrl}/`);
2871
+ if (target.origin !== apiUrl || target.username || target.password) throw new Error("origin");
2872
+ } catch {
2873
+ return refuse("The forwarded request does not target the configured API.");
2874
+ }
2875
+ try {
2876
+ const answer = await fetchImpl(target, {
2877
+ method: data.method,
2878
+ headers: forwardableHeaders(data.headers),
2879
+ body: data.method === "GET" ? void 0 : data.body,
2880
+ redirect: "error",
2881
+ signal: AbortSignal.any([signal, AbortSignal.timeout(FORWARD_TIMEOUT_MS)])
2882
+ });
2883
+ const headers = {};
2884
+ for (const name of ["content-type", "retry-after"]) {
2885
+ const value = answer.headers.get(name);
2886
+ if (value) headers[name] = value;
2887
+ }
2888
+ const chunks = [];
2889
+ let received = 0;
2890
+ if (answer.body)
2891
+ for await (const chunk of answer.body) {
2892
+ received += chunk.length;
2893
+ if (received > MAX_API_RESPONSE_BYTES)
2894
+ return {
2895
+ error: {
2896
+ code: "invalid_response",
2897
+ message: "The API answered with more than prim accepts.",
2898
+ terminal: false
2899
+ }
2900
+ };
2901
+ chunks.push(chunk);
2902
+ }
2903
+ return { status: answer.status, headers, body: Buffer.concat(chunks).toString("utf8") };
2904
+ } catch (error) {
2905
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
2906
+ return {
2907
+ error: {
2908
+ code: timedOut ? "request_timeout" : "authentication_unavailable",
2909
+ message: timedOut ? "Primitive did not answer through the cloud environment's proxy in time. The request may or may not have been applied." : "The request to Primitive through the cloud environment's proxy failed. Check the connection and retry.",
2910
+ terminal: false
2911
+ }
2912
+ };
2913
+ }
2914
+ }
2915
+ async function credentialResult(apiUrl, data, signal) {
2916
+ try {
2917
+ const current = cachedMachineCredential({ localEnvironment: true });
2918
+ const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
2919
+ const credential = await acquireMachineCredential(
2920
+ { force, signal },
2921
+ { localEnvironment: true }
1374
2922
  );
2923
+ if (!credential || credential.apiUrl !== apiUrl) throw new Error("Missing machine identity");
2924
+ return { credential };
2925
+ } catch (error) {
2926
+ return {
2927
+ error: error instanceof MachineAuthError ? {
2928
+ code: error.code,
2929
+ message: error.message,
2930
+ terminal: error.terminal,
2931
+ retryAt: error.retryAt
2932
+ } : {
2933
+ code: "broker_unavailable",
2934
+ message: "Machine authentication is temporarily unavailable.",
2935
+ terminal: false
2936
+ }
2937
+ };
1375
2938
  }
1376
2939
  }
1377
- async function startMachineBroker() {
1378
- const environment = environmentCredentials({});
1379
- if (!environment) throw new Error("Machine broker requires injected credentials");
1380
- const directory = primConfigDirectory();
1381
- const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
1382
- const path = descriptorPath(directory, environment.generation);
1383
- const nonce = randomBytes2(32).toString("hex");
1384
- const server = createServer(async (request2, response) => {
2940
+ function createBrokerServer(options) {
2941
+ const { environment, apiUrl, nonce } = options;
2942
+ const server = createServer(async (request3, response) => {
1385
2943
  response.setHeader("Cache-Control", "no-store");
1386
- if (request2.method === "GET" && request2.url === "/health") {
2944
+ if (request3.method === "GET" && request3.url === "/health") {
1387
2945
  response.end(nonce);
1388
2946
  return;
1389
2947
  }
1390
- if (request2.method !== "POST" || request2.url !== "/credential") {
2948
+ const forwarding = request3.url === "/forward" && environment.tokenInjection === "network";
2949
+ if (request3.method !== "POST" || request3.url !== "/credential" && !forwarding) {
1391
2950
  response.writeHead(404).end();
1392
2951
  return;
1393
2952
  }
1394
- let raw = "";
2953
+ const limit = forwarding ? MAX_FORWARD_REQUEST_BYTES : MAX_CREDENTIAL_REQUEST_BYTES;
1395
2954
  try {
1396
- for await (const chunk of request2) {
1397
- raw += chunk.toString();
1398
- if (Buffer.byteLength(raw) > 2048) {
2955
+ const chunks = [];
2956
+ let received = 0;
2957
+ for await (const chunk of request3) {
2958
+ received += chunk.length;
2959
+ if (received > limit) {
1399
2960
  response.writeHead(413).end();
1400
2961
  return;
1401
2962
  }
2963
+ chunks.push(chunk);
1402
2964
  }
1403
- if (!matches(signature(environment.clientSecret, nonce, raw), request2.headers["x-prim-proof"])) {
2965
+ const raw = Buffer.concat(chunks).toString("utf8");
2966
+ const proof = signature(
2967
+ environment.clientSecret,
2968
+ nonce,
2969
+ raw,
2970
+ forwarding ? FORWARD_REQUEST_PROOF : void 0
2971
+ );
2972
+ if (!matches(proof, request3.headers["x-prim-proof"])) {
1404
2973
  response.writeHead(403).end();
1405
2974
  return;
1406
2975
  }
@@ -1409,40 +2978,24 @@ async function startMachineBroker() {
1409
2978
  response.writeHead(403).end();
1410
2979
  return;
1411
2980
  }
1412
- idle.refresh();
2981
+ options.onRequest?.();
1413
2982
  const controller = new AbortController();
1414
2983
  response.once("close", () => {
1415
2984
  if (!response.writableFinished) controller.abort();
1416
2985
  });
1417
- let result;
1418
- try {
1419
- const current = cachedMachineCredential();
1420
- const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
1421
- const credential = await acquireMachineCredential(
1422
- { force, signal: controller.signal },
1423
- { localEnvironment: true }
1424
- );
1425
- if (!credential || credential.apiUrl !== apiUrl)
1426
- throw new Error("Missing machine identity");
1427
- result = { credential };
1428
- } catch (error) {
1429
- result = {
1430
- error: error instanceof MachineAuthError ? {
1431
- code: error.code,
1432
- message: error.message,
1433
- terminal: error.terminal,
1434
- retryAt: error.retryAt
1435
- } : {
1436
- code: "broker_unavailable",
1437
- message: "Machine authentication is temporarily unavailable.",
1438
- terminal: false
1439
- }
1440
- };
1441
- }
2986
+ const result = forwarding ? await forwardToApi(apiUrl, data, controller.signal) : await credentialResult(apiUrl, data, controller.signal);
1442
2987
  const body = JSON.stringify(result);
1443
2988
  response.setHeader("Content-Type", "application/json");
1444
2989
  response.end(
1445
- JSON.stringify({ body, proof: signature(environment.clientSecret, nonce, body) })
2990
+ JSON.stringify({
2991
+ body,
2992
+ proof: signature(
2993
+ environment.clientSecret,
2994
+ nonce,
2995
+ body,
2996
+ forwarding ? FORWARD_ANSWER_PROOF : void 0
2997
+ )
2998
+ })
1446
2999
  );
1447
3000
  } catch {
1448
3001
  response.writeHead(400).end();
@@ -1451,11 +3004,26 @@ async function startMachineBroker() {
1451
3004
  server.maxConnections = 64;
1452
3005
  server.requestTimeout = 1e4;
1453
3006
  server.headersTimeout = 1e4;
3007
+ return server;
3008
+ }
3009
+ async function startMachineBroker() {
3010
+ const environment = environmentCredentials({});
3011
+ if (!environment) throw new Error("Machine broker requires injected credentials");
3012
+ const directory = primConfigDirectory();
3013
+ const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
3014
+ const path = descriptorPath(directory, environment.generation);
3015
+ const nonce = randomBytes3(32).toString("hex");
3016
+ const server = createBrokerServer({
3017
+ environment,
3018
+ apiUrl,
3019
+ nonce,
3020
+ onRequest: () => idle.refresh()
3021
+ });
1454
3022
  const close = () => {
1455
3023
  clearTimeout(idle);
1456
3024
  server.closeAllConnections();
1457
3025
  server.close();
1458
- if (readDescriptor(path)?.nonce === nonce) rmSync5(path, { force: true });
3026
+ if (readDescriptor(path)?.nonce === nonce) rmSync6(path, { force: true });
1459
3027
  };
1460
3028
  const idle = setTimeout(close, IDLE_MS);
1461
3029
  process.once("SIGTERM", close);
@@ -1473,27 +3041,27 @@ async function startMachineBroker() {
1473
3041
  }
1474
3042
 
1475
3043
  // src/daemon/principal.ts
1476
- import { createHash as createHash5 } from "crypto";
3044
+ import { createHash as createHash7 } from "crypto";
1477
3045
 
1478
3046
  // src/lib/credentials.ts
1479
- import { createHash as createHash4 } from "crypto";
1480
- import { readFileSync as readFileSync6 } from "fs";
1481
- import { join as join7 } from "path";
3047
+ import { createHash as createHash6 } from "crypto";
3048
+ import { readFileSync as readFileSync7 } from "fs";
3049
+ import { join as join9 } from "path";
1482
3050
  var CONFIG_DIRECTORY = primConfigDirectory();
1483
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1484
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1485
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1486
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1487
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1488
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1489
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1490
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3051
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
3052
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
3053
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
3054
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
3055
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
3056
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
3057
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
3058
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1491
3059
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1492
3060
  var CREDENTIAL_MIGRATION_VERSION = 1;
1493
3061
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1494
3062
  function readTrimmed(path) {
1495
3063
  try {
1496
- const value = readFileSync6(path, "utf8").trim();
3064
+ const value = readFileSync7(path, "utf8").trim();
1497
3065
  return value || void 0;
1498
3066
  } catch {
1499
3067
  return void 0;
@@ -1502,7 +3070,7 @@ function readTrimmed(path) {
1502
3070
  function resolveAuthCredential(options = {}) {
1503
3071
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
1504
3072
  const machine = cachedMachineCredential({ env: options.env });
1505
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
3073
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
1506
3074
  }
1507
3075
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
1508
3076
  if (envToken) return { token: envToken, source: "environment" };
@@ -1515,22 +3083,22 @@ function resolveAuthCredential(options = {}) {
1515
3083
  );
1516
3084
  if (metadata.state === "legacy_broker") {
1517
3085
  if (metadata.metadata) {
1518
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1519
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3086
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3087
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1520
3088
  return void 0;
1521
3089
  }
1522
3090
  }
1523
3091
  return { token: stored, source: "token_file" };
1524
3092
  }
1525
3093
  if (metadata.state === "invalid") return void 0;
1526
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1527
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3094
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3095
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1528
3096
  return void 0;
1529
3097
  }
1530
3098
  return { token: stored, source: "token_file" };
1531
3099
  }
1532
3100
  function credentialFingerprint(value) {
1533
- return createHash4("sha256").update(value).digest("hex");
3101
+ return createHash6("sha256").update(value).digest("hex");
1534
3102
  }
1535
3103
  function parseLegacyBrokerCredentialMetadata(value) {
1536
3104
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1550,7 +3118,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1550
3118
  function readBoundedCredentialJson(path) {
1551
3119
  let raw;
1552
3120
  try {
1553
- raw = readFileSync6(path, "utf8");
3121
+ raw = readFileSync7(path, "utf8");
1554
3122
  } catch (error) {
1555
3123
  return error.code === "ENOENT" ? void 0 : null;
1556
3124
  }
@@ -1628,7 +3196,7 @@ function boundedClaim(value) {
1628
3196
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
1629
3197
  }
1630
3198
  function sha256(value) {
1631
- return createHash5("sha256").update(value).digest("hex");
3199
+ return createHash7("sha256").update(value).digest("hex");
1632
3200
  }
1633
3201
  function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
1634
3202
  if (hasMachineConfiguration()) {
@@ -1711,9 +3279,9 @@ function parseDaemonResponseEnvelope(value) {
1711
3279
  }
1712
3280
 
1713
3281
  // src/daemon/server.ts
1714
- import { chmodSync as chmodSync8, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync13, unlinkSync as unlinkSync3 } from "fs";
3282
+ import { chmodSync as chmodSync8, existsSync as existsSync12, mkdirSync as mkdirSync10, readFileSync as readFileSync15, unlinkSync as unlinkSync3 } from "fs";
1715
3283
  import { createServer as createServer2 } from "net";
1716
- import { join as join18 } from "path";
3284
+ import { join as join21 } from "path";
1717
3285
  import { fileURLToPath as fileURLToPath4 } from "url";
1718
3286
 
1719
3287
  // src/decisions/identity.ts
@@ -1794,14 +3362,14 @@ function publicDecisionResponse(value) {
1794
3362
  }
1795
3363
 
1796
3364
  // src/client.ts
1797
- import { createHash as createHash6 } from "crypto";
1798
- import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
1799
- import { dirname as dirname5 } from "path";
3365
+ import { createHash as createHash8 } from "crypto";
3366
+ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
3367
+ import { dirname as dirname6 } from "path";
1800
3368
 
1801
3369
  // src/daemon/client-instance-id.ts
1802
- import { randomBytes as randomBytes3 } from "crypto";
1803
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
1804
- import { join as join8 } from "path";
3370
+ import { randomBytes as randomBytes4 } from "crypto";
3371
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
3372
+ import { join as join10 } from "path";
1805
3373
  var CONFIG_DIRECTORY_MODE = 448;
1806
3374
  var INSTANCE_FILE_MODE = 384;
1807
3375
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -1814,7 +3382,7 @@ function isClientInstanceId(value) {
1814
3382
  }
1815
3383
  function ensurePrivateConfigDirectory(configDir) {
1816
3384
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
1817
- const metadata = lstatSync4(configDir);
3385
+ const metadata = lstatSync5(configDir);
1818
3386
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
1819
3387
  throw new Error("prim config path must be a private directory");
1820
3388
  }
@@ -1824,7 +3392,7 @@ function ensurePrivateConfigDirectory(configDir) {
1824
3392
  function readExisting(path) {
1825
3393
  let metadata;
1826
3394
  try {
1827
- metadata = lstatSync4(path);
3395
+ metadata = lstatSync5(path);
1828
3396
  } catch (error) {
1829
3397
  if (error.code === "ENOENT") {
1830
3398
  return;
@@ -1838,7 +3406,7 @@ function readExisting(path) {
1838
3406
  if (metadata.size > MAX_STORED_BYTES) {
1839
3407
  throw new Error("stored client instance identity is invalid");
1840
3408
  }
1841
- const raw = readFileSync7(path, "utf8");
3409
+ const raw = readFileSync8(path, "utf8");
1842
3410
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
1843
3411
  if (raw !== value && raw !== `${value}
1844
3412
  ` || !isClientInstanceId(value)) {
@@ -1852,8 +3420,8 @@ function atomicWrite(path, value) {
1852
3420
  }
1853
3421
  async function getOrCreateClientInstanceId(options) {
1854
3422
  const configDir = options.configDir;
1855
- const path = join8(configDir, "client_instance_id");
1856
- const lockPath = join8(configDir, "client-instance.lock");
3423
+ const path = join10(configDir, "client_instance_id");
3424
+ const lockPath = join10(configDir, "client-instance.lock");
1857
3425
  ensurePrivateConfigDirectory(configDir);
1858
3426
  return withFileLock(
1859
3427
  lockPath,
@@ -1862,7 +3430,7 @@ async function getOrCreateClientInstanceId(options) {
1862
3430
  if (existing !== void 0) {
1863
3431
  return existing;
1864
3432
  }
1865
- const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
3433
+ const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
1866
3434
  "base64url"
1867
3435
  )}`;
1868
3436
  if (!isClientInstanceId(generated)) {
@@ -1897,57 +3465,18 @@ async function ingestUploaderHeaders() {
1897
3465
  return headers;
1898
3466
  }
1899
3467
 
1900
- // src/lib/terminal-safe.ts
1901
- function replaceIsolatedSurrogates(value) {
1902
- let out = "";
1903
- for (let index = 0; index < value.length; index += 1) {
1904
- const unit = value.charCodeAt(index);
1905
- if (unit >= 55296 && unit <= 56319) {
1906
- const next = value.charCodeAt(index + 1);
1907
- if (next >= 56320 && next <= 57343) {
1908
- out += value[index] + value[index + 1];
1909
- index += 1;
1910
- } else {
1911
- out += "\uFFFD";
1912
- }
1913
- } else if (unit >= 56320 && unit <= 57343) {
1914
- out += "\uFFFD";
1915
- } else {
1916
- out += value[index];
1917
- }
1918
- }
1919
- return out;
1920
- }
1921
- function isUnsafeTerminalCodePoint(point) {
1922
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1923
- const bidiOrZeroWidth = point === 173 || // soft hyphen
1924
- point === 1564 || // Arabic letter mark
1925
- point === 6158 || // Mongolian vowel separator
1926
- point >= 8203 && point <= 8207 || // zero-width + directional marks
1927
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1928
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1929
- point >= 65529 && point <= 65531 || // interlinear annotation controls
1930
- point === 65279 || // zero-width no-break space / BOM
1931
- point >= 917504 && point <= 917631;
1932
- return c0OrC1 || bidiOrZeroWidth;
1933
- }
1934
- function terminalSafeText(value) {
1935
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1936
- }
1937
- function terminalSafeLine(value) {
1938
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1939
- }
1940
- var stripControlChars = terminalSafeText;
1941
-
1942
3468
  // src/client.ts
1943
3469
  var CONFIG_DIR_MODE = 448;
1944
3470
  var CREDENTIAL_FILE_MODE = 384;
1945
3471
  var REFRESH_THRESHOLD_MS = 6e4;
1946
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3472
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
1947
3473
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
3474
+ function authExpiredMessage() {
3475
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
3476
+ }
1948
3477
  function readTrimmed2(path) {
1949
3478
  try {
1950
- const value = readFileSync8(path, "utf8").trim();
3479
+ const value = readFileSync9(path, "utf8").trim();
1951
3480
  return value || void 0;
1952
3481
  } catch {
1953
3482
  return void 0;
@@ -1957,13 +3486,13 @@ function getSiteUrl() {
1957
3486
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
1958
3487
  }
1959
3488
  function getSiteUrlForEnvironment(primApiUrl) {
1960
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3489
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
1961
3490
  }
1962
3491
  function expiresAtFor(token, expiresIn) {
1963
3492
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
1964
3493
  }
1965
3494
  function ensureConfigDirectory() {
1966
- const directory = dirname5(TOKEN_FILE_PATH);
3495
+ const directory = dirname6(TOKEN_FILE_PATH);
1967
3496
  mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
1968
3497
  chmodSync3(directory, CONFIG_DIR_MODE);
1969
3498
  }
@@ -1973,7 +3502,7 @@ function atomicWrite2(path, content) {
1973
3502
  }
1974
3503
  function removeCredentialFile(path) {
1975
3504
  if (!existsSync4(path)) return false;
1976
- rmSync6(path, { force: true });
3505
+ rmSync7(path, { force: true });
1977
3506
  return true;
1978
3507
  }
1979
3508
  function getTokenExpiresAt() {
@@ -1988,23 +3517,23 @@ function isTokenExpiringSoon(credential) {
1988
3517
  const expiresAt = getTokenExpiresAt();
1989
3518
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
1990
3519
  }
1991
- function refreshFingerprint(refreshToken2) {
1992
- return createHash6("sha256").update(refreshToken2).digest("hex");
3520
+ function refreshFingerprint(refreshToken3) {
3521
+ return createHash8("sha256").update(refreshToken3).digest("hex");
1993
3522
  }
1994
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3523
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
1995
3524
  return {
1996
3525
  version: 1,
1997
3526
  family: "legacy_broker",
1998
3527
  accessTokenHash: refreshFingerprint(accessToken),
1999
- refreshTokenHash: refreshFingerprint(refreshToken2)
3528
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2000
3529
  };
2001
3530
  }
2002
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3531
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
2003
3532
  const hashes = {
2004
3533
  accessTokenHash: refreshFingerprint(accessToken),
2005
- refreshTokenHash: refreshFingerprint(refreshToken2)
3534
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2006
3535
  };
2007
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3536
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
2008
3537
  }
2009
3538
  function writeCredentialMigrationSentinel() {
2010
3539
  atomicWrite2(
@@ -2016,11 +3545,11 @@ function writeCredentialMigrationSentinel() {
2016
3545
  `
2017
3546
  );
2018
3547
  }
2019
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
2020
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3548
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3549
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
2021
3550
  return { state: "invalid" };
2022
3551
  }
2023
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3552
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2024
3553
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
2025
3554
  return { state: "invalid" };
2026
3555
  }
@@ -2037,17 +3566,17 @@ function preserveMarkerlessLegacyGeneration() {
2037
3566
  const metadata = readStoredCredentialMetadata();
2038
3567
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
2039
3568
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
2040
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
2041
- if (!(accessToken && refreshToken2)) return;
2042
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3569
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3570
+ if (!(accessToken && refreshToken3)) return;
3571
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2043
3572
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2044
3573
  `);
2045
3574
  }
2046
3575
  function terminalFingerprint() {
2047
3576
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2048
3577
  }
2049
- function writeTerminalFingerprint(refreshToken2) {
2050
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3578
+ function writeTerminalFingerprint(refreshToken3) {
3579
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2051
3580
  `);
2052
3581
  }
2053
3582
  function clearTerminalFingerprint() {
@@ -2056,20 +3585,20 @@ function clearTerminalFingerprint() {
2056
3585
  function isSessionEnded() {
2057
3586
  if (hasMachineConfiguration()) return machineSessionEnded();
2058
3587
  if (resolveAuthCredential()?.source !== "token_file") return false;
2059
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3588
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2060
3589
  const ended = terminalFingerprint();
2061
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3590
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2062
3591
  }
2063
3592
  function withCredentialLock(operation, options = {}) {
2064
3593
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2065
3594
  }
2066
3595
  function commitCredentialsUnlocked(credentials) {
2067
3596
  const accessToken = credentials.accessToken.trim();
2068
- const refreshToken2 = credentials.refreshToken.trim();
2069
- if (!accessToken || !refreshToken2) {
3597
+ const refreshToken3 = credentials.refreshToken.trim();
3598
+ if (!accessToken || !refreshToken3) {
2070
3599
  throw new Error("OAuth credentials require both access and refresh tokens");
2071
3600
  }
2072
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3601
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2073
3602
  if (credentials.metadata !== void 0) {
2074
3603
  preserveMarkerlessLegacyGeneration();
2075
3604
  writeCredentialMigrationSentinel();
@@ -2077,10 +3606,10 @@ function commitCredentialsUnlocked(credentials) {
2077
3606
  `);
2078
3607
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2079
3608
  `);
2080
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3609
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2081
3610
  `);
2082
3611
  } else {
2083
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3612
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2084
3613
  `);
2085
3614
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2086
3615
  `);
@@ -2117,15 +3646,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2117
3646
  `
2118
3647
  );
2119
3648
  }
2120
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3649
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2121
3650
  const current = readStoredCredentialMetadata();
2122
3651
  if (expected.state === "legacy_broker") {
2123
3652
  if (current.state !== "legacy_broker") return false;
2124
3653
  if (!expected.metadata) return current.metadata === void 0;
2125
- 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;
3654
+ 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;
2126
3655
  }
2127
3656
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2128
- 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;
3657
+ 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;
2129
3658
  }
2130
3659
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2131
3660
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2294,7 +3823,7 @@ async function performTokenRefresh(options = {}) {
2294
3823
  );
2295
3824
  }
2296
3825
  var _refreshInFlight;
2297
- function refreshToken(options = {}) {
3826
+ function refreshToken2(options = {}) {
2298
3827
  if (hasMachineConfiguration())
2299
3828
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2300
3829
  if (_refreshInFlight) return _refreshInFlight;
@@ -2326,7 +3855,7 @@ var CliManagementResponseError = class extends Error {
2326
3855
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
2327
3856
  async function managementResponseValue(response) {
2328
3857
  if (response.status === 401) {
2329
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3858
+ throw new HttpError(401, authExpiredMessage());
2330
3859
  }
2331
3860
  let value;
2332
3861
  try {
@@ -2348,23 +3877,50 @@ function selectedCredential() {
2348
3877
  }
2349
3878
  return _cachedCredential;
2350
3879
  }
3880
+ async function requestHeaders(method, path) {
3881
+ return {
3882
+ "Content-Type": "application/json",
3883
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
3884
+ };
3885
+ }
2351
3886
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
2352
3887
  return fetch(`${siteUrl}${path}`, {
2353
3888
  method,
2354
- headers: {
2355
- Authorization: `Bearer ${token}`,
2356
- "Content-Type": "application/json",
2357
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2358
- },
3889
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
2359
3890
  body: body === void 0 ? void 0 : JSON.stringify(body),
2360
3891
  signal: options?.signal,
2361
3892
  redirect: options?.redirect
2362
3893
  });
2363
3894
  }
3895
+ async function fetchAsMachine(credential, method, path, body, options) {
3896
+ if (!credential.tokenInjection)
3897
+ return fetchWithToken(
3898
+ method,
3899
+ path,
3900
+ body,
3901
+ { ...options, redirect: "error" },
3902
+ credential.accessToken,
3903
+ credential.apiUrl
3904
+ );
3905
+ try {
3906
+ return await forwardMachineRequest(
3907
+ {
3908
+ method,
3909
+ path,
3910
+ headers: await requestHeaders(method, path),
3911
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
3912
+ },
3913
+ options.signal
3914
+ );
3915
+ } catch (error) {
3916
+ if (!(error instanceof MachineAuthError)) throw error;
3917
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
3918
+ }
3919
+ }
2364
3920
  async function responseValue(response) {
2365
3921
  if (!response.ok) {
2366
3922
  if (response.status === 401) {
2367
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3923
+ throw new HttpError(401, authExpiredMessage());
2368
3924
  }
2369
3925
  const errorBody = await response.json().catch(() => null);
2370
3926
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -2391,14 +3947,7 @@ async function machineClient(options = {}, management = false) {
2391
3947
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
2392
3948
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
2393
3949
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2394
- let response = await fetchWithToken(
2395
- method,
2396
- path,
2397
- body,
2398
- { ...requestOptions, redirect: "error" },
2399
- current.accessToken,
2400
- selected.apiUrl
2401
- );
3950
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
2402
3951
  if (response.status === 401) {
2403
3952
  const renewed = await acquireMachineCredential({
2404
3953
  force: true,
@@ -2407,19 +3956,14 @@ async function machineClient(options = {}, management = false) {
2407
3956
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
2408
3957
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2409
3958
  }
2410
- response = await fetchWithToken(
2411
- method,
2412
- path,
2413
- body,
2414
- { ...requestOptions, redirect: "error" },
2415
- renewed.accessToken,
2416
- renewed.apiUrl
2417
- );
3959
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
2418
3960
  }
2419
3961
  if (response.status === 401)
2420
3962
  throw new HttpError(
2421
3963
  401,
2422
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3964
+ 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(
3965
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3966
+ )
2423
3967
  );
2424
3968
  return parse(response);
2425
3969
  };
@@ -2429,7 +3973,7 @@ async function machineClient(options = {}, management = false) {
2429
3973
  delete: (path, body, opts) => send("DELETE", path, body, opts)
2430
3974
  };
2431
3975
  }
2432
- async function request(method, path, body, options) {
3976
+ async function request2(method, path, body, options) {
2433
3977
  const machine = await machineClient(options);
2434
3978
  if (machine)
2435
3979
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -2438,17 +3982,17 @@ async function request(method, path, body, options) {
2438
3982
  let refreshAttempted = false;
2439
3983
  if (credential && isTokenExpiringSoon(credential)) {
2440
3984
  refreshAttempted = true;
2441
- const token = await refreshToken({
3985
+ const token = await refreshToken2({
2442
3986
  signal: options?.signal,
2443
3987
  quiet: options?.quietRefresh
2444
3988
  });
2445
3989
  if (token) credential = { token, source: "token_file" };
2446
3990
  }
2447
3991
  if (!credential) {
2448
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3992
+ throw new HttpError(401, authExpiredMessage());
2449
3993
  }
2450
3994
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
2451
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3995
+ throw new HttpError(401, authExpiredMessage());
2452
3996
  }
2453
3997
  const tokenUsed = credential.token;
2454
3998
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -2457,7 +4001,7 @@ async function request(method, path, body, options) {
2457
4001
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2458
4002
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2459
4003
  refreshAttempted = true;
2460
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4004
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2461
4005
  }
2462
4006
  if (retryToken) {
2463
4007
  _cachedCredential = {
@@ -2471,8 +4015,8 @@ async function request(method, path, body, options) {
2471
4015
  }
2472
4016
  function getClient() {
2473
4017
  return {
2474
- get: (path, options) => request("GET", path, void 0, options),
2475
- post: (path, body, options) => request("POST", path, body, options)
4018
+ get: (path, options) => request2("GET", path, void 0, options),
4019
+ post: (path, body, options) => request2("POST", path, body, options)
2476
4020
  };
2477
4021
  }
2478
4022
  async function getPinnedClient(options = {}) {
@@ -2481,14 +4025,14 @@ async function getPinnedClient(options = {}) {
2481
4025
  const siteUrl = getSiteUrl();
2482
4026
  let credential = selectedCredential();
2483
4027
  if (credential && isTokenExpiringSoon(credential)) {
2484
- const token2 = await refreshToken({
4028
+ const token2 = await refreshToken2({
2485
4029
  signal: options.signal,
2486
4030
  quiet: options.quietRefresh
2487
4031
  });
2488
4032
  if (token2) credential = { token: token2, source: "token_file" };
2489
4033
  }
2490
4034
  if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
2491
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
4035
+ throw new HttpError(401, authExpiredMessage());
2492
4036
  }
2493
4037
  const token = credential.token;
2494
4038
  const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
@@ -2500,10 +4044,10 @@ async function getPinnedClient(options = {}) {
2500
4044
 
2501
4045
  // src/flusher.ts
2502
4046
  import { createReadStream, renameSync as renameSync3, statSync as statSync2, unlinkSync } from "fs";
2503
- import { dirname as dirname10, join as join14 } from "path";
4047
+ import { dirname as dirname10, join as join17 } from "path";
2504
4048
 
2505
4049
  // src/dead-letter.ts
2506
- import { createHash as createHash7, randomBytes as randomBytes4 } from "crypto";
4050
+ import { createHash as createHash9, randomBytes as randomBytes5 } from "crypto";
2507
4051
  import {
2508
4052
  constants as constants2,
2509
4053
  chmodSync as chmodSync4,
@@ -2514,25 +4058,25 @@ import {
2514
4058
  mkdirSync as mkdirSync5,
2515
4059
  openSync as openSync2,
2516
4060
  renameSync as renameSync2,
2517
- rmSync as rmSync7,
2518
- writeFileSync as writeFileSync3
4061
+ rmSync as rmSync8,
4062
+ writeFileSync as writeFileSync4
2519
4063
  } from "fs";
2520
- import { dirname as dirname6, join as join10 } from "path";
4064
+ import { dirname as dirname7, join as join12 } from "path";
2521
4065
  var DIRECTORY_MODE2 = 448;
2522
4066
  var FILE_MODE2 = 384;
2523
4067
  var DEAD_LETTER_DIRNAME = "dead-letter";
2524
4068
  function deadLetterDirectoryForRotation(flushingPath) {
2525
- return join10(dirname6(flushingPath), DEAD_LETTER_DIRNAME);
4069
+ return join12(dirname7(flushingPath), DEAD_LETTER_DIRNAME);
2526
4070
  }
2527
4071
  function deadLetterPathForRawLine(flushingPath, rawLine) {
2528
- const quarantineId = createHash7("sha256").update(rawLine).digest("hex");
2529
- return join10(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
4072
+ const quarantineId = createHash9("sha256").update(rawLine).digest("hex");
4073
+ return join12(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
2530
4074
  }
2531
4075
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
2532
4076
  const directory = deadLetterDirectoryForRotation(flushingPath);
2533
4077
  mkdirSync5(directory, { recursive: true, mode: DIRECTORY_MODE2 });
2534
4078
  chmodSync4(directory, DIRECTORY_MODE2);
2535
- persistDirectory(dirname6(directory));
4079
+ persistDirectory(dirname7(directory));
2536
4080
  return directory;
2537
4081
  }
2538
4082
  function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
@@ -2540,16 +4084,16 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
2540
4084
  persistDirectory(directory);
2541
4085
  return;
2542
4086
  }
2543
- const temporaryPath = join10(
4087
+ const temporaryPath = join12(
2544
4088
  directory,
2545
- `.${quarantineId}.${String(process.pid)}.${randomBytes4(8).toString("hex")}.tmp`
4089
+ `.${quarantineId}.${String(process.pid)}.${randomBytes5(8).toString("hex")}.tmp`
2546
4090
  );
2547
4091
  const flags = constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW;
2548
4092
  try {
2549
4093
  const fd = openSync2(temporaryPath, flags, FILE_MODE2);
2550
4094
  try {
2551
4095
  fchmodSync2(fd, FILE_MODE2);
2552
- writeFileSync3(fd, `${JSON.stringify(record)}
4096
+ writeFileSync4(fd, `${JSON.stringify(record)}
2553
4097
  `, "utf8");
2554
4098
  fsyncSync2(fd);
2555
4099
  } finally {
@@ -2558,7 +4102,7 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
2558
4102
  renameSync2(temporaryPath, path);
2559
4103
  persistDirectory(directory);
2560
4104
  } finally {
2561
- rmSync7(temporaryPath, { force: true });
4105
+ rmSync8(temporaryPath, { force: true });
2562
4106
  }
2563
4107
  }
2564
4108
  function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
@@ -2567,12 +4111,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
2567
4111
  const serializedMove = JSON.stringify(move);
2568
4112
  const record = {
2569
4113
  version: 1,
2570
- quarantineId: createHash7("sha256").update(serializedMove).digest("hex"),
4114
+ quarantineId: createHash9("sha256").update(serializedMove).digest("hex"),
2571
4115
  quarantinedAt: now(),
2572
4116
  reason,
2573
4117
  move
2574
4118
  };
2575
- const path = join10(directory, `${record.quarantineId}.json`);
4119
+ const path = join12(directory, `${record.quarantineId}.json`);
2576
4120
  persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
2577
4121
  return record;
2578
4122
  }
@@ -2583,7 +4127,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
2583
4127
  const record = {
2584
4128
  version: 1,
2585
4129
  recordKind: "raw_line_v1",
2586
- quarantineId: createHash7("sha256").update(bytes).digest("hex"),
4130
+ quarantineId: createHash9("sha256").update(bytes).digest("hex"),
2587
4131
  quarantinedAt: now(),
2588
4132
  reason: "invalid_move",
2589
4133
  rawLineEncoding: "base64",
@@ -2604,12 +4148,12 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
2604
4148
  import {
2605
4149
  chmodSync as chmodSync5,
2606
4150
  existsSync as existsSync6,
2607
- readFileSync as readFileSync9,
2608
- readdirSync,
2609
- rmSync as rmSync8,
4151
+ readFileSync as readFileSync10,
4152
+ readdirSync as readdirSync2,
4153
+ rmSync as rmSync9,
2610
4154
  rmdirSync
2611
4155
  } from "fs";
2612
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
4156
+ import { basename as basename3, dirname as dirname8, join as join13 } from "path";
2613
4157
  var DIRECTORY_MODE3 = 448;
2614
4158
  var FILE_MODE3 = 384;
2615
4159
  var DRAIN_PROGRESS_DIRNAME = "drain-progress";
@@ -2618,10 +4162,10 @@ function rotationIdentity(stat) {
2618
4162
  return { size: stat.size, ino: stat.ino, dev: stat.dev };
2619
4163
  }
2620
4164
  function drainProgressDirectory(flushingPath) {
2621
- return join11(dirname7(flushingPath), DRAIN_PROGRESS_DIRNAME);
4165
+ return join13(dirname8(flushingPath), DRAIN_PROGRESS_DIRNAME);
2622
4166
  }
2623
4167
  function drainProgressPath(flushingPath) {
2624
- return join11(drainProgressDirectory(flushingPath), `${basename2(flushingPath)}.json`);
4168
+ return join13(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
2625
4169
  }
2626
4170
  function isByteCount(value) {
2627
4171
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -2629,7 +4173,7 @@ function isByteCount(value) {
2629
4173
  function drainResumeOffset(flushingPath, rotation) {
2630
4174
  let parsed;
2631
4175
  try {
2632
- parsed = JSON.parse(readFileSync9(drainProgressPath(flushingPath), "utf8"));
4176
+ parsed = JSON.parse(readFileSync10(drainProgressPath(flushingPath), "utf8"));
2633
4177
  } catch {
2634
4178
  return 0;
2635
4179
  }
@@ -2662,24 +4206,24 @@ function removeEmptyDirectory(directory) {
2662
4206
  }
2663
4207
  }
2664
4208
  function removeDrainCheckpoint(flushingPath) {
2665
- rmSync8(drainProgressPath(flushingPath), { force: true });
4209
+ rmSync9(drainProgressPath(flushingPath), { force: true });
2666
4210
  removeEmptyDirectory(drainProgressDirectory(flushingPath));
2667
4211
  }
2668
4212
  function sweepOrphanedDrainCheckpoints(bucketDirectory) {
2669
- const directory = join11(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
4213
+ const directory = join13(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
2670
4214
  let names;
2671
4215
  try {
2672
- names = readdirSync(directory);
4216
+ names = readdirSync2(directory);
2673
4217
  } catch {
2674
4218
  return;
2675
4219
  }
2676
4220
  for (const name of names) {
2677
4221
  const rotation = CHECKPOINT_NAME.exec(name)?.[1];
2678
- if (rotation === void 0 || existsSync6(join11(bucketDirectory, rotation))) {
4222
+ if (rotation === void 0 || existsSync6(join13(bucketDirectory, rotation))) {
2679
4223
  continue;
2680
4224
  }
2681
4225
  try {
2682
- rmSync8(join11(directory, name), { force: true });
4226
+ rmSync9(join13(directory, name), { force: true });
2683
4227
  } catch {
2684
4228
  }
2685
4229
  }
@@ -29376,22 +30920,38 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29376
30920
 
29377
30921
  // src/lib/activation.ts
29378
30922
  import { execFileSync as execFileSync4 } from "child_process";
29379
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
30923
+ import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
29380
30924
  import { homedir as homedir2 } from "os";
29381
- import { join as join12 } from "path";
30925
+ import { join as join15 } from "path";
30926
+
30927
+ // src/lib/cloud-prepared.ts
30928
+ import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
30929
+ import { join as join14 } from "path";
30930
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
30931
+ function cloudPreparedPath(env = process.env) {
30932
+ return join14(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30933
+ }
30934
+ function isPreparedCloudSession(env = process.env) {
30935
+ if (!isClaudeCloudSession(env)) return false;
30936
+ try {
30937
+ return existsSync7(cloudPreparedPath(env));
30938
+ } catch {
30939
+ return false;
30940
+ }
30941
+ }
29382
30942
 
29383
30943
  // src/lib/demo-pause.ts
29384
- import { execFileSync as execFileSync2 } from "child_process";
30944
+ import { execFileSync as execFileSync3 } from "child_process";
29385
30945
  var DEMO_PAUSE_MS = 30 * 6e4;
29386
30946
  var PAUSE_KEY = "prim.demoPause";
29387
- var GIT_TIMEOUT_MS = 1e3;
29388
- function git(cwd, args) {
30947
+ var GIT_TIMEOUT_MS3 = 1e3;
30948
+ function git2(cwd, args) {
29389
30949
  try {
29390
- return execFileSync2("git", args, {
30950
+ return execFileSync3("git", args, {
29391
30951
  cwd,
29392
30952
  encoding: "utf-8",
29393
30953
  stdio: ["ignore", "pipe", "ignore"],
29394
- timeout: GIT_TIMEOUT_MS
30954
+ timeout: GIT_TIMEOUT_MS3
29395
30955
  });
29396
30956
  } catch {
29397
30957
  return void 0;
@@ -29399,10 +30959,10 @@ function git(cwd, args) {
29399
30959
  }
29400
30960
  function setLocal(cwd, key, value) {
29401
30961
  try {
29402
- execFileSync2(
30962
+ execFileSync3(
29403
30963
  "git",
29404
30964
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
29405
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
30965
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
29406
30966
  );
29407
30967
  } catch (error) {
29408
30968
  if (value !== null || error.status !== 5) throw error;
@@ -29416,7 +30976,7 @@ function parsePause(value) {
29416
30976
  function readCaptureConfig(cwd) {
29417
30977
  let active;
29418
30978
  let pause;
29419
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
30979
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
29420
30980
  for (const line of out.split("\n")) {
29421
30981
  const space = line.indexOf(" ");
29422
30982
  const key = line.slice(0, space).toLowerCase();
@@ -29441,60 +31001,13 @@ function healDemoPause(cwd, pause, options = {}) {
29441
31001
  }
29442
31002
  }
29443
31003
 
29444
- // src/lib/git.ts
29445
- import { execFileSync as execFileSync3 } from "child_process";
29446
- import { createHash as createHash8 } from "crypto";
29447
- import { lstatSync as lstatSync5, realpathSync } from "fs";
29448
- import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
29449
- var GIT_TIMEOUT_MS2 = 1e3;
29450
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
29451
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
29452
- function gitToplevel(cwd) {
29453
- try {
29454
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
29455
- cwd,
29456
- encoding: "utf-8",
29457
- stdio: ["ignore", "pipe", "ignore"],
29458
- timeout: GIT_TIMEOUT_MS2
29459
- }).trim();
29460
- } catch {
29461
- return null;
29462
- }
29463
- }
29464
- function gitValue(cwd, args) {
29465
- try {
29466
- const value = execFileSync3("git", args, {
29467
- cwd,
29468
- encoding: "utf-8",
29469
- stdio: ["ignore", "pipe", "ignore"],
29470
- timeout: GIT_TIMEOUT_MS2
29471
- }).trim();
29472
- return value || void 0;
29473
- } catch {
29474
- return void 0;
29475
- }
29476
- }
29477
- function githubRepositoryFullName(cwd) {
29478
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
29479
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
29480
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29481
- remote
29482
- );
29483
- const path = match?.[1] ?? match?.[2];
29484
- if (!path) return null;
29485
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
29486
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
29487
- return null;
29488
- }
29489
- return `${parts[0]}/${parts[1]}`;
29490
- }
29491
-
29492
31004
  // src/lib/activation.ts
29493
31005
  var PRIM_ACTIVE_KEY = "prim.active";
31006
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
29494
31007
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
29495
31008
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
29496
31009
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
29497
- var GIT_TIMEOUT_MS3 = 1e3;
31010
+ var GIT_TIMEOUT_MS4 = 1e3;
29498
31011
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
29499
31012
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
29500
31013
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -29504,7 +31017,7 @@ function repoActiveFlag(cwd, strict = false) {
29504
31017
  cwd,
29505
31018
  encoding: "utf-8",
29506
31019
  stdio: ["ignore", "pipe", "ignore"],
29507
- timeout: GIT_TIMEOUT_MS3
31020
+ timeout: GIT_TIMEOUT_MS4
29508
31021
  }).trim();
29509
31022
  if (value === "true") return "true";
29510
31023
  if (value === "false") return "false";
@@ -29525,7 +31038,7 @@ function localGitConfigValue(cwd, key) {
29525
31038
  cwd,
29526
31039
  encoding: "utf-8",
29527
31040
  stdio: ["ignore", "pipe", "ignore"],
29528
- timeout: GIT_TIMEOUT_MS3
31041
+ timeout: GIT_TIMEOUT_MS4
29529
31042
  }).trim();
29530
31043
  return value || void 0;
29531
31044
  } catch {
@@ -29536,7 +31049,7 @@ function setLocalGitConfigValue(cwd, key, value) {
29536
31049
  execFileSync4("git", ["config", "--local", key, value], {
29537
31050
  cwd,
29538
31051
  stdio: ["ignore", "ignore", "pipe"],
29539
- timeout: GIT_TIMEOUT_MS3
31052
+ timeout: GIT_TIMEOUT_MS4
29540
31053
  });
29541
31054
  }
29542
31055
  function repoSyncId(cwd) {
@@ -29554,14 +31067,13 @@ function repositoryBindingState(cwd) {
29554
31067
  if (marker !== void 0) return "invalid";
29555
31068
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
29556
31069
  }
29557
- function hasProjectPrimInstall(cwd) {
29558
- const root = gitToplevel(cwd);
31070
+ function projectPrimInstallAt(root) {
29559
31071
  if (root === null || root === homedir2()) return false;
29560
31072
  for (const rel of PROJECT_INSTALL_FILES) {
29561
- const path = join12(root, rel);
29562
- if (existsSync7(path)) {
31073
+ const path = join15(root, rel);
31074
+ if (existsSync8(path)) {
29563
31075
  try {
29564
- const content = readFileSync10(path, "utf-8");
31076
+ const content = readFileSync12(path, "utf-8");
29565
31077
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
29566
31078
  } catch {
29567
31079
  }
@@ -29569,12 +31081,27 @@ function hasProjectPrimInstall(cwd) {
29569
31081
  }
29570
31082
  return false;
29571
31083
  }
31084
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
31085
+ function declaresInactiveAt(root) {
31086
+ if (root === null || root === homedir2()) return false;
31087
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
31088
+ const text = checkoutSettingsText(root);
31089
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
31090
+ try {
31091
+ JSON.parse(text);
31092
+ return false;
31093
+ } catch {
31094
+ return true;
31095
+ }
31096
+ }
29572
31097
  function isRepoActiveForCapture(cwd, options = {}) {
29573
31098
  let { active: flag, pause } = readCaptureConfig(cwd);
29574
31099
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
29575
31100
  if (flag === "true") return true;
29576
31101
  if (flag === "false") return false;
29577
- return hasProjectPrimInstall(cwd);
31102
+ const root = gitToplevel(cwd);
31103
+ if (declaresInactiveAt(root)) return false;
31104
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
29578
31105
  }
29579
31106
  function decisionIngestionStatus(cwd) {
29580
31107
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -29860,11 +31387,15 @@ function classifyJournalBuckets(buckets, binding) {
29860
31387
  continue;
29861
31388
  }
29862
31389
  if (binding.captureAuthorityKind === "workos_m2m") {
29863
- if (binding.clientId && bucket === machineJournalBucket({
29864
- apiUrl: machineApiUrl(getSiteUrl()),
31390
+ const apiUrl = machineApiUrl(getSiteUrl());
31391
+ if (binding.clientId && (bucket === machineJournalBucket({
31392
+ apiUrl,
29865
31393
  clientId: binding.clientId,
29866
31394
  authorizedUserId: binding.authorizedUserId
29867
- }))
31395
+ }) || // What this client captured before its identity was verified. Those
31396
+ // belong to whoever the server says the client is, which is now
31397
+ // known; no verified identity's bucket is opened this way.
31398
+ bucket === machinePendingBucket({ apiUrl, clientId: binding.clientId })))
29868
31399
  deliverableBuckets.add(bucket);
29869
31400
  else
29870
31401
  retainedBuckets.push({
@@ -29887,14 +31418,17 @@ function classifyJournalBuckets(buckets, binding) {
29887
31418
  }
29888
31419
  function buildOrganizationBoundMoveRequest(batch, binding) {
29889
31420
  const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
29890
- const request2 = {
31421
+ const request3 = {
29891
31422
  batch: batch.map((move) => {
29892
31423
  if (typeof move !== "object" || move === null || Array.isArray(move)) {
29893
31424
  return move;
29894
31425
  }
29895
31426
  const { captureActor, ...wireMove } = move;
29896
31427
  if (binding.captureAuthorityKind === "workos_m2m") {
29897
- if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId)
31428
+ if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || // An identity-pending actor names only its client and is bound to
31429
+ // the identity verified for it. Any other actor is a claim about a
31430
+ // verified identity and must match this one exactly.
31431
+ !identityPending(captureActor) && (captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId))
29898
31432
  throw new InvalidJournalEnvelopeError();
29899
31433
  } else if (captureActor) throw new InvalidJournalEnvelopeError();
29900
31434
  return {
@@ -29910,10 +31444,10 @@ function buildOrganizationBoundMoveRequest(batch, binding) {
29910
31444
  };
29911
31445
  })
29912
31446
  };
29913
- if (!isMoveIngestRequest(request2)) {
31447
+ if (!isMoveIngestRequest(request3)) {
29914
31448
  throw new InvalidJournalEnvelopeError();
29915
31449
  }
29916
- return request2;
31450
+ return request3;
29917
31451
  }
29918
31452
  async function inspectJournalDelivery(buckets, options = {}) {
29919
31453
  const bucketList = [...new Set(buckets)];
@@ -29948,17 +31482,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
29948
31482
  import {
29949
31483
  appendFileSync,
29950
31484
  closeSync as closeSync3,
29951
- existsSync as existsSync8,
31485
+ existsSync as existsSync9,
29952
31486
  fstatSync,
29953
- mkdirSync as mkdirSync6,
31487
+ mkdirSync as mkdirSync7,
29954
31488
  openSync as openSync3,
29955
31489
  opendirSync,
29956
- readFileSync as readFileSync11,
31490
+ readFileSync as readFileSync13,
29957
31491
  readSync,
29958
- readdirSync as readdirSync2
31492
+ readdirSync as readdirSync3
29959
31493
  } from "fs";
29960
- import { dirname as dirname9, join as join13 } from "path";
29961
- var JOURNAL_DIR = join13(primConfigDirectory(), "moves");
31494
+ import { dirname as dirname9, join as join16 } from "path";
31495
+ var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
29962
31496
  var JOURNAL_BASENAME = "journal.ndjson";
29963
31497
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
29964
31498
  var PENDING_STATS_MAX_FILES = 128;
@@ -29970,7 +31504,7 @@ function envSlug(apiUrl) {
29970
31504
  return slug;
29971
31505
  }
29972
31506
  function currentEnvDir() {
29973
- return join13(JOURNAL_DIR, envSlug(getSiteUrl()));
31507
+ return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
29974
31508
  }
29975
31509
  function parseMoves(content) {
29976
31510
  const moves = [];
@@ -29988,15 +31522,15 @@ function parseMoves(content) {
29988
31522
  function listBuckets() {
29989
31523
  const out = [];
29990
31524
  const envDir = currentEnvDir();
29991
- if (!existsSync8(envDir)) {
31525
+ if (!existsSync9(envDir)) {
29992
31526
  return out;
29993
31527
  }
29994
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31528
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
29995
31529
  if (!entry.isDirectory()) {
29996
31530
  continue;
29997
31531
  }
29998
- const path = join13(envDir, entry.name, JOURNAL_BASENAME);
29999
- if (existsSync8(path)) {
31532
+ const path = join16(envDir, entry.name, JOURNAL_BASENAME);
31533
+ if (existsSync9(path)) {
30000
31534
  out.push({ bucket: entry.name, path });
30001
31535
  }
30002
31536
  }
@@ -30058,7 +31592,7 @@ function parseFlushingPid(name) {
30058
31592
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
30059
31593
  }
30060
31594
  function listFlushingInDir(dir, bucket, options = {}) {
30061
- if (!existsSync8(dir)) {
31595
+ if (!existsSync9(dir)) {
30062
31596
  return [];
30063
31597
  }
30064
31598
  const out = [];
@@ -30072,7 +31606,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
30072
31606
  entry = entries.readSync();
30073
31607
  continue;
30074
31608
  }
30075
- const path = join13(dir, entry.name);
31609
+ const path = join16(dir, entry.name);
30076
31610
  let sample;
30077
31611
  try {
30078
31612
  sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
@@ -30099,18 +31633,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
30099
31633
  }
30100
31634
  function listFlushing(options = {}) {
30101
31635
  const envDir = currentEnvDir();
30102
- if (!existsSync8(envDir)) {
31636
+ if (!existsSync9(envDir)) {
30103
31637
  return [];
30104
31638
  }
30105
31639
  const out = [];
30106
31640
  let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
30107
31641
  const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
30108
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31642
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
30109
31643
  if (out.length >= maxFiles) {
30110
31644
  break;
30111
31645
  }
30112
31646
  if (entry.isDirectory()) {
30113
- const found = listFlushingInDir(join13(envDir, entry.name), entry.name, {
31647
+ const found = listFlushingInDir(join16(envDir, entry.name), entry.name, {
30114
31648
  sampleBytes: remainingBytes,
30115
31649
  maxFiles: maxFiles - out.length
30116
31650
  });
@@ -30125,12 +31659,12 @@ function listFlushing(options = {}) {
30125
31659
  }
30126
31660
  function sweepOrphanedDrainProgress() {
30127
31661
  const envDir = currentEnvDir();
30128
- if (!existsSync8(envDir)) {
31662
+ if (!existsSync9(envDir)) {
30129
31663
  return;
30130
31664
  }
30131
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31665
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
30132
31666
  if (entry.isDirectory()) {
30133
- sweepOrphanedDrainCheckpoints(join13(envDir, entry.name));
31667
+ sweepOrphanedDrainCheckpoints(join16(envDir, entry.name));
30134
31668
  }
30135
31669
  }
30136
31670
  }
@@ -30309,11 +31843,11 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
30309
31843
  const postBatch = async (batch2) => {
30310
31844
  const moves = batch2.map((entry) => entry.move);
30311
31845
  try {
30312
- const request2 = buildOrganizationBoundMoveRequest(moves, binding);
30313
- if (Buffer.byteLength(JSON.stringify(request2)) > MAX_INGEST_REQUEST_BYTES) {
31846
+ const request3 = buildOrganizationBoundMoveRequest(moves, binding);
31847
+ if (Buffer.byteLength(JSON.stringify(request3)) > MAX_INGEST_REQUEST_BYTES) {
30314
31848
  throw new IngestRequestTooLargeError();
30315
31849
  }
30316
- const response = await client2.post("/api/cli/moves/ingest", request2, {
31850
+ const response = await client2.post("/api/cli/moves/ingest", request3, {
30317
31851
  signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
30318
31852
  });
30319
31853
  requireDurableIngestAcknowledgement(response, moves.length, collectionScopeRoots(moves));
@@ -30458,12 +31992,12 @@ async function recoverOrphans(candidates, options) {
30458
31992
  if (summary.failedBuckets.has(file.bucket)) {
30459
31993
  continue;
30460
31994
  }
30461
- const { counts, failure } = await settleDrain((onProgress) => drain(file.path, onProgress));
31995
+ const { counts, failure: failure2 } = await settleDrain((onProgress) => drain(file.path, onProgress));
30462
31996
  summary.flushed += counts.flushed;
30463
31997
  summary.quarantined += counts.quarantined;
30464
- if (failure) {
31998
+ if (failure2) {
30465
31999
  summary.failedDrainFlushed += counts.flushed;
30466
- summary.errors.push(failure.error);
32000
+ summary.errors.push(failure2.error);
30467
32001
  summary.failedBuckets.add(file.bucket);
30468
32002
  }
30469
32003
  }
@@ -30522,14 +32056,14 @@ async function flushOnce() {
30522
32056
  if (recovered.failedBuckets.has(bucket)) {
30523
32057
  continue;
30524
32058
  }
30525
- const { counts, failure } = await settleDrain(
32059
+ const { counts, failure: failure2 } = await settleDrain(
30526
32060
  (onProgress) => drainPath(path, client2, binding, onProgress)
30527
32061
  );
30528
32062
  total += counts.flushed;
30529
32063
  quarantined += counts.quarantined;
30530
- if (failure) {
32064
+ if (failure2) {
30531
32065
  failedDrainFlushed += counts.flushed;
30532
- errors.push(failure.error);
32066
+ errors.push(failure2.error);
30533
32067
  }
30534
32068
  }
30535
32069
  if (errors.length > 0) {
@@ -30544,7 +32078,7 @@ async function flushOnce() {
30544
32078
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
30545
32079
  }
30546
32080
  var flushInFlight;
30547
- var FLUSH_LOCK_PATH = join14(dirname10(JOURNAL_DIR), ".flush.lock");
32081
+ var FLUSH_LOCK_PATH = join17(dirname10(JOURNAL_DIR), ".flush.lock");
30548
32082
  var FLUSH_LOCK_TIMEOUT_MS = 250;
30549
32083
  function isFlushLockContended(error) {
30550
32084
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -30746,14 +32280,14 @@ var StatuslineIngestionCache = class {
30746
32280
 
30747
32281
  // src/daemon/client.ts
30748
32282
  import { createConnection } from "net";
30749
- import { join as join15 } from "path";
30750
- var SOCK_PATH = join15(primConfigDirectory(), "sock");
32283
+ import { join as join18 } from "path";
32284
+ var SOCK_PATH = join18(primConfigDirectory(), "sock");
30751
32285
  var DEFAULT_TIMEOUT_MS2 = 250;
30752
32286
  var nextRequestId = 1;
30753
32287
  function daemonRequest(method, params = {}, opts = {}) {
30754
32288
  const id = nextRequestId++;
30755
32289
  const caller = resolveDaemonPrincipal();
30756
- const request2 = {
32290
+ const request3 = {
30757
32291
  id,
30758
32292
  method,
30759
32293
  params,
@@ -30792,7 +32326,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30792
32326
  });
30793
32327
  socket.on("connect", () => {
30794
32328
  try {
30795
- socket?.write(`${JSON.stringify(request2)}
32329
+ socket?.write(`${JSON.stringify(request3)}
30796
32330
  `);
30797
32331
  } catch {
30798
32332
  clearTimeout(timer);
@@ -30837,7 +32371,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30837
32371
  }
30838
32372
 
30839
32373
  // src/daemon/decision-digest-cache.ts
30840
- import { randomBytes as randomBytes5 } from "crypto";
32374
+ import { randomBytes as randomBytes6 } from "crypto";
30841
32375
  var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
30842
32376
  var DECISION_DIGEST_CACHE_LIMIT = 100;
30843
32377
  var DECISION_DIGEST_CACHE_WINDOW = "24h";
@@ -30867,7 +32401,7 @@ function errorMessage(error) {
30867
32401
  return error instanceof Error ? error.message : String(error);
30868
32402
  }
30869
32403
  function privatePageToken() {
30870
- return randomBytes5(16).toString("hex");
32404
+ return randomBytes6(16).toString("hex");
30871
32405
  }
30872
32406
  var DecisionDigestCache = class {
30873
32407
  constructor(load, now = Date.now, options = {}) {
@@ -31018,8 +32552,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
31018
32552
  }
31019
32553
 
31020
32554
  // src/daemon/health.ts
31021
- import { chmodSync as chmodSync6, existsSync as existsSync9, mkdirSync as mkdirSync7, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "fs";
31022
- import { dirname as dirname11, join as join16 } from "path";
32555
+ import { chmodSync as chmodSync6, existsSync as existsSync10, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
32556
+ import { dirname as dirname11, join as join19 } from "path";
31023
32557
  var CONFIG_DIR_MODE2 = 448;
31024
32558
  var HEALTH_FILE_MODE = 384;
31025
32559
  var INGESTION_SLA_MS = 3e4;
@@ -31027,7 +32561,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
31027
32561
  var HEARTBEAT_RETRY_CAP_MS = 3e4;
31028
32562
  var INGESTION_RETRY_BASE_MS = 5e3;
31029
32563
  var INGESTION_RETRY_CAP_MS = 15e3;
31030
- var DAEMON_HEALTH_PATH = join16(primConfigDirectory(), "daemon-health.json");
32564
+ var DAEMON_HEALTH_PATH = join19(primConfigDirectory(), "daemon-health.json");
31031
32565
  function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
31032
32566
  return {
31033
32567
  schemaVersion: 1,
@@ -31069,11 +32603,11 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
31069
32603
  }
31070
32604
  function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
31071
32605
  const dir = dirname11(path);
31072
- if (!existsSync9(dir)) {
31073
- mkdirSync7(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
32606
+ if (!existsSync10(dir)) {
32607
+ mkdirSync8(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
31074
32608
  }
31075
- const tmp = join16(dir, `.${process.pid}.daemon-health.tmp`);
31076
- writeFileSync4(tmp, `${JSON.stringify(state, null, 2)}
32609
+ const tmp = join19(dir, `.${process.pid}.daemon-health.tmp`);
32610
+ writeFileSync6(tmp, `${JSON.stringify(state, null, 2)}
31077
32611
  `, { mode: HEALTH_FILE_MODE });
31078
32612
  chmodSync6(tmp, HEALTH_FILE_MODE);
31079
32613
  renameSync4(tmp, path);
@@ -31083,22 +32617,22 @@ function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
31083
32617
  import { randomUUID as randomUUID3 } from "crypto";
31084
32618
  import {
31085
32619
  chmodSync as chmodSync7,
31086
- existsSync as existsSync10,
31087
- mkdirSync as mkdirSync8,
31088
- readFileSync as readFileSync12,
32620
+ existsSync as existsSync11,
32621
+ mkdirSync as mkdirSync9,
32622
+ readFileSync as readFileSync14,
31089
32623
  renameSync as renameSync5,
31090
- rmSync as rmSync9,
32624
+ rmSync as rmSync11,
31091
32625
  statSync as statSync3,
31092
32626
  unlinkSync as unlinkSync2,
31093
- writeFileSync as writeFileSync5
32627
+ writeFileSync as writeFileSync7
31094
32628
  } from "fs";
31095
- import { join as join17 } from "path";
32629
+ import { join as join20 } from "path";
31096
32630
  var DIR_MODE = 448;
31097
32631
  var FILE_MODE4 = 384;
31098
32632
  var DAEMON_STARTUP_GRACE_MS = 5e3;
31099
32633
  function readLockRecord(path) {
31100
32634
  try {
31101
- const value = JSON.parse(readFileSync12(path, "utf-8"));
32635
+ const value = JSON.parse(readFileSync14(path, "utf-8"));
31102
32636
  if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
31103
32637
  return value;
31104
32638
  }
@@ -31108,17 +32642,17 @@ function readLockRecord(path) {
31108
32642
  }
31109
32643
  function numericPid(path) {
31110
32644
  try {
31111
- const pid = Number(readFileSync12(path, "utf-8").trim());
32645
+ const pid = Number(readFileSync14(path, "utf-8").trim());
31112
32646
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
31113
32647
  } catch {
31114
32648
  return;
31115
32649
  }
31116
32650
  }
31117
32651
  function readDaemonOwner(configDir) {
31118
- return readLockRecord(join17(configDir, "daemon.lock", "owner.json"));
32652
+ return readLockRecord(join20(configDir, "daemon.lock", "owner.json"));
31119
32653
  }
31120
32654
  function readDaemonPid(configDir) {
31121
- const path = join17(configDir, "daemon.pid");
32655
+ const path = join20(configDir, "daemon.pid");
31122
32656
  const pid = numericPid(path);
31123
32657
  if (pid === void 0) {
31124
32658
  return;
@@ -31133,16 +32667,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31133
32667
  const pid = opts.pid ?? process.pid;
31134
32668
  const now = opts.now ?? Date.now();
31135
32669
  const isAlive = opts.isAlive ?? processIsAlive;
31136
- const lockDir = join17(configDir, "daemon.lock");
31137
- const ownerPath2 = join17(lockDir, "owner.json");
31138
- const pidPath = join17(configDir, "daemon.pid");
32670
+ const lockDir = join20(configDir, "daemon.lock");
32671
+ const ownerPath2 = join20(lockDir, "owner.json");
32672
+ const pidPath = join20(configDir, "daemon.pid");
31139
32673
  const instanceId2 = randomUUID3();
31140
- if (!existsSync10(configDir)) {
31141
- mkdirSync8(configDir, { recursive: true, mode: DIR_MODE });
32674
+ if (!existsSync11(configDir)) {
32675
+ mkdirSync9(configDir, { recursive: true, mode: DIR_MODE });
31142
32676
  }
31143
32677
  for (; ; ) {
31144
32678
  try {
31145
- mkdirSync8(lockDir, { mode: DIR_MODE });
32679
+ mkdirSync9(lockDir, { mode: DIR_MODE });
31146
32680
  break;
31147
32681
  } catch (err) {
31148
32682
  if (err.code !== "EEXIST") {
@@ -31169,7 +32703,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31169
32703
  const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
31170
32704
  try {
31171
32705
  renameSync5(lockDir, stale);
31172
- rmSync9(stale, { recursive: true, force: true });
32706
+ rmSync11(stale, { recursive: true, force: true });
31173
32707
  } catch (renameErr) {
31174
32708
  if (renameErr.code !== "ENOENT") {
31175
32709
  throw renameErr;
@@ -31186,15 +32720,15 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31186
32720
  instanceId: instanceId2
31187
32721
  };
31188
32722
  const record = { pid, instanceId: instanceId2, startedAt: now };
31189
- writeFileSync5(ownerPath2, `${JSON.stringify(record)}
32723
+ writeFileSync7(ownerPath2, `${JSON.stringify(record)}
31190
32724
  `, { mode: FILE_MODE4 });
31191
32725
  chmodSync7(ownerPath2, FILE_MODE4);
31192
32726
  const legacyPid = numericPid(pidPath);
31193
32727
  if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
31194
- rmSync9(lockDir, { recursive: true, force: true });
32728
+ rmSync11(lockDir, { recursive: true, force: true });
31195
32729
  throw new Error(`daemon already running (pid=${String(legacyPid)})`);
31196
32730
  }
31197
- writeFileSync5(pidPath, String(pid), { mode: FILE_MODE4 });
32731
+ writeFileSync7(pidPath, String(pid), { mode: FILE_MODE4 });
31198
32732
  chmodSync7(pidPath, FILE_MODE4);
31199
32733
  return ownership2;
31200
32734
  }
@@ -31225,7 +32759,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
31225
32759
  }
31226
32760
  }
31227
32761
  }
31228
- rmSync9(ownership2.lockDir, { recursive: true, force: true });
32762
+ rmSync11(ownership2.lockDir, { recursive: true, force: true });
31229
32763
  if (cleanupError) {
31230
32764
  throw cleanupError;
31231
32765
  }
@@ -31262,15 +32796,15 @@ function isLegacyHeartbeatResponse(value) {
31262
32796
  ) && hasOptionalField(value, "unavailable", (candidate) => typeof candidate === "string");
31263
32797
  }
31264
32798
  function buildPresenceHeartbeatRequest(sessionId, clientInstanceId2) {
31265
- const request2 = {
32799
+ const request3 = {
31266
32800
  sessionId,
31267
32801
  clientInstanceId: clientInstanceId2,
31268
32802
  decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
31269
32803
  };
31270
- if (!isPresenceHeartbeatRequest(request2)) {
32804
+ if (!isPresenceHeartbeatRequest(request3)) {
31271
32805
  throw new Error("presence heartbeat identity or session is invalid");
31272
32806
  }
31273
- return request2;
32807
+ return request3;
31274
32808
  }
31275
32809
  function normalizePresenceHeartbeatResponse(value) {
31276
32810
  if (isPresenceHeartbeatResponse(value)) {
@@ -31320,7 +32854,7 @@ function parseStatuslineRequest(buffer) {
31320
32854
 
31321
32855
  // src/daemon/server.ts
31322
32856
  var CONFIG_DIR = primConfigDirectory();
31323
- var SOCK_PATH2 = join18(CONFIG_DIR, "sock");
32857
+ var SOCK_PATH2 = join21(CONFIG_DIR, "sock");
31324
32858
  var CONFIG_DIR_MODE3 = 448;
31325
32859
  var SOCKET_MODE = 384;
31326
32860
  var MAX_SOCKET_CONNECTIONS = 64;
@@ -31389,7 +32923,7 @@ function resolveRuntimeVersion() {
31389
32923
  }
31390
32924
  try {
31391
32925
  const here = fileURLToPath4(new URL(".", import.meta.url));
31392
- const pkg = JSON.parse(readFileSync13(join18(here, "..", "..", "package.json"), "utf-8"));
32926
+ const pkg = JSON.parse(readFileSync15(join21(here, "..", "..", "package.json"), "utf-8"));
31393
32927
  return pkg.version ?? "unknown";
31394
32928
  } catch {
31395
32929
  return "unknown";
@@ -31428,7 +32962,7 @@ function assertCallerPrincipalMatches(caller) {
31428
32962
  return credentialKey;
31429
32963
  }
31430
32964
  function ensureDaemonDirectoryPermissions() {
31431
- mkdirSync9(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
32965
+ mkdirSync10(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
31432
32966
  chmodSync8(CONFIG_DIR, CONFIG_DIR_MODE3);
31433
32967
  }
31434
32968
  function persistHealth() {
@@ -31515,7 +33049,7 @@ async function takeOwnership() {
31515
33049
  (pid) => pid !== void 0 && processIsAlive(pid)
31516
33050
  )
31517
33051
  );
31518
- if (existsSync11(SOCK_PATH2) || candidatePids.size > 0) {
33052
+ if (existsSync12(SOCK_PATH2) || candidatePids.size > 0) {
31519
33053
  const snapshot = await daemonRequest(
31520
33054
  "status_snapshot",
31521
33055
  {},
@@ -31660,7 +33194,7 @@ async function ensureTokenFresh() {
31660
33194
  }
31661
33195
  if (Date.now() >= expiresAt - TOKEN_REFRESH_THRESHOLD_MS) {
31662
33196
  try {
31663
- await refreshToken({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
33197
+ await refreshToken2({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
31664
33198
  } catch {
31665
33199
  }
31666
33200
  }
@@ -31965,15 +33499,15 @@ function handleConnection(conn) {
31965
33499
  }
31966
33500
  try {
31967
33501
  const line = utf8Decoder2.decode(jsonBuffer.subarray(0, newlineIdx));
31968
- const request2 = parseDaemonRequestEnvelope(JSON.parse(line));
31969
- if (!request2) {
33502
+ const request3 = parseDaemonRequestEnvelope(JSON.parse(line));
33503
+ if (!request3) {
31970
33504
  conn.end();
31971
33505
  return;
31972
33506
  }
31973
33507
  dispatched = true;
31974
33508
  conn.pause();
31975
- void dispatchRequest(request2).then(writeJsonResponse, () => {
31976
- writeJsonResponse({ id: request2.id, ok: false, error: "daemon request failed" });
33509
+ void dispatchRequest(request3).then(writeJsonResponse, () => {
33510
+ writeJsonResponse({ id: request3.id, ok: false, error: "daemon request failed" });
31977
33511
  });
31978
33512
  } catch {
31979
33513
  conn.end();