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

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 (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
  3. package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
  4. package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
  5. package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
  6. package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
  7. package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
  8. package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
  9. package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
  10. package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
  11. package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
  12. package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
  13. package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
  14. package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
  15. package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
  16. package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
  17. package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
  19. package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
  20. package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
  21. package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
  22. package/dist/daemon/server.js +1769 -487
  23. package/dist/hook-runtime/daemon/server.js +1769 -487
  24. package/dist/hook-runtime/hooks/post-commit.js +611 -337
  25. package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
  27. package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
  29. package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
  30. package/dist/hook-runtime/hooks/session-end.js +538 -385
  31. package/dist/hook-runtime/hooks/session-start.js +1379 -233
  32. package/dist/hook-runtime/index.js +5438 -4052
  33. package/dist/hook-runtime/statusline-main.js +547 -273
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +18 -18
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +64 -22
  42. package/dist/index.js +396 -52
  43. package/dist/statusline-main.js +547 -273
  44. package/package.json +1 -1
@@ -591,6 +591,7 @@ import { createRequire } from "module";
591
591
  import { dirname as dirname4, join as join3 } from "path";
592
592
  import { fileURLToPath as fileURLToPath2 } from "url";
593
593
  var require2 = createRequire(import.meta.url);
594
+ var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
594
595
 
595
596
  // src/lib/paths.ts
596
597
  import { homedir } from "os";
@@ -621,7 +622,9 @@ function primConfigDirectory(options = {}) {
621
622
  }
622
623
 
623
624
  // src/lib/hook-runtime.ts
625
+ var HOOK_RUNTIME_SCHEMA_VERSION = 1;
624
626
  var RELEASE_PREFIX = "release-";
627
+ var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
625
628
  var MAX_MANIFEST_BYTES = 64 * 1024;
626
629
  var RELEASE_GRACE_MS = 10 * 60 * 1e3;
627
630
  var HOOK_RUNTIME_ENTRIES = {
@@ -664,6 +667,153 @@ function hookRuntimePaths(options = {}) {
664
667
  selectionLock: join5(runtimeDir, "selection.lock")
665
668
  };
666
669
  }
670
+ function sha256(path) {
671
+ return createHash("sha256").update(readFileSync3(path)).digest("hex");
672
+ }
673
+ function exactManifest(manifest) {
674
+ return `${JSON.stringify(manifest, null, 2)}
675
+ `;
676
+ }
677
+ function exactKeys(value, expected) {
678
+ const actual = Object.keys(value).sort();
679
+ const wanted = [...expected].sort();
680
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
681
+ }
682
+ function releaseId(manifest) {
683
+ return createHash("sha256").update(exactManifest(manifest)).digest("hex");
684
+ }
685
+ function runtimePackageJson(manifest) {
686
+ return `${JSON.stringify(
687
+ {
688
+ name: "@primitive.ai/prim",
689
+ version: manifest.version,
690
+ type: "module",
691
+ bin: HOOK_RUNTIME_ENTRIES
692
+ },
693
+ null,
694
+ 2
695
+ )}
696
+ `;
697
+ }
698
+ function validateRelease(releaseDir, manifest) {
699
+ try {
700
+ if (!directReleaseLayout(releaseDir, manifest)) return false;
701
+ if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
702
+ return false;
703
+ }
704
+ if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
705
+ return false;
706
+ }
707
+ if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
708
+ `) {
709
+ return false;
710
+ }
711
+ for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
712
+ const target = join5(releaseDir, relativePath);
713
+ if (sha256(target) !== manifest.files[bin]) return false;
714
+ }
715
+ for (const [path, digest] of Object.entries(manifest.native ?? {})) {
716
+ if (sha256(join5(releaseDir, path)) !== digest) return false;
717
+ }
718
+ return true;
719
+ } catch {
720
+ return false;
721
+ }
722
+ }
723
+ function directReleaseLayout(releaseDir, manifest) {
724
+ try {
725
+ const directories = /* @__PURE__ */ new Set([releaseDir]);
726
+ for (const relativePath of [
727
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
728
+ ...Object.keys(manifest.native ?? {})
729
+ ]) {
730
+ for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
731
+ directories.add(join5(releaseDir, directory));
732
+ }
733
+ }
734
+ if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
735
+ const files = [
736
+ "manifest.json",
737
+ "package.json",
738
+ "node",
739
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
740
+ ...Object.keys(manifest.native ?? {})
741
+ ];
742
+ const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
743
+ if (![...directories].every(
744
+ (directory) => readdirSync(directory).every((name) => owned.has(join5(directory, name)))
745
+ ))
746
+ return false;
747
+ return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
748
+ } catch {
749
+ return false;
750
+ }
751
+ }
752
+ function readReleaseManifest(releaseDir, releaseName) {
753
+ try {
754
+ const manifestPath = join5(releaseDir, "manifest.json");
755
+ const manifestStat = statSync2(manifestPath);
756
+ if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
757
+ const raw = readFileSync3(manifestPath, "utf8");
758
+ const parsed = JSON.parse(raw);
759
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
760
+ if (!exactKeys(parsed, [
761
+ "schemaVersion",
762
+ "version",
763
+ "nodePath",
764
+ "files",
765
+ ..."native" in parsed ? ["native"] : []
766
+ ]))
767
+ return null;
768
+ const candidate = parsed;
769
+ if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute3(candidate.nodePath) || /[\r\n]/u.test(candidate.nodePath) || !candidate.files || typeof candidate.files !== "object" || Array.isArray(candidate.files) || !exactKeys(candidate.files, Object.keys(HOOK_RUNTIME_ENTRIES)) || Object.values(candidate.files).some(
770
+ (digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
771
+ )) {
772
+ return null;
773
+ }
774
+ if (candidate.native !== void 0 && (!candidate.native || typeof candidate.native !== "object" || Array.isArray(candidate.native) || !exactKeys(candidate.native, KEYRING_NATIVE_FILES) || Object.values(candidate.native).some(
775
+ (digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
776
+ )))
777
+ return null;
778
+ const manifest = candidate;
779
+ if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
780
+ return null;
781
+ }
782
+ return manifest;
783
+ } catch {
784
+ return null;
785
+ }
786
+ }
787
+ function readSelectedRelease(paths) {
788
+ let raw;
789
+ try {
790
+ raw = readFileSync3(paths.current, "utf8");
791
+ } catch (error) {
792
+ if (error.code === "ENOENT") return null;
793
+ throw error;
794
+ }
795
+ const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
796
+ if (`${name}
797
+ ` !== raw || !RELEASE_NAME_RE.test(name)) {
798
+ throw new Error("cannot stage hook runtime: selected release is malformed");
799
+ }
800
+ const dir = join5(paths.releasesDir, name);
801
+ const manifest = readReleaseManifest(dir, name);
802
+ if (!manifest) {
803
+ throw new Error("cannot stage hook runtime: immutable release is corrupt");
804
+ }
805
+ return { name, dir, manifest };
806
+ }
807
+ function selectedHookRuntimeKeyringLoader(options = {}) {
808
+ try {
809
+ const selected = readSelectedRelease(hookRuntimePaths(options));
810
+ if (!selected?.manifest.native) return void 0;
811
+ const loader = join5(selected.dir, "native", "keyring.cjs");
812
+ return existsSync4(loader) ? loader : void 0;
813
+ } catch {
814
+ return void 0;
815
+ }
816
+ }
667
817
  var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
668
818
  set -eu
669
819
  case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
@@ -742,6 +892,8 @@ function isClaudeCloudSession(env = process.env) {
742
892
  }
743
893
  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';
744
894
  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';
895
+ 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}.`;
896
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
745
897
  function cloudSetupPointer(message, env = process.env) {
746
898
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
747
899
  }
@@ -831,13 +983,20 @@ var GIT_TIMEOUT_MS2 = 1e3;
831
983
  var MAX_SETTINGS_BYTES = 1024 * 1024;
832
984
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
833
985
  var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
986
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
987
+ function gitChildEnvironment(env = process.env) {
988
+ return Object.fromEntries(
989
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
990
+ );
991
+ }
834
992
  function gitToplevel(cwd) {
835
993
  try {
836
994
  return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
837
995
  cwd,
838
996
  encoding: "utf-8",
839
997
  stdio: ["ignore", "pipe", "ignore"],
840
- timeout: GIT_TIMEOUT_MS2
998
+ timeout: GIT_TIMEOUT_MS2,
999
+ env: gitChildEnvironment()
841
1000
  }).trim();
842
1001
  } catch {
843
1002
  return null;
@@ -849,13 +1008,17 @@ function gitValue(cwd, args) {
849
1008
  cwd,
850
1009
  encoding: "utf-8",
851
1010
  stdio: ["ignore", "pipe", "ignore"],
852
- timeout: GIT_TIMEOUT_MS2
1011
+ timeout: GIT_TIMEOUT_MS2,
1012
+ env: gitChildEnvironment()
853
1013
  }).trim();
854
1014
  return value || void 0;
855
1015
  } catch {
856
1016
  return void 0;
857
1017
  }
858
1018
  }
1019
+ function currentBranch(cwd) {
1020
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1021
+ }
859
1022
  function parseGithubRepositoryName(path) {
860
1023
  const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
861
1024
  if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
@@ -1522,18 +1685,18 @@ function publicDecisionResponse(value) {
1522
1685
  }
1523
1686
 
1524
1687
  // src/client.ts
1525
- import { createHash as createHash7 } from "crypto";
1526
- import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync8 } from "fs";
1688
+ import { createHash as createHash8 } from "crypto";
1689
+ import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
1527
1690
  import { dirname as dirname9 } from "path";
1528
1691
 
1529
1692
  // src/lib/credentials.ts
1530
- import { createHash as createHash6 } from "crypto";
1693
+ import { createHash as createHash7 } from "crypto";
1531
1694
  import { readFileSync as readFileSync12 } from "fs";
1532
- import { join as join14 } from "path";
1695
+ import { join as join15 } from "path";
1533
1696
 
1534
1697
  // src/lib/machine-credentials.ts
1535
1698
  import { execFileSync as execFileSync5 } from "child_process";
1536
- import { createHash as createHash5, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
1699
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
1537
1700
  import {
1538
1701
  chmodSync as chmodSync2,
1539
1702
  existsSync as existsSync9,
@@ -1541,11 +1704,11 @@ import {
1541
1704
  lstatSync as lstatSync6,
1542
1705
  mkdirSync as mkdirSync5,
1543
1706
  readFileSync as readFileSync11,
1544
- rmSync as rmSync7,
1707
+ rmSync as rmSync8,
1545
1708
  writeFileSync as writeFileSync5
1546
1709
  } from "fs";
1547
1710
  import { createRequire as createRequire2 } from "module";
1548
- import { dirname as dirname8, join as join13 } from "path";
1711
+ import { dirname as dirname8, join as join14 } from "path";
1549
1712
  import { fileURLToPath as fileURLToPath4 } from "url";
1550
1713
 
1551
1714
  // src/lib/machine-broker.ts
@@ -1722,10 +1885,10 @@ function parseWorkosConnectTokens(value, options = {}) {
1722
1885
  "access_token",
1723
1886
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
1724
1887
  );
1725
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
1888
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
1726
1889
  return {
1727
1890
  accessToken,
1728
- refreshToken: refreshToken2,
1891
+ refreshToken: refreshToken3,
1729
1892
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
1730
1893
  };
1731
1894
  }
@@ -2300,32 +2463,999 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
2300
2463
  }
2301
2464
  }
2302
2465
 
