@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
@@ -55,34 +55,34 @@ var require_ucs2length = __commonJS({
55
55
  // src/hooks/prim-hook.ts
56
56
  import { spawn as spawn2 } from "child_process";
57
57
  import { readFileSync as readFileSync23 } from "fs";
58
- import { dirname as dirname15, join as join27 } from "path";
58
+ import { dirname as dirname15, join as join28 } from "path";
59
59
  import { fileURLToPath as fileURLToPath5 } from "url";
60
60
 
61
61
  // src/binding.ts
62
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
63
- import { dirname as dirname5, join as join8 } from "path";
62
+ import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
63
+ import { dirname as dirname8, join as join12 } from "path";
64
64
 
65
65
  // src/lib/credentials.ts
66
- import { createHash as createHash4 } from "crypto";
67
- import { readFileSync as readFileSync6 } from "fs";
68
- import { join as join7 } from "path";
66
+ import { createHash as createHash7 } from "crypto";
67
+ import { readFileSync as readFileSync8 } from "fs";
68
+ import { join as join11 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
- import { execFileSync } from "child_process";
72
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
71
+ import { execFileSync as execFileSync2 } from "child_process";
72
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
73
73
  import {
74
- chmodSync,
75
- existsSync as existsSync3,
74
+ chmodSync as chmodSync2,
75
+ existsSync as existsSync5,
76
76
  linkSync,
77
- lstatSync as lstatSync3,
78
- mkdirSync as mkdirSync3,
79
- readFileSync as readFileSync5,
80
- rmSync as rmSync5,
81
- writeFileSync as writeFileSync3
77
+ lstatSync as lstatSync5,
78
+ mkdirSync as mkdirSync4,
79
+ readFileSync as readFileSync7,
80
+ rmSync as rmSync7,
81
+ writeFileSync as writeFileSync4
82
82
  } from "fs";
83
- import { createRequire } from "module";
84
- import { dirname as dirname4, join as join6 } from "path";
85
- import { fileURLToPath as fileURLToPath3 } from "url";
83
+ import { createRequire as createRequire2 } from "module";
84
+ import { dirname as dirname7, join as join10 } from "path";
85
+ import { fileURLToPath as fileURLToPath4 } from "url";
86
86
 
87
87
  // src/lib/atomic-file.ts
88
88
  import { randomUUID } from "crypto";
@@ -333,18 +333,71 @@ async function withFileLock(lockDir, operation, options = {}) {
333
333
  }
334
334
  }
335
335
 
336
- // src/lib/machine-broker.ts
337
- import { spawn } from "child_process";
338
- import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
339
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
340
- import { createServer } from "http";
341
- import { basename, join as join4 } from "path";
342
- import { fileURLToPath as fileURLToPath2 } from "url";
336
+ // src/lib/hook-runtime.ts
337
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
338
+ import {
339
+ constants as constants2,
340
+ accessSync,
341
+ chmodSync,
342
+ copyFileSync,
343
+ existsSync as existsSync4,
344
+ lstatSync,
345
+ mkdirSync as mkdirSync3,
346
+ mkdtempSync,
347
+ readFileSync as readFileSync3,
348
+ readdirSync,
349
+ realpathSync,
350
+ renameSync as renameSync2,
351
+ rmSync as rmSync3,
352
+ statSync as statSync2,
353
+ utimesSync,
354
+ writeFileSync as writeFileSync3
355
+ } from "fs";
356
+ import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
343
357
 
344
358
  // src/lib/bin-path.ts
345
359
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
346
360
  import { dirname as dirname3, isAbsolute, join as join2 } from "path";
347
361
  import { fileURLToPath } from "url";
362
+
363
+ // src/lib/semver.ts
364
+ function parseSemver(value) {
365
+ if (typeof value !== "string" || value.length > 256) return;
366
+ const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
367
+ value
368
+ );
369
+ if (!match) return;
370
+ const prerelease = match[4]?.split(".") ?? [];
371
+ if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
372
+ return;
373
+ }
374
+ return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
375
+ }
376
+ function compareSemver(left, right) {
377
+ const a = parseSemver(left);
378
+ const b = parseSemver(right);
379
+ if (!a || !b) return;
380
+ for (let i = 0; i < a.core.length; i += 1) {
381
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
382
+ }
383
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) {
384
+ return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
385
+ }
386
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
387
+ const x = a.prerelease[i];
388
+ const y = b.prerelease[i];
389
+ if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
390
+ if (x === y) continue;
391
+ const xNumeric = /^\d+$/u.test(x);
392
+ const yNumeric = /^\d+$/u.test(y);
393
+ if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
394
+ if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
395
+ return x < y ? -1 : 1;
396
+ }
397
+ return 0;
398
+ }
399
+
400
+ // src/lib/bin-path.ts
348
401
  var PKG_NAME = "@primitive.ai/prim";
349
402
  var ROOT_WALK_LIMIT = 6;
350
403
  var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
@@ -419,6 +472,309 @@ function detachedHookShimCommand(bin, args = "") {
419
472
  return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
420
473
  }
421
474
 