2466
+ // src/lib/session-identity.ts
2467
+ import { execFile } from "child_process";
2468
+ import { createHash as createHash5 } from "crypto";
2469
+ import { rmSync as rmSync7 } from "fs";
2470
+ import { join as join13 } from "path";
2471
+ import { promisify } from "util";
2472
+
2473
+ // src/lib/terminal-safe.ts
2474
+ function replaceIsolatedSurrogates(value) {
2475
+ let out = "";
2476
+ for (let index = 0; index < value.length; index += 1) {
2477
+ const unit = value.charCodeAt(index);
2478
+ if (unit >= 55296 && unit <= 56319) {
2479
+ const next = value.charCodeAt(index + 1);
2480
+ if (next >= 56320 && next <= 57343) {
2481
+ out += value[index] + value[index + 1];
2482
+ index += 1;
2483
+ } else {
2484
+ out += "\uFFFD";
2485
+ }
2486
+ } else if (unit >= 56320 && unit <= 57343) {
2487
+ out += "\uFFFD";
2488
+ } else {
2489
+ out += value[index];
2490
+ }
2491
+ }
2492
+ return out;
2493
+ }
2494
+ function isUnsafeTerminalCodePoint(point) {
2495
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
2496
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
2497
+ point === 1564 || // Arabic letter mark
2498
+ point === 6158 || // Mongolian vowel separator
2499
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
2500
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
2501
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
2502
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
2503
+ point === 65279 || // zero-width no-break space / BOM
2504
+ point >= 917504 && point <= 917631;
2505
+ return c0OrC1 || bidiOrZeroWidth;
2506
+ }
2507
+ function terminalSafeText(value) {
2508
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
2509
+ }
2510
+ function terminalSafeLine(value) {
2511
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
2512
+ }
2513
+ function isTerminalSafeText(value) {
2514
+ return terminalSafeText(value) === value;
2515
+ }
2516
+ var stripControlChars = terminalSafeText;
2517
+
2518
+ // src/lib/session-identity.ts
2519
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
2520
+ var SESSION_IDENTITY_VALUE = "session";
2521
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
2522
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
2523
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
2524
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
2525
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
2526
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
2527
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
2528
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
2529
+ var SESSION_IDENTITY_ROUTES = {
2530
+ challenge: "/api/cli/session-identity/challenge",
2531
+ token: "/api/cli/session-identity/token",
2532
+ refresh: "/api/cli/session-identity/token/refresh",
2533
+ link: "/api/cli/session-identity/link"
2534
+ };
2535
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
2536
+ var RENEW_BEFORE_MS = 6e4;
2537
+ var GIT_TIMEOUT_MS4 = 1e4;
2538
+ var POLL_BUDGET_MS = 15e3;
2539
+ var POLL_FIRST_DELAY_MS = 500;
2540
+ var POLL_MAX_DELAY_MS = 3e3;
2541
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
2542
+ var LOCK_TIMEOUT_MS = 6e4;
2543
+ var RESPONSE_MAX_BYTES = 64 * 1024;
2544
+ function sessionIdentityRequested(env = process.env) {
2545
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
2546
+ }
2547
+ function sessionIdentityMode(deps = {}) {
2548
+ const env = deps.env ?? process.env;
2549
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
2550
+ }
2551
+ function failure(code, cause, remedy) {
2552
+ return { status: "failed", code, cause, remedy };
2553
+ }
2554
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
2555
+ var NEW_SESSION_REMEDY = "start a new cloud session";
2556
+ 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';
2557
+ var SESSION_REVOKED = failure(
2558
+ "session_revoked",
2559
+ "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",
2560
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
2561
+ );
2562
+ var CHALLENGE_WINDOW_PASSED = failure(
2563
+ "challenge_expired",
2564
+ "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)",
2565
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
2566
+ );
2567
+ var CHALLENGE_GONE = failure(
2568
+ "challenge_not_found",
2569
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
2570
+ NEW_SESSION_REMEDY
2571
+ );
2572
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
2573
+ function rejectionFailure(reason, repository) {
2574
+ switch (reason) {
2575
+ case "identity_mismatch":
2576
+ return failure(
2577
+ "identity_mismatch",
2578
+ "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",
2579
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
2580
+ );
2581
+ case "push_after_expiry":
2582
+ return failure(
2583
+ "push_after_expiry",
2584
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
2585
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
2586
+ );
2587
+ case "repository_mismatch":
2588
+ return failure(
2589
+ "repository_mismatch",
2590
+ `Primitive received the identity push from a different repository than ${repository}`,
2591
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
2592
+ );
2593
+ case "conflicting_push":
2594
+ return failure(
2595
+ "conflicting_push",
2596
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
2597
+ NEW_SESSION_REMEDY
2598
+ );
2599
+ case "unsupported_sender":
2600
+ return failure(
2601
+ "unsupported_sender",
2602
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
2603
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
2604
+ );
2605
+ default:
2606
+ return failure(
2607
+ "challenge_rejected",
2608
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
2609
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
2610
+ );
2611
+ }
2612
+ }
2613
+ function sessionIdentityMessage(outcome) {
2614
+ if (outcome.status === "link_required")
2615
+ 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.`;
2616
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
2617
+ }
2618
+ function hash(value) {
2619
+ return createHash5("sha256").update(value).digest("hex");
2620
+ }
2621
+ function sessionContext(deps) {
2622
+ const env = deps.env ?? process.env;
2623
+ const environment = environmentCredentials(deps);
2624
+ if (!environment)
2625
+ return failure(
2626
+ "environment_credential_missing",
2627
+ "the cloud environment has no environment credential",
2628
+ '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'
2629
+ );
2630
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
2631
+ if (!sessionId || !SESSION_ID.test(sessionId))
2632
+ return failure(
2633
+ "session_id_missing",
2634
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
2635
+ NEW_SESSION_REMEDY
2636
+ );
2637
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
2638
+ const directory = deps.directory ?? primConfigDirectory({ env });
2639
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
2640
+ return {
2641
+ directory,
2642
+ apiUrl,
2643
+ clientId: environment.clientId,
2644
+ generation: environment.generation,
2645
+ sessionId,
2646
+ tokenPath: join13(directory, `session_identity_${key}.json`),
2647
+ statePath: join13(directory, `session_identity_${key}.state.json`),
2648
+ lockPath: join13(directory, "session-identity.lock")
2649
+ };
2650
+ }
2651
+ function readRecord(path) {
2652
+ try {
2653
+ const value = readMachineMetadata(path);
2654
+ return value === void 0 ? void 0 : machineRecord(value);
2655
+ } catch {
2656
+ return void 0;
2657
+ }
2658
+ }
2659
+ function finiteNumber(value) {
2660
+ return typeof value === "number" && Number.isFinite(value);
2661
+ }
2662
+ function readToken(context) {
2663
+ const data = readRecord(context.tokenPath);
2664
+ 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))
2665
+ return void 0;
2666
+ const identity = data.identity;
2667
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
2668
+ return void 0;
2669
+ return data;
2670
+ }
2671
+ function readState(context) {
2672
+ const data = readRecord(context.statePath);
2673
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
2674
+ return void 0;
2675
+ return data;
2676
+ }
2677
+ function writeToken(context, record) {
2678
+ prepareMachineMetadataDirectory(context.directory);
2679
+ writeMachineMetadata(context.tokenPath, record);
2680
+ rmSync7(context.statePath, { force: true });
2681
+ }
2682
+ function writeState(context, state) {
2683
+ try {
2684
+ prepareMachineMetadataDirectory(context.directory);
2685
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
2686
+ } catch {
2687
+ }
2688
+ }
2689
+ function tokenValid(record, now = Date.now()) {
2690
+ return now < record.expiresAt - RENEW_BEFORE_MS;
2691
+ }
2692
+ function tokenFresh(record, now = Date.now()) {
2693
+ return tokenValid(record, now) && now < record.refreshAfter;
2694
+ }
2695
+ function toCredential(record) {
2696
+ return {
2697
+ issuer: record.issuer,
2698
+ audience: record.audience,
2699
+ ...record.identity,
2700
+ accessToken: record.accessToken,
2701
+ expiresAt: record.expiresAt,
2702
+ apiUrl: record.apiUrl,
2703
+ generation: record.generation,
2704
+ storage: "environment",
2705
+ session: {
2706
+ userId: record.userId,
2707
+ displayName: record.displayName,
2708
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
2709
+ refreshAfter: record.refreshAfter
2710
+ }
2711
+ };
2712
+ }
2713
+ function identified(record, reused) {
2714
+ return {
2715
+ status: "ok",
2716
+ credential: toCredential(record),
2717
+ displayName: record.displayName,
2718
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
2719
+ reused
2720
+ };
2721
+ }
2722
+ function cachedSessionCredential(deps = {}) {
2723
+ if (!sessionIdentityMode(deps)) return void 0;
2724
+ let context;
2725
+ try {
2726
+ context = sessionContext(deps);
2727
+ } catch {
2728
+ return void 0;
2729
+ }
2730
+ if ("status" in context) return void 0;
2731
+ const record = readToken(context);
2732
+ return record && tokenValid(record) ? toCredential(record) : void 0;
2733
+ }
2734
+ function outcomeFromState(state) {
2735
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
2736
+ return {
2737
+ status: "link_required",
2738
+ githubLogin: state.githubLogin,
2739
+ challengeId: state.challengeId,
2740
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
2741
+ };
2742
+ return failure(
2743
+ state.code,
2744
+ state.cause ?? "the last identity check failed",
2745
+ state.remedy ?? RETRY_REMEDY
2746
+ );
2747
+ }
2748
+ function parseInstant(value) {
2749
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
2750
+ if (typeof value === "string" && value.length <= 64) {
2751
+ const parsed = Date.parse(value);
2752
+ return Number.isFinite(parsed) ? parsed : void 0;
2753
+ }
2754
+ return void 0;
2755
+ }
2756
+ async function sendJson(url, init, fetchImpl) {
2757
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
2758
+ let value;
2759
+ try {
2760
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
2761
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
2762
+ } catch {
2763
+ value = void 0;
2764
+ }
2765
+ return { status: response.status, value };
2766
+ }
2767
+ function environmentOnly(deps) {
2768
+ return { ...deps, environmentOnly: true };
2769
+ }
2770
+ async function environmentRequest(method, path, body, deps, signal) {
2771
+ const send = async (credential2) => {
2772
+ const headers = { "Content-Type": "application/json" };
2773
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
2774
+ if (credential2.tokenInjection) {
2775
+ const response = await forwardMachineRequest(
2776
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
2777
+ signal,
2778
+ environmentOnly(deps)
2779
+ );
2780
+ const parsed = await response.json().catch(() => void 0);
2781
+ return {
2782
+ status: response.status,
2783
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
2784
+ };
2785
+ }
2786
+ return sendJson(
2787
+ `${credential2.apiUrl}${path}`,
2788
+ {
2789
+ method,
2790
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
2791
+ ...text === void 0 ? {} : { body: text },
2792
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS4)
2793
+ },
2794
+ deps.fetch ?? fetch
2795
+ );
2796
+ };
2797
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
2798
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
2799
+ let answer = await send(credential);
2800
+ if (answer.status === 401) {
2801
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
2802
+ if (!credential)
2803
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
2804
+ answer = await send(credential);
2805
+ }
2806
+ return answer;
2807
+ }
2808
+ function environmentFailure(error, apiUrl) {
2809
+ if (error instanceof MachineAuthError && error.terminal)
2810
+ return failure(
2811
+ "environment_credential_rejected",
2812
+ "Primitive rejected the cloud environment's credential",
2813
+ ENVIRONMENT_CREDENTIAL_REMEDY
2814
+ );
2815
+ const host = (() => {
2816
+ try {
2817
+ return new URL(apiUrl).hostname;
2818
+ } catch {
2819
+ return "Primitive";
2820
+ }
2821
+ })();
2822
+ return failure(
2823
+ "identity_unavailable",
2824
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
2825
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
2826
+ );
2827
+ }
2828
+ function answerError(answer) {
2829
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
2830
+ }
2831
+ async function git2(root, args, signal) {
2832
+ try {
2833
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
2834
+ cwd: root,
2835
+ encoding: "utf8",
2836
+ timeout: GIT_TIMEOUT_MS4,
2837
+ signal,
2838
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
2839
+ maxBuffer: 1024 * 1024
2840
+ });
2841
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
2842
+ } catch (error) {
2843
+ const failed = error;
2844
+ return {
2845
+ ok: false,
2846
+ code: typeof failed.code === "number" ? failed.code : void 0,
2847
+ stdout: failed.stdout ?? "",
2848
+ stderr: failed.stderr ?? "",
2849
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
2850
+ };
2851
+ }
2852
+ }
2853
+ function gitDetail(stderr) {
2854
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
2855
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
2856
+ }
2857
+ async function defaultSleep2(milliseconds, signal) {
2858
+ await new Promise((resolve10, reject) => {
2859
+ const timer = setTimeout(resolve10, milliseconds);
2860
+ signal?.addEventListener(
2861
+ "abort",
2862
+ () => {
2863
+ clearTimeout(timer);
2864
+ reject(signal.reason);
2865
+ },
2866
+ { once: true }
2867
+ );
2868
+ });
2869
+ }
2870
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
2871
+ const sleep = deps.sleep ?? defaultSleep2;
2872
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
2873
+ let delay = POLL_FIRST_DELAY_MS;
2874
+ let unreachable2;
2875
+ for (; ; ) {
2876
+ const remaining = deadline - Date.now();
2877
+ if (remaining <= 0) break;
2878
+ await sleep(Math.min(delay, remaining), signal);
2879
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
2880
+ let answer;
2881
+ try {
2882
+ answer = await environmentRequest(
2883
+ "GET",
2884
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
2885
+ void 0,
2886
+ deps,
2887
+ signal
2888
+ );
2889
+ } catch (error) {
2890
+ signal?.throwIfAborted();
2891
+ unreachable2 = error;
2892
+ continue;
2893
+ }
2894
+ if (answer.status === 404) return CHALLENGE_GONE;
2895
+ if (answer.status === 401 || answer.status === 403)
2896
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
2897
+ if (answer.status < 200 || answer.status > 299) {
2898
+ unreachable2 = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
2899
+ continue;
2900
+ }
2901
+ unreachable2 = void 0;
2902
+ const status = answer.value;
2903
+ if (status?.status === "verified")
2904
+ return {
2905
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
2906
+ };
2907
+ if (status?.status === "expired")
2908
+ return failure(
2909
+ "challenge_expired",
2910
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
2911
+ NEW_SESSION_REMEDY
2912
+ );
2913
+ if (status?.status === "rejected")
2914
+ return rejectionFailure(status.reason, repository);
2915
+ }
2916
+ if (unreachable2) return environmentFailure(unreachable2, apiUrl);
2917
+ return failure(
2918
+ "webhook_timeout",
2919
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
2920
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2921
+ );
2922
+ }
2923
+ function parseTokenAnswer(value) {
2924
+ if (!value) return void 0;
2925
+ const user = value.user;
2926
+ const expiresAt = parseInstant(value.expiresAt);
2927
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
2928
+ 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))
2929
+ return void 0;
2930
+ return {
2931
+ accessToken: value.accessToken,
2932
+ expiresAt,
2933
+ refreshAfter: Math.min(refreshAfter, expiresAt),
2934
+ userId: user.id,
2935
+ displayName: user.displayName,
2936
+ organizationId: value.organizationId
2937
+ };
2938
+ }
2939
+ var SERVER_CONTRACT_FAILURE = failure(
2940
+ "server_contract",
2941
+ "Primitive's answer did not identify the linked member",
2942
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
2943
+ );
2944
+ async function recordFor(context, answer, extra, deps, signal) {
2945
+ let identity;
2946
+ let environment;
2947
+ try {
2948
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
2949
+ identity = await verifyMachineIdentity(
2950
+ context.apiUrl,
2951
+ answer.accessToken,
2952
+ context.clientId,
2953
+ signal,
2954
+ deps.fetch
2955
+ );
2956
+ } catch (error) {
2957
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
2958
+ return SERVER_CONTRACT_FAILURE;
2959
+ return environmentFailure(error, context.apiUrl);
2960
+ }
2961
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
2962
+ return SERVER_CONTRACT_FAILURE;
2963
+ return {
2964
+ version: 1,
2965
+ apiUrl: context.apiUrl,
2966
+ clientId: context.clientId,
2967
+ generation: context.generation,
2968
+ sessionId: context.sessionId,
2969
+ issuer: environment.issuer,
2970
+ audience: environment.audience,
2971
+ accessToken: answer.accessToken,
2972
+ expiresAt: answer.expiresAt,
2973
+ refreshAfter: answer.refreshAfter,
2974
+ userId: answer.userId,
2975
+ displayName: answer.displayName,
2976
+ organizationId: answer.organizationId,
2977
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
2978
+ identity,
2979
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
2980
+ };
2981
+ }
2982
+ async function refreshToken(context, record, deps, signal) {
2983
+ let answer;
2984
+ try {
2985
+ answer = await environmentRequest(
2986
+ "POST",
2987
+ SESSION_IDENTITY_ROUTES.refresh,
2988
+ { accessToken: record.accessToken },
2989
+ deps,
2990
+ signal
2991
+ );
2992
+ } catch (error) {
2993
+ signal?.throwIfAborted();
2994
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
2995
+ }
2996
+ const code = answerError(answer);
2997
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
2998
+ return { status: "refused", failure: SESSION_REVOKED };
2999
+ if (answer.status === 401 || answer.status === 403)
3000
+ return {
3001
+ status: "refused",
3002
+ failure: environmentFailure(
3003
+ new MachineAuthError("rejected", "rejected", true),
3004
+ context.apiUrl
3005
+ )
3006
+ };
3007
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
3008
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
3009
+ return { status: "unavailable" };
3010
+ return {
3011
+ status: "ok",
3012
+ record: {
3013
+ ...record,
3014
+ accessToken: token.accessToken,
3015
+ expiresAt: token.expiresAt,
3016
+ refreshAfter: token.refreshAfter,
3017
+ displayName: token.displayName
3018
+ }
3019
+ };
3020
+ }
3021
+ function exchangeRefusal(answer, repository) {
3022
+ if (answer.status === 404) return CHALLENGE_GONE;
3023
+ if (answer.status !== 409) return void 0;
3024
+ switch (answerError(answer)) {
3025
+ case "identity_mismatch":
3026
+ return rejectionFailure("identity_mismatch", repository);
3027
+ case "challenge_rejected":
3028
+ return rejectionFailure(answer.value?.reason, repository);
3029
+ case "challenge_expired":
3030
+ return CHALLENGE_WINDOW_PASSED;
3031
+ case "challenge_already_exchanged":
3032
+ return failure(
3033
+ "challenge_already_exchanged",
3034
+ "this session's identity check was already exchanged for a token this VM does not hold",
3035
+ NEW_SESSION_REMEDY
3036
+ );
3037
+ case "challenge_pending":
3038
+ return failure(
3039
+ "webhook_timeout",
3040
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
3041
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
3042
+ );
3043
+ default:
3044
+ return void 0;
3045
+ }
3046
+ }
3047
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
3048
+ let answer;
3049
+ try {
3050
+ answer = await environmentRequest(
3051
+ "POST",
3052
+ SESSION_IDENTITY_ROUTES.token,
3053
+ { challengeId: challenge.challengeId },
3054
+ deps,
3055
+ signal
3056
+ );
3057
+ } catch (error) {
3058
+ signal?.throwIfAborted();
3059
+ return environmentFailure(error, context.apiUrl);
3060
+ }
3061
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
3062
+ const login = answer.value?.githubLogin;
3063
+ return {
3064
+ status: "link_required",
3065
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
3066
+ challengeId: challenge.challengeId,
3067
+ challengeExpiresAt: challenge.challengeExpiresAt
3068
+ };
3069
+ }
3070
+ const refused = exchangeRefusal(
3071
+ answer,
3072
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
3073
+ );
3074
+ if (refused) return refused;
3075
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
3076
+ if (!token) {
3077
+ if (answer.status === 401 || answer.status === 403)
3078
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
3079
+ return answer.status >= 500 ? environmentFailure(
3080
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
3081
+ context.apiUrl
3082
+ ) : SERVER_CONTRACT_FAILURE;
3083
+ }
3084
+ return recordFor(
3085
+ context,
3086
+ token,
3087
+ { githubLogin: challenge.githubLogin, repositoryRoot },
3088
+ deps,
3089
+ signal
3090
+ );
3091
+ }
3092
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
3093
+ const env = deps.env ?? process.env;
3094
+ const repository = githubRepositoryFullName(root);
3095
+ if (!repository)
3096
+ return failure(
3097
+ "repository_unidentified",
3098
+ "this checkout does not name its GitHub repository",
3099
+ "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"
3100
+ );
3101
+ const branch = currentBranch(root);
3102
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
3103
+ return failure(
3104
+ "not_session_branch",
3105
+ `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`,
3106
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
3107
+ );
3108
+ attempt.branch = branch;
3109
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
3110
+ if (!baseSha) {
3111
+ const head = await git2(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
3112
+ baseSha = head.stdout.trim();
3113
+ if (!head.ok || !SHA.test(baseSha))
3114
+ return failure(
3115
+ "no_commit",
3116
+ "this checkout has no commit to create the session branch at",
3117
+ NEW_SESSION_REMEDY
3118
+ );
3119
+ }
3120
+ const published = await git2(
3121
+ root,
3122
+ [
3123
+ "for-each-ref",
3124
+ "--count=1",
3125
+ "--format=%(refname)",
3126
+ "--contains",
3127
+ baseSha,
3128
+ "refs/remotes/origin/"
3129
+ ],
3130
+ signal
3131
+ );
3132
+ if (!published.ok || published.stdout.trim() === "")
3133
+ return failure(
3134
+ "unpublished_commits",
3135
+ `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`,
3136
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
3137
+ );
3138
+ attempt.baseSha = baseSha;
3139
+ const remote = await git2(
3140
+ root,
3141
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
3142
+ signal
3143
+ );
3144
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
3145
+ if (remote.ok && recorded) {
3146
+ Object.assign(attempt, recorded);
3147
+ return { ...recorded, repository };
3148
+ }
3149
+ if (remote.ok)
3150
+ return failure(
3151
+ "branch_exists",
3152
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
3153
+ NEW_SESSION_REMEDY
3154
+ );
3155
+ if (remote.code !== 2)
3156
+ return failure(
3157
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
3158
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
3159
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
3160
+ );
3161
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
3162
+ Object.assign(attempt, recorded);
3163
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
3164
+ }
3165
+ let answer;
3166
+ try {
3167
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
3168
+ answer = await environmentRequest(
3169
+ "POST",
3170
+ SESSION_IDENTITY_ROUTES.challenge,
3171
+ {
3172
+ repositoryFullName: repository,
3173
+ claudeSessionId: context.sessionId,
3174
+ branch,
3175
+ baseSha,
3176
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
3177
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
3178
+ },
3179
+ deps,
3180
+ signal
3181
+ );
3182
+ } catch (error) {
3183
+ signal?.throwIfAborted();
3184
+ return environmentFailure(error, context.apiUrl);
3185
+ }
3186
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
3187
+ return failure(
3188
+ "repository_not_connected",
3189
+ `${repository} is not connected to Primitive`,
3190
+ CLOUD_GITHUB_CONNECT_REMEDY
3191
+ );
3192
+ if (answer.status === 401 || answer.status === 403)
3193
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
3194
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
3195
+ return failure(
3196
+ "challenge_open",
3197
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
3198
+ `wait five minutes, then ${RETRY_REMEDY}`
3199
+ );
3200
+ if (answer.status === 429)
3201
+ return failure(
3202
+ "too_many_challenges",
3203
+ "too many sessions of this cloud environment are being identified at once",
3204
+ `wait a few minutes, then ${RETRY_REMEDY}`
3205
+ );
3206
+ const challengeId = answer.value?.challengeId;
3207
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
3208
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
3209
+ return answer.status >= 500 ? environmentFailure(
3210
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
3211
+ context.apiUrl
3212
+ ) : SERVER_CONTRACT_FAILURE;
3213
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
3214
+ attempt.challengeId = challengeId;
3215
+ attempt.challengeExpiresAt = challengeExpiresAt;
3216
+ return pushSessionBranch(
3217
+ root,
3218
+ repository,
3219
+ branch,
3220
+ baseSha,
3221
+ { challengeId, challengeExpiresAt },
3222
+ signal
3223
+ );
3224
+ }
3225
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
3226
+ const push = await git2(
3227
+ root,
3228
+ [
3229
+ "-c",
3230
+ "core.hooksPath=/dev/null",
3231
+ "-c",
3232
+ "push.followTags=false",
3233
+ "-c",
3234
+ "push.recurseSubmodules=no",
3235
+ "-c",
3236
+ "push.gpgSign=false",
3237
+ "-c",
3238
+ "push.pushOption=",
3239
+ "push",
3240
+ "--no-verify",
3241
+ "--no-follow-tags",
3242
+ "--no-recurse-submodules",
3243
+ "--no-signed",
3244
+ "--quiet",
3245
+ "origin",
3246
+ `${baseSha}:refs/heads/${branch}`
3247
+ ],
3248
+ signal
3249
+ );
3250
+ if (!push.ok)
3251
+ return push.timedOut ? failure(
3252
+ "push_timeout",
3253
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS4 / 1e3} s`,
3254
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
3255
+ ) : failure(
3256
+ "push_refused",
3257
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
3258
+ `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}`
3259
+ );
3260
+ return { ...challenge, repository };
3261
+ }
3262
+ async function ensureSessionIdentity(options = {}, deps = {}) {
3263
+ let context;
3264
+ try {
3265
+ context = sessionContext(deps);
3266
+ } catch (error) {
3267
+ return failure(
3268
+ "environment_credential_invalid",
3269
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
3270
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
3271
+ );
3272
+ }
3273
+ if ("status" in context) return context;
3274
+ const ctx = context;
3275
+ const startedAt = Date.now();
3276
+ prepareMachineMetadataDirectory(ctx.directory);
3277
+ return withFileLock(
3278
+ ctx.lockPath,
3279
+ async () => {
3280
+ const record = readToken(ctx);
3281
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
3282
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
3283
+ if (record) {
3284
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
3285
+ if (refreshed.status === "ok") {
3286
+ writeToken(ctx, refreshed.record);
3287
+ return identified(refreshed.record, true);
3288
+ }
3289
+ if (refreshed.status === "refused") {
3290
+ rmSync7(ctx.tokenPath, { force: true });
3291
+ writeState(ctx, {
3292
+ sessionId: ctx.sessionId,
3293
+ status: "failed",
3294
+ code: refreshed.failure.code,
3295
+ cause: refreshed.failure.cause,
3296
+ remedy: refreshed.failure.remedy,
3297
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
3298
+ at: Date.now()
3299
+ });
3300
+ return refreshed.failure;
3301
+ }
3302
+ if (!forced && tokenValid(record)) return identified(record, true);
3303
+ }
3304
+ const state = readState(ctx);
3305
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
3306
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
3307
+ if (!options.explicit) {
3308
+ if (!root || !(record || state))
3309
+ return failure(
3310
+ "not_identified",
3311
+ "this session has not identified who started it yet",
3312
+ RETRY_REMEDY
3313
+ );
3314
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
3315
+ } else if (state && state.at >= startedAt) {
3316
+ return outcomeFromState(state);
3317
+ }
3318
+ if (!root)
3319
+ return failure(
3320
+ "repository_missing",
3321
+ "this is not a git repository",
3322
+ "run it in the repository the session cloned"
3323
+ );
3324
+ const attempt = { root };
3325
+ const remember = (outcome) => {
3326
+ writeState(ctx, {
3327
+ sessionId: ctx.sessionId,
3328
+ status: outcome.status,
3329
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
3330
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
3331
+ githubLogin: outcome.githubLogin
3332
+ },
3333
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
3334
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
3335
+ repositoryRoot: root,
3336
+ branch: attempt.branch ?? state?.branch,
3337
+ baseSha: attempt.baseSha ?? state?.baseSha,
3338
+ at: Date.now()
3339
+ });
3340
+ return outcome;
3341
+ };
3342
+ let challenge;
3343
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
3344
+ attempt.challengeId = state.challengeId;
3345
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
3346
+ attempt.branch = state.branch;
3347
+ attempt.baseSha = state.baseSha;
3348
+ challenge = {
3349
+ challengeId: state.challengeId,
3350
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
3351
+ repository: githubRepositoryFullName(root) ?? "the repository"
3352
+ };
3353
+ } else if (state?.status === "link_required" && state.challengeId) {
3354
+ attempt.challengeId = state.challengeId;
3355
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
3356
+ const exchanged2 = await exchangeChallenge(
3357
+ ctx,
3358
+ {
3359
+ challengeId: state.challengeId,
3360
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
3361
+ githubLogin: state.githubLogin
3362
+ },
3363
+ root,
3364
+ deps,
3365
+ options.signal
3366
+ );
3367
+ if ("status" in exchanged2) return remember(exchanged2);
3368
+ writeToken(ctx, exchanged2);
3369
+ return identified(exchanged2, false);
3370
+ } else if (!options.explicit) {
3371
+ return state ? outcomeFromState(state) : failure(
3372
+ "not_identified",
3373
+ "this session has not identified who started it yet",
3374
+ RETRY_REMEDY
3375
+ );
3376
+ } else {
3377
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
3378
+ if ("status" in pushed) return remember(pushed);
3379
+ challenge = pushed;
3380
+ }
3381
+ const verified = await pollChallenge(
3382
+ ctx.apiUrl,
3383
+ challenge.challengeId,
3384
+ challenge.repository,
3385
+ // A hook process waits only briefly for a late notice.
3386
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
3387
+ options.signal
3388
+ );
3389
+ if ("status" in verified) return remember(verified);
3390
+ const exchanged = await exchangeChallenge(
3391
+ ctx,
3392
+ { ...challenge, githubLogin: verified.githubLogin },
3393
+ root,
3394
+ deps,
3395
+ options.signal
3396
+ );
3397
+ if ("status" in exchanged) return remember(exchanged);
3398
+ writeToken(ctx, exchanged);
3399
+ return identified(exchanged, false);
3400
+ },
3401
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
3402
+ );
3403
+ }
3404
+ async function acquireSessionCredential(options = {}, deps = {}) {
3405
+ const cached2 = cachedSessionCredential(deps);
3406
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
3407
+ if (cached2 && fresh && !options.force) return cached2;
3408
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
3409
+ let outcome;
3410
+ try {
3411
+ outcome = await ensureSessionIdentity(
3412
+ { force: options.force, observedToken: cached2?.accessToken, signal },
3413
+ deps
3414
+ );
3415
+ } catch (error) {
3416
+ options.signal?.throwIfAborted();
3417
+ if (error instanceof MachineAuthError) throw error;
3418
+ throw new MachineAuthError(
3419
+ "identity_unavailable",
3420
+ "Identifying who started this cloud session is still in progress; retry shortly."
3421
+ );
3422
+ }
3423
+ if (outcome.status === "ok") return outcome.credential;
3424
+ throw new MachineAuthError(
3425
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
3426
+ sessionIdentityMessage(outcome)
3427
+ );
3428
+ }
3429
+
2303
3430
  // src/lib/machine-credentials.ts
3431
+ function sessionScoped(deps) {
3432
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
3433
+ }
2304
3434
  var require3 = createRequire2(import.meta.url);
2305
3435
  var SERVICE = "ai.primitive.prim.machine";
2306
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
3436
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
2307
3437
  var PROFILE_FILE = "machine_profile.json";
2308
- var RENEW_BEFORE_MS = 6e4;
3438
+ var RENEW_BEFORE_MS2 = 6e4;
2309
3439
  var cached;
2310
3440
  function configurationDirectory(deps) {
2311
3441
  return deps.directory ?? primConfigDirectory({ env: deps.env });
2312
3442
  }
2313
3443
  function apiUrlFor(deps) {
2314
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
3444
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
2315
3445
  }
2316
- function hash(value) {
2317
- return createHash5("sha256").update(value).digest("hex");
3446
+ function hash2(value) {
3447
+ return createHash6("sha256").update(value).digest("hex");
2318
3448
  }
2319
3449
  function recordPath(directory, generation) {
2320
- return join13(directory, `machine_${generation}.json`);
3450
+ return join14(directory, `machine_${generation}.json`);
2321
3451
  }
2322
3452
  function storageKey(directory, generation) {
2323
- return `${hash(directory)}:${generation}`;
3453
+ return `${hash2(directory)}:${generation}`;
2324
3454
  }
2325
3455
  function environmentContextPath(deps, clientId) {
2326
- return join13(
3456
+ return join14(
2327
3457
  configurationDirectory(deps),
2328
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
3458
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2329
3459
  );
2330
3460
  }
2331
3461
  function writeEnvironmentContext(credential, deps) {
@@ -2383,17 +3513,23 @@ function readEnvironmentContext(environment, deps) {
2383
3513
  return void 0;
2384
3514
  }
2385
3515
  }
2386
- function keyringEntry(key) {
2387
- let directory = dirname8(fileURLToPath4(import.meta.url));
3516
+ function keyringLoaderPath(start, options = {}) {
3517
+ let directory = start;
2388
3518
  for (let depth = 0; depth < 5; depth++) {
2389
- const loader = join13(directory, "native", "keyring.cjs");
2390
- if (existsSync9(loader)) {
2391
- const module2 = require3(loader);
2392
- return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
2393
- }
3519
+ const loader = join14(directory, "native", "keyring.cjs");
3520
+ if (existsSync9(loader)) return loader;
2394
3521
  directory = dirname8(directory);
2395
3522
  }
2396
- const module = require3("@napi-rs/keyring");
3523
+ try {
3524
+ createRequire2(join14(start, "noop.js")).resolve("@napi-rs/keyring");
3525
+ return void 0;
3526
+ } catch {
3527
+ return selectedHookRuntimeKeyringLoader(options);
3528
+ }
3529
+ }
3530
+ function keyringEntry(key) {
3531
+ const loader = keyringLoaderPath(dirname8(fileURLToPath4(import.meta.url)));
3532
+ const module = require3(loader ?? "@napi-rs/keyring");
2397
3533
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
2398
3534
  }
2399
3535
  function protectPath(path, directory) {
@@ -2428,6 +3564,9 @@ function writePrivate(path, value) {
2428
3564
  `, { mode: 384 });
2429
3565
  protectPath(path, false);
2430
3566
  }
3567
+ function readMachineMetadata(path) {
3568
+ return readPrivate(path);
3569
+ }
2431
3570
  function readPrivate(path) {
2432
3571
  let raw;
2433
3572
  try {
@@ -2483,7 +3622,7 @@ function parseProfile(value) {
2483
3622
  };
2484
3623
  }
2485
3624
  function readMachineProfile(deps = {}) {
2486
- const value = readPrivate(join13(configurationDirectory(deps), PROFILE_FILE));
3625
+ const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
2487
3626
  return value === void 0 ? void 0 : parseProfile(value);
2488
3627
  }
2489
3628
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -2492,7 +3631,7 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2492
3631
  var brokerKeys = /* @__PURE__ */ new Map();
2493
3632
  function networkSecretBrokerKey(deps, clientId) {
2494
3633
  const directory = configurationDirectory(deps);
2495
- const path = join13(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
3634
+ const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2496
3635
  const known = brokerKeys.get(path);
2497
3636
  if (known) return known;
2498
3637
  ensureDirectory(directory);
@@ -2533,7 +3672,7 @@ function networkSecretBrokerKey(deps, clientId) {
2533
3672
  } catch (error) {
2534
3673
  if (error.code !== "EEXIST") throw error;
2535
3674
  } finally {
2536
- rmSync7(staged, { force: true });
3675
+ rmSync8(staged, { force: true });
2537
3676
  }
2538
3677
  }
2539
3678
  const key = read()?.key;
@@ -2566,7 +3705,7 @@ function environmentCredentials(deps) {
2566
3705
  "conflicting_credentials",
2567
3706
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2568
3707
  );
2569
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
3708
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2570
3709
  const credentials = {
2571
3710
  clientId,
2572
3711
  generation,
@@ -2587,12 +3726,12 @@ function environmentCredentials(deps) {
2587
3726
  return {
2588
3727
  clientId,
2589
3728
  clientSecret,
2590
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
3729
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2591
3730
  };
2592
3731
  }
2593
3732
  function hasMachineConfiguration(deps = {}) {
2594
3733
  const env = deps.env ?? process.env;
2595
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(join13(configurationDirectory(deps), PROFILE_FILE));
3734
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(join14(configurationDirectory(deps), PROFILE_FILE));
2596
3735
  if (configured && env.PRIM_TOKEN?.trim()) {
2597
3736
  throw new MachineAuthError(
2598
3737
  "conflicting_credentials",
@@ -2604,6 +3743,7 @@ function hasMachineConfiguration(deps = {}) {
2604
3743
  }
2605
3744
  function machineContext(deps = {}) {
2606
3745
  if (!hasMachineConfiguration(deps)) return void 0;
3746
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
2607
3747
  const environment = environmentCredentials(deps);
2608
3748
  if (environment) {
2609
3749
  if (environmentTerminal === environment.generation) return void 0;
@@ -2618,6 +3758,7 @@ function machineContext(deps = {}) {
2618
3758
  return profile;
2619
3759
  }
2620
3760
  function cachedMachineCredential(deps = {}) {
3761
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
2621
3762
  const context = machineContext(deps);
2622
3763
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
2623
3764
  }
@@ -2626,7 +3767,7 @@ function machineSessionEnded(deps = {}) {
2626
3767
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
2627
3768
  if (!generation) return false;
2628
3769
  if (environmentCredentials(deps)) return environmentTerminal === generation;
2629
- return readPrivate(join13(configurationDirectory(deps), "machine_terminal.json")) === generation;
3770
+ return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
2630
3771
  }
2631
3772
  var environmentTerminal;
2632
3773
  var NETWORK_REJECTION_PAUSE_MS = 3e4;
@@ -2690,6 +3831,7 @@ async function persistRecord(record, deps, signal) {
2690
3831
  }
2691
3832
  async function acquireMachineCredential(options = {}, deps = {}) {
2692
3833
  if (!hasMachineConfiguration(deps)) return void 0;
3834
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
2693
3835
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2694
3836
  const apiUrl = apiUrlFor(deps);
2695
3837
  const environment = environmentCredentials(deps);
@@ -2718,7 +3860,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2718
3860
  }
2719
3861
  }
2720
3862
  return withFileLock(
2721
- join13(directory2, "credentials.lock"),
3863
+ join14(directory2, "credentials.lock"),
2722
3864
  async () => {
2723
3865
  if (machineSessionEnded(deps))
2724
3866
  throw new MachineAuthError(
@@ -2726,7 +3868,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2726
3868
  rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
2727
3869
  true
2728
3870
  );
2729
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
3871
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
2730
3872
  return cached;
2731
3873
  if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2732
3874
  throw networkRejection.error;
@@ -2800,7 +3942,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2800
3942
  const contextPath = environmentContextPath(deps, environment.clientId);
2801
3943
  try {
2802
3944
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2803
- rmSync7(contextPath, { force: true });
3945
+ rmSync8(contextPath, { force: true });
2804
3946
  } catch {
2805
3947
  }
2806
3948
  throw error;
@@ -2810,7 +3952,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2810
3952
  const contextPath = environmentContextPath(deps, environment.clientId);
2811
3953
  try {
2812
3954
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2813
- rmSync7(contextPath, { force: true });
3955
+ rmSync8(contextPath, { force: true });
2814
3956
  } catch {
2815
3957
  }
2816
3958
  }
@@ -2824,7 +3966,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2824
3966
  const expected = machineContext(deps);
2825
3967
  const directory = configurationDirectory(deps);
2826
3968
  return withFileLock(
2827
- join13(directory, "credentials.lock"),
3969
+ join14(directory, "credentials.lock"),
2828
3970
  async () => {
2829
3971
  const profile = readMachineProfile(deps);
2830
3972
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -2839,7 +3981,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2839
3981
  true
2840
3982
  );
2841
3983
  let record = await loadRecord(profile, deps, signal);
2842
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
3984
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
2843
3985
  try {
2844
3986
  const { tokens, identity } = await withMachineCooldown(
2845
3987
  directory,
@@ -2874,7 +4016,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2874
4016
  await persistRecord(record, deps, signal);
2875
4017
  } catch (error) {
2876
4018
  if (error instanceof MachineAuthError && error.terminal)
2877
- writePrivate(join13(directory, "machine_terminal.json"), profile.generation);
4019
+ writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
2878
4020
  throw error;
2879
4021
  }
2880
4022
  }
@@ -2903,17 +4045,23 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
2903
4045
  signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2904
4046
  });
2905
4047
  }
4048
+ function prepareMachineMetadataDirectory(directory) {
4049
+ ensureDirectory(directory);
4050
+ }
4051
+ function writeMachineMetadata(path, value) {
4052
+ writePrivate(path, value);
4053
+ }
2906
4054
 
2907
4055
  // src/lib/credentials.ts
2908
4056
  var CONFIG_DIRECTORY = primConfigDirectory();
2909
- var TOKEN_FILE_PATH = join14(CONFIG_DIRECTORY, "token");
2910
- var REFRESH_TOKEN_PATH = join14(CONFIG_DIRECTORY, "refresh_token");
2911
- var TOKEN_EXPIRES_PATH = join14(CONFIG_DIRECTORY, "token_expires_at");
2912
- var TERMINAL_REFRESH_PATH = join14(CONFIG_DIRECTORY, "refresh_terminal");
2913
- var CREDENTIAL_METADATA_PATH = join14(CONFIG_DIRECTORY, "credential_metadata.json");
2914
- var CREDENTIAL_FAMILY_PATH = join14(CONFIG_DIRECTORY, "credential_family.json");
2915
- var CREDENTIAL_MIGRATION_PATH = join14(CONFIG_DIRECTORY, "credential_migration.json");
2916
- var CREDENTIAL_LOCK_PATH = join14(CONFIG_DIRECTORY, "credentials.lock");
4057
+ var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
4058
+ var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
4059
+ var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
4060
+ var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
4061
+ var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
4062
+ var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
4063
+ var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
4064
+ var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
2917
4065
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
2918
4066
  var CREDENTIAL_MIGRATION_VERSION = 1;
2919
4067
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
@@ -2941,16 +4089,16 @@ function resolveAuthCredential(options = {}) {
2941
4089
  );
2942
4090
  if (metadata.state === "legacy_broker") {
2943
4091
  if (metadata.metadata) {
2944
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2945
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
4092
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
4093
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
2946
4094
  return void 0;
2947
4095
  }
2948
4096
  }
2949
4097
  return { token: stored, source: "token_file" };
2950
4098
  }
2951
4099
  if (metadata.state === "invalid") return void 0;
2952
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2953
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
4100
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
4101
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
2954
4102
  return void 0;
2955
4103
  }
2956
4104
  return { token: stored, source: "token_file" };
@@ -2959,15 +4107,15 @@ function resolveStoredCredential(env = process.env) {
2959
4107
  const directory = primConfigDirectory({ env });
2960
4108
  return resolveAuthCredential({
2961
4109
  env,
2962
- tokenFilePath: join14(directory, "token"),
2963
- refreshTokenPath: join14(directory, "refresh_token"),
2964
- metadataPath: join14(directory, "credential_metadata.json"),
2965
- familyPath: join14(directory, "credential_family.json"),
2966
- migrationPath: join14(directory, "credential_migration.json")
4110
+ tokenFilePath: join15(directory, "token"),
4111
+ refreshTokenPath: join15(directory, "refresh_token"),
4112
+ metadataPath: join15(directory, "credential_metadata.json"),
4113
+ familyPath: join15(directory, "credential_family.json"),
4114
+ migrationPath: join15(directory, "credential_migration.json")
2967
4115
  });
2968
4116
  }
2969
4117
  function credentialFingerprint(value) {
2970
- return createHash6("sha256").update(value).digest("hex");
4118
+ return createHash7("sha256").update(value).digest("hex");
2971
4119
  }
2972
4120
  function parseLegacyBrokerCredentialMetadata(value) {
2973
4121
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -3061,7 +4209,7 @@ function jwtExpiresAt(token) {
3061
4209
  // src/daemon/client-instance-id.ts
3062
4210
  import { randomBytes as randomBytes5 } from "crypto";
3063
4211
  import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
3064
- import { join as join15 } from "path";
4212
+ import { join as join16 } from "path";
3065
4213
  var CONFIG_DIRECTORY_MODE = 448;
3066
4214
  var INSTANCE_FILE_MODE = 384;
3067
4215
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -3112,8 +4260,8 @@ function atomicWrite(path, value) {
3112
4260
  }
3113
4261
  async function getOrCreateClientInstanceId(options) {
3114
4262
  const configDir = options.configDir;
3115
- const path = join15(configDir, "client_instance_id");
3116
- const lockPath = join15(configDir, "client-instance.lock");
4263
+ const path = join16(configDir, "client_instance_id");
4264
+ const lockPath = join16(configDir, "client-instance.lock");
3117
4265
  ensurePrivateConfigDirectory(configDir);
3118
4266
  return withFileLock(
3119
4267
  lockPath,
@@ -3157,56 +4305,11 @@ async function ingestUploaderHeaders() {
3157
4305
  return headers;
3158
4306
  }
3159
4307
 
3160
- // src/lib/terminal-safe.ts
3161
- function replaceIsolatedSurrogates(value) {
3162
- let out = "";
3163
- for (let index = 0; index < value.length; index += 1) {
3164
- const unit = value.charCodeAt(index);
3165
- if (unit >= 55296 && unit <= 56319) {
3166
- const next = value.charCodeAt(index + 1);
3167
- if (next >= 56320 && next <= 57343) {
3168
- out += value[index] + value[index + 1];
3169
- index += 1;
3170
- } else {
3171
- out += "\uFFFD";
3172
- }
3173
- } else if (unit >= 56320 && unit <= 57343) {
3174
- out += "\uFFFD";
3175
- } else {
3176
- out += value[index];
3177
- }
3178
- }
3179
- return out;
3180
- }
3181
- function isUnsafeTerminalCodePoint(point) {
3182
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
3183
- const bidiOrZeroWidth = point === 173 || // soft hyphen
3184
- point === 1564 || // Arabic letter mark
3185
- point === 6158 || // Mongolian vowel separator
3186
- point >= 8203 && point <= 8207 || // zero-width + directional marks
3187
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
3188
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
3189
- point >= 65529 && point <= 65531 || // interlinear annotation controls
3190
- point === 65279 || // zero-width no-break space / BOM
3191
- point >= 917504 && point <= 917631;
3192
- return c0OrC1 || bidiOrZeroWidth;
3193
- }
3194
- function terminalSafeText(value) {
3195
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
3196
- }
3197
- function terminalSafeLine(value) {
3198
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
3199
- }
3200
- function isTerminalSafeText(value) {
3201
- return terminalSafeText(value) === value;
3202
- }
3203
- var stripControlChars = terminalSafeText;
3204
-
3205
4308
  // src/client.ts
3206
4309
  var CONFIG_DIR_MODE = 448;
3207
4310
  var CREDENTIAL_FILE_MODE = 384;
3208
4311
  var REFRESH_THRESHOLD_MS = 6e4;
3209
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
4312
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
3210
4313
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
3211
4314
  function authExpiredMessage() {
3212
4315
  return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
@@ -3223,7 +4326,7 @@ function getSiteUrl() {
3223
4326
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
3224
4327
  }
3225
4328
  function getSiteUrlForEnvironment(primApiUrl) {
3226
- return primApiUrl?.trim() || DEFAULT_API_URL2;
4329
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
3227
4330
  }
3228
4331
  function expiresAtFor(token, expiresIn) {
3229
4332
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
@@ -3239,7 +4342,7 @@ function atomicWrite2(path, content) {
3239
4342
  }
3240
4343
  function removeCredentialFile(path) {
3241
4344
  if (!existsSync10(path)) return false;
3242
- rmSync8(path, { force: true });
4345
+ rmSync9(path, { force: true });
3243
4346
  return true;
3244
4347
  }
3245
4348
  function getTokenExpiresAt() {
@@ -3254,23 +4357,23 @@ function isTokenExpiringSoon(credential) {
3254
4357
  const expiresAt = getTokenExpiresAt();
3255
4358
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
3256
4359
  }
3257
- function refreshFingerprint(refreshToken2) {
3258
- return createHash7("sha256").update(refreshToken2).digest("hex");
4360
+ function refreshFingerprint(refreshToken3) {
4361
+ return createHash8("sha256").update(refreshToken3).digest("hex");
3259
4362
  }
3260
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
4363
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
3261
4364
  return {
3262
4365
  version: 1,
3263
4366
  family: "legacy_broker",
3264
4367
  accessTokenHash: refreshFingerprint(accessToken),
3265
- refreshTokenHash: refreshFingerprint(refreshToken2)
4368
+ refreshTokenHash: refreshFingerprint(refreshToken3)
3266
4369
  };
3267
4370
  }
3268
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
4371
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
3269
4372
  const hashes = {
3270
4373
  accessTokenHash: refreshFingerprint(accessToken),
3271
- refreshTokenHash: refreshFingerprint(refreshToken2)
4374
+ refreshTokenHash: refreshFingerprint(refreshToken3)
3272
4375
  };
3273
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
4376
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
3274
4377
  }
3275
4378
  function writeCredentialMigrationSentinel() {
3276
4379
  atomicWrite2(
@@ -3282,11 +4385,11 @@ function writeCredentialMigrationSentinel() {
3282
4385
  `
3283
4386
  );
3284
4387
  }
3285
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
3286
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
4388
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
4389
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
3287
4390
  return { state: "invalid" };
3288
4391
  }
3289
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
4392
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
3290
4393
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
3291
4394
  return { state: "invalid" };
3292
4395
  }
@@ -3303,17 +4406,17 @@ function preserveMarkerlessLegacyGeneration() {
3303
4406
  const metadata = readStoredCredentialMetadata();
3304
4407
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
3305
4408
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
3306
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3307
- if (!(accessToken && refreshToken2)) return;
3308
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
4409
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
4410
+ if (!(accessToken && refreshToken3)) return;
4411
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
3309
4412
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
3310
4413
  `);
3311
4414
  }
3312
4415
  function terminalFingerprint() {
3313
4416
  return readTrimmed2(TERMINAL_REFRESH_PATH);
3314
4417
  }
3315
- function writeTerminalFingerprint(refreshToken2) {
3316
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
4418
+ function writeTerminalFingerprint(refreshToken3) {
4419
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
3317
4420
  `);
3318
4421
  }