475
+ // src/lib/git-hook-contract.ts
476
+ var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
477
+ var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
478
+ # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
479
+ # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
480
+ # where prim is active (git config prim.active true) and never fails the hook.
481
+ case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
482
+ prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
483
+ [ -x "$prim_launcher" ] || exit 0
484
+ [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
485
+ prim_hook=\${1-}
486
+ if [ "$#" -gt 0 ]; then shift; fi
487
+ case "$prim_hook" in
488
+ pre-commit)
489
+ "$prim_launcher" prim-pre-commit "$@" || :
490
+ ;;
491
+ post-commit)
492
+ prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
493
+ case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
494
+ case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
495
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
496
+ prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
497
+ (
498
+ trap '' HUP
499
+ trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
500
+ PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
501
+ ) </dev/null >/dev/null 2>&1 &
502
+ ;;
503
+ post-rewrite)
504
+ case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
505
+ prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
506
+ if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
507
+ rm -f "$prim_pairs"
508
+ exit 0
509
+ fi
510
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
511
+ (
512
+ trap '' HUP
513
+ trap 'rm -f "$prim_pairs"' 0
514
+ PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
515
+ ) </dev/null >/dev/null 2>&1 &
516
+ ;;
517
+ esac
518
+ exit 0
519
+ `;
520
+
521
+ // src/lib/native-keyring.ts
522
+ import { existsSync as existsSync3 } from "fs";
523
+ import { createRequire } from "module";
524
+ import { dirname as dirname4, join as join3 } from "path";
525
+ import { fileURLToPath as fileURLToPath2 } from "url";
526
+ var require2 = createRequire(import.meta.url);
527
+ var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
528
+
529
+ // src/lib/paths.ts
530
+ import { homedir } from "os";
531
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
532
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
533
+ function absolutePath(value, variable) {
534
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
535
+ throw new Error(`${variable} contains unsafe characters`);
536
+ }
537
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
538
+ const normalized = normalize(value);
539
+ return normalized === value ? value : void 0;
540
+ }
541
+ function resolvePrimConfigDirectory(options = {}) {
542
+ const env = options.env ?? process.env;
543
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
544
+ if (explicit) return { path: explicit, source: "explicit" };
545
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
546
+ if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
547
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
548
+ if (!home) {
549
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
550
+ }
551
+ return { path: join4(home, ".config", "prim"), source: "default" };
552
+ }
553
+ function primConfigDirectory(options = {}) {
554
+ return resolvePrimConfigDirectory(options).path;
555
+ }
556
+
557
+ // src/lib/hook-runtime.ts
558
+ var HOOK_RUNTIME_SCHEMA_VERSION = 1;
559
+ var RELEASE_PREFIX = "release-";
560
+ var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
561
+ var MAX_MANIFEST_BYTES = 64 * 1024;
562
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
563
+ var HOOK_RUNTIME_ENTRIES = {
564
+ // SessionStart self-healing resolves this exact CLI entry to run
565
+ // `daemon ensure`; it must travel with the immutable hook release.
566
+ prim: "dist/index.js",
567
+ "prim-hook": "dist/hooks/prim-hook.js",
568
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
569
+ "prim-post-commit": "dist/hooks/post-commit.js",
570
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
571
+ "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
572
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
573
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
574
+ "prim-session-start": "dist/hooks/session-start.js",
575
+ "prim-session-end": "dist/hooks/session-end.js",
576
+ "prim-daemon-server": "dist/daemon/server.js",
577
+ "prim-statusline": "dist/statusline-main.js"
578
+ };
579
+ var SOURCE_ENTRIES = Object.fromEntries(
580
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
581
+ bin,
582
+ target.replace(/^dist\//u, "")
583
+ ])
584
+ );
585
+ function hookRuntimePaths(options = {}) {
586
+ const env = options.env ?? process.env;
587
+ const configDir = primConfigDirectory({
588
+ ...options,
589
+ env,
590
+ homeDir: options.homeDir ?? env.HOME ?? ""
591
+ });
592
+ const runtimeDir = join5(configDir, "hook-runtime");
593
+ return {
594
+ configDir,
595
+ launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
596
+ gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
597
+ runtimeDir,
598
+ releasesDir: join5(runtimeDir, "releases"),
599
+ current: join5(runtimeDir, "current"),
600
+ selectionLock: join5(runtimeDir, "selection.lock")
601
+ };
602
+ }
603
+ function sha256(path) {
604
+ return createHash("sha256").update(readFileSync3(path)).digest("hex");
605
+ }
606
+ function exactManifest(manifest) {
607
+ return `${JSON.stringify(manifest, null, 2)}
608
+ `;
609
+ }
610
+ function exactKeys(value, expected) {
611
+ const actual = Object.keys(value).sort();
612
+ const wanted = [...expected].sort();
613
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
614
+ }
615
+ function releaseId(manifest) {
616
+ return createHash("sha256").update(exactManifest(manifest)).digest("hex");
617
+ }
618
+ function runtimePackageJson(manifest) {
619
+ return `${JSON.stringify(
620
+ {
621
+ name: "@primitive.ai/prim",
622
+ version: manifest.version,
623
+ type: "module",
624
+ bin: HOOK_RUNTIME_ENTRIES
625
+ },
626
+ null,
627
+ 2
628
+ )}
629
+ `;
630
+ }
631
+ function validateRelease(releaseDir, manifest) {
632
+ try {
633
+ if (!directReleaseLayout(releaseDir, manifest)) return false;
634
+ if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
635
+ return false;
636
+ }
637
+ if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
638
+ return false;
639
+ }
640
+ if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
641
+ `) {
642
+ return false;
643
+ }
644
+ for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
645
+ const target = join5(releaseDir, relativePath);
646
+ if (sha256(target) !== manifest.files[bin]) return false;
647
+ }
648
+ for (const [path, digest] of Object.entries(manifest.native ?? {})) {
649
+ if (sha256(join5(releaseDir, path)) !== digest) return false;
650
+ }
651
+ return true;
652
+ } catch {
653
+ return false;
654
+ }
655
+ }
656
+ function directReleaseLayout(releaseDir, manifest) {
657
+ try {
658
+ const directories = /* @__PURE__ */ new Set([releaseDir]);
659
+ for (const relativePath of [
660
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
661
+ ...Object.keys(manifest.native ?? {})
662
+ ]) {
663
+ for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
664
+ directories.add(join5(releaseDir, directory));
665
+ }
666
+ }
667
+ if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
668
+ const files = [
669
+ "manifest.json",
670
+ "package.json",
671
+ "node",
672
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
673
+ ...Object.keys(manifest.native ?? {})
674
+ ];
675
+ const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
676
+ if (![...directories].every(
677
+ (directory) => readdirSync(directory).every((name2) => owned.has(join5(directory, name2)))
678
+ ))
679
+ return false;
680
+ return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
681
+ } catch {
682
+ return false;
683
+ }
684
+ }
685
+ function readReleaseManifest(releaseDir, releaseName) {
686
+ try {
687
+ const manifestPath = join5(releaseDir, "manifest.json");
688
+ const manifestStat = statSync2(manifestPath);
689
+ if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
690
+ const raw = readFileSync3(manifestPath, "utf8");
691
+ const parsed = JSON.parse(raw);
692
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
693
+ if (!exactKeys(parsed, [
694
+ "schemaVersion",
695
+ "version",
696
+ "nodePath",
697
+ "files",
698
+ ..."native" in parsed ? ["native"] : []
699
+ ]))
700
+ return null;
701
+ const candidate = parsed;
702
+ 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(
703
+ (digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
704
+ )) {
705
+ return null;
706
+ }
707
+ 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(
708
+ (digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
709
+ )))
710
+ return null;
711
+ const manifest = candidate;
712
+ if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
713
+ return null;
714
+ }
715
+ return manifest;
716
+ } catch {
717
+ return null;
718
+ }
719
+ }
720
+ function readSelectedRelease(paths) {
721
+ let raw;
722
+ try {
723
+ raw = readFileSync3(paths.current, "utf8");
724
+ } catch (error) {
725
+ if (error.code === "ENOENT") return null;
726
+ throw error;
727
+ }
728
+ const name2 = raw.endsWith("\n") ? raw.slice(0, -1) : "";
729
+ if (`${name2}
730
+ ` !== raw || !RELEASE_NAME_RE.test(name2)) {
731
+ throw new Error("cannot stage hook runtime: selected release is malformed");
732
+ }
733
+ const dir = join5(paths.releasesDir, name2);
734
+ const manifest = readReleaseManifest(dir, name2);
735
+ if (!manifest) {
736
+ throw new Error("cannot stage hook runtime: immutable release is corrupt");
737
+ }
738
+ return { name: name2, dir, manifest };
739
+ }
740
+ function selectedHookRuntimeKeyringLoader(options = {}) {
741
+ try {
742
+ const selected = readSelectedRelease(hookRuntimePaths(options));
743
+ if (!selected?.manifest.native) return void 0;
744
+ const loader = join5(selected.dir, "native", "keyring.cjs");
745
+ return existsSync4(loader) ? loader : void 0;
746
+ } catch {
747
+ return void 0;
748
+ }
749
+ }
750
+ var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
751
+ set -eu
752
+ case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
753
+ IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
754
+ case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
755
+ prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
756
+ case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
757
+ [ "\${#prim_release_id}" -eq 64 ] || exit 69
758
+ prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
759
+ case "\${1-}" in
760
+ ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
761
+ *) exit 64 ;;
762
+ esac
763
+ shift
764
+ IFS= read -r prim_node < "$prim_release/node" || exit 69
765
+ case "$prim_node" in /*) ;; *) exit 69 ;; esac
766
+ [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
767
+ exec "$prim_node" "$prim_entry" "$@"
768
+ `;
769
+
770
+ // src/lib/machine-broker.ts
771
+ import { spawn } from "child_process";
772
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
773
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
774
+ import { createServer } from "http";
775
+ import { basename, join as join6 } from "path";
776
+ import { fileURLToPath as fileURLToPath3 } from "url";
777
+
422
778
  // src/lib/loopback-fetch.ts
423
779
  import { request } from "http";
424
780
  import { Readable } from "stream";
@@ -455,6 +811,8 @@ function isClaudeCloudSession(env = process.env) {
455
811
  }
456
812
  var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
457
813
  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';
814
+ 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}.`;
815
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
458
816
  function cloudSetupPointer(message, env = process.env) {
459
817
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
460
818
  }
@@ -596,10 +954,10 @@ function parseWorkosConnectTokens(value, options = {}) {
596
954
  "access_token",
597
955
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
598
956
  );
599
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
957
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
600
958
  return {
601
959
  accessToken,
602
- refreshToken: refreshToken2,
960
+ refreshToken: refreshToken3,
603
961
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
604
962
  };
605
963
  }
@@ -850,34 +1208,6 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
850
1208
  return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
851
1209
  }
852
1210
 
853
- // src/lib/paths.ts
854
- import { homedir } from "os";
855
- import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
856
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
857
- function absolutePath(value, variable) {
858
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
859
- throw new Error(`${variable} contains unsafe characters`);
860
- }
861
- if (!value || value.trim() !== value || !isAbsolute2(value)) return;
862
- const normalized = normalize(value);
863
- return normalized === value ? value : void 0;
864
- }
865
- function resolvePrimConfigDirectory(options = {}) {
866
- const env = options.env ?? process.env;
867
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
868
- if (explicit) return { path: explicit, source: "explicit" };
869
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
870
- if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
871
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
872
- if (!home) {
873
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
874
- }
875
- return { path: join3(home, ".config", "prim"), source: "default" };
876
- }
877
- function primConfigDirectory(options = {}) {
878
- return resolvePrimConfigDirectory(options).path;
879
- }
880
-
881
1211
  // src/lib/machine-broker.ts
882
1212
  var MAX_RESPONSE_BYTES = 96 * 1024;
883
1213
  var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
@@ -887,14 +1217,14 @@ var FORWARD_REQUEST_PROOF = "forward-request";
887
1217
  var FORWARD_ANSWER_PROOF = "forward-answer";
888
1218
  var IDLE_MS = 5 * 6e4;
889
1219
  function descriptorPath(directory, generation) {
890
- return join4(directory, `machine_broker_${generation}.json`);
1220
+ return join6(directory, `machine_broker_${generation}.json`);
891
1221
  }
892
1222
  function readDescriptor(path) {
893
1223
  try {
894
- const stat = lstatSync(path);
1224
+ const stat = lstatSync2(path);
895
1225
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
896
1226
  return void 0;
897
- const data = JSON.parse(readFileSync3(path, "utf8"));
1227
+ const data = JSON.parse(readFileSync4(path, "utf8"));
898
1228
  return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
899
1229
  } catch {
900
1230
  return void 0;
@@ -907,7 +1237,7 @@ function matches(left, right) {
907
1237
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
908
1238
  }
909
1239
  function tokenHash(token) {
910
- return token ? createHash("sha256").update(token).digest("hex") : void 0;
1240
+ return token ? createHash2("sha256").update(token).digest("hex") : void 0;
911
1241
  }
912
1242
  async function brokerRequest(descriptor, environment, options) {
913
1243
  const body = JSON.stringify({
@@ -984,7 +1314,7 @@ async function acquireBrokerCredential(options) {
984
1314
  async function ensureBroker(options) {
985
1315
  const path = descriptorPath(options.directory, options.environment.generation);
986
1316
  return withFileLock(
987
- join4(options.directory, "machine-broker.lock"),
1317
+ join6(options.directory, "machine-broker.lock"),
988
1318
  async () => {
989
1319
  const current = readDescriptor(path);
990
1320
  if (current) {
@@ -997,7 +1327,7 @@ async function ensureBroker(options) {
997
1327
  options.signal.throwIfAborted();
998
1328
  }
999
1329
  }
1000
- const bundled = fileURLToPath2(import.meta.url);
1330
+ const bundled = fileURLToPath3(import.meta.url);
1001
1331
  const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
1002
1332
  if (!entry)
1003
1333
  throw new MachineAuthError(
@@ -1135,23 +1465,23 @@ async function forwardBrokerRequest(options) {
1135
1465
  }
1136
1466
 
1137
1467
  // src/lib/machine-retry.ts
1138
- import { createHash as createHash2 } from "crypto";
1139
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
1140
- import { join as join5 } from "path";
1468
+ import { createHash as createHash3 } from "crypto";
1469
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
1470
+ import { join as join7 } from "path";
1141
1471
  var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
1142
1472
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
1143
1473
  async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
1144
1474
  signal?.throwIfAborted();
1145
- const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
1146
- const path = join5(directory, `machine_retry_${key}.json`);
1475
+ const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
1476
+ const path = join7(directory, `machine_retry_${key}.json`);
1147
1477
  let state = {
1148
1478
  failures: 0,
1149
1479
  retryAt: 0
1150
1480
  };
1151
1481
  try {
1152
- const stat = lstatSync2(path);
1482
+ const stat = lstatSync3(path);
1153
1483
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
1154
- const data = JSON.parse(readFileSync4(path, "utf8"));
1484
+ const data = JSON.parse(readFileSync5(path, "utf8"));
1155
1485
  if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
1156
1486
  throw new Error("Invalid retry state");
1157
1487
  state = data;
@@ -1175,7 +1505,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
1175
1505
  );
1176
1506
  try {
1177
1507
  const result = await request3();
1178
- rmSync4(path, { force: true });
1508
+ rmSync5(path, { force: true });
1179
1509
  return result;
1180
1510
  } catch (error) {
1181
1511
  if (!signal?.aborted && error instanceof MachineAuthError && [
@@ -1202,32 +1532,1267 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
1202
1532
  }
1203
1533
  }
1204
1534
 
1535
+ // src/lib/session-identity.ts
1536
+ import { execFile } from "child_process";
1537
+ import { createHash as createHash5 } from "crypto";
1538
+ import { rmSync as rmSync6 } from "fs";
1539
+ import { join as join9 } from "path";
1540
+ import { promisify } from "util";
1541
+
1542
+ // src/lib/git.ts
1543
+ import { execFileSync } from "child_process";
1544
+ import { createHash as createHash4 } from "crypto";
1545
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
1546
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
1547
+ var GIT_TIMEOUT_MS = 1e3;
1548
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1549
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1550
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1551
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1552
+ function gitChildEnvironment(env = process.env) {
1553
+ return Object.fromEntries(
1554
+ Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
1555
+ );
1556
+ }
1557
+ function gitToplevel(cwd) {
1558
+ try {
1559
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1560
+ cwd,
1561
+ encoding: "utf-8",
1562
+ stdio: ["ignore", "pipe", "ignore"],
1563
+ timeout: GIT_TIMEOUT_MS,
1564
+ env: gitChildEnvironment()
1565
+ }).trim();
1566
+ } catch {
1567
+ return null;
1568
+ }
1569
+ }
1570
+ function gitValue(cwd, args) {
1571
+ try {
1572
+ const value = execFileSync("git", args, {
1573
+ cwd,
1574
+ encoding: "utf-8",
1575
+ stdio: ["ignore", "pipe", "ignore"],
1576
+ timeout: GIT_TIMEOUT_MS,
1577
+ env: gitChildEnvironment()
1578
+ }).trim();
1579
+ return value || void 0;
1580
+ } catch {
1581
+ return void 0;
1582
+ }
1583
+ }
1584
+ function currentBranch(cwd) {
1585
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1586
+ }
1587
+ function parseGithubRepositoryName(path) {
1588
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1589
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1590
+ return null;
1591
+ }
1592
+ return `${parts[0]}/${parts[1]}`;
1593
+ }
1594
+ function githubRepositoryFromRemote(remote) {
1595
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1596
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1597
+ remote
1598
+ );
1599
+ const path = match?.[1] ?? match?.[2];
1600
+ return path ? parseGithubRepositoryName(path) : null;
1601
+ }
1602
+ function checkoutSettingsText(repoRoot) {
1603
+ const path = join8(repoRoot, ".claude", "settings.json");
1604
+ try {
1605
+ if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
1606
+ const stat = lstatSync4(path);
1607
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1608
+ return readFileSync6(path, "utf8");
1609
+ } catch {
1610
+ return null;
1611
+ }
1612
+ }
1613
+ function checkoutDeclaration(repoRoot, name2) {
1614
+ const text = checkoutSettingsText(repoRoot);
1615
+ if (text === null) return null;
1616
+ let parsed;
1617
+ try {
1618
+ parsed = JSON.parse(text);
1619
+ } catch {
1620
+ return null;
1621
+ }
1622
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1623
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
1624
+ return typeof value === "string" ? value : null;
1625
+ }
1626
+ function declaredGithubRepository(repoRoot) {
1627
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1628
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1629
+ }
1630
+ function githubRepositoryFullName(cwd) {
1631
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1632
+ if (remote) {
1633
+ const fromOrigin = githubRepositoryFromRemote(remote);
1634
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1635
+ }
1636
+ const root = gitToplevel(cwd);
1637
+ return root ? declaredGithubRepository(root) : null;
1638
+ }
1639
+ function canonicalGitRoot(cwd) {
1640
+ try {
1641
+ const top = gitToplevel(cwd);
1642
+ return top ? realpathSync2.native(top) : null;
1643
+ } catch {
1644
+ return null;
1645
+ }
1646
+ }
1647
+ function relatedWorktreeTarget(path, cwd, origin) {
1648
+ let parent = dirname6(resolve2(cwd, path));
1649
+ while (true) {
1650
+ try {
1651
+ realpathSync2.native(parent);
1652
+ break;
1653
+ } catch {
1654
+ const next = dirname6(parent);
1655
+ if (next === parent) return null;
1656
+ parent = next;
1657
+ }
1658
+ }
1659
+ const target = resolveRepositoryContext(parent);
1660
+ if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
1661
+ const common = (root) => {
1662
+ const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
1663
+ try {
1664
+ return value ? realpathSync2.native(resolve2(root, value)) : void 0;
1665
+ } catch {
1666
+ return void 0;
1667
+ }
1668
+ };
1669
+ const originCommon = common(origin.repoRoot);
1670
+ return originCommon && originCommon === common(target.repoRoot) ? target : null;
1671
+ }
1672
+ function normalizeOriginRemote(remote) {
1673
+ const value = remote.trim();
1674
+ if (!value) return void 0;
1675
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1676
+ if (scp?.host && scp.path) {
1677
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1678
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1679
+ }
1680
+ try {
1681
+ const url = new URL(value);
1682
+ url.username = "";
1683
+ url.password = "";
1684
+ url.search = "";
1685
+ url.hash = "";
1686
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1687
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1688
+ return void 0;
1689
+ } catch {
1690
+ return void 0;
1691
+ }
1692
+ }
1693
+ function opaqueRepoKey(source, value) {
1694
+ return `repo_v1_${createHash4("sha256").update(`${source}\0${value}`).digest("hex")}`;
1695
+ }
1696
+ function resolveRepositoryContext(cwd = process.cwd()) {
1697
+ const top = gitToplevel(cwd);
1698
+ if (!top) return null;
1699
+ let repoRoot;
1700
+ try {
1701
+ repoRoot = realpathSync2.native(top);
1702
+ } catch {
1703
+ repoRoot = resolve2(top);
1704
+ }
1705
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1706
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1707
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1708
+ if (normalizedOrigin) {
1709
+ return {
1710
+ repoRoot,
1711
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
1712
+ identitySource: "origin",
1713
+ repoFullName
1714
+ };
1715
+ }
1716
+ if (repoFullName) {
1717
+ return {
1718
+ repoRoot,
1719
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1720
+ identitySource: "declared",
1721
+ repoFullName
1722
+ };
1723
+ }
1724
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1725
+ if (roots && roots.length > 0) {
1726
+ return {
1727
+ repoRoot,
1728
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1729
+ identitySource: "root_commit",
1730
+ repoFullName
1731
+ };
1732
+ }
1733
+ return { repoRoot, repoFullName };
1734
+ }
1735
+ function nearestExistingAncestor(path) {
1736
+ const suffix = [];
1737
+ let cursor = path;
1738
+ while (true) {
1739
+ try {
1740
+ lstatSync4(cursor);
1741
+ break;
1742
+ } catch (error) {
1743
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1744
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1745
+ const parent = dirname6(cursor);
1746
+ if (parent === cursor) return null;
1747
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1748
+ cursor = parent;
1749
+ }
1750
+ }
1751
+ try {
1752
+ return { real: realpathSync2.native(cursor), suffix };
1753
+ } catch {
1754
+ return null;
1755
+ }
1756
+ }
1757
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1758
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1759
+ return { ok: false, reason: "invalid_path" };
1760
+ }
1761
+ const absolute = resolve2(baseDir, filePath);
1762
+ const resolved = nearestExistingAncestor(absolute);
1763
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1764
+ const target = resolve2(resolved.real, ...resolved.suffix);
1765
+ const rel = relative(context.repoRoot, target);
1766
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1767
+ if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1768
+ return { ok: false, reason: "outside_repository" };
1769
+ }
1770
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1771
+ }
1772
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1773
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1774
+ return null;
1775
+ const absolute = resolve2(cwd, filePath);
1776
+ let target;
1777
+ try {
1778
+ const stat = lstatSync4(absolute);
1779
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1780
+ target = realpathSync2.native(absolute);
1781
+ } catch (error) {
1782
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1783
+ return null;
1784
+ }
1785
+ try {
1786
+ const parent = realpathSync2.native(dirname6(absolute));
1787
+ if (!lstatSync4(parent).isDirectory()) return null;
1788
+ target = resolve2(parent, basename2(absolute));
1789
+ } catch {
1790
+ return null;
1791
+ }
1792
+ }
1793
+ const rel = relative(repositoryRoot, target);
1794
+ if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1795
+ return null;
1796
+ }
1797
+ return sep === "/" ? rel : rel.split(sep).join("/");
1798
+ }
1799
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1800
+ if (typeof contextOrCwd === "string") {
1801
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1802
+ }
1803
+ return canonicalRepositoryPathScoped(
1804
+ filePath,
1805
+ contextOrCwd,
1806
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1807
+ );
1808
+ }
1809
+
1810
+ // src/lib/terminal-safe.ts
1811
+ function replaceIsolatedSurrogates(value) {
1812
+ let out = "";
1813
+ for (let index = 0; index < value.length; index += 1) {
1814
+ const unit = value.charCodeAt(index);
1815
+ if (unit >= 55296 && unit <= 56319) {
1816
+ const next = value.charCodeAt(index + 1);
1817
+ if (next >= 56320 && next <= 57343) {
1818
+ out += value[index] + value[index + 1];
1819
+ index += 1;
1820
+ } else {
1821
+ out += "\uFFFD";
1822
+ }
1823
+ } else if (unit >= 56320 && unit <= 57343) {
1824
+ out += "\uFFFD";
1825
+ } else {
1826
+ out += value[index];
1827
+ }
1828
+ }
1829
+ return out;
1830
+ }
1831
+ function isUnsafeTerminalCodePoint(point) {
1832
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1833
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1834
+ point === 1564 || // Arabic letter mark
1835
+ point === 6158 || // Mongolian vowel separator
1836
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1837
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1838
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1839
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1840
+ point === 65279 || // zero-width no-break space / BOM
1841
+ point >= 917504 && point <= 917631;
1842
+ return c0OrC1 || bidiOrZeroWidth;
1843
+ }
1844
+ function terminalSafeText(value) {
1845
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1846
+ }
1847
+ function terminalSafeLine(value) {
1848
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1849
+ }
1850
+ function isTerminalSafeText(value) {
1851
+ return terminalSafeText(value) === value;
1852
+ }
1853
+ var stripControlChars = terminalSafeText;
1854
+
1855
+ // src/lib/session-identity.ts
1856
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1857
+ var SESSION_IDENTITY_VALUE = "session";
1858
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1859
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1860
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1861
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1862
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1863
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1864
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1865
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1866
+ var SESSION_IDENTITY_ROUTES = {
1867
+ challenge: "/api/cli/session-identity/challenge",
1868
+ token: "/api/cli/session-identity/token",
1869
+ refresh: "/api/cli/session-identity/token/refresh",
1870
+ link: "/api/cli/session-identity/link"
1871
+ };
1872
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1873
+ var RENEW_BEFORE_MS = 6e4;
1874
+ var GIT_TIMEOUT_MS2 = 1e4;
1875
+ var POLL_BUDGET_MS = 15e3;
1876
+ var POLL_FIRST_DELAY_MS = 500;
1877
+ var POLL_MAX_DELAY_MS = 3e3;
1878
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1879
+ var LOCK_TIMEOUT_MS = 6e4;
1880
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1881
+ function sessionIdentityRequested(env = process.env) {
1882
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1883
+ }
1884
+ function sessionIdentityMode(deps = {}) {
1885
+ const env = deps.env ?? process.env;
1886
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1887
+ }
1888
+ function failure(code, cause, remedy) {
1889
+ return { status: "failed", code, cause, remedy };
1890
+ }
1891
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1892
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1893
+ 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';
1894
+ var SESSION_REVOKED = failure(
1895
+ "session_revoked",
1896
+ "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",
1897
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1898
+ );
1899
+ var CHALLENGE_WINDOW_PASSED = failure(
1900
+ "challenge_expired",
1901
+ "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)",
1902
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1903
+ );
1904
+ var CHALLENGE_GONE = failure(
1905
+ "challenge_not_found",
1906
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1907
+ NEW_SESSION_REMEDY
1908
+ );
1909
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1910
+ function rejectionFailure(reason, repository) {
1911
+ switch (reason) {
1912
+ case "identity_mismatch":
1913
+ return failure(
1914
+ "identity_mismatch",
1915
+ "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",
1916
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1917
+ );
1918
+ case "push_after_expiry":
1919
+ return failure(
1920
+ "push_after_expiry",
1921
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1922
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1923
+ );
1924
+ case "repository_mismatch":
1925
+ return failure(
1926
+ "repository_mismatch",
1927
+ `Primitive received the identity push from a different repository than ${repository}`,
1928
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1929
+ );
1930
+ case "conflicting_push":
1931
+ return failure(
1932
+ "conflicting_push",
1933
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1934
+ NEW_SESSION_REMEDY
1935
+ );
1936
+ case "unsupported_sender":
1937
+ return failure(
1938
+ "unsupported_sender",
1939
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1940
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1941
+ );
1942
+ default:
1943
+ return failure(
1944
+ "challenge_rejected",
1945
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1946
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1947
+ );
1948
+ }
1949
+ }
1950
+ function sessionIdentityMessage(outcome) {
1951
+ if (outcome.status === "link_required")
1952
+ 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.`;
1953
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1954
+ }
1955
+ function hash(value) {
1956
+ return createHash5("sha256").update(value).digest("hex");
1957
+ }
1958
+ function sessionContext(deps) {
1959
+ const env = deps.env ?? process.env;
1960
+ const environment = environmentCredentials(deps);
1961
+ if (!environment)
1962
+ return failure(
1963
+ "environment_credential_missing",
1964
+ "the cloud environment has no environment credential",
1965
+ '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'
1966
+ );
1967
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1968
+ if (!sessionId || !SESSION_ID.test(sessionId))
1969
+ return failure(
1970
+ "session_id_missing",
1971
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1972
+ NEW_SESSION_REMEDY
1973
+ );
1974
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1975
+ const directory = deps.directory ?? primConfigDirectory({ env });
1976
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1977
+ return {
1978
+ directory,
1979
+ apiUrl,
1980
+ clientId: environment.clientId,
1981
+ generation: environment.generation,
1982
+ sessionId,
1983
+ tokenPath: join9(directory, `session_identity_${key}.json`),
1984
+ statePath: join9(directory, `session_identity_${key}.state.json`),
1985
+ lockPath: join9(directory, "session-identity.lock")
1986
+ };
1987
+ }
1988
+ function readRecord(path) {
1989
+ try {
1990
+ const value = readMachineMetadata(path);
1991
+ return value === void 0 ? void 0 : machineRecord(value);
1992
+ } catch {
1993
+ return void 0;
1994
+ }
1995
+ }
1996
+ function finiteNumber(value) {
1997
+ return typeof value === "number" && Number.isFinite(value);
1998
+ }
1999
+ function readToken(context) {
2000
+ const data = readRecord(context.tokenPath);
2001
+ 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))
2002
+ return void 0;
2003
+ const identity = data.identity;
2004
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
2005
+ return void 0;
2006
+ return data;
2007
+ }
2008
+ function readState(context) {
2009
+ const data = readRecord(context.statePath);
2010
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
2011
+ return void 0;
2012
+ return data;
2013
+ }
2014
+ function writeToken(context, record) {
2015
+ prepareMachineMetadataDirectory(context.directory);
2016
+ writeMachineMetadata(context.tokenPath, record);
2017
+ rmSync6(context.statePath, { force: true });
2018
+ }
2019
+ function writeState(context, state) {
2020
+ try {
2021
+ prepareMachineMetadataDirectory(context.directory);
2022
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
2023
+ } catch {
2024
+ }
2025
+ }
2026
+ function tokenValid(record, now = Date.now()) {
2027
+ return now < record.expiresAt - RENEW_BEFORE_MS;
2028
+ }
2029
+ function tokenFresh(record, now = Date.now()) {
2030
+ return tokenValid(record, now) && now < record.refreshAfter;
2031
+ }
2032
+ function toCredential(record) {
2033
+ return {
2034
+ issuer: record.issuer,
2035
+ audience: record.audience,
2036
+ ...record.identity,
2037
+ accessToken: record.accessToken,
2038
+ expiresAt: record.expiresAt,
2039
+ apiUrl: record.apiUrl,
2040
+ generation: record.generation,
2041
+ storage: "environment",
2042
+ session: {
2043
+ userId: record.userId,
2044
+ displayName: record.displayName,
2045
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
2046
+ refreshAfter: record.refreshAfter
2047
+ }
2048
+ };
2049
+ }
2050
+ function identified(record, reused) {
2051
+ return {
2052
+ status: "ok",
2053
+ credential: toCredential(record),
2054
+ displayName: record.displayName,
2055
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
2056
+ reused
2057
+ };
2058
+ }
2059
+ function cachedSessionCredential(deps = {}) {
2060
+ if (!sessionIdentityMode(deps)) return void 0;
2061
+ let context;
2062
+ try {
2063
+ context = sessionContext(deps);
2064
+ } catch {
2065
+ return void 0;
2066
+ }
2067
+ if ("status" in context) return void 0;
2068
+ const record = readToken(context);
2069
+ return record && tokenValid(record) ? toCredential(record) : void 0;
2070
+ }
2071
+ function outcomeFromState(state) {
2072
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
2073
+ return {
2074
+ status: "link_required",
2075
+ githubLogin: state.githubLogin,
2076
+ challengeId: state.challengeId,
2077
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
2078
+ };
2079
+ return failure(
2080
+ state.code,
2081
+ state.cause ?? "the last identity check failed",
2082
+ state.remedy ?? RETRY_REMEDY
2083
+ );
2084
+ }
2085
+ function parseInstant(value) {
2086
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
2087
+ if (typeof value === "string" && value.length <= 64) {
2088
+ const parsed = Date.parse(value);
2089
+ return Number.isFinite(parsed) ? parsed : void 0;
2090
+ }
2091
+ return void 0;
2092
+ }
2093
+ async function sendJson(url, init, fetchImpl) {
2094
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
2095
+ let value;
2096
+ try {
2097
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
2098
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
2099
+ } catch {
2100
+ value = void 0;
2101
+ }
2102
+ return { status: response.status, value };
2103
+ }
2104
+ function environmentOnly(deps) {
2105
+ return { ...deps, environmentOnly: true };
2106
+ }
2107
+ async function environmentRequest(method, path, body, deps, signal) {
2108
+ const send = async (credential2) => {
2109
+ const headers = { "Content-Type": "application/json" };
2110
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
2111
+ if (credential2.tokenInjection) {
2112
+ const response = await forwardMachineRequest(
2113
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
2114
+ signal,
2115
+ environmentOnly(deps)
2116
+ );
2117
+ const parsed = await response.json().catch(() => void 0);
2118
+ return {
2119
+ status: response.status,
2120
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
2121
+ };
2122
+ }
2123
+ return sendJson(
2124
+ `${credential2.apiUrl}${path}`,
2125
+ {
2126
+ method,
2127
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
2128
+ ...text === void 0 ? {} : { body: text },
2129
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
2130
+ },
2131
+ deps.fetch ?? fetch
2132
+ );
2133
+ };
2134
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
2135
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
2136
+ let answer = await send(credential);
2137
+ if (answer.status === 401) {
2138
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
2139
+ if (!credential)
2140
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
2141
+ answer = await send(credential);
2142
+ }
2143
+ return answer;
2144
+ }
2145
+ function environmentFailure(error, apiUrl) {
2146
+ if (error instanceof MachineAuthError && error.terminal)
2147
+ return failure(
2148
+ "environment_credential_rejected",
2149
+ "Primitive rejected the cloud environment's credential",
2150
+ ENVIRONMENT_CREDENTIAL_REMEDY
2151
+ );
2152
+ const host = (() => {
2153
+ try {
2154
+ return new URL(apiUrl).hostname;
2155
+ } catch {
2156
+ return "Primitive";
2157
+ }
2158
+ })();
2159
+ return failure(
2160
+ "identity_unavailable",
2161
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
2162
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
2163
+ );
2164
+ }
2165
+ function answerError(answer) {
2166
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
2167
+ }
2168
+ async function git(root, args, signal) {
2169
+ try {
2170
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
2171
+ cwd: root,
2172
+ encoding: "utf8",
2173
+ timeout: GIT_TIMEOUT_MS2,
2174
+ signal,
2175
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
2176
+ maxBuffer: 1024 * 1024
2177
+ });
2178
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
2179
+ } catch (error) {
2180
+ const failed = error;
2181
+ return {
2182
+ ok: false,
2183
+ code: typeof failed.code === "number" ? failed.code : void 0,
2184
+ stdout: failed.stdout ?? "",
2185
+ stderr: failed.stderr ?? "",
2186
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
2187
+ };
2188
+ }
2189
+ }
2190
+ function gitDetail(stderr) {
2191
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
2192
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
2193
+ }
2194
+ async function defaultSleep2(milliseconds, signal) {
2195
+ await new Promise((resolve9, reject) => {
2196
+ const timer = setTimeout(resolve9, milliseconds);
2197
+ signal?.addEventListener(
2198
+ "abort",
2199
+ () => {
2200
+ clearTimeout(timer);
2201
+ reject(signal.reason);
2202
+ },
2203
+ { once: true }
2204
+ );
2205
+ });
2206
+ }
2207
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
2208
+ const sleep = deps.sleep ?? defaultSleep2;
2209
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
2210
+ let delay = POLL_FIRST_DELAY_MS;
2211
+ let unreachable;
2212
+ for (; ; ) {
2213
+ const remaining = deadline - Date.now();
2214
+ if (remaining <= 0) break;
2215
+ await sleep(Math.min(delay, remaining), signal);
2216
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
2217
+ let answer;
2218
+ try {
2219
+ answer = await environmentRequest(
2220
+ "GET",
2221
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
2222
+ void 0,
2223
+ deps,
2224
+ signal
2225
+ );
2226
+ } catch (error) {
2227
+ signal?.throwIfAborted();
2228
+ unreachable = error;
2229
+ continue;
2230
+ }
2231
+ if (answer.status === 404) return CHALLENGE_GONE;
2232
+ if (answer.status === 401 || answer.status === 403)
2233
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
2234
+ if (answer.status < 200 || answer.status > 299) {
2235
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
2236
+ continue;
2237
+ }
2238
+ unreachable = void 0;
2239
+ const status = answer.value;
2240
+ if (status?.status === "verified")
2241
+ return {
2242
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
2243
+ };
2244
+ if (status?.status === "expired")
2245
+ return failure(
2246
+ "challenge_expired",
2247
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
2248
+ NEW_SESSION_REMEDY
2249
+ );
2250
+ if (status?.status === "rejected")
2251
+ return rejectionFailure(status.reason, repository);
2252
+ }
2253
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
2254
+ return failure(
2255
+ "webhook_timeout",
2256
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
2257
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2258
+ );
2259
+ }
2260
+ function parseTokenAnswer(value) {
2261
+ if (!value) return void 0;
2262
+ const user = value.user;
2263
+ const expiresAt = parseInstant(value.expiresAt);
2264
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
2265
+ 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))
2266
+ return void 0;
2267
+ return {
2268
+ accessToken: value.accessToken,
2269
+ expiresAt,
2270
+ refreshAfter: Math.min(refreshAfter, expiresAt),
2271
+ userId: user.id,
2272
+ displayName: user.displayName,
2273
+ organizationId: value.organizationId
2274
+ };
2275
+ }
2276
+ var SERVER_CONTRACT_FAILURE = failure(
2277
+ "server_contract",
2278
+ "Primitive's answer did not identify the linked member",
2279
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
2280
+ );
2281
+ async function recordFor(context, answer, extra, deps, signal) {
2282
+ let identity;
2283
+ let environment;
2284
+ try {
2285
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
2286
+ identity = await verifyMachineIdentity(
2287
+ context.apiUrl,
2288
+ answer.accessToken,
2289
+ context.clientId,
2290
+ signal,
2291
+ deps.fetch
2292
+ );
2293
+ } catch (error) {
2294
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
2295
+ return SERVER_CONTRACT_FAILURE;
2296
+ return environmentFailure(error, context.apiUrl);
2297
+ }
2298
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
2299
+ return SERVER_CONTRACT_FAILURE;
2300
+ return {
2301
+ version: 1,
2302
+ apiUrl: context.apiUrl,
2303
+ clientId: context.clientId,
2304
+ generation: context.generation,
2305
+ sessionId: context.sessionId,
2306
+ issuer: environment.issuer,
2307
+ audience: environment.audience,
2308
+ accessToken: answer.accessToken,
2309
+ expiresAt: answer.expiresAt,
2310
+ refreshAfter: answer.refreshAfter,
2311
+ userId: answer.userId,
2312
+ displayName: answer.displayName,
2313
+ organizationId: answer.organizationId,
2314
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
2315
+ identity,
2316
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
2317
+ };
2318
+ }
2319
+ async function refreshToken(context, record, deps, signal) {
2320
+ let answer;
2321
+ try {
2322
+ answer = await environmentRequest(
2323
+ "POST",
2324
+ SESSION_IDENTITY_ROUTES.refresh,
2325
+ { accessToken: record.accessToken },
2326
+ deps,
2327
+ signal
2328
+ );
2329
+ } catch (error) {
2330
+ signal?.throwIfAborted();
2331
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
2332
+ }
2333
+ const code = answerError(answer);
2334
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
2335
+ return { status: "refused", failure: SESSION_REVOKED };
2336
+ if (answer.status === 401 || answer.status === 403)
2337
+ return {
2338
+ status: "refused",
2339
+ failure: environmentFailure(
2340
+ new MachineAuthError("rejected", "rejected", true),
2341
+ context.apiUrl
2342
+ )
2343
+ };
2344
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2345
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
2346
+ return { status: "unavailable" };
2347
+ return {
2348
+ status: "ok",
2349
+ record: {
2350
+ ...record,
2351
+ accessToken: token.accessToken,
2352
+ expiresAt: token.expiresAt,
2353
+ refreshAfter: token.refreshAfter,
2354
+ displayName: token.displayName
2355
+ }
2356
+ };
2357
+ }
2358
+ function exchangeRefusal(answer, repository) {
2359
+ if (answer.status === 404) return CHALLENGE_GONE;
2360
+ if (answer.status !== 409) return void 0;
2361
+ switch (answerError(answer)) {
2362
+ case "identity_mismatch":
2363
+ return rejectionFailure("identity_mismatch", repository);
2364
+ case "challenge_rejected":
2365
+ return rejectionFailure(answer.value?.reason, repository);
2366
+ case "challenge_expired":
2367
+ return CHALLENGE_WINDOW_PASSED;
2368
+ case "challenge_already_exchanged":
2369
+ return failure(
2370
+ "challenge_already_exchanged",
2371
+ "this session's identity check was already exchanged for a token this VM does not hold",
2372
+ NEW_SESSION_REMEDY
2373
+ );
2374
+ case "challenge_pending":
2375
+ return failure(
2376
+ "webhook_timeout",
2377
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
2378
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2379
+ );
2380
+ default:
2381
+ return void 0;
2382
+ }
2383
+ }
2384
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
2385
+ let answer;
2386
+ try {
2387
+ answer = await environmentRequest(
2388
+ "POST",
2389
+ SESSION_IDENTITY_ROUTES.token,
2390
+ { challengeId: challenge.challengeId },
2391
+ deps,
2392
+ signal
2393
+ );
2394
+ } catch (error) {
2395
+ signal?.throwIfAborted();
2396
+ return environmentFailure(error, context.apiUrl);
2397
+ }
2398
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
2399
+ const login = answer.value?.githubLogin;
2400
+ return {
2401
+ status: "link_required",
2402
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
2403
+ challengeId: challenge.challengeId,
2404
+ challengeExpiresAt: challenge.challengeExpiresAt
2405
+ };
2406
+ }
2407
+ const refused = exchangeRefusal(
2408
+ answer,
2409
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
2410
+ );
2411
+ if (refused) return refused;
2412
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2413
+ if (!token) {
2414
+ if (answer.status === 401 || answer.status === 403)
2415
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2416
+ return answer.status >= 500 ? environmentFailure(
2417
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2418
+ context.apiUrl
2419
+ ) : SERVER_CONTRACT_FAILURE;
2420
+ }
2421
+ return recordFor(
2422
+ context,
2423
+ token,
2424
+ { githubLogin: challenge.githubLogin, repositoryRoot },
2425
+ deps,
2426
+ signal
2427
+ );
2428
+ }
2429
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
2430
+ const env = deps.env ?? process.env;
2431
+ const repository = githubRepositoryFullName(root);
2432
+ if (!repository)
2433
+ return failure(
2434
+ "repository_unidentified",
2435
+ "this checkout does not name its GitHub repository",
2436
+ "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"
2437
+ );
2438
+ const branch = currentBranch(root);
2439
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
2440
+ return failure(
2441
+ "not_session_branch",
2442
+ `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`,
2443
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
2444
+ );
2445
+ attempt.branch = branch;
2446
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
2447
+ if (!baseSha) {
2448
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
2449
+ baseSha = head.stdout.trim();
2450
+ if (!head.ok || !SHA.test(baseSha))
2451
+ return failure(
2452
+ "no_commit",
2453
+ "this checkout has no commit to create the session branch at",
2454
+ NEW_SESSION_REMEDY
2455
+ );
2456
+ }
2457
+ const published = await git(
2458
+ root,
2459
+ [
2460
+ "for-each-ref",
2461
+ "--count=1",
2462
+ "--format=%(refname)",
2463
+ "--contains",
2464
+ baseSha,
2465
+ "refs/remotes/origin/"
2466
+ ],
2467
+ signal
2468
+ );
2469
+ if (!published.ok || published.stdout.trim() === "")
2470
+ return failure(
2471
+ "unpublished_commits",
2472
+ `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`,
2473
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
2474
+ );
2475
+ attempt.baseSha = baseSha;
2476
+ const remote = await git(
2477
+ root,
2478
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2479
+ signal
2480
+ );
2481
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2482
+ if (remote.ok && recorded) {
2483
+ Object.assign(attempt, recorded);
2484
+ return { ...recorded, repository };
2485
+ }
2486
+ if (remote.ok)
2487
+ return failure(
2488
+ "branch_exists",
2489
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2490
+ NEW_SESSION_REMEDY
2491
+ );
2492
+ if (remote.code !== 2)
2493
+ return failure(
2494
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2495
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2496
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2497
+ );
2498
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2499
+ Object.assign(attempt, recorded);
2500
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2501
+ }
2502
+ let answer;
2503
+ try {
2504
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2505
+ answer = await environmentRequest(
2506
+ "POST",
2507
+ SESSION_IDENTITY_ROUTES.challenge,
2508
+ {
2509
+ repositoryFullName: repository,
2510
+ claudeSessionId: context.sessionId,
2511
+ branch,
2512
+ baseSha,
2513
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2514
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2515
+ },
2516
+ deps,
2517
+ signal
2518
+ );
2519
+ } catch (error) {
2520
+ signal?.throwIfAborted();
2521
+ return environmentFailure(error, context.apiUrl);
2522
+ }
2523
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2524
+ return failure(
2525
+ "repository_not_connected",
2526
+ `${repository} is not connected to Primitive`,
2527
+ CLOUD_GITHUB_CONNECT_REMEDY
2528
+ );
2529
+ if (answer.status === 401 || answer.status === 403)
2530
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2531
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2532
+ return failure(
2533
+ "challenge_open",
2534
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2535
+ `wait five minutes, then ${RETRY_REMEDY}`
2536
+ );
2537
+ if (answer.status === 429)
2538
+ return failure(
2539
+ "too_many_challenges",
2540
+ "too many sessions of this cloud environment are being identified at once",
2541
+ `wait a few minutes, then ${RETRY_REMEDY}`
2542
+ );
2543
+ const challengeId = answer.value?.challengeId;
2544
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2545
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2546
+ return answer.status >= 500 ? environmentFailure(
2547
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2548
+ context.apiUrl
2549
+ ) : SERVER_CONTRACT_FAILURE;
2550
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2551
+ attempt.challengeId = challengeId;
2552
+ attempt.challengeExpiresAt = challengeExpiresAt;
2553
+ return pushSessionBranch(
2554
+ root,
2555
+ repository,
2556
+ branch,
2557
+ baseSha,
2558
+ { challengeId, challengeExpiresAt },
2559
+ signal
2560
+ );
2561
+ }
2562
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2563
+ const push = await git(
2564
+ root,
2565
+ [
2566
+ "-c",
2567
+ "core.hooksPath=/dev/null",
2568
+ "-c",
2569
+ "push.followTags=false",
2570
+ "-c",
2571
+ "push.recurseSubmodules=no",
2572
+ "-c",
2573
+ "push.gpgSign=false",
2574
+ "-c",
2575
+ "push.pushOption=",
2576
+ "push",
2577
+ "--no-verify",
2578
+ "--no-follow-tags",
2579
+ "--no-recurse-submodules",
2580
+ "--no-signed",
2581
+ "--quiet",
2582
+ "origin",
2583
+ `${baseSha}:refs/heads/${branch}`
2584
+ ],
2585
+ signal
2586
+ );
2587
+ if (!push.ok)
2588
+ return push.timedOut ? failure(
2589
+ "push_timeout",
2590
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2591
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2592
+ ) : failure(
2593
+ "push_refused",
2594
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2595
+ `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}`
2596
+ );
2597
+ return { ...challenge, repository };
2598
+ }
2599
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2600
+ let context;
2601
+ try {
2602
+ context = sessionContext(deps);
2603
+ } catch (error) {
2604
+ return failure(
2605
+ "environment_credential_invalid",
2606
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2607
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2608
+ );
2609
+ }
2610
+ if ("status" in context) return context;
2611
+ const ctx = context;
2612
+ const startedAt = Date.now();
2613
+ prepareMachineMetadataDirectory(ctx.directory);
2614
+ return withFileLock(
2615
+ ctx.lockPath,
2616
+ async () => {
2617
+ const record = readToken(ctx);
2618
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2619
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2620
+ if (record) {
2621
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2622
+ if (refreshed.status === "ok") {
2623
+ writeToken(ctx, refreshed.record);
2624
+ return identified(refreshed.record, true);
2625
+ }
2626
+ if (refreshed.status === "refused") {
2627
+ rmSync6(ctx.tokenPath, { force: true });
2628
+ writeState(ctx, {
2629
+ sessionId: ctx.sessionId,
2630
+ status: "failed",
2631
+ code: refreshed.failure.code,
2632
+ cause: refreshed.failure.cause,
2633
+ remedy: refreshed.failure.remedy,
2634
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2635
+ at: Date.now()
2636
+ });
2637
+ return refreshed.failure;
2638
+ }
2639
+ if (!forced && tokenValid(record)) return identified(record, true);
2640
+ }
2641
+ const state = readState(ctx);
2642
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2643
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2644
+ if (!options.explicit) {
2645
+ if (!root || !(record || state))
2646
+ return failure(
2647
+ "not_identified",
2648
+ "this session has not identified who started it yet",
2649
+ RETRY_REMEDY
2650
+ );
2651
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2652
+ } else if (state && state.at >= startedAt) {
2653
+ return outcomeFromState(state);
2654
+ }
2655
+ if (!root)
2656
+ return failure(
2657
+ "repository_missing",
2658
+ "this is not a git repository",
2659
+ "run it in the repository the session cloned"
2660
+ );
2661
+ const attempt = { root };
2662
+ const remember = (outcome) => {
2663
+ writeState(ctx, {
2664
+ sessionId: ctx.sessionId,
2665
+ status: outcome.status,
2666
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2667
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2668
+ githubLogin: outcome.githubLogin
2669
+ },
2670
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2671
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2672
+ repositoryRoot: root,
2673
+ branch: attempt.branch ?? state?.branch,
2674
+ baseSha: attempt.baseSha ?? state?.baseSha,
2675
+ at: Date.now()
2676
+ });
2677
+ return outcome;
2678
+ };
2679
+ let challenge;
2680
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2681
+ attempt.challengeId = state.challengeId;
2682
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2683
+ attempt.branch = state.branch;
2684
+ attempt.baseSha = state.baseSha;
2685
+ challenge = {
2686
+ challengeId: state.challengeId,
2687
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2688
+ repository: githubRepositoryFullName(root) ?? "the repository"
2689
+ };
2690
+ } else if (state?.status === "link_required" && state.challengeId) {
2691
+ attempt.challengeId = state.challengeId;
2692
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2693
+ const exchanged2 = await exchangeChallenge(
2694
+ ctx,
2695
+ {
2696
+ challengeId: state.challengeId,
2697
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2698
+ githubLogin: state.githubLogin
2699
+ },
2700
+ root,
2701
+ deps,
2702
+ options.signal
2703
+ );
2704
+ if ("status" in exchanged2) return remember(exchanged2);
2705
+ writeToken(ctx, exchanged2);
2706
+ return identified(exchanged2, false);
2707
+ } else if (!options.explicit) {
2708
+ return state ? outcomeFromState(state) : failure(
2709
+ "not_identified",
2710
+ "this session has not identified who started it yet",
2711
+ RETRY_REMEDY
2712
+ );
2713
+ } else {
2714
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2715
+ if ("status" in pushed) return remember(pushed);
2716
+ challenge = pushed;
2717
+ }
2718
+ const verified = await pollChallenge(
2719
+ ctx.apiUrl,
2720
+ challenge.challengeId,
2721
+ challenge.repository,
2722
+ // A hook process waits only briefly for a late notice.
2723
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2724
+ options.signal
2725
+ );
2726
+ if ("status" in verified) return remember(verified);
2727
+ const exchanged = await exchangeChallenge(
2728
+ ctx,
2729
+ { ...challenge, githubLogin: verified.githubLogin },
2730
+ root,
2731
+ deps,
2732
+ options.signal
2733
+ );
2734
+ if ("status" in exchanged) return remember(exchanged);
2735
+ writeToken(ctx, exchanged);
2736
+ return identified(exchanged, false);
2737
+ },
2738
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2739
+ );
2740
+ }
2741
+ async function acquireSessionCredential(options = {}, deps = {}) {
2742
+ const cached2 = cachedSessionCredential(deps);
2743
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2744
+ if (cached2 && fresh && !options.force) return cached2;
2745
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2746
+ let outcome;
2747
+ try {
2748
+ outcome = await ensureSessionIdentity(
2749
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2750
+ deps
2751
+ );
2752
+ } catch (error) {
2753
+ options.signal?.throwIfAborted();
2754
+ if (error instanceof MachineAuthError) throw error;
2755
+ throw new MachineAuthError(
2756
+ "identity_unavailable",
2757
+ "Identifying who started this cloud session is still in progress; retry shortly."
2758
+ );
2759
+ }
2760
+ if (outcome.status === "ok") return outcome.credential;
2761
+ throw new MachineAuthError(
2762
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2763
+ sessionIdentityMessage(outcome)
2764
+ );
2765
+ }
2766
+
1205
2767
  // src/lib/machine-credentials.ts
1206
- var require2 = createRequire(import.meta.url);
2768
+ function sessionScoped(deps) {
2769
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2770
+ }
2771
+ var require3 = createRequire2(import.meta.url);
1207
2772
  var SERVICE = "ai.primitive.prim.machine";
1208
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2773
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1209
2774
  var PROFILE_FILE = "machine_profile.json";
1210
- var RENEW_BEFORE_MS = 6e4;
2775
+ var RENEW_BEFORE_MS2 = 6e4;
1211
2776
  var cached;
1212
2777
  function configurationDirectory(deps) {
1213
2778
  return deps.directory ?? primConfigDirectory({ env: deps.env });
1214
2779
  }
1215
2780
  function apiUrlFor(deps) {
1216
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2781
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
1217
2782
  }
1218
- function hash(value) {
1219
- return createHash3("sha256").update(value).digest("hex");
2783
+ function hash2(value) {
2784
+ return createHash6("sha256").update(value).digest("hex");
1220
2785
  }
1221
2786
  function recordPath(directory, generation) {
1222
- return join6(directory, `machine_${generation}.json`);
2787
+ return join10(directory, `machine_${generation}.json`);
1223
2788
  }
1224
2789
  function storageKey(directory, generation) {
1225
- return `${hash(directory)}:${generation}`;
2790
+ return `${hash2(directory)}:${generation}`;
1226
2791
  }
1227
2792
  function environmentContextPath(deps, clientId) {
1228
- return join6(
2793
+ return join10(
1229
2794
  configurationDirectory(deps),
1230
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2795
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1231
2796
  );
1232
2797
  }
1233
2798
  function writeEnvironmentContext(credential, deps) {
@@ -1285,27 +2850,33 @@ function readEnvironmentContext(environment, deps) {
1285
2850
  return void 0;
1286
2851
  }
1287
2852
  }
1288
- function keyringEntry(key) {
1289
- let directory = dirname4(fileURLToPath3(import.meta.url));
2853
+ function keyringLoaderPath(start, options = {}) {
2854
+ let directory = start;
1290
2855
  for (let depth = 0; depth < 5; depth++) {
1291
- const loader = join6(directory, "native", "keyring.cjs");
1292
- if (existsSync3(loader)) {
1293
- const module2 = require2(loader);
1294
- return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1295
- }
1296
- directory = dirname4(directory);
2856
+ const loader = join10(directory, "native", "keyring.cjs");
2857
+ if (existsSync5(loader)) return loader;
2858
+ directory = dirname7(directory);
1297
2859
  }
1298
- const module = require2("@napi-rs/keyring");
2860
+ try {
2861
+ createRequire2(join10(start, "noop.js")).resolve("@napi-rs/keyring");
2862
+ return void 0;
2863
+ } catch {
2864
+ return selectedHookRuntimeKeyringLoader(options);
2865
+ }
2866
+ }
2867
+ function keyringEntry(key) {
2868
+ const loader = keyringLoaderPath(dirname7(fileURLToPath4(import.meta.url)));
2869
+ const module = require3(loader ?? "@napi-rs/keyring");
1299
2870
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1300
2871
  }
1301
2872
  function protectPath(path, directory) {
1302
2873
  if (process.platform !== "win32") {
1303
- chmodSync(path, directory ? 448 : 384);
2874
+ chmodSync2(path, directory ? 448 : 384);
1304
2875
  return;
1305
2876
  }
1306
2877
  const encodedPath = Buffer.from(path).toString("base64");
1307
2878
  const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
1308
- execFileSync(
2879
+ execFileSync2(
1309
2880
  "powershell.exe",
1310
2881
  [
1311
2882
  "-NoProfile",
@@ -1317,8 +2888,8 @@ function protectPath(path, directory) {
1317
2888
  );
1318
2889
  }
1319
2890
  function ensureDirectory(directory) {
1320
- mkdirSync3(directory, { recursive: true, mode: 448 });
1321
- if (lstatSync3(directory).isSymbolicLink())
2891
+ mkdirSync4(directory, { recursive: true, mode: 448 });
2892
+ if (lstatSync5(directory).isSymbolicLink())
1322
2893
  throw new MachineAuthError(
1323
2894
  "unsafe_storage",
1324
2895
  "Credential directory must not be a symbolic link."
@@ -1330,17 +2901,20 @@ function writePrivate(path, value) {
1330
2901
  `, { mode: 384 });
1331
2902
  protectPath(path, false);
1332
2903
  }
2904
+ function readMachineMetadata(path) {
2905
+ return readPrivate(path);
2906
+ }
1333
2907
  function readPrivate(path) {
1334
2908
  let raw;
1335
2909
  try {
1336
- const stat = lstatSync3(path);
2910
+ const stat = lstatSync5(path);
1337
2911
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1338
2912
  throw new MachineAuthError(
1339
2913
  "unsafe_storage",
1340
2914
  "Machine credential files must be owner-only regular files."
1341
2915
  );
1342
2916
  }
1343
- raw = readFileSync5(path, "utf8");
2917
+ raw = readFileSync7(path, "utf8");
1344
2918
  } catch (error) {
1345
2919
  if (error.code === "ENOENT") return void 0;
1346
2920
  throw error;
@@ -1385,7 +2959,7 @@ function parseProfile(value) {
1385
2959
  };
1386
2960
  }
1387
2961
  function readMachineProfile(deps = {}) {
1388
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
2962
+ const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
1389
2963
  return value === void 0 ? void 0 : parseProfile(value);
1390
2964
  }
1391
2965
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -1394,20 +2968,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
1394
2968
  var brokerKeys = /* @__PURE__ */ new Map();