3319
4422
  function clearTerminalFingerprint() {
@@ -3322,20 +4425,20 @@ function clearTerminalFingerprint() {
3322
4425
  function isSessionEnded() {
3323
4426
  if (hasMachineConfiguration()) return machineSessionEnded();
3324
4427
  if (resolveAuthCredential()?.source !== "token_file") return false;
3325
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
4428
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3326
4429
  const ended = terminalFingerprint();
3327
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
4430
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
3328
4431
  }
3329
4432
  function withCredentialLock(operation, options = {}) {
3330
4433
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
3331
4434
  }
3332
4435
  function commitCredentialsUnlocked(credentials) {
3333
4436
  const accessToken = credentials.accessToken.trim();
3334
- const refreshToken2 = credentials.refreshToken.trim();
3335
- if (!accessToken || !refreshToken2) {
4437
+ const refreshToken3 = credentials.refreshToken.trim();
4438
+ if (!accessToken || !refreshToken3) {
3336
4439
  throw new Error("OAuth credentials require both access and refresh tokens");
3337
4440
  }
3338
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
4441
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
3339
4442
  if (credentials.metadata !== void 0) {
3340
4443
  preserveMarkerlessLegacyGeneration();
3341
4444
  writeCredentialMigrationSentinel();
@@ -3343,10 +4446,10 @@ function commitCredentialsUnlocked(credentials) {
3343
4446
  `);
3344
4447
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
3345
4448
  `);
3346
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
4449
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
3347
4450
  `);
3348
4451
  } else {
3349
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
4452
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
3350
4453
  `);
3351
4454
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
3352
4455
  `);
@@ -3383,15 +4486,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
3383
4486
  `
3384
4487
  );
3385
4488
  }
3386
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
4489
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
3387
4490
  const current = readStoredCredentialMetadata();
3388
4491
  if (expected.state === "legacy_broker") {
3389
4492
  if (current.state !== "legacy_broker") return false;
3390
4493
  if (!expected.metadata) return current.metadata === void 0;
3391
- 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;
4494
+ 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;
3392
4495
  }
3393
4496
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
3394
- 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;
4497
+ 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;
3395
4498
  }
3396
4499
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
3397
4500
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -3560,7 +4663,7 @@ async function performTokenRefresh(options = {}) {
3560
4663
  );
3561
4664
  }