1395
2969
  function networkSecretBrokerKey(deps, clientId) {
1396
2970
  const directory = configurationDirectory(deps);
1397
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2971
+ const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
1398
2972
  const known = brokerKeys.get(path);
1399
2973
  if (known) return known;
1400
2974
  ensureDirectory(directory);
1401
2975
  const read = () => {
1402
2976
  try {
1403
- const stat = lstatSync3(path);
2977
+ const stat = lstatSync5(path);
1404
2978
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
1405
2979
  throw new MachineAuthError(
1406
2980
  "unsafe_storage",
1407
2981
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
1408
2982
  true
1409
2983
  );
1410
- const value = readFileSync5(path, "utf8").trim();
2984
+ const value = readFileSync7(path, "utf8").trim();
1411
2985
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
1412
2986
  } catch (error) {
1413
2987
  if (error.code === "ENOENT") return void 0;
@@ -1426,16 +3000,16 @@ function networkSecretBrokerKey(deps, clientId) {
1426
3000
  `The machine broker key at ${path} is damaged. Delete it and retry.`,
1427
3001
  true
1428
3002
  );
1429
- const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
3003
+ const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
1430
3004
  try {
1431
- writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
3005
+ writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
1432
3006
  `, { mode: 384, flag: "wx" });
1433
3007
  protectPath(staged, false);
1434
3008
  linkSync(staged, path);
1435
3009
  } catch (error) {
1436
3010
  if (error.code !== "EEXIST") throw error;
1437
3011
  } finally {
1438
- rmSync5(staged, { force: true });
3012
+ rmSync7(staged, { force: true });
1439
3013
  }
1440
3014
  }
1441
3015
  const key = read()?.key;
@@ -1468,7 +3042,7 @@ function environmentCredentials(deps) {
1468
3042
  "conflicting_credentials",
1469
3043
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
1470
3044
  );
1471
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
3045
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1472
3046
  const credentials = {
1473
3047
  clientId,
1474
3048
  generation,
@@ -1489,12 +3063,12 @@ function environmentCredentials(deps) {
1489
3063
  return {
1490
3064
  clientId,
1491
3065
  clientSecret,
1492
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
3066
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1493
3067
  };
1494
3068
  }
1495
3069
  function hasMachineConfiguration(deps = {}) {
1496
3070
  const env = deps.env ?? process.env;
1497
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
3071
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
1498
3072
  if (configured && env.PRIM_TOKEN?.trim()) {
1499
3073
  throw new MachineAuthError(
1500
3074
  "conflicting_credentials",
@@ -1506,6 +3080,7 @@ function hasMachineConfiguration(deps = {}) {
1506
3080
  }
1507
3081
  function machineContext(deps = {}) {
1508
3082
  if (!hasMachineConfiguration(deps)) return void 0;
3083
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1509
3084
  const environment = environmentCredentials(deps);
1510
3085
  if (environment) {
1511
3086
  if (environmentTerminal === environment.generation) return void 0;
@@ -1520,6 +3095,7 @@ function machineContext(deps = {}) {
1520
3095
  return profile;
1521
3096
  }
1522
3097
  function cachedMachineCredential(deps = {}) {
3098
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1523
3099
  const context = machineContext(deps);
1524
3100
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1525
3101
  }
@@ -1528,7 +3104,7 @@ function machineSessionEnded(deps = {}) {
1528
3104
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1529
3105
  if (!generation) return false;
1530
3106
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1531
- return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
3107
+ return readPrivate(join10(configurationDirectory(deps), "machine_terminal.json")) === generation;
1532
3108
  }
1533
3109
  var environmentTerminal;
1534
3110
  var NETWORK_REJECTION_PAUSE_MS = 3e4;
@@ -1592,6 +3168,7 @@ async function persistRecord(record, deps, signal) {
1592
3168
  }
1593
3169
  async function acquireMachineCredential(options = {}, deps = {}) {
1594
3170
  if (!hasMachineConfiguration(deps)) return void 0;
3171
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1595
3172
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1596
3173
  const apiUrl = apiUrlFor(deps);
1597
3174
  const environment = environmentCredentials(deps);
@@ -1620,7 +3197,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1620
3197
  }
1621
3198
  }
1622
3199
  return withFileLock(
1623
- join6(directory2, "credentials.lock"),
3200
+ join10(directory2, "credentials.lock"),
1624
3201
  async () => {
1625
3202
  if (machineSessionEnded(deps))
1626
3203
  throw new MachineAuthError(
@@ -1628,7 +3205,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1628
3205
  rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1629
3206
  true
1630
3207
  );
1631
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
3208
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1632
3209
  return cached;
1633
3210
  if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
1634
3211
  throw networkRejection.error;
@@ -1702,7 +3279,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1702
3279
  const contextPath = environmentContextPath(deps, environment.clientId);
1703
3280
  try {
1704
3281
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1705
- rmSync5(contextPath, { force: true });
3282
+ rmSync7(contextPath, { force: true });
1706
3283
  } catch {
1707
3284
  }
1708
3285
  throw error;
@@ -1712,7 +3289,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1712
3289
  const contextPath = environmentContextPath(deps, environment.clientId);
1713
3290
  try {
1714
3291
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1715
- rmSync5(contextPath, { force: true });
3292
+ rmSync7(contextPath, { force: true });
1716
3293
  } catch {
1717
3294
  }
1718
3295
  }
@@ -1726,7 +3303,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1726
3303
  const expected = machineContext(deps);
1727
3304
  const directory = configurationDirectory(deps);
1728
3305
  return withFileLock(
1729
- join6(directory, "credentials.lock"),
3306
+ join10(directory, "credentials.lock"),
1730
3307
  async () => {
1731
3308
  const profile = readMachineProfile(deps);
1732
3309
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1741,7 +3318,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1741
3318
  true
1742
3319
  );
1743
3320
  let record = await loadRecord(profile, deps, signal);
1744
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
3321
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1745
3322
  try {
1746
3323
  const { tokens, identity } = await withMachineCooldown(
1747
3324
  directory,
@@ -1776,7 +3353,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1776
3353
  await persistRecord(record, deps, signal);
1777
3354
  } catch (error) {
1778
3355
  if (error instanceof MachineAuthError && error.terminal)
1779
- writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
3356
+ writePrivate(join10(directory, "machine_terminal.json"), profile.generation);
1780
3357
  throw error;
1781
3358
  }
1782
3359
  }
@@ -1822,31 +3399,37 @@ function machineCaptureActor(deps = {}) {
1822
3399
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
1823
3400
  }
1824
3401
  function machineJournalBucket(identity) {
1825
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
3402
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1826
3403
  }
1827
3404
  function identityPending(actor) {
1828
3405
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1829
3406
  }
1830
3407
  function machinePendingBucket(identity) {
1831
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
3408
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
3409
+ }
3410
+ function prepareMachineMetadataDirectory(directory) {
3411
+ ensureDirectory(directory);
3412
+ }
3413
+ function writeMachineMetadata(path, value) {
3414
+ writePrivate(path, value);
1832
3415
  }
1833
3416
 
1834
3417
  // src/lib/credentials.ts
1835
3418
  var CONFIG_DIRECTORY = primConfigDirectory();
1836
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1837
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1838
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1839
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1840
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1841
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1842
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1843
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3419
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
3420
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
3421
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
3422
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
3423
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
3424
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
3425
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
3426
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
1844
3427
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1845
3428
  var CREDENTIAL_MIGRATION_VERSION = 1;
1846
3429
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1847
3430
  function readTrimmed(path) {
1848
3431
  try {
1849
- const value = readFileSync6(path, "utf8").trim();
3432
+ const value = readFileSync8(path, "utf8").trim();
1850
3433
  return value || void 0;
1851
3434
  } catch {
1852
3435
  return void 0;
@@ -1868,22 +3451,22 @@ function resolveAuthCredential(options = {}) {
1868
3451
  );
1869
3452
  if (metadata.state === "legacy_broker") {
1870
3453
  if (metadata.metadata) {
1871
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1872
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3454
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3455
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1873
3456
  return void 0;
1874
3457
  }
1875
3458
  }
1876
3459
  return { token: stored, source: "token_file" };
1877
3460
  }
1878
3461
  if (metadata.state === "invalid") return void 0;
1879
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1880
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3462
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3463
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1881
3464
  return void 0;
1882
3465
  }
1883
3466
  return { token: stored, source: "token_file" };
1884
3467
  }
1885
3468
  function credentialFingerprint(value) {
1886
- return createHash4("sha256").update(value).digest("hex");
3469
+ return createHash7("sha256").update(value).digest("hex");
1887
3470
  }
1888
3471
  function parseLegacyBrokerCredentialMetadata(value) {
1889
3472
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1903,7 +3486,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1903
3486
  function readBoundedCredentialJson(path) {
1904
3487
  let raw;
1905
3488
  try {
1906
- raw = readFileSync6(path, "utf8");
3489
+ raw = readFileSync8(path, "utf8");
1907
3490
  } catch (error) {
1908
3491
  return error.code === "ENOENT" ? void 0 : null;
1909
3492
  }
@@ -1980,14 +3563,14 @@ function jwtOrganizationId(token) {
1980
3563
 
1981
3564
  // src/binding.ts
1982
3565
  var PRIM_CONFIG_DIR = primConfigDirectory();
1983
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
3566
+ var SESSIONS_DIR = join12(PRIM_CONFIG_DIR, "sessions");
1984
3567
  var WORKSPACE_FILE = ".prim/workspace.json";
1985
3568
  function readJsonSafe(path) {
1986
- if (!existsSync4(path)) {
3569
+ if (!existsSync6(path)) {
1987
3570
  return;
1988
3571
  }
1989
3572
  try {
1990
- return JSON.parse(readFileSync7(path, "utf-8"));
3573
+ return JSON.parse(readFileSync9(path, "utf-8"));
1991
3574
  } catch {
1992
3575
  return;
1993
3576
  }
@@ -1996,17 +3579,17 @@ function fromSessionMarker(sessionId) {
1996
3579
  if (!sessionId) {
1997
3580
  return;
1998
3581
  }
1999
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
3582
+ const marker = readJsonSafe(join12(SESSIONS_DIR, `${sessionId}.json`));
2000
3583
  return marker?.orgId;
2001
3584
  }
2002
3585
  function fromWorkspaceFile(startDir) {
2003
3586
  let dir = startDir;
2004
3587
  while (true) {
2005
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
3588
+ const config = readJsonSafe(join12(dir, WORKSPACE_FILE));
2006
3589
  if (config?.orgId) {
2007
3590
  return config.orgId;
2008
3591
  }
2009
- const parent = dirname5(dir);
3592
+ const parent = dirname8(dir);
2010
3593
  if (parent === dir) {
2011
3594
  return;
2012
3595
  }
@@ -2116,14 +3699,14 @@ function publicDecisionResponse(value) {
2116
3699
  }
2117
3700
 
2118
3701
  // src/client.ts
2119
- import { createHash as createHash5 } from "crypto";
2120
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
2121
- import { dirname as dirname6 } from "path";
3702
+ import { createHash as createHash8 } from "crypto";
3703
+ import { chmodSync as chmodSync4, existsSync as existsSync7, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync8 } from "fs";
3704
+ import { dirname as dirname9 } from "path";
2122
3705
 
2123
3706
  // src/daemon/client-instance-id.ts
2124
- import { randomBytes as randomBytes4 } from "crypto";
2125
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
2126
- import { join as join9 } from "path";
3707
+ import { randomBytes as randomBytes5 } from "crypto";
3708
+ import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync10 } from "fs";
3709
+ import { join as join13 } from "path";
2127
3710
  var CONFIG_DIRECTORY_MODE = 448;
2128
3711
  var INSTANCE_FILE_MODE = 384;
2129
3712
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -2136,17 +3719,17 @@ function isClientInstanceId(value) {
2136
3719
  }
2137
3720
  function ensurePrivateConfigDirectory(configDir) {
2138
3721
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
2139
- const metadata = lstatSync4(configDir);
3722
+ const metadata = lstatSync6(configDir);
2140
3723
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
2141
3724
  throw new Error("prim config path must be a private directory");
2142
3725
  }
2143
- chmodSync2(configDir, CONFIG_DIRECTORY_MODE);
3726
+ chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
2144
3727
  syncDirectory(configDir);
2145
3728
  }
2146
3729
  function readExisting(path) {
2147
3730
  let metadata;
2148
3731
  try {
2149
- metadata = lstatSync4(path);
3732
+ metadata = lstatSync6(path);
2150
3733
  } catch (error) {
2151
3734
  if (error.code === "ENOENT") {
2152
3735
  return;
@@ -2156,11 +3739,11 @@ function readExisting(path) {
2156
3739
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
2157
3740
  throw new Error("stored client instance identity is invalid");
2158
3741
  }
2159
- chmodSync2(path, INSTANCE_FILE_MODE);
3742
+ chmodSync3(path, INSTANCE_FILE_MODE);
2160
3743
  if (metadata.size > MAX_STORED_BYTES) {
2161
3744
  throw new Error("stored client instance identity is invalid");
2162
3745
  }
2163
- const raw = readFileSync8(path, "utf8");
3746
+ const raw = readFileSync10(path, "utf8");
2164
3747
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
2165
3748
  if (raw !== value && raw !== `${value}
2166
3749
  ` || !isClientInstanceId(value)) {
@@ -2174,8 +3757,8 @@ function atomicWrite(path, value) {
2174
3757
  }
2175
3758
  async function getOrCreateClientInstanceId(options) {
2176
3759
  const configDir = options.configDir;
2177
- const path = join9(configDir, "client_instance_id");
2178
- const lockPath = join9(configDir, "client-instance.lock");
3760
+ const path = join13(configDir, "client_instance_id");
3761
+ const lockPath = join13(configDir, "client-instance.lock");
2179
3762
  ensurePrivateConfigDirectory(configDir);
2180
3763
  return withFileLock(
2181
3764
  lockPath,
@@ -2184,7 +3767,7 @@ async function getOrCreateClientInstanceId(options) {
2184
3767
  if (existing !== void 0) {
2185
3768
  return existing;
2186
3769
  }
2187
- const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
3770
+ const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
2188
3771
  "base64url"
2189
3772
  )}`;
2190
3773
  if (!isClientInstanceId(generated)) {
@@ -2219,63 +3802,18 @@ async function ingestUploaderHeaders() {
2219
3802
  return headers;
2220
3803
  }
2221
3804
 
2222
- // src/lib/terminal-safe.ts
2223
- function replaceIsolatedSurrogates(value) {
2224
- let out = "";
2225
- for (let index = 0; index < value.length; index += 1) {
2226
- const unit = value.charCodeAt(index);
2227
- if (unit >= 55296 && unit <= 56319) {
2228
- const next = value.charCodeAt(index + 1);
2229
- if (next >= 56320 && next <= 57343) {
2230
- out += value[index] + value[index + 1];
2231
- index += 1;
2232
- } else {
2233
- out += "\uFFFD";
2234
- }
2235
- } else if (unit >= 56320 && unit <= 57343) {
2236
- out += "\uFFFD";
2237
- } else {
2238
- out += value[index];
2239
- }
2240
- }
2241
- return out;
2242
- }
2243
- function isUnsafeTerminalCodePoint(point) {
2244
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
2245
- const bidiOrZeroWidth = point === 173 || // soft hyphen
2246
- point === 1564 || // Arabic letter mark
2247
- point === 6158 || // Mongolian vowel separator
2248
- point >= 8203 && point <= 8207 || // zero-width + directional marks
2249
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
2250
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
2251
- point >= 65529 && point <= 65531 || // interlinear annotation controls
2252
- point === 65279 || // zero-width no-break space / BOM
2253
- point >= 917504 && point <= 917631;
2254
- return c0OrC1 || bidiOrZeroWidth;
2255
- }
2256
- function terminalSafeText(value) {
2257
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
2258
- }
2259
- function terminalSafeLine(value) {
2260
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
2261
- }
2262
- function isTerminalSafeText(value) {
2263
- return terminalSafeText(value) === value;
2264
- }
2265
- var stripControlChars = terminalSafeText;
2266
-
2267
3805
  // src/client.ts
2268
3806
  var CONFIG_DIR_MODE = 448;
2269
3807
  var CREDENTIAL_FILE_MODE = 384;
2270
3808
  var REFRESH_THRESHOLD_MS = 6e4;
2271
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3809
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
2272
3810
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
2273
3811
  function authExpiredMessage() {
2274
3812
  return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
2275
3813
  }
2276
3814
  function readTrimmed2(path) {
2277
3815
  try {
2278
- const value = readFileSync9(path, "utf8").trim();
3816
+ const value = readFileSync11(path, "utf8").trim();
2279
3817
  return value || void 0;
2280
3818
  } catch {
2281
3819
  return void 0;
@@ -2285,23 +3823,23 @@ function getSiteUrl() {
2285
3823
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
2286
3824
  }
2287
3825
  function getSiteUrlForEnvironment(primApiUrl) {
2288
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3826
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
2289
3827
  }
2290
3828
  function expiresAtFor(token, expiresIn) {
2291
3829
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
2292
3830
  }
2293
3831
  function ensureConfigDirectory() {
2294
- const directory = dirname6(TOKEN_FILE_PATH);
2295
- mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
2296
- chmodSync3(directory, CONFIG_DIR_MODE);
3832
+ const directory = dirname9(TOKEN_FILE_PATH);
3833
+ mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
3834
+ chmodSync4(directory, CONFIG_DIR_MODE);
2297
3835
  }
2298
3836
  function atomicWrite2(path, content2) {
2299
3837
  ensureConfigDirectory();
2300
3838
  atomicWriteFile(path, content2, { mode: CREDENTIAL_FILE_MODE });
2301
3839
  }
2302
3840
  function removeCredentialFile(path) {
2303
- if (!existsSync5(path)) return false;
2304
- rmSync6(path, { force: true });
3841
+ if (!existsSync7(path)) return false;
3842
+ rmSync8(path, { force: true });
2305
3843
  return true;
2306
3844
  }
2307
3845
  function getTokenExpiresAt() {
@@ -2316,23 +3854,23 @@ function isTokenExpiringSoon(credential) {
2316
3854
  const expiresAt = getTokenExpiresAt();
2317
3855
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
2318
3856
  }
2319
- function refreshFingerprint(refreshToken2) {
2320
- return createHash5("sha256").update(refreshToken2).digest("hex");
3857
+ function refreshFingerprint(refreshToken3) {
3858
+ return createHash8("sha256").update(refreshToken3).digest("hex");
2321
3859
  }
2322
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3860
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
2323
3861
  return {
2324
3862
  version: 1,
2325
3863
  family: "legacy_broker",
2326
3864
  accessTokenHash: refreshFingerprint(accessToken),
2327
- refreshTokenHash: refreshFingerprint(refreshToken2)
3865
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2328
3866
  };
2329
3867
  }
2330
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3868
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
2331
3869
  const hashes = {
2332
3870
  accessTokenHash: refreshFingerprint(accessToken),
2333
- refreshTokenHash: refreshFingerprint(refreshToken2)
3871
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2334
3872
  };
2335
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3873
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
2336
3874
  }
2337
3875
  function writeCredentialMigrationSentinel() {
2338
3876
  atomicWrite2(
@@ -2344,11 +3882,11 @@ function writeCredentialMigrationSentinel() {
2344
3882
  `
2345
3883
  );
2346
3884
  }
2347
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
2348
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3885
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3886
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
2349
3887
  return { state: "invalid" };
2350
3888
  }
2351
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3889
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2352
3890
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
2353
3891
  return { state: "invalid" };
2354
3892
  }
@@ -2365,17 +3903,17 @@ function preserveMarkerlessLegacyGeneration() {
2365
3903
  const metadata = readStoredCredentialMetadata();
2366
3904
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
2367
3905
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
2368
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
2369
- if (!(accessToken && refreshToken2)) return;
2370
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3906
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3907
+ if (!(accessToken && refreshToken3)) return;
3908
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2371
3909
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2372
3910
  `);
2373
3911
  }
2374
3912
  function terminalFingerprint() {
2375
3913
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2376
3914
  }
2377
- function writeTerminalFingerprint(refreshToken2) {
2378
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3915
+ function writeTerminalFingerprint(refreshToken3) {
3916
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2379
3917
  `);
2380
3918
  }
2381
3919
  function clearTerminalFingerprint() {
@@ -2384,20 +3922,20 @@ function clearTerminalFingerprint() {
2384
3922
  function isSessionEnded() {
2385
3923
  if (hasMachineConfiguration()) return machineSessionEnded();
2386
3924
  if (resolveAuthCredential()?.source !== "token_file") return false;
2387
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3925
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2388
3926
  const ended = terminalFingerprint();
2389
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3927
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2390
3928
  }
2391
3929
  function withCredentialLock(operation, options = {}) {
2392
3930
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2393
3931
  }
2394
3932
  function commitCredentialsUnlocked(credentials) {
2395
3933
  const accessToken = credentials.accessToken.trim();
2396
- const refreshToken2 = credentials.refreshToken.trim();
2397
- if (!accessToken || !refreshToken2) {
3934
+ const refreshToken3 = credentials.refreshToken.trim();
3935
+ if (!accessToken || !refreshToken3) {
2398
3936
  throw new Error("OAuth credentials require both access and refresh tokens");
2399
3937
  }
2400
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3938
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2401
3939
  if (credentials.metadata !== void 0) {
2402
3940
  preserveMarkerlessLegacyGeneration();
2403
3941
  writeCredentialMigrationSentinel();
@@ -2405,10 +3943,10 @@ function commitCredentialsUnlocked(credentials) {
2405
3943
  `);
2406
3944
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2407
3945
  `);
2408
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3946
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2409
3947
  `);
2410
3948
  } else {
2411
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3949
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2412
3950
  `);
2413
3951
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2414
3952
  `);
@@ -2445,15 +3983,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2445
3983
  `
2446
3984
  );
2447
3985
  }
2448
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3986
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2449
3987
  const current = readStoredCredentialMetadata();
2450
3988
  if (expected.state === "legacy_broker") {
2451
3989
  if (current.state !== "legacy_broker") return false;
2452
3990
  if (!expected.metadata) return current.metadata === void 0;
2453
- 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;
3991
+ 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;
2454
3992
  }
2455
3993
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2456
- 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;
3994
+ 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;
2457
3995
  }
2458
3996
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2459
3997
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2622,7 +4160,7 @@ async function performTokenRefresh(options = {}) {
2622
4160
  );
2623
4161
  }
2624
4162
  var _refreshInFlight;
2625
- function refreshToken(options = {}) {
4163
+ function refreshToken2(options = {}) {
2626
4164
  if (hasMachineConfiguration())
2627
4165
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2628
4166
  if (_refreshInFlight) return _refreshInFlight;
@@ -2760,7 +4298,7 @@ async function machineClient(options = {}, management = false) {
2760
4298
  if (response.status === 401)
2761
4299
  throw new HttpError(
2762
4300
  401,
2763
- selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
4301
+ 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(
2764
4302
  "Machine access was rejected. Ask your administrator to check or rotate its credentials."
2765
4303
  )
2766
4304
  );
@@ -2781,7 +4319,7 @@ async function request2(method, path, body, options) {
2781
4319
  let refreshAttempted = false;
2782
4320
  if (credential && isTokenExpiringSoon(credential)) {
2783
4321
  refreshAttempted = true;
2784
- const token = await refreshToken({
4322
+ const token = await refreshToken2({
2785
4323
  signal: options?.signal,
2786
4324
  quiet: options?.quietRefresh
2787
4325
  });
@@ -2800,7 +4338,7 @@ async function request2(method, path, body, options) {
2800
4338
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2801
4339
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2802
4340
  refreshAttempted = true;
2803
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4341
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2804
4342
  }
2805
4343
  if (retryToken) {
2806
4344
  _cachedCredential = {
@@ -3005,132 +4543,12 @@ import { existsSync as existsSync10 } from "fs";
3005
4543
 
3006
4544
  // src/demo/diagnostics.ts
3007
4545
  import { existsSync as existsSync9 } from "fs";
3008
- import { join as join14 } from "path";
3009
-
3010
- // src/lib/hook-runtime.ts
3011
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
3012
- import {
3013
- constants as constants2,
3014
- accessSync,
3015
- chmodSync as chmodSync4,
3016
- copyFileSync,
3017
- existsSync as existsSync7,
3018
- lstatSync as lstatSync5,
3019
- mkdirSync as mkdirSync5,
3020
- mkdtempSync,
3021
- readFileSync as readFileSync10,
3022
- readdirSync as readdirSync2,
3023
- realpathSync,
3024
- renameSync as renameSync2,
3025
- rmSync as rmSync7,
3026
- statSync as statSync2,
3027
- utimesSync,
3028
- writeFileSync as writeFileSync4
3029
- } from "fs";
3030
- import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join12, resolve as resolve2 } from "path";
3031
-
3032
- // src/lib/git-hook-contract.ts
3033
- var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
3034
- # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
3035
- # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
3036
- # where prim is active (git config prim.active true) and never fails the hook.
3037
- case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
3038
- prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
3039
- [ -x "$prim_launcher" ] || exit 0
3040
- [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
3041
- prim_hook=\${1-}
3042
- if [ "$#" -gt 0 ]; then shift; fi
3043
- case "$prim_hook" in
3044
- pre-commit)
3045
- "$prim_launcher" prim-pre-commit "$@" || :
3046
- ;;
3047
- post-commit)
3048
- prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
3049
- case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
3050
- case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
3051
- prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
3052
- prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
3053
- (
3054
- trap '' HUP
3055
- trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
3056
- PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
3057
- ) </dev/null >/dev/null 2>&1 &
3058
- ;;
3059
- post-rewrite)
3060
- case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
3061
- prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
3062
- if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
3063
- rm -f "$prim_pairs"
3064
- exit 0
3065
- fi
3066
- prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
3067
- (
3068
- trap '' HUP
3069
- trap 'rm -f "$prim_pairs"' 0
3070
- PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
3071
- ) </dev/null >/dev/null 2>&1 &
3072
- ;;
3073
- esac
3074
- exit 0
3075
- `;
3076
-
3077
- // src/lib/native-keyring.ts
3078
- import { existsSync as existsSync6 } from "fs";
3079
- import { createRequire as createRequire2 } from "module";
3080
- import { dirname as dirname7, join as join11 } from "path";
3081
- import { fileURLToPath as fileURLToPath4 } from "url";
3082
- var require3 = createRequire2(import.meta.url);
3083
-
3084
- // src/lib/hook-runtime.ts
3085
- var RELEASE_PREFIX = "release-";
3086
- var MAX_MANIFEST_BYTES = 64 * 1024;
3087
- var RELEASE_GRACE_MS = 10 * 60 * 1e3;
3088
- var HOOK_RUNTIME_ENTRIES = {
3089
- // SessionStart self-healing resolves this exact CLI entry to run
3090
- // `daemon ensure`; it must travel with the immutable hook release.
3091
- prim: "dist/index.js",
3092
- "prim-hook": "dist/hooks/prim-hook.js",
3093
- "prim-pre-commit": "dist/hooks/pre-commit.js",
3094
- "prim-post-commit": "dist/hooks/post-commit.js",
3095
- "prim-post-rewrite": "dist/hooks/post-rewrite.js",
3096
- "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
3097
- "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
3098
- "prim-post-tool-use": "dist/hooks/post-tool-use.js",
3099
- "prim-session-start": "dist/hooks/session-start.js",
3100
- "prim-session-end": "dist/hooks/session-end.js",
3101
- "prim-daemon-server": "dist/daemon/server.js",
3102
- "prim-statusline": "dist/statusline-main.js"
3103
- };
3104
- var SOURCE_ENTRIES = Object.fromEntries(
3105
- Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
3106
- bin,
3107
- target.replace(/^dist\//u, "")
3108
- ])
3109
- );
3110
- var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
3111
- set -eu
3112
- case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
3113
- IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
3114
- case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
3115
- prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
3116
- case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
3117
- [ "\${#prim_release_id}" -eq 64 ] || exit 69
3118
- prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
3119
- case "\${1-}" in
3120
- ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
3121
- *) exit 64 ;;
3122
- esac
3123
- shift
3124
- IFS= read -r prim_node < "$prim_release/node" || exit 69
3125
- case "$prim_node" in /*) ;; *) exit 69 ;; esac
3126
- [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
3127
- exec "$prim_node" "$prim_entry" "$@"
3128
- `;
4546
+ import { join as join16 } from "path";
3129
4547
 
3130
4548
  // src/demo/state.ts
3131
- import { createHash as createHash7, randomUUID as randomUUID3 } from "crypto";
3132
- import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3133
- import { join as join13, resolve as resolve3 } from "path";
4549
+ import { createHash as createHash9, randomUUID as randomUUID3 } from "crypto";
4550
+ import { existsSync as existsSync8, lstatSync as lstatSync7, readFileSync as readFileSync12, readdirSync as readdirSync3 } from "fs";
4551
+ import { join as join15, resolve as resolve4 } from "path";
3134
4552
 
3135
4553
  // src/generated/cli-http-v1.validators.js
3136
4554
  var import_ucs2length = __toESM(require_ucs2length(), 1);
@@ -29816,15 +31234,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29816
31234
 
29817
31235
  // src/demo/state.ts
29818
31236
  var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
29819
- var demoDirectory = () => join13(primConfigDirectory(), "demo");
31237
+ var demoDirectory = () => join15(primConfigDirectory(), "demo");
29820
31238
  var runPath = (id2) => {
29821
31239
  if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
29822
- return join13(demoDirectory(), "runs", `${id2}.json`);
31240
+ return join15(demoDirectory(), "runs", `${id2}.json`);
29823
31241
  };
29824
31242
  function readDemoJson(path) {
29825
- const stat = lstatSync6(path);
31243
+ const stat = lstatSync7(path);
29826
31244
  if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
29827
- return JSON.parse(readFileSync11(path, "utf8"));
31245
+ return JSON.parse(readFileSync12(path, "utf8"));
29828
31246
  }
29829
31247
  function saveDemoJson(path, value) {
29830
31248
  atomicWriteFile(path, `${JSON.stringify(value)}
@@ -29861,11 +31279,11 @@ function demoCommand(run, action, choice, reason) {
29861
31279
  ].map(quote).join(" ");
29862
31280
  }
29863
31281
  function sessionKey(agent, session) {
29864
- return createHash7("sha256").update(`${agent}\0${session}`).digest("hex");
31282
+ return createHash9("sha256").update(`${agent}\0${session}`).digest("hex");
29865
31283
  }
29866
31284
  function exclusionPath(key) {
29867
31285
  if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
29868
- return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
31286
+ return join15(demoDirectory(), "excluded-sessions", `${key}.json`);
29869
31287
  }
29870
31288
  function sessionExcluded(agent, session) {
29871
31289
  if (typeof session !== "string" || !session) return false;
@@ -29904,7 +31322,7 @@ function demoArgv(command) {
29904
31322
  }
29905
31323
 
29906
31324
  // src/demo/diagnostics.ts
29907
- var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
31325
+ var observationPath = (id2) => join16(demoDirectory(), "observations", `${id2}.json`);
29908
31326
  function observeRun(id2, observation) {
29909
31327
  try {
29910
31328
  saveDemoJson(observationPath(id2), observation);
@@ -29998,25 +31416,25 @@ import {
29998
31416
  mkdirSync as mkdirSync6,
29999
31417
  openSync as openSync2,
30000
31418
  opendirSync,
30001
- readFileSync as readFileSync13,
31419
+ readFileSync as readFileSync14,
30002
31420
  readSync,
30003
31421
  readdirSync as readdirSync5
30004
31422
  } from "fs";
30005
- import { dirname as dirname10, join as join16 } from "path";
31423
+ import { dirname as dirname11, join as join18 } from "path";
30006
31424
 
30007
31425
  // src/drain-progress.ts
30008
31426
  import {
30009
31427
  chmodSync as chmodSync5,
30010
31428
  existsSync as existsSync11,
30011
- readFileSync as readFileSync12,
31429
+ readFileSync as readFileSync13,
30012
31430
  readdirSync as readdirSync4,
30013
- rmSync as rmSync8,
31431
+ rmSync as rmSync9,
30014
31432
  rmdirSync
30015
31433
  } from "fs";
30016
- import { basename as basename2, dirname as dirname9, join as join15 } from "path";
31434
+ import { basename as basename3, dirname as dirname10, join as join17 } from "path";
30017
31435
 
30018
31436
  // src/journal.ts
30019
- var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
31437
+ var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
30020
31438
  var UNBOUND_BUCKET = "_unbound";
30021
31439
  var JOURNAL_BASENAME = "journal.ndjson";
30022
31440
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -30028,14 +31446,14 @@ function envSlug(apiUrl) {
30028
31446
  return slug;
30029
31447
  }
30030
31448
  function currentEnvDir() {
30031
- return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
31449
+ return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
30032
31450
  }
30033
31451
  var DIR_MODE = 448;
30034
31452
  var FILE_MODE2 = 384;
30035
31453
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
30036
31454
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
30037
31455
  function appendMoveToPath(path, move) {
30038
- const dir = dirname10(path);
31456
+ const dir = dirname11(path);
30039
31457
  if (!existsSync12(dir)) {
30040
31458
  mkdirSync6(dir, { recursive: true, mode: DIR_MODE });
30041
31459
  }
@@ -30044,10 +31462,10 @@ function appendMoveToPath(path, move) {
30044
31462
  }
30045
31463
  function bucketDir(orgId) {
30046
31464
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
30047
- return join16(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
31465
+ return join18(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
30048
31466
  }
30049
31467
  function journalPath(orgId) {
30050
- return join16(bucketDir(orgId), JOURNAL_BASENAME);
31468
+ return join18(bucketDir(orgId), JOURNAL_BASENAME);
30051
31469
  }
30052
31470
  function appendMove(move, orgId) {
30053
31471
  const actor = machineCaptureActor();
@@ -30062,14 +31480,14 @@ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
30062
31480
  import { execFileSync as execFileSync4 } from "child_process";
30063
31481
  import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
30064
31482
  import { homedir as homedir2 } from "os";
30065
- import { join as join19 } from "path";
31483
+ import { join as join20 } from "path";
30066
31484
 
30067
31485
  // src/lib/cloud-prepared.ts
30068
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync14, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
30069
- import { join as join17 } from "path";
31486
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync15, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
31487
+ import { join as join19 } from "path";
30070
31488
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
30071
31489
  function cloudPreparedPath(env = process.env) {
30072
- return join17(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
31490
+ return join19(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30073
31491
  }
30074
31492
  function isPreparedCloudSession(env = process.env) {
30075
31493
  if (!isClaudeCloudSession(env)) return false;
@@ -30081,17 +31499,17 @@ function isPreparedCloudSession(env = process.env) {
30081
31499
  }
30082
31500
 
30083
31501
  // src/lib/demo-pause.ts
30084
- import { execFileSync as execFileSync2 } from "child_process";
31502
+ import { execFileSync as execFileSync3 } from "child_process";
30085
31503
  var DEMO_PAUSE_MS = 30 * 6e4;
30086
31504
  var PAUSE_KEY = "prim.demoPause";
30087
- var GIT_TIMEOUT_MS = 1e3;
30088
- function git(cwd, args) {
31505
+ var GIT_TIMEOUT_MS3 = 1e3;
31506
+ function git2(cwd, args) {
30089
31507
  try {
30090
- return execFileSync2("git", args, {
31508
+ return execFileSync3("git", args, {
30091
31509
  cwd,
30092
31510
  encoding: "utf-8",
30093
31511
  stdio: ["ignore", "pipe", "ignore"],
30094
- timeout: GIT_TIMEOUT_MS
31512
+ timeout: GIT_TIMEOUT_MS3
30095
31513
  });
30096
31514
  } catch {
30097
31515
  return void 0;
@@ -30099,10 +31517,10 @@ function git(cwd, args) {
30099
31517
  }
30100
31518
  function setLocal(cwd, key, value) {
30101
31519
  try {
30102
- execFileSync2(
31520
+ execFileSync3(
30103
31521
  "git",
30104
31522
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
30105
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
31523
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
30106
31524
  );
30107
31525
  } catch (error) {
30108
31526
  if (value !== null || error.status !== 5) throw error;
@@ -30116,7 +31534,7 @@ function parsePause(value) {
30116
31534
  function readCaptureConfig(cwd) {
30117
31535
  let active;
30118
31536
  let pause;
30119
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
31537
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
30120
31538
  for (const line of out.split("\n")) {
30121
31539
  const space3 = line.indexOf(" ");
30122
31540
  const key = line.slice(0, space3).toLowerCase();
@@ -30141,273 +31559,13 @@ function healDemoPause(cwd, pause, options = {}) {
30141
31559
  }
30142
31560
  }
30143
31561
 
30144
- // src/lib/git.ts
30145
- import { execFileSync as execFileSync3 } from "child_process";
30146
- import { createHash as createHash8 } from "crypto";
30147
- import { lstatSync as lstatSync7, readFileSync as readFileSync15, realpathSync as realpathSync2 } from "fs";
30148
- import { basename as basename3, dirname as dirname11, isAbsolute as isAbsolute4, join as join18, relative, resolve as resolve4, sep } from "path";
30149
- var GIT_TIMEOUT_MS2 = 1e3;
30150
- var MAX_SETTINGS_BYTES = 1024 * 1024;
30151
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
30152
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
30153
- function gitToplevel(cwd) {
30154
- try {
30155
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
30156
- cwd,
30157
- encoding: "utf-8",
30158
- stdio: ["ignore", "pipe", "ignore"],
30159
- timeout: GIT_TIMEOUT_MS2
30160
- }).trim();
30161
- } catch {
30162
- return null;
30163
- }
30164
- }
30165
- function gitValue(cwd, args) {
30166
- try {
30167
- const value = execFileSync3("git", args, {
30168
- cwd,
30169
- encoding: "utf-8",
30170
- stdio: ["ignore", "pipe", "ignore"],
30171
- timeout: GIT_TIMEOUT_MS2
30172
- }).trim();
30173
- return value || void 0;
30174
- } catch {
30175
- return void 0;
30176
- }
30177
- }
30178
- function currentBranch(cwd) {
30179
- return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
30180
- }
30181
- function parseGithubRepositoryName(path) {
30182
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
30183
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
30184
- return null;
30185
- }
30186
- return `${parts[0]}/${parts[1]}`;
30187
- }
30188
- function githubRepositoryFromRemote(remote) {
30189
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
30190
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
30191
- remote
30192
- );
30193
- const path = match?.[1] ?? match?.[2];
30194
- return path ? parseGithubRepositoryName(path) : null;
30195
- }
30196
- function checkoutSettingsText(repoRoot) {
30197
- const path = join18(repoRoot, ".claude", "settings.json");
30198
- try {
30199
- if (!lstatSync7(join18(repoRoot, ".claude")).isDirectory()) return null;
30200
- const stat = lstatSync7(path);
30201
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
30202
- return readFileSync15(path, "utf8");
30203
- } catch {
30204
- return null;
30205
- }
30206
- }
30207
- function checkoutDeclaration(repoRoot, name2) {
30208
- const text = checkoutSettingsText(repoRoot);
30209
- if (text === null) return null;
30210
- let parsed;
30211
- try {
30212
- parsed = JSON.parse(text);
30213
- } catch {
30214
- return null;
30215
- }
30216
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
30217
- const value = typeof env === "object" && env !== null ? env[name2] : void 0;
30218
- return typeof value === "string" ? value : null;
30219
- }
30220
- function declaredGithubRepository(repoRoot) {
30221
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
30222
- return value === null ? null : parseGithubRepositoryName(value.trim());
30223
- }
30224
- function githubRepositoryFullName(cwd) {
30225
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
30226
- if (remote) {
30227
- const fromOrigin = githubRepositoryFromRemote(remote);
30228
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
30229
- }
30230
- const root = gitToplevel(cwd);
30231
- return root ? declaredGithubRepository(root) : null;
30232
- }
30233
- function canonicalGitRoot(cwd) {
30234
- try {
30235
- const top = gitToplevel(cwd);
30236
- return top ? realpathSync2.native(top) : null;
30237
- } catch {
30238
- return null;
30239
- }
30240
- }
30241
- function relatedWorktreeTarget(path, cwd, origin) {
30242
- let parent = dirname11(resolve4(cwd, path));
30243
- while (true) {
30244
- try {
30245
- realpathSync2.native(parent);
30246
- break;
30247
- } catch {
30248
- const next = dirname11(parent);
30249
- if (next === parent) return null;
30250
- parent = next;
30251
- }
30252
- }
30253
- const target = resolveRepositoryContext(parent);
30254
- if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
30255
- const common = (root) => {
30256
- const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
30257
- try {
30258
- return value ? realpathSync2.native(resolve4(root, value)) : void 0;
30259
- } catch {
30260
- return void 0;
30261
- }
30262
- };
30263
- const originCommon = common(origin.repoRoot);
30264
- return originCommon && originCommon === common(target.repoRoot) ? target : null;
30265
- }
30266
- function normalizeOriginRemote(remote) {
30267
- const value = remote.trim();
30268
- if (!value) return void 0;
30269
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
30270
- if (scp?.host && scp.path) {
30271
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30272
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
30273
- }
30274
- try {
30275
- const url = new URL(value);
30276
- url.username = "";
30277
- url.password = "";
30278
- url.search = "";
30279
- url.hash = "";
30280
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30281
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
30282
- return void 0;
30283
- } catch {
30284
- return void 0;
30285
- }
30286
- }
30287
- function opaqueRepoKey(source, value) {
30288
- return `repo_v1_${createHash8("sha256").update(`${source}\0${value}`).digest("hex")}`;
30289
- }
30290
- function resolveRepositoryContext(cwd = process.cwd()) {
30291
- const top = gitToplevel(cwd);
30292
- if (!top) return null;
30293
- let repoRoot;
30294
- try {
30295
- repoRoot = realpathSync2.native(top);
30296
- } catch {
30297
- repoRoot = resolve4(top);
30298
- }
30299
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
30300
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
30301
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
30302
- if (normalizedOrigin) {
30303
- return {
30304
- repoRoot,
30305
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
30306
- identitySource: "origin",
30307
- repoFullName
30308
- };
30309
- }
30310
- if (repoFullName) {
30311
- return {
30312
- repoRoot,
30313
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
30314
- identitySource: "declared",
30315
- repoFullName
30316
- };
30317
- }
30318
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
30319
- if (roots && roots.length > 0) {
30320
- return {
30321
- repoRoot,
30322
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
30323
- identitySource: "root_commit",
30324
- repoFullName
30325
- };
30326
- }
30327
- return { repoRoot, repoFullName };
30328
- }
30329
- function nearestExistingAncestor(path) {
30330
- const suffix = [];
30331
- let cursor = path;
30332
- while (true) {
30333
- try {
30334
- lstatSync7(cursor);
30335
- break;
30336
- } catch (error) {
30337
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
30338
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
30339
- const parent = dirname11(cursor);
30340
- if (parent === cursor) return null;
30341
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
30342
- cursor = parent;
30343
- }
30344
- }
30345
- try {
30346
- return { real: realpathSync2.native(cursor), suffix };
30347
- } catch {
30348
- return null;
30349
- }
30350
- }
30351
- function canonicalRepositoryPathScoped(filePath, context, baseDir) {
30352
- if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
30353
- return { ok: false, reason: "invalid_path" };
30354
- }
30355
- const absolute = resolve4(baseDir, filePath);
30356
- const resolved = nearestExistingAncestor(absolute);
30357
- if (!resolved) return { ok: false, reason: "invalid_path" };
30358
- const target = resolve4(resolved.real, ...resolved.suffix);
30359
- const rel = relative(context.repoRoot, target);
30360
- if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
30361
- if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
30362
- return { ok: false, reason: "outside_repository" };
30363
- }
30364
- return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
30365
- }
30366
- function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
30367
- if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
30368
- return null;
30369
- const absolute = resolve4(cwd, filePath);
30370
- let target;
30371
- try {
30372
- const stat = lstatSync7(absolute);
30373
- if (!stat.isFile() || stat.isSymbolicLink()) return null;
30374
- target = realpathSync2.native(absolute);
30375
- } catch (error) {
30376
- if (!(error instanceof Error) || error.code !== "ENOENT") {
30377
- return null;
30378
- }
30379
- try {
30380
- const parent = realpathSync2.native(dirname11(absolute));
30381
- if (!lstatSync7(parent).isDirectory()) return null;
30382
- target = resolve4(parent, basename3(absolute));
30383
- } catch {
30384
- return null;
30385
- }
30386
- }
30387
- const rel = relative(repositoryRoot, target);
30388
- if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
30389
- return null;
30390
- }
30391
- return sep === "/" ? rel : rel.split(sep).join("/");
30392
- }
30393
- function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
30394
- if (typeof contextOrCwd === "string") {
30395
- return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
30396
- }
30397
- return canonicalRepositoryPathScoped(
30398
- filePath,
30399
- contextOrCwd,
30400
- baseDirOrRoot ?? contextOrCwd.repoRoot
30401
- );
30402
- }
30403
-
30404
31562
  // src/lib/activation.ts
30405
31563
  var PRIM_ACTIVE_KEY = "prim.active";
30406
31564
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
30407
31565
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
30408
31566
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
30409
31567
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
30410
- var GIT_TIMEOUT_MS3 = 1e3;
31568
+ var GIT_TIMEOUT_MS4 = 1e3;
30411
31569
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
30412
31570
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
30413
31571
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -30417,7 +31575,7 @@ function repoActiveFlag(cwd, strict = false) {
30417
31575
  cwd,
30418
31576
  encoding: "utf-8",
30419
31577
  stdio: ["ignore", "pipe", "ignore"],
30420
- timeout: GIT_TIMEOUT_MS3
31578
+ timeout: GIT_TIMEOUT_MS4
30421
31579
  }).trim();
30422
31580
  if (value === "true") return "true";
30423
31581
  if (value === "false") return "false";
@@ -30438,7 +31596,7 @@ function localGitConfigValue(cwd, key) {
30438
31596
  cwd,
30439
31597
  encoding: "utf-8",
30440
31598
  stdio: ["ignore", "pipe", "ignore"],
30441
- timeout: GIT_TIMEOUT_MS3
31599
+ timeout: GIT_TIMEOUT_MS4
30442
31600
  }).trim();
30443
31601
  return value || void 0;
30444
31602
  } catch {
@@ -30463,7 +31621,7 @@ function repositoryBindingState(cwd) {
30463
31621
  function projectPrimInstallAt(root) {
30464
31622
  if (root === null || root === homedir2()) return false;
30465
31623
  for (const rel of PROJECT_INSTALL_FILES) {
30466
- const path = join19(root, rel);
31624
+ const path = join20(root, rel);
30467
31625
  if (existsSync14(path)) {
30468
31626
  try {
30469
31627
  const content2 = readFileSync16(path, "utf-8");
@@ -30790,14 +31948,14 @@ function cachedCollectScopeAdmits(cwd, facts) {
30790
31948
  // src/lib/commit-heartbeat.ts
30791
31949
  import { execFileSync as execFileSync5 } from "child_process";
30792
31950
  import { mkdirSync as mkdirSync8, readFileSync as readFileSync17, readdirSync as readdirSync6, unlinkSync } from "fs";
30793
- import { dirname as dirname12, join as join20, resolve as resolve5 } from "path";
30794
- var GIT_TIMEOUT_MS4 = 1e3;
31951
+ import { dirname as dirname12, join as join21, resolve as resolve5 } from "path";
31952
+ var GIT_TIMEOUT_MS5 = 1e3;
30795
31953
  function gitPath(cwd, relative3) {
30796
31954
  const value = execFileSync5("git", ["rev-parse", "--git-path", relative3], {
30797
31955
  cwd,
30798
31956
  encoding: "utf8",
30799
31957
  stdio: ["ignore", "pipe", "ignore"],
30800
- timeout: GIT_TIMEOUT_MS4
31958
+ timeout: GIT_TIMEOUT_MS5
30801
31959
  }).replace(/\r?\n$/u, "");
30802
31960
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
30803
31961
  return resolve5(cwd, value);
@@ -30842,8 +32000,8 @@ import {
30842
32000
  unlinkSync as unlinkSync2,
30843
32001
  writeFileSync as writeFileSync6
30844
32002
  } from "fs";
30845
- import { dirname as dirname13, isAbsolute as isAbsolute5, join as join21, resolve as resolve6 } from "path";
30846
- var WORKSPACE_ID_RELATIVE_PATH = join21("prim", "workspace-id");
32003
+ import { dirname as dirname13, isAbsolute as isAbsolute5, join as join22, resolve as resolve6 } from "path";
32004
+ var WORKSPACE_ID_RELATIVE_PATH = join22("prim", "workspace-id");
30847
32005
  var MAX_ANCESTORS = 64;
30848
32006
  var MAX_GIT_FILE_BYTES = 4096;
30849
32007
  var MAX_ID_FILE_BYTES = 128;
@@ -30902,11 +32060,11 @@ function resolveWorkspaceIdPath(cwd) {
30902
32060
  function resolveFromFilesystem(cwd) {
30903
32061
  let current = resolve6(cwd);
30904
32062
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
30905
- const dotGit = join21(current, ".git");
32063
+ const dotGit = join22(current, ".git");
30906
32064
  try {
30907
32065
  const stat = lstatSync8(dotGit);
30908
32066
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
30909
- return join21(dotGit, WORKSPACE_ID_RELATIVE_PATH);
32067
+ return join22(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30910
32068
  }
30911
32069
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
30912
32070
  const contents = readFileSync18(dotGit, "utf8");
@@ -30914,7 +32072,7 @@ function resolveFromFilesystem(cwd) {
30914
32072
  if (match?.[1]) {
30915
32073
  const gitDirectory = isAbsolute5(match[1]) ? resolve6(match[1]) : resolve6(current, match[1]);
30916
32074
  if (isGitDirectory(gitDirectory)) {
30917
- return join21(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
32075
+ return join22(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30918
32076
  }
30919
32077
  }
30920
32078
  }
@@ -30933,7 +32091,7 @@ function resolveFromFilesystem(cwd) {
30933
32091
  }
30934
32092
  function isGitDirectory(path) {
30935
32093
  try {
30936
- return statSync3(join21(path, "HEAD")).isFile();
32094
+ return statSync3(join22(path, "HEAD")).isFile();
30937
32095
  } catch {
30938
32096
  return false;
30939
32097
  }
@@ -30971,7 +32129,7 @@ function inspectPath(path) {
30971
32129
  function createWorkspaceId(path) {
30972
32130
  const parent = dirname13(path);
30973
32131
  const workspaceId = randomUUID4();
30974
- const temporaryPath = join21(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
32132
+ const temporaryPath = join22(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30975
32133
  let temporaryCreated = false;
30976
32134
  let publishing = false;
30977
32135
  try {
@@ -31041,7 +32199,7 @@ function parseAgent(argv) {
31041
32199
  }
31042
32200
 
31043
32201
  // src/hooks/codex-context.ts
31044
- import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
32202
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
31045
32203
  import {
31046
32204
  chmodSync as chmodSync7,
31047
32205
  existsSync as existsSync15,
@@ -31049,31 +32207,31 @@ import {
31049
32207
  readFileSync as readFileSync19,
31050
32208
  readdirSync as readdirSync7,
31051
32209
  renameSync as renameSync3,
31052
- rmSync as rmSync10,
32210
+ rmSync as rmSync11,
31053
32211
  statSync as statSync4,
31054
32212
  unlinkSync as unlinkSync3,
31055
32213
  writeFileSync as writeFileSync7
31056
32214
  } from "fs";
31057
- import { join as join23 } from "path";
32215
+ import { join as join24 } from "path";
31058
32216
 
31059
32217
  // src/daemon/principal.ts
31060
- import { createHash as createHash9 } from "crypto";
32218
+ import { createHash as createHash10 } from "crypto";
31061
32219
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
31062
32220
  function boundedClaim(value) {
31063
32221
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
31064
32222
  }
31065
- function sha256(value) {
31066
- return createHash9("sha256").update(value).digest("hex");
32223
+ function sha2562(value) {
32224
+ return createHash10("sha256").update(value).digest("hex");
31067
32225
  }
31068
32226
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
31069
32227
  if (hasMachineConfiguration()) {
31070
32228
  const machine = machineContext();
31071
32229
  return machine ? {
31072
- principalId: sha256(
32230
+ principalId: sha2562(
31073
32231
  `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
31074
32232
  ),
31075
32233
  organizationId: machine.workosOrganizationId,
31076
- credentialFingerprint: sha256(machine.generation)
32234
+ credentialFingerprint: sha2562(machine.generation)
31077
32235
  } : void 0;
31078
32236
  }
31079
32237
  if (!token) return void 0;
@@ -31083,9 +32241,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
31083
32241
  if (!(subject && organizationId)) return void 0;
31084
32242
  const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
31085
32243
  return {
31086
- principalId: sha256(`${issuer}\0${subject}`),
32244
+ principalId: sha2562(`${issuer}\0${subject}`),
31087
32245
  organizationId,
31088
- credentialFingerprint: sha256(token)
32246
+ credentialFingerprint: sha2562(token)
31089
32247
  };
31090
32248
  }
31091
32249
  function daemonPrincipalsMatch(caller, daemon) {
@@ -31117,8 +32275,8 @@ function parseDaemonResponseEnvelope(value) {
31117
32275
 
31118
32276
  // src/daemon/client.ts
31119
32277
  import { createConnection } from "net";
31120
- import { join as join22 } from "path";
31121
- var SOCK_PATH = join22(primConfigDirectory(), "sock");
32278
+ import { join as join23 } from "path";
32279
+ var SOCK_PATH = join23(primConfigDirectory(), "sock");
31122
32280
  var DEFAULT_TIMEOUT_MS2 = 250;
31123
32281
  var nextRequestId = 1;
31124
32282
  function daemonRequest(method, params = {}, opts = {}) {
@@ -31367,10 +32525,10 @@ var STATE_VERSION = 1;
31367
32525
  var DRAFT_STATE_VERSION = 2;
31368
32526
  var NO_CURSOR = -1;
31369
32527
  function stateRoot(namespace) {
31370
- return join23(primConfigDirectory(), namespace, "decision-digests");
32528
+ return join24(primConfigDirectory(), namespace, "decision-digests");
31371
32529
  }
31372
32530
  function draftStateRoot(namespace) {
31373
- return join23(primConfigDirectory(), namespace, "decision-draft-deliveries");
32531
+ return join24(primConfigDirectory(), namespace, "decision-draft-deliveries");
31374
32532
  }
31375
32533
  function workspaceFor(cwd) {
31376
32534
  try {
@@ -31381,13 +32539,13 @@ function workspaceFor(cwd) {
31381
32539
  }
31382
32540
  function statePath(args) {
31383
32541
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
31384
- const key = createHash10("sha256").update(identity).digest("hex");
31385
- return join23(stateRoot(args.namespace), `${key}.json`);
32542
+ const key = createHash11("sha256").update(identity).digest("hex");
32543
+ return join24(stateRoot(args.namespace), `${key}.json`);
31386
32544
  }
31387
32545
  function draftStatePath(args) {
31388
32546
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
31389
- const key = createHash10("sha256").update(identity).digest("hex");
31390
- return join23(draftStateRoot(args.namespace), `${key}.json`);
32547
+ const key = createHash11("sha256").update(identity).digest("hex");
32548
+ return join24(draftStateRoot(args.namespace), `${key}.json`);
31391
32549
  }
31392
32550
  function parseState(value) {
31393
32551
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -31425,7 +32583,7 @@ function parseDraftState(value) {
31425
32583
  updatedAt: record.updatedAt
31426
32584
  };
31427
32585
  }
31428
- function readState(path) {
32586
+ function readState2(path) {
31429
32587
  if (!existsSync15(path)) return void 0;
31430
32588
  try {
31431
32589
  return parseState(JSON.parse(readFileSync19(path, "utf8")));
@@ -31444,7 +32602,7 @@ function readDraftState(path) {
31444
32602
  function writeStateFile(path, directory, state) {
31445
32603
  mkdirSync10(directory, { recursive: true, mode: 448 });
31446
32604
  chmodSync7(directory, 448);
31447
- const temporary = join23(
32605
+ const temporary = join24(
31448
32606
  directory,
31449
32607
  `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
31450
32608
  );
@@ -31475,7 +32633,7 @@ function cleanupStateFiles(directory, now) {
31475
32633
  const files = [];
31476
32634
  const residue = [];
31477
32635
  for (const name2 of names) {
31478
- const path = join23(directory, name2);
32636
+ const path = join24(directory, name2);
31479
32637
  try {
31480
32638
  const mtimeMs = statSync4(path).mtimeMs;
31481
32639
  if (name2.endsWith(".json")) {
@@ -31497,7 +32655,7 @@ function cleanupStateFiles(directory, now) {
31497
32655
  for (const path of residue) {
31498
32656
  try {
31499
32657
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
31500
- rmSync10(path, { recursive: true, force: true });
32658
+ rmSync11(path, { recursive: true, force: true });
31501
32659
  }
31502
32660
  } catch {
31503
32661
  }
@@ -31583,7 +32741,7 @@ async function commitState(path, args, namespace) {
31583
32741
  await withFileLock(
31584
32742
  `${path}.lock`,
31585
32743
  () => {
31586
- const latest = readState(path);
32744
+ const latest = readState2(path);
31587
32745
  writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
31588
32746
  cleanupStateFiles(stateRoot(namespace), args.now);
31589
32747
  },
@@ -31630,7 +32788,7 @@ async function prepareCodexContext(options) {
31630
32788
  const siteUrl = getSiteUrl();
31631
32789
  const workspace = workspaceFor(options.cwd);
31632
32790
  const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
31633
- const previous = readState(path);
32791
+ const previous = readState2(path);
31634
32792
  const principal = resolveDaemonPrincipal();
31635
32793
  const privatePath = principal ? draftStatePath({
31636
32794
  cwd: options.cwd,
@@ -31815,7 +32973,7 @@ async function processCodexMessageContext(envelope, deps = defaultDeps) {
31815
32973
  // src/commands/cursor-install.ts
31816
32974
  import { existsSync as existsSync17, readFileSync as readFileSync21 } from "fs";
31817
32975
  import { homedir as homedir4 } from "os";
31818
- import { isAbsolute as isAbsolute6, join as join25 } from "path";
32976
+ import { isAbsolute as isAbsolute6, join as join26 } from "path";
31819
32977
 
31820
32978
  // src/lib/preflight-host.ts
31821
32979
  import { execFileSync as execFileSync7 } from "child_process";
@@ -31823,7 +32981,7 @@ import { execFileSync as execFileSync7 } from "child_process";
31823
32981
  // src/commands/claude-install.ts
31824
32982
  import { existsSync as existsSync16, lstatSync as lstatSync9, readFileSync as readFileSync20 } from "fs";
31825
32983
  import { homedir as homedir3 } from "os";
31826
- import { join as join24 } from "path";
32984
+ import { join as join25 } from "path";
31827
32985
  var CAPTURE_BIN = "prim-hook";
31828
32986
  var GATE_BIN = "prim-pre-tool-use";
31829
32987
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -31832,7 +32990,7 @@ var SESSION_END_BIN = "prim-session-end";
31832
32990
  var STATUSLINE_BIN = "prim-statusline";
31833
32991
  var STATUSLINE_ARGS = "";
31834
32992
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
31835
- var USER_SCOPE_PATH = join24(homedir3(), ".claude", "settings.json");
32993
+ var USER_SCOPE_PATH = join25(homedir3(), ".claude", "settings.json");
31836
32994
  function projectRoot() {
31837
32995
  return gitToplevel() ?? process.cwd();
31838
32996
  }
@@ -31912,11 +33070,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
31912
33070
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
31913
33071
  if (explicit && isAbsolute6(explicit)) return explicit;
31914
33072
  const xdg = env.XDG_CONFIG_HOME?.trim();
31915
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join25(xdg, "cursor");
31916
- return join25(home, ".cursor");
33073
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join26(xdg, "cursor");
33074
+ return join26(home, ".cursor");
31917
33075
  }
31918
33076
  function cursorHooksPath(scope, root = projectRoot()) {
31919
- return scope === "user" ? join25(cursorConfigDirectory(), "hooks.json") : join25(root, ".cursor", "hooks.json");
33077
+ return scope === "user" ? join26(cursorConfigDirectory(), "hooks.json") : join26(root, ".cursor", "hooks.json");
31920
33078
  }
31921
33079
  function plainObject(value) {
31922
33080
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -32198,7 +33356,7 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
32198
33356
 
32199
33357
  // src/hooks/redact.ts
32200
33358
  import { existsSync as existsSync18, readFileSync as readFileSync22, statSync as statSync5 } from "fs";
32201
- import { join as join26 } from "path";
33359
+ import { join as join27 } from "path";
32202
33360
  import { Worker } from "worker_threads";
32203
33361
  var USER_HOME_RULES = [
32204
33362
  {
@@ -32279,7 +33437,7 @@ function normalizedWorkspaceFlags(value) {
32279
33437
  return [...new Set(`g${requested}`)].sort().join("");
32280
33438
  }
32281
33439
  function loadWorkspaceRules(cwd) {
32282
- const path = join26(cwd, WORKSPACE_FILE2);
33440
+ const path = join27(cwd, WORKSPACE_FILE2);
32283
33441
  if (!existsSync18(path)) return [];
32284
33442
  let cfg;
32285
33443
  try {
@@ -38643,7 +39801,7 @@ var TokenGroup = class {
38643
39801
  }
38644
39802
  token(input, stack) {
38645
39803
  let { parser: parser3 } = stack.p;
38646
- readToken(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
39804
+ readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
38647
39805
  }
38648
39806
  };
38649
39807
  TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
@@ -38657,7 +39815,7 @@ var LocalTokenGroup = class {
38657
39815
  let start = input.pos, skipped = 0;
38658
39816
  for (; ; ) {
38659
39817
  let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
38660
- readToken(this.data, input, stack, 0, this.data, this.precTable);
39818
+ readToken2(this.data, input, stack, 0, this.data, this.precTable);
38661
39819
  if (input.token.value > -1)
38662
39820
  break;
38663
39821
  if (this.elseToken == null)
@@ -38690,7 +39848,7 @@ var ExternalTokenizer = class {
38690
39848
  this.extend = !!options.extend;
38691
39849
  }
38692
39850
  };
38693
- function readToken(data, input, stack, group, precTable, precOffset) {
39851
+ function readToken2(data, input, stack, group, precTable, precOffset) {
38694
39852
  let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
38695
39853
  scan: for (; ; ) {
38696
39854
  if ((groupMask & data[state]) == 0)
@@ -40503,7 +41661,7 @@ var newline2 = 10;
40503
41661
  var carriageReturn = 13;
40504
41662
  var space2 = 32;
40505
41663
  var tab = 9;
40506
- var hash2 = 35;
41664
+ var hash3 = 35;
40507
41665
  var parenOpen = 40;
40508
41666
  var dot2 = 46;
40509
41667
  var braceOpen = 123;
@@ -40556,7 +41714,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
40556
41714
  input.advance();
40557
41715
  spaces2++;
40558
41716
  }
40559
- if (input.next == newline2 || input.next == carriageReturn || input.next == hash2)
41717
+ if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
40560
41718
  input.acceptToken(blankLineStart, -spaces2);
40561
41719
  } else if (isLineBreak(input.next)) {
40562
41720
  input.acceptToken(newline$1, 1);
@@ -40575,7 +41733,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
40575
41733
  input.advance();
40576
41734
  chars++;
40577
41735
  }
40578
- if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash2) {
41736
+ if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
40579
41737
  if (depth < context.indent) input.acceptToken(dedent, -chars);
40580
41738
  else input.acceptToken(indent);
40581
41739
  }
@@ -40649,7 +41807,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
40649
41807
  for (let off = 0; ; off++) {
40650
41808
  let next = input.peek(off);
40651
41809
  if (next == space2 || next == tab) continue;
40652
- if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash2)
41810
+ if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
40653
41811
  input.acceptToken(printKeyword);
40654
41812
  return;
40655
41813
  }
@@ -41860,7 +43018,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
41860
43018
  }
41861
43019
 
41862
43020
  // src/hooks/normalize.ts
41863
- import { createHash as createHash11 } from "crypto";
43021
+ import { createHash as createHash12 } from "crypto";
41864
43022
  import { realpathSync as realpathSync4 } from "fs";
41865
43023
  import { isAbsolute as isAbsolute8, resolve as resolve8 } from "path";
41866
43024
  var HERMES_EVENT_MAP = {
@@ -41905,7 +43063,7 @@ function requiredId(value, field) {
41905
43063
  }
41906
43064
  function cursorToolUseId(value) {
41907
43065
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
41908
- return `cursor:tool:v1:${createHash11("sha256").update(value).digest("hex")}`;
43066
+ return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
41909
43067
  }
41910
43068
  function workspaceCandidates(value) {
41911
43069
  if (!Array.isArray(value)) return [];
@@ -42002,7 +43160,7 @@ function normalizeEnvelope(parsed, agent) {
42002
43160
  ]);
42003
43161
  return {
42004
43162
  ...parsed,
42005
- tool_use_id: `codex:fallback:v1:${createHash11("sha256").update(stableToolIdentity).digest("hex")}`
43163
+ tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
42006
43164
  };
42007
43165
  }
42008
43166
  return parsed;
@@ -42018,7 +43176,7 @@ function normalizeEnvelope(parsed, agent) {
42018
43176
  }
42019
43177
 
42020
43178
  // src/hooks/prim-hook-core.ts
42021
- import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
43179
+ import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
42022
43180
  import { platform } from "os";
42023
43181
 
42024
43182
  // src/protocol/move.ts
@@ -42092,9 +43250,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
42092
43250
  const toolOutcome = toolOutcomeFor(parsed, agent);
42093
43251
  let moveId;
42094
43252
  if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
42095
- moveId = `posttool:v1:${createHash12("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
43253
+ moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
42096
43254
  } else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
42097
- moveId = `posttool:fallback:v1:${createHash12("sha256").update(
43255
+ moveId = `posttool:fallback:v1:${createHash13("sha256").update(
42098
43256
  JSON.stringify([
42099
43257
  agent,
42100
43258
  sessionId,
@@ -42145,14 +43303,14 @@ function emitOutput(output, acknowledge) {
42145
43303
  }
42146
43304
  function resolveCliVersion() {
42147
43305
  try {
42148
- const pkg = JSON.parse(readFileSync23(join27(here, "..", "..", "package.json"), "utf-8"));
43306
+ const pkg = JSON.parse(readFileSync23(join28(here, "..", "..", "package.json"), "utf-8"));
42149
43307
  return pkg.version ?? "unknown";
42150
43308
  } catch {
42151
43309
  return "unknown";
42152
43310
  }
42153
43311
  }
42154
43312
  function spawnBackgroundFlush() {
42155
- const entry = join27(here, "..", "index.js");
43313
+ const entry = join28(here, "..", "index.js");
42156
43314
  spawn2(process.execPath, [entry, "moves", "flush"], {
42157
43315
  detached: true,
42158
43316
  stdio: "ignore",