3562
4665
  var _refreshInFlight;
3563
- function refreshToken(options = {}) {
4666
+ function refreshToken2(options = {}) {
3564
4667
  if (hasMachineConfiguration())
3565
4668
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
3566
4669
  if (_refreshInFlight) return _refreshInFlight;
@@ -3698,7 +4801,7 @@ async function machineClient(options = {}, management = false) {
3698
4801
  if (response.status === 401)
3699
4802
  throw new HttpError(
3700
4803
  401,
3701
- 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(
4804
+ 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(
3702
4805
  "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3703
4806
  )
3704
4807
  );
@@ -3719,7 +4822,7 @@ async function request2(method, path, body, options) {
3719
4822
  let refreshAttempted = false;
3720
4823
  if (credential && isTokenExpiringSoon(credential)) {
3721
4824
  refreshAttempted = true;
3722
- const token = await refreshToken({
4825
+ const token = await refreshToken2({
3723
4826
  signal: options?.signal,
3724
4827
  quiet: options?.quietRefresh
3725
4828
  });
@@ -3738,7 +4841,7 @@ async function request2(method, path, body, options) {
3738
4841
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
3739
4842
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
3740
4843
  refreshAttempted = true;
3741
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4844
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
3742
4845
  }
3743
4846
  if (retryToken) {
3744
4847
  _cachedCredential = {
@@ -3758,7 +4861,7 @@ function getClient() {
3758
4861
  }
3759
4862
 
3760
4863
  // src/commands/claude-plugin.ts
3761
- import { createHash as createHash10 } from "crypto";
4864
+ import { createHash as createHash11 } from "crypto";
3762
4865
  import {
3763
4866
  constants as constants4,
3764
4867
  closeSync as closeSync3,
@@ -3771,11 +4874,11 @@ import {
3771
4874
  readSync as readSync2,
3772
4875
  readdirSync as readdirSync5,
3773
4876
  realpathSync as realpathSync3,
3774
- rmSync as rmSync9,
4877
+ rmSync as rmSync10,
3775
4878
  rmdirSync as rmdirSync3
3776
4879
  } from "fs";
3777
4880
  import { homedir as homedir7 } from "os";
3778
- import { dirname as dirname12, isAbsolute as isAbsolute6, join as join20, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
4881
+ import { dirname as dirname12, isAbsolute as isAbsolute6, join as join21, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
3779
4882
  import { fileURLToPath as fileURLToPath6 } from "url";
3780
4883
 
3781
4884
  // node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
@@ -10046,7 +11149,7 @@ function parse(src, reviver, options) {
10046
11149
  }
10047
11150
 
10048
11151
  // src/commands/skill.ts
10049
- import { createHash as createHash9 } from "crypto";
11152
+ import { createHash as createHash10 } from "crypto";
10050
11153
  import {
10051
11154
  constants as constants3,
10052
11155
  closeSync as closeSync2,
@@ -10061,7 +11164,7 @@ import {
10061
11164
  unlinkSync as unlinkSync2
10062
11165
  } from "fs";
10063
11166
  import { homedir as homedir6 } from "os";
10064
- import { dirname as dirname11, join as join19, resolve as resolve4 } from "path";
11167
+ import { dirname as dirname11, join as join20, resolve as resolve4 } from "path";
10065
11168
  import { fileURLToPath as fileURLToPath5 } from "url";
10066
11169
 
10067
11170
  // node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
@@ -10231,7 +11334,7 @@ Diff.prototype = {
10231
11334
  tokenize: function tokenize(value) {
10232
11335
  return value.split("");
10233
11336
  },
10234
- join: function join17(chars) {
11337
+ join: function join18(chars) {
10235
11338
  return chars.join("");
10236
11339
  }
10237
11340
  };
@@ -10416,11 +11519,11 @@ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
10416
11519
  };
10417
11520
 
10418
11521
  // src/commands/welcome-skill.ts
10419
- import { createHash as createHash8 } from "crypto";
11522
+ import { createHash as createHash9 } from "crypto";
10420
11523
  import { existsSync as existsSync11, lstatSync as lstatSync8, readFileSync as readFileSync15, readdirSync as readdirSync3, rmdirSync, unlinkSync } from "fs";
10421
11524
  import { homedir as homedir5 } from "os";
10422
- import { dirname as dirname10, join as join18 } from "path";
10423
- var WELCOME_SKILL_SOURCE = join18("skills", "prim-welcome", "SKILL.md");
11525
+ import { dirname as dirname10, join as join19 } from "path";
11526
+ var WELCOME_SKILL_SOURCE = join19("skills", "prim-welcome", "SKILL.md");
10424
11527
 
10425
11528
  // src/commands/skill.ts
10426
11529
  var __dirname = dirname11(fileURLToPath5(import.meta.url));
@@ -10455,10 +11558,10 @@ function readCodexGuidance(path) {
10455
11558
  }
10456
11559
  }
10457
11560
  function effectiveCodexGuidance(scope) {
10458
- const override = readCodexGuidance(join19(scope, "AGENTS.override.md"));
11561
+ const override = readCodexGuidance(join20(scope, "AGENTS.override.md"));
10459
11562
  if (override === null) return null;
10460
11563
  if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
10461
- const base = readCodexGuidance(join19(scope, "AGENTS.md"));
11564
+ const base = readCodexGuidance(join20(scope, "AGENTS.md"));
10462
11565
  return base ?? null;
10463
11566
  }
10464
11567
  function hasUsablePrimBlock(content, visibleBytes) {
@@ -10481,7 +11584,7 @@ function hasUsablePrimBlock(content, visibleBytes) {
10481
11584
  }
10482
11585
  function hasUsableCodexGuidance(projectRoot2) {
10483
11586
  try {
10484
- const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join19(homedir6(), ".codex");
11587
+ const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join20(homedir6(), ".codex");
10485
11588
  const scopes = [
10486
11589
  { path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
10487
11590
  { path: projectRoot2, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
@@ -10496,19 +11599,19 @@ function hasUsableCodexGuidance(projectRoot2) {
10496
11599
  }
10497
11600
  var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
10498
11601
  var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
10499
- function sha256(content) {
10500
- return createHash9("sha256").update(content).digest("hex");
11602
+ function sha2562(content) {
11603
+ return createHash10("sha256").update(content).digest("hex");
10501
11604
  }
10502
11605
  function cursorSkillDirectory(cwd, scope) {
10503
11606
  const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
10504
- return join19(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
11607
+ return join20(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
10505
11608
  }
10506
11609
  function cursorSkillPaths(cwd, scope) {
10507
11610
  const directory = cursorSkillDirectory(cwd, scope);
10508
11611
  return {
10509
11612
  directory,
10510
- skill: join19(directory, "SKILL.md"),
10511
- manifest: join19(directory, CURSOR_SKILL_MANIFEST)
11613
+ skill: join20(directory, "SKILL.md"),
11614
+ manifest: join20(directory, CURSOR_SKILL_MANIFEST)
10512
11615
  };
10513
11616
  }
10514
11617
  function readCursorSkillManifest(path) {
@@ -10529,7 +11632,7 @@ function cursorSkillStatus(cwd, scope) {
10529
11632
  const manifest = readCursorSkillManifest(paths.manifest);
10530
11633
  const content = existsSync12(paths.skill) ? readFileSync16(paths.skill, "utf8") : void 0;
10531
11634
  const owned = manifest !== void 0;
10532
- const installed = owned && content !== void 0 && sha256(content) === manifest.contentSha256;
11635
+ const installed = owned && content !== void 0 && sha2562(content) === manifest.contentSha256;
10533
11636
  return {
10534
11637
  installed,
10535
11638
  owned,
@@ -10561,8 +11664,8 @@ var MAX_SKILL_BYTES = 1024 * 1024;
10561
11664
  var REFRESH_LOCK_TIMEOUT_MS = 150;
10562
11665
  var REFRESH_LOCK_POLL_MS = 10;
10563
11666
  function pluginDirFor(cwd, scope) {
10564
- const base = scope === "user" ? join20(homedir7(), ".claude") : join20(gitToplevel(cwd) ?? cwd, ".claude");
10565
- return join20(base, "skills", "prim");
11667
+ const base = scope === "user" ? join21(homedir7(), ".claude") : join21(gitToplevel(cwd) ?? cwd, ".claude");
11668
+ return join21(base, "skills", "prim");
10566
11669
  }
10567
11670
  function packageVersion2() {
10568
11671
  let dir = __dirname2;
@@ -10584,8 +11687,8 @@ function renderClaudePlugin() {
10584
11687
  }
10585
11688
  function pluginPaths(dir) {
10586
11689
  return {
10587
- manifestPath: join20(dir, ".claude-plugin", "plugin.json"),
10588
- skillPath: join20(dir, "SKILL.md")
11690
+ manifestPath: join21(dir, ".claude-plugin", "plugin.json"),
11691
+ skillPath: join21(dir, "SKILL.md")
10589
11692
  };
10590
11693
  }
10591
11694
  function pathIsInside(root, path) {
@@ -10650,9 +11753,9 @@ function inspectRecognizedInstallation(paths, projectRoot2) {
10650
11753
  };
10651
11754
  }
10652
11755
  function refreshLockDir(physicalPluginDir) {
10653
- const cacheRoot = process.env.XDG_CACHE_HOME || join20(homedir7(), ".cache");
10654
- const identity = createHash10("sha256").update(physicalPluginDir).digest("hex");
10655
- return join20(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
11756
+ const cacheRoot = process.env.XDG_CACHE_HOME || join21(homedir7(), ".cache");
11757
+ const identity = createHash11("sha256").update(physicalPluginDir).digest("hex");
11758
+ return join21(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
10656
11759
  }
10657
11760
  async function refreshClaudePlugins(cwd, options = {}) {
10658
11761
  const result = { installed: 0, refreshed: 0 };
@@ -10660,7 +11763,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
10660
11763
  if (options.includeProject !== false) {
10661
11764
  const projectRoot2 = options.projectRoot ?? gitToplevel(cwd);
10662
11765
  if (projectRoot2 !== null && isAbsolute6(projectRoot2)) {
10663
- candidates.push({ dir: join20(projectRoot2, ".claude", "skills", "prim"), projectRoot: projectRoot2 });
11766
+ candidates.push({ dir: join21(projectRoot2, ".claude", "skills", "prim"), projectRoot: projectRoot2 });
10664
11767
  }
10665
11768
  }
10666
11769
  candidates.push({ dir: pluginDirFor(cwd, "user") });
@@ -10723,23 +11826,23 @@ async function refreshClaudePlugins(cwd, options = {}) {
10723
11826
  }
10724
11827
 
10725
11828
  // src/daemon/principal.ts
10726
- import { createHash as createHash11 } from "crypto";
11829
+ import { createHash as createHash12 } from "crypto";
10727
11830
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
10728
11831
  function boundedClaim(value) {
10729
11832
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
10730
11833
  }
10731
- function sha2562(value) {
10732
- return createHash11("sha256").update(value).digest("hex");
11834
+ function sha2563(value) {
11835
+ return createHash12("sha256").update(value).digest("hex");
10733
11836
  }
10734
11837
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
10735
11838
  if (hasMachineConfiguration()) {
10736
11839
  const machine = machineContext();
10737
11840
  return machine ? {
10738
- principalId: sha2562(
11841
+ principalId: sha2563(
10739
11842
  `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
10740
11843
  ),
10741
11844
  organizationId: machine.workosOrganizationId,
10742
- credentialFingerprint: sha2562(machine.generation)
11845
+ credentialFingerprint: sha2563(machine.generation)
10743
11846
  } : void 0;
10744
11847
  }
10745
11848
  if (!token) return void 0;
@@ -10749,9 +11852,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
10749
11852
  if (!(subject && organizationId)) return void 0;
10750
11853
  const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
10751
11854
  return {
10752
- principalId: sha2562(`${issuer}\0${subject}`),
11855
+ principalId: sha2563(`${issuer}\0${subject}`),
10753
11856
  organizationId,
10754
- credentialFingerprint: sha2562(token)
11857
+ credentialFingerprint: sha2563(token)
10755
11858
  };
10756
11859
  }
10757
11860
  function daemonPrincipalsMatch(caller, daemon) {
@@ -10783,8 +11886,8 @@ function parseDaemonResponseEnvelope(value) {
10783
11886
 
10784
11887
  // src/daemon/client.ts
10785
11888
  import { createConnection } from "net";
10786
- import { join as join21 } from "path";
10787
- var SOCK_PATH = join21(primConfigDirectory(), "sock");
11889
+ import { join as join22 } from "path";
11890
+ var SOCK_PATH = join22(primConfigDirectory(), "sock");
10788
11891
  var DEFAULT_TIMEOUT_MS2 = 250;
10789
11892
  var nextRequestId = 1;
10790
11893
  function daemonRequest(method, params = {}, opts = {}) {
@@ -11093,13 +12196,13 @@ async function acknowledgeDecisionFeedback(input, dependencies = {}) {
11093
12196
  // src/lib/bin-cache.ts
11094
12197
  import { chmodSync as chmodSync5, mkdirSync as mkdirSync8 } from "fs";
11095
12198
  import { homedir as homedir8 } from "os";
11096
- import { join as join22 } from "path";
12199
+ import { join as join23 } from "path";
11097
12200
  var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
11098
12201
  var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
11099
12202
  var GIT_HOOK_CACHED_BINS = ["prim-post-commit", "prim-post-rewrite"];
11100
12203
  function binCacheDir() {
11101
- const base = process.env.XDG_CACHE_HOME || join22(homedir8(), ".cache");
11102
- return join22(base, "prim", "bin");
12204
+ const base = process.env.XDG_CACHE_HOME || join23(homedir8(), ".cache");
12205
+ return join23(base, "prim", "bin");
11103
12206
  }
11104
12207
  function writeAtomic(path, content) {
11105
12208
  atomicWriteFile(path, content, { mode: 384 });
@@ -11112,11 +12215,11 @@ function warmBinCache() {
11112
12215
  const dir = binCacheDir();
11113
12216
  mkdirSync8(dir, { recursive: true, mode: 448 });
11114
12217
  chmodSync5(dir, 448);
11115
- writeAtomic(join22(dir, "node"), process.execPath);
12218
+ writeAtomic(join23(dir, "node"), process.execPath);
11116
12219
  for (const bin of GIT_HOOK_CACHED_BINS) {
11117
12220
  const file = binFile(bin);
11118
12221
  if (file) {
11119
- writeAtomic(join22(dir, bin), file);
12222
+ writeAtomic(join23(dir, bin), file);
11120
12223
  }
11121
12224
  }
11122
12225
  } catch {
@@ -11164,11 +12267,14 @@ async function probe(url, fetchImpl) {
11164
12267
  return { ok: false, failure: probeFailure(error) };
11165
12268
  }
11166
12269
  }
11167
- function unreachable(what, failure, remedy) {
11168
- if (failure === "blocked") return `this environment cannot reach ${what}. To fix it, ${remedy}.`;
11169
- if (failure === "timeout")
12270
+ function unreachable(what, failure2, remedy) {
12271
+ if (failure2 === "blocked") return `this environment cannot reach ${what}. To fix it, ${remedy}.`;
12272
+ if (failure2 === "timeout")
11170
12273
  return `${what} did not answer in time. If this persists, check that you ${remedy.replace(/^add /u, "added ")}.`;
11171
- return `${what} could not be reached (${failure}). Check the environment's network access: ${remedy}.`;
12274
+ return `${what} could not be reached (${failure2}). Check the environment's network access: ${remedy}.`;
12275
+ }
12276
+ function credentialRejected(error) {
12277
+ return error instanceof HttpError && error.status === 401;
11172
12278
  }
11173
12279
  async function diagnoseCloudSession(options = {}) {
11174
12280
  const env = options.env ?? process.env;
@@ -11184,6 +12290,7 @@ async function diagnoseCloudSession(options = {}) {
11184
12290
  }
11185
12291
  if (!machine && !resolveStoredCredential(env))
11186
12292
  return `${prefix}: it has no credentials. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
12293
+ if (machine && credentialRejected(options.bindFailure)) return CLOUD_REJECTED_CREDENTIALS_NOTICE;
11187
12294
  if (options.cwd !== void 0 && !githubRepositoryFullName(options.cwd))
11188
12295
  return `${prefix}: ${repositoryIdentityRemedy(options.cwd)}.`;
11189
12296
  const fetchImpl = options.fetch ?? fetch;
@@ -38022,19 +39129,19 @@ async function fetchAndCacheCollectScope(cwd, dependencies = defaultDependencies
38022
39129
  // src/lib/commit-heartbeat.ts
38023
39130
  import { execFileSync as execFileSync6 } from "child_process";
38024
39131
  import { mkdirSync as mkdirSync9, readFileSync as readFileSync18, readdirSync as readdirSync6, unlinkSync as unlinkSync3 } from "fs";
38025
- import { dirname as dirname13, join as join23, resolve as resolve6 } from "path";
39132
+ import { dirname as dirname13, join as join24, resolve as resolve6 } from "path";
38026
39133
  var WIRED_PATH = "prim/git-hooks-wired";
38027
- var GIT_TIMEOUT_MS4 = 1e3;
39134
+ var GIT_TIMEOUT_MS5 = 1e3;
38028
39135
  var MAX_STAMP_BYTES = 1024;
38029
39136
  function commonPath(cwd, relative4) {
38030
39137
  const value = execFileSync6("git", ["rev-parse", "--git-common-dir"], {
38031
39138
  cwd,
38032
39139
  encoding: "utf8",
38033
39140
  stdio: ["ignore", "pipe", "ignore"],
38034
- timeout: GIT_TIMEOUT_MS4
39141
+ timeout: GIT_TIMEOUT_MS5
38035
39142
  }).replace(/\r?\n$/u, "");
38036
39143
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
38037
- return join23(resolve6(cwd, value), relative4);
39144
+ return join24(resolve6(cwd, value), relative4);
38038
39145
  }
38039
39146
  function ensurePrivateParent(path) {
38040
39147
  mkdirSync9(dirname13(dirname13(path)), { recursive: true, mode: 448 });
@@ -38072,7 +39179,7 @@ function clearHooksWired(cwd) {
38072
39179
 
38073
39180
  // src/lib/git-hooks.ts
38074
39181
  import { execFileSync as execFileSync7 } from "child_process";
38075
- import { createHash as createHash12, randomUUID as randomUUID3 } from "crypto";
39182
+ import { createHash as createHash13, randomUUID as randomUUID3 } from "crypto";
38076
39183
  import {
38077
39184
  constants as constants5,
38078
39185
  closeSync as closeSync4,
@@ -38088,7 +39195,7 @@ import {
38088
39195
  unlinkSync as unlinkSync4,
38089
39196
  writeFileSync as writeFileSync6
38090
39197
  } from "fs";
38091
- import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as join24, relative as relative3, resolve as resolve7, sep as sep3 } from "path";
39198
+ import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as join25, relative as relative3, resolve as resolve7, sep as sep3 } from "path";
38092
39199
 
38093
39200
  // src/lib/git-hook-legacy.ts
38094
39201
  import { isAbsolute as isAbsolute7 } from "path";
@@ -38267,7 +39374,7 @@ var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
38267
39374
  var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
38268
39375
  var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
38269
39376
  var MAX_HOOK_BYTES = 1048576;
38270
- var GIT_TIMEOUT_MS5 = 1e3;
39377
+ var GIT_TIMEOUT_MS6 = 1e3;
38271
39378
  var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
38272
39379
  "#!/bin/sh",
38273
39380
  "#!/usr/bin/env sh",
@@ -38317,7 +39424,7 @@ function gitHooksMode(options = {}) {
38317
39424
  cwd: options.cwd,
38318
39425
  encoding: "utf8",
38319
39426
  stdio: ["ignore", "pipe", "ignore"],
38320
- timeout: GIT_TIMEOUT_MS5
39427
+ timeout: GIT_TIMEOUT_MS6
38321
39428
  }
38322
39429
  ).trim();
38323
39430
  return value === "manual" ? "manual" : "auto";
@@ -38397,7 +39504,7 @@ function realpathLoose(path) {
38397
39504
  let current = resolve7(path);
38398
39505
  for (; ; ) {
38399
39506
  try {
38400
- return join24(realpathSync4.native(current), ...missing);
39507
+ return join25(realpathSync4.native(current), ...missing);
38401
39508
  } catch {
38402
39509
  const parent = dirname14(current);
38403
39510
  if (parent === current) return resolve7(path);
@@ -38412,7 +39519,7 @@ function isWithin(path, directory) {
38412
39519
  }
38413
39520
  function primGitHooksDirectory() {
38414
39521
  try {
38415
- return join24(primConfigDirectory(), "git-hooks");
39522
+ return join25(primConfigDirectory(), "git-hooks");
38416
39523
  } catch {
38417
39524
  return void 0;
38418
39525
  }
@@ -38424,7 +39531,7 @@ function otherWorktreeRoots(gitRoot) {
38424
39531
  cwd: gitRoot,
38425
39532
  encoding: "utf8",
38426
39533
  stdio: ["ignore", "pipe", "ignore"],
38427
- timeout: GIT_TIMEOUT_MS5
39534
+ timeout: GIT_TIMEOUT_MS6
38428
39535
  }).split("\n").flatMap((line) => line.startsWith("worktree ") ? [realpathLoose(line.slice(9))] : []).filter((root) => root !== self);
38429
39536
  } catch {
38430
39537
  return [];
@@ -38458,7 +39565,7 @@ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
38458
39565
  cwd: gitRoot,
38459
39566
  encoding: "utf8",
38460
39567
  stdio: ["ignore", "pipe", "ignore"],
38461
- timeout: GIT_TIMEOUT_MS5
39568
+ timeout: GIT_TIMEOUT_MS6
38462
39569
  }
38463
39570
  ).replace(/\r?\n$/u, "").split(/\r?\n/u);
38464
39571
  if (lines.length !== 3) throw new Error("Git returned unexpected repository paths");
@@ -38515,7 +39622,7 @@ function assertUsableHuskyDispatcher(target, spec) {
38515
39622
  const huskyRuntime = resolve7(dirname14(target.dispatcherPath), "h");
38516
39623
  const runtimeStat = assertSafeFile(huskyRuntime, spec);
38517
39624
  const runtime = runtimeStat ? readHookFile(huskyRuntime) : void 0;
38518
- const runtimeHash = runtime ? createHash12("sha256").update(runtime).digest("hex") : void 0;
39625
+ const runtimeHash = runtime ? createHash13("sha256").update(runtime).digest("hex") : void 0;
38519
39626
  if (!runtimeHash || !HUSKY_V9_RUNTIME_HASHES.has(runtimeHash)) {
38520
39627
  throw new Error(`unrecognized Husky v9 hook runtime: ${huskyRuntime}`);
38521
39628
  }
@@ -38593,7 +39700,7 @@ function blockInsertionPoint(content, spec, huskyV8) {
38593
39700
  var HUSKY_SPEC_MAJOR_RE = /^\s*[~^]?=?\s*v?([0-9]+)(?:\.(?:[0-9]+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?\s*$/u;
38594
39701
  function declaredHuskyMajor(dir) {
38595
39702
  for (let current = resolve7(dir); ; ) {
38596
- const manifest = join24(current, "package.json");
39703
+ const manifest = join25(current, "package.json");
38597
39704
  if (existsSync14(manifest)) {
38598
39705
  try {
38599
39706
  if (lstatSync11(manifest).size > MAX_HOOK_BYTES) return void 0;
@@ -38606,12 +39713,12 @@ function declaredHuskyMajor(dir) {
38606
39713
  }
38607
39714
  }
38608
39715
  const parent = dirname14(current);
38609
- if (parent === current || existsSync14(join24(current, ".git"))) return void 0;
39716
+ if (parent === current || existsSync14(join25(current, ".git"))) return void 0;
38610
39717
  current = parent;
38611
39718
  }
38612
39719
  }
38613
39720
  function isHuskyV8Hook(hookPath) {
38614
- const runtime = join24(dirname14(hookPath), "_", "husky.sh");
39721
+ const runtime = join25(dirname14(hookPath), "_", "husky.sh");
38615
39722
  try {
38616
39723
  const stat = lstatSync11(runtime);
38617
39724
  return stat.isFile() && stat.size <= MAX_HOOK_BYTES && readFileSync19(runtime, "utf8").includes("husky_skip_init");
@@ -38939,8 +40046,8 @@ import {
38939
40046
  unlinkSync as unlinkSync5,
38940
40047
  writeFileSync as writeFileSync7
38941
40048
  } from "fs";
38942
- import { dirname as dirname15, isAbsolute as isAbsolute9, join as join25, resolve as resolve8 } from "path";
38943
- var WORKSPACE_ID_RELATIVE_PATH = join25("prim", "workspace-id");
40049
+ import { dirname as dirname15, isAbsolute as isAbsolute9, join as join26, resolve as resolve8 } from "path";
40050
+ var WORKSPACE_ID_RELATIVE_PATH = join26("prim", "workspace-id");
38944
40051
  var MAX_ANCESTORS = 64;
38945
40052
  var MAX_GIT_FILE_BYTES = 4096;
38946
40053
  var MAX_ID_FILE_BYTES = 128;
@@ -38999,11 +40106,11 @@ function resolveWorkspaceIdPath(cwd) {
38999
40106
  function resolveFromFilesystem(cwd) {
39000
40107
  let current = resolve8(cwd);
39001
40108
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
39002
- const dotGit = join25(current, ".git");
40109
+ const dotGit = join26(current, ".git");
39003
40110
  try {
39004
40111
  const stat = lstatSync12(dotGit);
39005
40112
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
39006
- return join25(dotGit, WORKSPACE_ID_RELATIVE_PATH);
40113
+ return join26(dotGit, WORKSPACE_ID_RELATIVE_PATH);
39007
40114
  }
39008
40115
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
39009
40116
  const contents = readFileSync20(dotGit, "utf8");
@@ -39011,7 +40118,7 @@ function resolveFromFilesystem(cwd) {
39011
40118
  if (match?.[1]) {
39012
40119
  const gitDirectory = isAbsolute9(match[1]) ? resolve8(match[1]) : resolve8(current, match[1]);
39013
40120
  if (isGitDirectory(gitDirectory)) {
39014
- return join25(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
40121
+ return join26(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
39015
40122
  }
39016
40123
  }
39017
40124
  }
@@ -39030,7 +40137,7 @@ function resolveFromFilesystem(cwd) {
39030
40137
  }
39031
40138
  function isGitDirectory(path) {
39032
40139
  try {
39033
- return statSync3(join25(path, "HEAD")).isFile();
40140
+ return statSync3(join26(path, "HEAD")).isFile();
39034
40141
  } catch {
39035
40142
  return false;
39036
40143
  }
@@ -39068,7 +40175,7 @@ function inspectPath(path) {
39068
40175
  function createWorkspaceId(path) {
39069
40176
  const parent = dirname15(path);
39070
40177
  const workspaceId = randomUUID4();
39071
- const temporaryPath = join25(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
40178
+ const temporaryPath = join26(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
39072
40179
  let temporaryCreated = false;
39073
40180
  let publishing = false;
39074
40181
  try {
@@ -39128,7 +40235,7 @@ function errorCode2(error) {
39128
40235
  }
39129
40236
 
39130
40237
  // src/hooks/codex-context.ts
39131
- import { createHash as createHash13, randomBytes as randomBytes7 } from "crypto";
40238
+ import { createHash as createHash14, randomBytes as randomBytes7 } from "crypto";
39132
40239
  import {
39133
40240
  chmodSync as chmodSync7,
39134
40241
  existsSync as existsSync15,
@@ -39136,12 +40243,12 @@ import {
39136
40243
  readFileSync as readFileSync21,
39137
40244
  readdirSync as readdirSync7,
39138
40245
  renameSync as renameSync4,
39139
- rmSync as rmSync10,
40246
+ rmSync as rmSync11,
39140
40247
  statSync as statSync4,
39141
40248
  unlinkSync as unlinkSync6,
39142
40249
  writeFileSync as writeFileSync8
39143
40250
  } from "fs";
39144
- import { join as join26 } from "path";
40251
+ import { join as join27 } from "path";
39145
40252
 
39146
40253
  // src/daemon/decision-digest-cache.ts
39147
40254
  import { randomBytes as randomBytes6 } from "crypto";
@@ -39294,10 +40401,10 @@ var STATE_VERSION = 1;
39294
40401
  var DRAFT_STATE_VERSION = 2;
39295
40402
  var NO_CURSOR = -1;
39296
40403
  function stateRoot(namespace) {
39297
- return join26(primConfigDirectory(), namespace, "decision-digests");
40404
+ return join27(primConfigDirectory(), namespace, "decision-digests");
39298
40405
  }
39299
40406
  function draftStateRoot(namespace) {
39300
- return join26(primConfigDirectory(), namespace, "decision-draft-deliveries");
40407
+ return join27(primConfigDirectory(), namespace, "decision-draft-deliveries");
39301
40408
  }
39302
40409
  function workspaceFor(cwd) {
39303
40410
  try {
@@ -39308,13 +40415,13 @@ function workspaceFor(cwd) {
39308
40415
  }
39309
40416
  function statePath(args) {
39310
40417
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
39311
- const key = createHash13("sha256").update(identity).digest("hex");
39312
- return join26(stateRoot(args.namespace), `${key}.json`);
40418
+ const key = createHash14("sha256").update(identity).digest("hex");
40419
+ return join27(stateRoot(args.namespace), `${key}.json`);
39313
40420
  }
39314
40421
  function draftStatePath(args) {
39315
40422
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
39316
- const key = createHash13("sha256").update(identity).digest("hex");
39317
- return join26(draftStateRoot(args.namespace), `${key}.json`);
40423
+ const key = createHash14("sha256").update(identity).digest("hex");
40424
+ return join27(draftStateRoot(args.namespace), `${key}.json`);
39318
40425
  }
39319
40426
  function parseState(value) {
39320
40427
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -39352,7 +40459,7 @@ function parseDraftState(value) {
39352
40459
  updatedAt: record.updatedAt
39353
40460
  };
39354
40461
  }
39355
- function readState(path) {
40462
+ function readState2(path) {
39356
40463
  if (!existsSync15(path)) return void 0;
39357
40464
  try {
39358
40465
  return parseState(JSON.parse(readFileSync21(path, "utf8")));
@@ -39371,7 +40478,7 @@ function readDraftState(path) {
39371
40478
  function writeStateFile(path, directory, state) {
39372
40479
  mkdirSync12(directory, { recursive: true, mode: 448 });
39373
40480
  chmodSync7(directory, 448);
39374
- const temporary = join26(
40481
+ const temporary = join27(
39375
40482
  directory,
39376
40483
  `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
39377
40484
  );
@@ -39402,7 +40509,7 @@ function cleanupStateFiles(directory, now) {
39402
40509
  const files = [];
39403
40510
  const residue = [];
39404
40511
  for (const name of names) {
39405
- const path = join26(directory, name);
40512
+ const path = join27(directory, name);
39406
40513
  try {
39407
40514
  const mtimeMs = statSync4(path).mtimeMs;
39408
40515
  if (name.endsWith(".json")) {
@@ -39424,7 +40531,7 @@ function cleanupStateFiles(directory, now) {
39424
40531
  for (const path of residue) {
39425
40532
  try {
39426
40533
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
39427
- rmSync10(path, { recursive: true, force: true });
40534
+ rmSync11(path, { recursive: true, force: true });
39428
40535
  }
39429
40536
  } catch {
39430
40537
  }
@@ -39510,7 +40617,7 @@ async function commitState(path, args, namespace) {
39510
40617
  await withFileLock(
39511
40618
  `${path}.lock`,
39512
40619
  () => {
39513
- const latest = readState(path);
40620
+ const latest = readState2(path);
39514
40621
  writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
39515
40622
  cleanupStateFiles(stateRoot(namespace), args.now);
39516
40623
  },
@@ -39557,7 +40664,7 @@ async function prepareCodexContext(options) {
39557
40664
  const siteUrl = getSiteUrl();
39558
40665
  const workspace = workspaceFor(options.cwd);
39559
40666
  const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
39560
- const previous = readState(path);
40667
+ const previous = readState2(path);
39561
40668
  const principal = resolveDaemonPrincipal();
39562
40669
  const privatePath = principal ? draftStatePath({
39563
40670
  cwd: options.cwd,
@@ -39707,7 +40814,7 @@ async function prepareCodexContext(options) {
39707
40814
  }
39708
40815
 
39709
40816
  // src/hooks/normalize.ts
39710
- import { createHash as createHash14 } from "crypto";
40817
+ import { createHash as createHash15 } from "crypto";
39711
40818
  import { realpathSync as realpathSync5 } from "fs";
39712
40819
  import { isAbsolute as isAbsolute10, resolve as resolve9 } from "path";
39713
40820
  var HERMES_EVENT_MAP = {
@@ -39752,7 +40859,7 @@ function requiredId(value, field) {
39752
40859
  }
39753
40860
  function cursorToolUseId(value) {
39754
40861
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
39755
- return `cursor:tool:v1:${createHash14("sha256").update(value).digest("hex")}`;
40862
+ return `cursor:tool:v1:${createHash15("sha256").update(value).digest("hex")}`;
39756
40863
  }
39757
40864
  function workspaceCandidates(value) {
39758
40865
  if (!Array.isArray(value)) return [];
@@ -39849,7 +40956,7 @@ function normalizeEnvelope(parsed, agent) {
39849
40956
  ]);
39850
40957
  return {
39851
40958
  ...parsed,
39852
- tool_use_id: `codex:fallback:v1:${createHash14("sha256").update(stableToolIdentity).digest("hex")}`
40959
+ tool_use_id: `codex:fallback:v1:${createHash15("sha256").update(stableToolIdentity).digest("hex")}`
39853
40960
  };
39854
40961
  }
39855
40962
  return parsed;
@@ -39865,11 +40972,18 @@ function normalizeEnvelope(parsed, agent) {
39865
40972
  }
39866
40973
 
39867
40974
  // src/hooks/reauth-notice.ts
40975
+ function sharedEnvironment() {
40976
+ try {
40977
+ return sessionIdentityMode();
40978
+ } catch {
40979
+ return false;
40980
+ }
40981
+ }
39868
40982
  var REAUTH_NOTICE = "[prim] authentication ended \u2014 run `prim auth login` to resume decision capture";
39869
40983
  function reauthNoticeFields(agent) {
39870
40984
  if (agent === "claude_code") {
39871
40985
  if (isClaudeCloudSession()) {
39872
- const notice = `Primitive is not connected in this Claude Code cloud session: ${hasMachineConfiguration() ? `its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}` : `its sign-in ended. To fix it, ${CLOUD_CREDENTIALS_REMEDY}`}.`;
40986
+ const notice = !hasMachineConfiguration() ? `Primitive is not connected in this Claude Code cloud session: its sign-in ended. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.` : sharedEnvironment() ? `Primitive is not connected in this Claude Code cloud session: its environment credential was rejected. To fix it, ${ENVIRONMENT_CREDENTIAL_REMEDY}.` : CLOUD_REJECTED_CREDENTIALS_NOTICE;
39873
40987
  return {
39874
40988
  systemMessage: notice,
39875
40989
  additionalContext: `${notice} Tell the user this in one sentence before starting their task.`
@@ -39886,6 +41000,18 @@ function reauthNoticeFields(agent) {
39886
41000
  var DAEMON_TIMEOUT_MS = 250;
39887
41001
  var REPOSITORY_BIND_TIMEOUT_MS = 1e3;
39888
41002
  var CLOUD_REPOSITORY_BIND_TIMEOUT_MS = 1e4;
41003
+ var SESSION_IDENTITY_TIMEOUT_MS = 35e3;
41004
+ function sessionIdentityNotice(outcome) {
41005
+ if (!outcome || outcome.status === "ok") return void 0;
41006
+ const notice = `${sessionIdentityMessage(outcome)} Until then, nothing this session captures is sent to Primitive.`;
41007
+ return outcome.status === "link_required" ? {
41008
+ notice,
41009
+ instruction: `${notice} Before starting their task, tell the user this in one sentence. When they agree, run \`prim auth link\` as a background command (it waits until they finish signing in), and give them the sign-in URL and code it prints as soon as they appear.`
41010
+ } : {
41011
+ notice,
41012
+ instruction: `${notice} Tell the user this in one sentence before starting their task.`
41013
+ };
41014
+ }
39889
41015
  var PRIM_TRIGGER = "When this task chooses between plausible approaches or establishes or changes a lasting goal, priority, constraint, invariant, default, commitment, tradeoff, exception, or shared instruction";
39890
41016
  var PRIM_EXCLUSIONS = "Never invoke `prim` for routine implementation that merely follows an existing decision made before this task or for temporary tactics; they never qualify, including for evaluation.";
39891
41017
  function primReminder(action, rationaleAction) {
@@ -39938,9 +41064,9 @@ async function activeProjectRoot(cwd) {
39938
41064
  } catch {
39939
41065
  }
39940
41066
  return { root, binding };
39941
- } catch {
41067
+ } catch (error) {
41068
+ return { root, bindFailure: error };
39942
41069
  }
39943
- return { root };
39944
41070
  } catch {
39945
41071
  return null;
39946
41072
  }
@@ -39987,11 +41113,31 @@ async function processSessionStart(raw, agent, feedbackSignal) {
39987
41113
  let active = false;
39988
41114
  let skillState = { installed: 0, refreshed: 0 };
39989
41115
  let claudeBinding;
41116
+ let bindFailure;
41117
+ let identityNotice;
39990
41118
  if (agent === "claude_code") {
41119
+ let identityMode = false;
41120
+ try {
41121
+ identityMode = sessionIdentityMode();
41122
+ } catch {
41123
+ }
41124
+ if (identityMode) {
41125
+ try {
41126
+ identityNotice = sessionIdentityNotice(
41127
+ await ensureSessionIdentity({
41128
+ cwd,
41129
+ explicit: true,
41130
+ signal: AbortSignal.timeout(SESSION_IDENTITY_TIMEOUT_MS)
41131
+ })
41132
+ );
41133
+ } catch {
41134
+ }
41135
+ }
39991
41136
  const activeProject = await activeProjectRoot(cwd);
39992
41137
  projectRoot2 = activeProject?.root ?? null;
39993
41138
  active = projectRoot2 !== null;
39994
41139
  claudeBinding = activeProject?.binding;
41140
+ bindFailure = activeProject?.bindFailure;
39995
41141
  try {
39996
41142
  skillState = await refreshClaudePlugins(
39997
41143
  cwd,
@@ -40000,7 +41146,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
40000
41146
  } catch {
40001
41147
  }
40002
41148
  }
40003
- if (isSessionEnded() && agent !== "codex" && agent !== "cursor") {
41149
+ if (isSessionEnded() && agent !== "codex" && agent !== "cursor" && !identityNotice) {
40004
41150
  const notice = reauthNoticeFields(agent);
40005
41151
  if (notice) {
40006
41152
  return {
@@ -40063,15 +41209,15 @@ async function processSessionStart(raw, agent, feedbackSignal) {
40063
41209
  };
40064
41210
  }
40065
41211
  if (agent === "claude_code") {
40066
- let cloudNotice;
40067
- if (active && !claudeBinding && isClaudeCloudSession()) {
41212
+ let cloudNotice = identityNotice?.notice;
41213
+ if (active && !claudeBinding && isClaudeCloudSession() && !identityNotice) {
40068
41214
  try {
40069
- cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd });
41215
+ cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd, bindFailure });
40070
41216
  } catch {
40071
41217
  }
40072
41218
  }
40073
41219
  const additionalContext = [
40074
- cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
41220
+ identityNotice ? identityNotice.instruction : cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
40075
41221
  claudeBinding ? claudeBindingReminder(claudeBinding, isClaudeCloudSession()) : void 0,
40076
41222
  active && skillState.installed > 0 ? PRIM_SKILL_REMINDER : void 0
40077
41223
  ].filter((value) => value !== void 0).join("\n\n");