@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
@@ -54,11 +54,11 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/lib/machine-broker.ts
56
56
  import { spawn } from "child_process";
57
- import { createHash as createHash3, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
58
- import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
57
+ import { createHash as createHash6, createHmac, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
58
+ import { lstatSync as lstatSync5, readFileSync as readFileSync7, rmSync as rmSync7 } from "fs";
59
59
  import { createServer } from "http";
60
- import { basename, join as join6 } from "path";
61
- import { fileURLToPath as fileURLToPath3 } from "url";
60
+ import { basename as basename2, join as join10 } from "path";
61
+ import { fileURLToPath as fileURLToPath4 } from "url";
62
62
 
63
63
  // src/lib/atomic-file.ts
64
64
  import { randomUUID } from "crypto";
@@ -143,8 +143,48 @@ function atomicWriteFile(target, content, options = {}) {
143
143
  import { existsSync, readFileSync } from "fs";
144
144
  import { dirname as dirname2, isAbsolute, join } from "path";
145
145
  import { fileURLToPath } from "url";
146
+
147
+ // src/lib/semver.ts
148
+ function parseSemver(value) {
149
+ if (typeof value !== "string" || value.length > 256) return;
150
+ 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(
151
+ value
152
+ );
153
+ if (!match) return;
154
+ const prerelease = match[4]?.split(".") ?? [];
155
+ if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
156
+ return;
157
+ }
158
+ return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
159
+ }
160
+ function compareSemver(left, right) {
161
+ const a = parseSemver(left);
162
+ const b = parseSemver(right);
163
+ if (!a || !b) return;
164
+ for (let i = 0; i < a.core.length; i += 1) {
165
+ if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
166
+ }
167
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) {
168
+ return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
169
+ }
170
+ for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
171
+ const x = a.prerelease[i];
172
+ const y = b.prerelease[i];
173
+ if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
174
+ if (x === y) continue;
175
+ const xNumeric = /^\d+$/u.test(x);
176
+ const yNumeric = /^\d+$/u.test(y);
177
+ if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
178
+ if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
179
+ return x < y ? -1 : 1;
180
+ }
181
+ return 0;
182
+ }
183
+
184
+ // src/lib/bin-path.ts
146
185
  var PKG_NAME = "@primitive.ai/prim";
147
186
  var ROOT_WALK_LIMIT = 6;
187
+ var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
148
188
  var resolvedRoot;
149
189
  function locateRoot() {
150
190
  if (resolvedRoot !== void 0) {
@@ -285,14 +325,14 @@ function throwIfAborted(signal) {
285
325
  }
286
326
  async function defaultSleep(ms, signal) {
287
327
  if (!signal) {
288
- await new Promise((resolve3) => setTimeout(resolve3, ms));
328
+ await new Promise((resolve4) => setTimeout(resolve4, ms));
289
329
  return;
290
330
  }
291
331
  throwIfAborted(signal);
292
- await new Promise((resolve3, reject) => {
332
+ await new Promise((resolve4, reject) => {
293
333
  const timer = setTimeout(() => {
294
334
  signal.removeEventListener("abort", onAbort);
295
- resolve3();
335
+ resolve4();
296
336
  }, ms);
297
337
  const onAbort = () => {
298
338
  clearTimeout(timer);
@@ -341,7 +381,7 @@ function loopbackFetch(url, init = {}) {
341
381
  const target = new URL(url);
342
382
  if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
343
383
  return Promise.reject(new Error(`not a loopback URL: ${url}`));
344
- return new Promise((resolve3, reject) => {
384
+ return new Promise((resolve4, reject) => {
345
385
  const outgoing = request(
346
386
  target,
347
387
  { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
@@ -352,7 +392,7 @@ function loopbackFetch(url, init = {}) {
352
392
  if (typeof value === "string") headers.set(name, value);
353
393
  const status = incoming.statusCode ?? 502;
354
394
  const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
355
- resolve3(new Response(body, { status, headers }));
395
+ resolve4(new Response(body, { status, headers }));
356
396
  } catch (error) {
357
397
  incoming.destroy();
358
398
  reject(error);
@@ -365,21 +405,338 @@ function loopbackFetch(url, init = {}) {
365
405
  }
366
406
 
367
407
  // src/lib/machine-credentials.ts
368
- import { execFileSync } from "child_process";
369
- import { createHash as createHash2, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
408
+ import { execFileSync as execFileSync2 } from "child_process";
409
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
370
410
  import {
371
- chmodSync,
372
- existsSync as existsSync3,
411
+ chmodSync as chmodSync2,
412
+ existsSync as existsSync5,
373
413
  linkSync,
374
- lstatSync as lstatSync2,
414
+ lstatSync as lstatSync4,
415
+ mkdirSync as mkdirSync4,
416
+ readFileSync as readFileSync6,
417
+ rmSync as rmSync6,
418
+ writeFileSync as writeFileSync4
419
+ } from "fs";
420
+ import { createRequire as createRequire2 } from "module";
421
+ import { dirname as dirname7, join as join9 } from "path";
422
+ import { fileURLToPath as fileURLToPath3 } from "url";
423
+
424
+ // src/lib/hook-runtime.ts
425
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
426
+ import {
427
+ constants as constants2,
428
+ accessSync,
429
+ chmodSync,
430
+ copyFileSync,
431
+ existsSync as existsSync4,
432
+ lstatSync,
375
433
  mkdirSync as mkdirSync3,
376
- readFileSync as readFileSync4,
377
- rmSync as rmSync4,
434
+ mkdtempSync,
435
+ readFileSync as readFileSync3,
436
+ readdirSync,
437
+ realpathSync,
438
+ renameSync as renameSync2,
439
+ rmSync as rmSync3,
440
+ statSync as statSync2,
441
+ utimesSync,
378
442
  writeFileSync as writeFileSync3
379
443
  } from "fs";
444
+ import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
445
+
446
+ // src/lib/git-hook-contract.ts
447
+ var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
448
+ var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
449
+ # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
450
+ # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
451
+ # where prim is active (git config prim.active true) and never fails the hook.
452
+ case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
453
+ prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
454
+ [ -x "$prim_launcher" ] || exit 0
455
+ [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
456
+ prim_hook=\${1-}
457
+ if [ "$#" -gt 0 ]; then shift; fi
458
+ case "$prim_hook" in
459
+ pre-commit)
460
+ "$prim_launcher" prim-pre-commit "$@" || :
461
+ ;;
462
+ post-commit)
463
+ prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
464
+ case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
465
+ case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
466
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
467
+ prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
468
+ (
469
+ trap '' HUP
470
+ trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
471
+ PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
472
+ ) </dev/null >/dev/null 2>&1 &
473
+ ;;
474
+ post-rewrite)
475
+ case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
476
+ prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
477
+ if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
478
+ rm -f "$prim_pairs"
479
+ exit 0
480
+ fi
481
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
482
+ (
483
+ trap '' HUP
484
+ trap 'rm -f "$prim_pairs"' 0
485
+ PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
486
+ ) </dev/null >/dev/null 2>&1 &
487
+ ;;
488
+ esac
489
+ exit 0
490
+ `;
491
+
492
+ // src/lib/native-keyring.ts
493
+ import { existsSync as existsSync3 } from "fs";
380
494
  import { createRequire } from "module";
381
- import { dirname as dirname4, join as join5 } from "path";
495
+ import { dirname as dirname4, join as join3 } from "path";
382
496
  import { fileURLToPath as fileURLToPath2 } from "url";
497
+ var require2 = createRequire(import.meta.url);
498
+ var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
499
+
500
+ // src/lib/paths.ts
501
+ import { homedir } from "os";
502
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
503
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
504
+ function absolutePath(value, variable) {
505
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
506
+ throw new Error(`${variable} contains unsafe characters`);
507
+ }
508
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
509
+ const normalized = normalize(value);
510
+ return normalized === value ? value : void 0;
511
+ }
512
+ function resolvePrimConfigDirectory(options = {}) {
513
+ const env = options.env ?? process.env;
514
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
515
+ if (explicit) return { path: explicit, source: "explicit" };
516
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
517
+ if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
518
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
519
+ if (!home) {
520
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
521
+ }
522
+ return { path: join4(home, ".config", "prim"), source: "default" };
523
+ }
524
+ function primConfigDirectory(options = {}) {
525
+ return resolvePrimConfigDirectory(options).path;
526
+ }
527
+
528
+ // src/lib/hook-runtime.ts
529
+ var HOOK_RUNTIME_SCHEMA_VERSION = 1;
530
+ var RELEASE_PREFIX = "release-";
531
+ var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
532
+ var MAX_MANIFEST_BYTES = 64 * 1024;
533
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
534
+ var HOOK_RUNTIME_ENTRIES = {
535
+ // SessionStart self-healing resolves this exact CLI entry to run
536
+ // `daemon ensure`; it must travel with the immutable hook release.
537
+ prim: "dist/index.js",
538
+ "prim-hook": "dist/hooks/prim-hook.js",
539
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
540
+ "prim-post-commit": "dist/hooks/post-commit.js",
541
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
542
+ "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
543
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
544
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
545
+ "prim-session-start": "dist/hooks/session-start.js",
546
+ "prim-session-end": "dist/hooks/session-end.js",
547
+ "prim-daemon-server": "dist/daemon/server.js",
548
+ "prim-statusline": "dist/statusline-main.js"
549
+ };
550
+ var SOURCE_ENTRIES = Object.fromEntries(
551
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
552
+ bin,
553
+ target.replace(/^dist\//u, "")
554
+ ])
555
+ );
556
+ function hookRuntimePaths(options = {}) {
557
+ const env = options.env ?? process.env;
558
+ const configDir = primConfigDirectory({
559
+ ...options,
560
+ env,
561
+ homeDir: options.homeDir ?? env.HOME ?? ""
562
+ });
563
+ const runtimeDir = join5(configDir, "hook-runtime");
564
+ return {
565
+ configDir,
566
+ launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
567
+ gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
568
+ runtimeDir,
569
+ releasesDir: join5(runtimeDir, "releases"),
570
+ current: join5(runtimeDir, "current"),
571
+ selectionLock: join5(runtimeDir, "selection.lock")
572
+ };
573
+ }
574
+ function sha256(path) {
575
+ return createHash("sha256").update(readFileSync3(path)).digest("hex");
576
+ }
577
+ function exactManifest(manifest) {
578
+ return `${JSON.stringify(manifest, null, 2)}
579
+ `;
580
+ }
581
+ function exactKeys(value, expected) {
582
+ const actual = Object.keys(value).sort();
583
+ const wanted = [...expected].sort();
584
+ return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
585
+ }
586
+ function releaseId(manifest) {
587
+ return createHash("sha256").update(exactManifest(manifest)).digest("hex");
588
+ }
589
+ function runtimePackageJson(manifest) {
590
+ return `${JSON.stringify(
591
+ {
592
+ name: "@primitive.ai/prim",
593
+ version: manifest.version,
594
+ type: "module",
595
+ bin: HOOK_RUNTIME_ENTRIES
596
+ },
597
+ null,
598
+ 2
599
+ )}
600
+ `;
601
+ }
602
+ function validateRelease(releaseDir, manifest) {
603
+ try {
604
+ if (!directReleaseLayout(releaseDir, manifest)) return false;
605
+ if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
606
+ return false;
607
+ }
608
+ if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
609
+ return false;
610
+ }
611
+ if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
612
+ `) {
613
+ return false;
614
+ }
615
+ for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
616
+ const target = join5(releaseDir, relativePath);
617
+ if (sha256(target) !== manifest.files[bin]) return false;
618
+ }
619
+ for (const [path, digest] of Object.entries(manifest.native ?? {})) {
620
+ if (sha256(join5(releaseDir, path)) !== digest) return false;
621
+ }
622
+ return true;
623
+ } catch {
624
+ return false;
625
+ }
626
+ }
627
+ function directReleaseLayout(releaseDir, manifest) {
628
+ try {
629
+ const directories = /* @__PURE__ */ new Set([releaseDir]);
630
+ for (const relativePath of [
631
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
632
+ ...Object.keys(manifest.native ?? {})
633
+ ]) {
634
+ for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
635
+ directories.add(join5(releaseDir, directory));
636
+ }
637
+ }
638
+ if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
639
+ const files = [
640
+ "manifest.json",
641
+ "package.json",
642
+ "node",
643
+ ...Object.values(HOOK_RUNTIME_ENTRIES),
644
+ ...Object.keys(manifest.native ?? {})
645
+ ];
646
+ const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
647
+ if (![...directories].every(
648
+ (directory) => readdirSync(directory).every((name) => owned.has(join5(directory, name)))
649
+ ))
650
+ return false;
651
+ return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
652
+ } catch {
653
+ return false;
654
+ }
655
+ }
656
+ function readReleaseManifest(releaseDir, releaseName) {
657
+ try {
658
+ const manifestPath = join5(releaseDir, "manifest.json");
659
+ const manifestStat = statSync2(manifestPath);
660
+ if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
661
+ const raw = readFileSync3(manifestPath, "utf8");
662
+ const parsed = JSON.parse(raw);
663
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
664
+ if (!exactKeys(parsed, [
665
+ "schemaVersion",
666
+ "version",
667
+ "nodePath",
668
+ "files",
669
+ ..."native" in parsed ? ["native"] : []
670
+ ]))
671
+ return null;
672
+ const candidate = parsed;
673
+ 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(
674
+ (digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
675
+ )) {
676
+ return null;
677
+ }
678
+ 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(
679
+ (digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
680
+ )))
681
+ return null;
682
+ const manifest = candidate;
683
+ if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
684
+ return null;
685
+ }
686
+ return manifest;
687
+ } catch {
688
+ return null;
689
+ }
690
+ }
691
+ function readSelectedRelease(paths) {
692
+ let raw;
693
+ try {
694
+ raw = readFileSync3(paths.current, "utf8");
695
+ } catch (error) {
696
+ if (error.code === "ENOENT") return null;
697
+ throw error;
698
+ }
699
+ const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
700
+ if (`${name}
701
+ ` !== raw || !RELEASE_NAME_RE.test(name)) {
702
+ throw new Error("cannot stage hook runtime: selected release is malformed");
703
+ }
704
+ const dir = join5(paths.releasesDir, name);
705
+ const manifest = readReleaseManifest(dir, name);
706
+ if (!manifest) {
707
+ throw new Error("cannot stage hook runtime: immutable release is corrupt");
708
+ }
709
+ return { name, dir, manifest };
710
+ }
711
+ function selectedHookRuntimeKeyringLoader(options = {}) {
712
+ try {
713
+ const selected = readSelectedRelease(hookRuntimePaths(options));
714
+ if (!selected?.manifest.native) return void 0;
715
+ const loader = join5(selected.dir, "native", "keyring.cjs");
716
+ return existsSync4(loader) ? loader : void 0;
717
+ } catch {
718
+ return void 0;
719
+ }
720
+ }
721
+ var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
722
+ set -eu
723
+ case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
724
+ IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
725
+ case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
726
+ prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
727
+ case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
728
+ [ "\${#prim_release_id}" -eq 64 ] || exit 69
729
+ prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
730
+ case "\${1-}" in
731
+ ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
732
+ *) exit 64 ;;
733
+ esac
734
+ shift
735
+ IFS= read -r prim_node < "$prim_release/node" || exit 69
736
+ case "$prim_node" in /*) ;; *) exit 69 ;; esac
737
+ [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
738
+ exec "$prim_node" "$prim_entry" "$@"
739
+ `;
383
740
 
384
741
  // src/lib/cloud-env.ts
385
742
  function isClaudeCloudSession(env = process.env) {
@@ -387,6 +744,8 @@ function isClaudeCloudSession(env = process.env) {
387
744
  }
388
745
  var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
389
746
  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';
747
+ 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}.`;
748
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
390
749
  function cloudSetupPointer(message, env = process.env) {
391
750
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
392
751
  }
@@ -528,10 +887,10 @@ function parseWorkosConnectTokens(value, options = {}) {
528
887
  "access_token",
529
888
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
530
889
  );
531
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
890
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
532
891
  return {
533
892
  accessToken,
534
- refreshToken: refreshToken2,
893
+ refreshToken: refreshToken3,
535
894
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
536
895
  };
537
896
  }
@@ -783,23 +1142,23 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
783
1142
  }
784
1143
 
785
1144
  // src/lib/machine-retry.ts
786
- import { createHash } from "crypto";
787
- import { lstatSync, readFileSync as readFileSync3, readdirSync, rmSync as rmSync3 } from "fs";
788
- import { join as join3 } from "path";
1145
+ import { createHash as createHash2 } from "crypto";
1146
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync2, rmSync as rmSync4 } from "fs";
1147
+ import { join as join6 } from "path";
789
1148
  var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
790
1149
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
791
1150
  async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
792
1151
  signal?.throwIfAborted();
793
- const key = createHash("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
794
- const path = join3(directory, `machine_retry_${key}.json`);
1152
+ const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
1153
+ const path = join6(directory, `machine_retry_${key}.json`);
795
1154
  let state = {
796
1155
  failures: 0,
797
1156
  retryAt: 0
798
1157
  };
799
1158
  try {
800
- const stat = lstatSync(path);
1159
+ const stat = lstatSync2(path);
801
1160
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
802
- const data = JSON.parse(readFileSync3(path, "utf8"));
1161
+ const data = JSON.parse(readFileSync4(path, "utf8"));
803
1162
  if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
804
1163
  throw new Error("Invalid retry state");
805
1164
  state = data;
@@ -823,7 +1182,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
823
1182
  );
824
1183
  try {
825
1184
  const result = await request3();
826
- rmSync3(path, { force: true });
1185
+ rmSync4(path, { force: true });
827
1186
  return result;
828
1187
  } catch (error) {
829
1188
  if (!signal?.aborted && error instanceof MachineAuthError && [
@@ -850,60 +1209,1115 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
850
1209
  }
851
1210
  }
852
1211
 
853
- // src/lib/paths.ts
854
- import { homedir } from "os";
855
- import { isAbsolute as isAbsolute2, join as join4, 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`);
1212
+ // src/lib/session-identity.ts
1213
+ import { execFile } from "child_process";
1214
+ import { createHash as createHash4 } from "crypto";
1215
+ import { rmSync as rmSync5 } from "fs";
1216
+ import { join as join8 } from "path";
1217
+ import { promisify } from "util";
1218
+
1219
+ // src/lib/git.ts
1220
+ import { execFileSync } from "child_process";
1221
+ import { createHash as createHash3 } from "crypto";
1222
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
1223
+ import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve2, sep } from "path";
1224
+ var GIT_TIMEOUT_MS = 1e3;
1225
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1226
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1227
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1228
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1229
+ function gitChildEnvironment(env = process.env) {
1230
+ return Object.fromEntries(
1231
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
1232
+ );
1233
+ }
1234
+ function gitToplevel(cwd) {
1235
+ try {
1236
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1237
+ cwd,
1238
+ encoding: "utf-8",
1239
+ stdio: ["ignore", "pipe", "ignore"],
1240
+ timeout: GIT_TIMEOUT_MS,
1241
+ env: gitChildEnvironment()
1242
+ }).trim();
1243
+ } catch {
1244
+ return null;
860
1245
  }
861
- if (!value || value.trim() !== value || !isAbsolute2(value)) return;
862
- const normalized = normalize(value);
863
- return normalized === value ? value : void 0;
864
1246
  }
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: join4(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");
1247
+ function gitValue(cwd, args) {
1248
+ try {
1249
+ const value = execFileSync("git", args, {
1250
+ cwd,
1251
+ encoding: "utf-8",
1252
+ stdio: ["ignore", "pipe", "ignore"],
1253
+ timeout: GIT_TIMEOUT_MS,
1254
+ env: gitChildEnvironment()
1255
+ }).trim();
1256
+ return value || void 0;
1257
+ } catch {
1258
+ return void 0;
1259
+ }
1260
+ }
1261
+ function currentBranch(cwd) {
1262
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1263
+ }
1264
+ function parseGithubRepositoryName(path) {
1265
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1266
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1267
+ return null;
1268
+ }
1269
+ return `${parts[0]}/${parts[1]}`;
1270
+ }
1271
+ function githubRepositoryFromRemote(remote) {
1272
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1273
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1274
+ remote
1275
+ );
1276
+ const path = match?.[1] ?? match?.[2];
1277
+ return path ? parseGithubRepositoryName(path) : null;
1278
+ }
1279
+ function checkoutSettingsText(repoRoot) {
1280
+ const path = join7(repoRoot, ".claude", "settings.json");
1281
+ try {
1282
+ if (!lstatSync3(join7(repoRoot, ".claude")).isDirectory()) return null;
1283
+ const stat = lstatSync3(path);
1284
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1285
+ return readFileSync5(path, "utf8");
1286
+ } catch {
1287
+ return null;
1288
+ }
1289
+ }
1290
+ function checkoutDeclaration(repoRoot, name) {
1291
+ const text = checkoutSettingsText(repoRoot);
1292
+ if (text === null) return null;
1293
+ let parsed;
1294
+ try {
1295
+ parsed = JSON.parse(text);
1296
+ } catch {
1297
+ return null;
1298
+ }
1299
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1300
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
1301
+ return typeof value === "string" ? value : null;
1302
+ }
1303
+ function declaredGithubRepository(repoRoot) {
1304
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1305
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1306
+ }
1307
+ function githubRepositoryFullName(cwd) {
1308
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1309
+ if (remote) {
1310
+ const fromOrigin = githubRepositoryFromRemote(remote);
1311
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1312
+ }
1313
+ const root = gitToplevel(cwd);
1314
+ return root ? declaredGithubRepository(root) : null;
1315
+ }
1316
+ function normalizeOriginRemote(remote) {
1317
+ const value = remote.trim();
1318
+ if (!value) return void 0;
1319
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1320
+ if (scp?.host && scp.path) {
1321
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1322
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1323
+ }
1324
+ try {
1325
+ const url = new URL(value);
1326
+ url.username = "";
1327
+ url.password = "";
1328
+ url.search = "";
1329
+ url.hash = "";
1330
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1331
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1332
+ return void 0;
1333
+ } catch {
1334
+ return void 0;
1335
+ }
1336
+ }
1337
+
1338
+ // src/lib/terminal-safe.ts
1339
+ function replaceIsolatedSurrogates(value) {
1340
+ let out = "";
1341
+ for (let index = 0; index < value.length; index += 1) {
1342
+ const unit = value.charCodeAt(index);
1343
+ if (unit >= 55296 && unit <= 56319) {
1344
+ const next = value.charCodeAt(index + 1);
1345
+ if (next >= 56320 && next <= 57343) {
1346
+ out += value[index] + value[index + 1];
1347
+ index += 1;
1348
+ } else {
1349
+ out += "\uFFFD";
1350
+ }
1351
+ } else if (unit >= 56320 && unit <= 57343) {
1352
+ out += "\uFFFD";
1353
+ } else {
1354
+ out += value[index];
1355
+ }
1356
+ }
1357
+ return out;
1358
+ }
1359
+ function isUnsafeTerminalCodePoint(point) {
1360
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1361
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1362
+ point === 1564 || // Arabic letter mark
1363
+ point === 6158 || // Mongolian vowel separator
1364
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1365
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1366
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1367
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1368
+ point === 65279 || // zero-width no-break space / BOM
1369
+ point >= 917504 && point <= 917631;
1370
+ return c0OrC1 || bidiOrZeroWidth;
1371
+ }
1372
+ function terminalSafeText(value) {
1373
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1374
+ }
1375
+ function terminalSafeLine(value) {
1376
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1377
+ }
1378
+ var stripControlChars = terminalSafeText;
1379
+
1380
+ // src/lib/session-identity.ts
1381
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1382
+ var SESSION_IDENTITY_VALUE = "session";
1383
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1384
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1385
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1386
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1387
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1388
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1389
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1390
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1391
+ var SESSION_IDENTITY_ROUTES = {
1392
+ challenge: "/api/cli/session-identity/challenge",
1393
+ token: "/api/cli/session-identity/token",
1394
+ refresh: "/api/cli/session-identity/token/refresh",
1395
+ link: "/api/cli/session-identity/link"
1396
+ };
1397
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1398
+ var RENEW_BEFORE_MS = 6e4;
1399
+ var GIT_TIMEOUT_MS2 = 1e4;
1400
+ var POLL_BUDGET_MS = 15e3;
1401
+ var POLL_FIRST_DELAY_MS = 500;
1402
+ var POLL_MAX_DELAY_MS = 3e3;
1403
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1404
+ var LOCK_TIMEOUT_MS = 6e4;
1405
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1406
+ function sessionIdentityRequested(env = process.env) {
1407
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1408
+ }
1409
+ function sessionIdentityMode(deps = {}) {
1410
+ const env = deps.env ?? process.env;
1411
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1412
+ }
1413
+ function failure(code, cause, remedy) {
1414
+ return { status: "failed", code, cause, remedy };
1415
+ }
1416
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1417
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1418
+ 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';
1419
+ var SESSION_REVOKED = failure(
1420
+ "session_revoked",
1421
+ "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",
1422
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1423
+ );
1424
+ var CHALLENGE_WINDOW_PASSED = failure(
1425
+ "challenge_expired",
1426
+ "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)",
1427
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1428
+ );
1429
+ var CHALLENGE_GONE = failure(
1430
+ "challenge_not_found",
1431
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1432
+ NEW_SESSION_REMEDY
1433
+ );
1434
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1435
+ function rejectionFailure(reason, repository) {
1436
+ switch (reason) {
1437
+ case "identity_mismatch":
1438
+ return failure(
1439
+ "identity_mismatch",
1440
+ "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",
1441
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1442
+ );
1443
+ case "push_after_expiry":
1444
+ return failure(
1445
+ "push_after_expiry",
1446
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1447
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1448
+ );
1449
+ case "repository_mismatch":
1450
+ return failure(
1451
+ "repository_mismatch",
1452
+ `Primitive received the identity push from a different repository than ${repository}`,
1453
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1454
+ );
1455
+ case "conflicting_push":
1456
+ return failure(
1457
+ "conflicting_push",
1458
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1459
+ NEW_SESSION_REMEDY
1460
+ );
1461
+ case "unsupported_sender":
1462
+ return failure(
1463
+ "unsupported_sender",
1464
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1465
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1466
+ );
1467
+ default:
1468
+ return failure(
1469
+ "challenge_rejected",
1470
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1471
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1472
+ );
1473
+ }
1474
+ }
1475
+ function sessionIdentityMessage(outcome) {
1476
+ if (outcome.status === "link_required")
1477
+ 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.`;
1478
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1479
+ }
1480
+ function hash(value) {
1481
+ return createHash4("sha256").update(value).digest("hex");
1482
+ }
1483
+ function sessionContext(deps) {
1484
+ const env = deps.env ?? process.env;
1485
+ const environment = environmentCredentials(deps);
1486
+ if (!environment)
1487
+ return failure(
1488
+ "environment_credential_missing",
1489
+ "the cloud environment has no environment credential",
1490
+ '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'
1491
+ );
1492
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1493
+ if (!sessionId || !SESSION_ID.test(sessionId))
1494
+ return failure(
1495
+ "session_id_missing",
1496
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1497
+ NEW_SESSION_REMEDY
1498
+ );
1499
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1500
+ const directory = deps.directory ?? primConfigDirectory({ env });
1501
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1502
+ return {
1503
+ directory,
1504
+ apiUrl,
1505
+ clientId: environment.clientId,
1506
+ generation: environment.generation,
1507
+ sessionId,
1508
+ tokenPath: join8(directory, `session_identity_${key}.json`),
1509
+ statePath: join8(directory, `session_identity_${key}.state.json`),
1510
+ lockPath: join8(directory, "session-identity.lock")
1511
+ };
1512
+ }
1513
+ function readRecord(path) {
1514
+ try {
1515
+ const value = readMachineMetadata(path);
1516
+ return value === void 0 ? void 0 : machineRecord(value);
1517
+ } catch {
1518
+ return void 0;
1519
+ }
1520
+ }
1521
+ function finiteNumber(value) {
1522
+ return typeof value === "number" && Number.isFinite(value);
1523
+ }
1524
+ function readToken(context) {
1525
+ const data = readRecord(context.tokenPath);
1526
+ 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))
1527
+ return void 0;
1528
+ const identity = data.identity;
1529
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1530
+ return void 0;
1531
+ return data;
1532
+ }
1533
+ function readState(context) {
1534
+ const data = readRecord(context.statePath);
1535
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1536
+ return void 0;
1537
+ return data;
1538
+ }
1539
+ function writeToken(context, record) {
1540
+ prepareMachineMetadataDirectory(context.directory);
1541
+ writeMachineMetadata(context.tokenPath, record);
1542
+ rmSync5(context.statePath, { force: true });
1543
+ }
1544
+ function writeState(context, state) {
1545
+ try {
1546
+ prepareMachineMetadataDirectory(context.directory);
1547
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1548
+ } catch {
1549
+ }
1550
+ }
1551
+ function tokenValid(record, now = Date.now()) {
1552
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1553
+ }
1554
+ function tokenFresh(record, now = Date.now()) {
1555
+ return tokenValid(record, now) && now < record.refreshAfter;
1556
+ }
1557
+ function toCredential(record) {
1558
+ return {
1559
+ issuer: record.issuer,
1560
+ audience: record.audience,
1561
+ ...record.identity,
1562
+ accessToken: record.accessToken,
1563
+ expiresAt: record.expiresAt,
1564
+ apiUrl: record.apiUrl,
1565
+ generation: record.generation,
1566
+ storage: "environment",
1567
+ session: {
1568
+ userId: record.userId,
1569
+ displayName: record.displayName,
1570
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1571
+ refreshAfter: record.refreshAfter
1572
+ }
1573
+ };
1574
+ }
1575
+ function identified(record, reused) {
1576
+ return {
1577
+ status: "ok",
1578
+ credential: toCredential(record),
1579
+ displayName: record.displayName,
1580
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1581
+ reused
1582
+ };
1583
+ }
1584
+ function cachedSessionCredential(deps = {}) {
1585
+ if (!sessionIdentityMode(deps)) return void 0;
1586
+ let context;
1587
+ try {
1588
+ context = sessionContext(deps);
1589
+ } catch {
1590
+ return void 0;
1591
+ }
1592
+ if ("status" in context) return void 0;
1593
+ const record = readToken(context);
1594
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1595
+ }
1596
+ function outcomeFromState(state) {
1597
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1598
+ return {
1599
+ status: "link_required",
1600
+ githubLogin: state.githubLogin,
1601
+ challengeId: state.challengeId,
1602
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1603
+ };
1604
+ return failure(
1605
+ state.code,
1606
+ state.cause ?? "the last identity check failed",
1607
+ state.remedy ?? RETRY_REMEDY
1608
+ );
1609
+ }
1610
+ function parseInstant(value) {
1611
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1612
+ if (typeof value === "string" && value.length <= 64) {
1613
+ const parsed = Date.parse(value);
1614
+ return Number.isFinite(parsed) ? parsed : void 0;
1615
+ }
1616
+ return void 0;
1617
+ }
1618
+ async function sendJson(url, init, fetchImpl) {
1619
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1620
+ let value;
1621
+ try {
1622
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1623
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1624
+ } catch {
1625
+ value = void 0;
1626
+ }
1627
+ return { status: response.status, value };
1628
+ }
1629
+ function environmentOnly(deps) {
1630
+ return { ...deps, environmentOnly: true };
1631
+ }
1632
+ async function environmentRequest(method, path, body, deps, signal) {
1633
+ const send = async (credential2) => {
1634
+ const headers = { "Content-Type": "application/json" };
1635
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1636
+ if (credential2.tokenInjection) {
1637
+ const response = await forwardMachineRequest(
1638
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1639
+ signal,
1640
+ environmentOnly(deps)
1641
+ );
1642
+ const parsed = await response.json().catch(() => void 0);
1643
+ return {
1644
+ status: response.status,
1645
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1646
+ };
1647
+ }
1648
+ return sendJson(
1649
+ `${credential2.apiUrl}${path}`,
1650
+ {
1651
+ method,
1652
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1653
+ ...text === void 0 ? {} : { body: text },
1654
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1655
+ },
1656
+ deps.fetch ?? fetch
1657
+ );
1658
+ };
1659
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1660
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1661
+ let answer = await send(credential);
1662
+ if (answer.status === 401) {
1663
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1664
+ if (!credential)
1665
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1666
+ answer = await send(credential);
1667
+ }
1668
+ return answer;
1669
+ }
1670
+ function environmentFailure(error, apiUrl) {
1671
+ if (error instanceof MachineAuthError && error.terminal)
1672
+ return failure(
1673
+ "environment_credential_rejected",
1674
+ "Primitive rejected the cloud environment's credential",
1675
+ ENVIRONMENT_CREDENTIAL_REMEDY
1676
+ );
1677
+ const host = (() => {
1678
+ try {
1679
+ return new URL(apiUrl).hostname;
1680
+ } catch {
1681
+ return "Primitive";
1682
+ }
1683
+ })();
1684
+ return failure(
1685
+ "identity_unavailable",
1686
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1687
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1688
+ );
1689
+ }
1690
+ function answerError(answer) {
1691
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1692
+ }
1693
+ async function git(root, args, signal) {
1694
+ try {
1695
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1696
+ cwd: root,
1697
+ encoding: "utf8",
1698
+ timeout: GIT_TIMEOUT_MS2,
1699
+ signal,
1700
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1701
+ maxBuffer: 1024 * 1024
1702
+ });
1703
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1704
+ } catch (error) {
1705
+ const failed = error;
1706
+ return {
1707
+ ok: false,
1708
+ code: typeof failed.code === "number" ? failed.code : void 0,
1709
+ stdout: failed.stdout ?? "",
1710
+ stderr: failed.stderr ?? "",
1711
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1712
+ };
1713
+ }
1714
+ }
1715
+ function gitDetail(stderr) {
1716
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1717
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1718
+ }
1719
+ async function defaultSleep2(milliseconds, signal) {
1720
+ await new Promise((resolve4, reject) => {
1721
+ const timer = setTimeout(resolve4, milliseconds);
1722
+ signal?.addEventListener(
1723
+ "abort",
1724
+ () => {
1725
+ clearTimeout(timer);
1726
+ reject(signal.reason);
1727
+ },
1728
+ { once: true }
1729
+ );
1730
+ });
1731
+ }
1732
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1733
+ const sleep = deps.sleep ?? defaultSleep2;
1734
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1735
+ let delay = POLL_FIRST_DELAY_MS;
1736
+ let unreachable;
1737
+ for (; ; ) {
1738
+ const remaining = deadline - Date.now();
1739
+ if (remaining <= 0) break;
1740
+ await sleep(Math.min(delay, remaining), signal);
1741
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1742
+ let answer;
1743
+ try {
1744
+ answer = await environmentRequest(
1745
+ "GET",
1746
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1747
+ void 0,
1748
+ deps,
1749
+ signal
1750
+ );
1751
+ } catch (error) {
1752
+ signal?.throwIfAborted();
1753
+ unreachable = error;
1754
+ continue;
1755
+ }
1756
+ if (answer.status === 404) return CHALLENGE_GONE;
1757
+ if (answer.status === 401 || answer.status === 403)
1758
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1759
+ if (answer.status < 200 || answer.status > 299) {
1760
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1761
+ continue;
1762
+ }
1763
+ unreachable = void 0;
1764
+ const status = answer.value;
1765
+ if (status?.status === "verified")
1766
+ return {
1767
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1768
+ };
1769
+ if (status?.status === "expired")
1770
+ return failure(
1771
+ "challenge_expired",
1772
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1773
+ NEW_SESSION_REMEDY
1774
+ );
1775
+ if (status?.status === "rejected")
1776
+ return rejectionFailure(status.reason, repository);
1777
+ }
1778
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1779
+ return failure(
1780
+ "webhook_timeout",
1781
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1782
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1783
+ );
1784
+ }
1785
+ function parseTokenAnswer(value) {
1786
+ if (!value) return void 0;
1787
+ const user = value.user;
1788
+ const expiresAt = parseInstant(value.expiresAt);
1789
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1790
+ 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))
1791
+ return void 0;
1792
+ return {
1793
+ accessToken: value.accessToken,
1794
+ expiresAt,
1795
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1796
+ userId: user.id,
1797
+ displayName: user.displayName,
1798
+ organizationId: value.organizationId
1799
+ };
1800
+ }
1801
+ var SERVER_CONTRACT_FAILURE = failure(
1802
+ "server_contract",
1803
+ "Primitive's answer did not identify the linked member",
1804
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1805
+ );
1806
+ async function recordFor(context, answer, extra, deps, signal) {
1807
+ let identity;
1808
+ let environment;
1809
+ try {
1810
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1811
+ identity = await verifyMachineIdentity(
1812
+ context.apiUrl,
1813
+ answer.accessToken,
1814
+ context.clientId,
1815
+ signal,
1816
+ deps.fetch
1817
+ );
1818
+ } catch (error) {
1819
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1820
+ return SERVER_CONTRACT_FAILURE;
1821
+ return environmentFailure(error, context.apiUrl);
1822
+ }
1823
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1824
+ return SERVER_CONTRACT_FAILURE;
1825
+ return {
1826
+ version: 1,
1827
+ apiUrl: context.apiUrl,
1828
+ clientId: context.clientId,
1829
+ generation: context.generation,
1830
+ sessionId: context.sessionId,
1831
+ issuer: environment.issuer,
1832
+ audience: environment.audience,
1833
+ accessToken: answer.accessToken,
1834
+ expiresAt: answer.expiresAt,
1835
+ refreshAfter: answer.refreshAfter,
1836
+ userId: answer.userId,
1837
+ displayName: answer.displayName,
1838
+ organizationId: answer.organizationId,
1839
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1840
+ identity,
1841
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1842
+ };
1843
+ }
1844
+ async function refreshToken(context, record, deps, signal) {
1845
+ let answer;
1846
+ try {
1847
+ answer = await environmentRequest(
1848
+ "POST",
1849
+ SESSION_IDENTITY_ROUTES.refresh,
1850
+ { accessToken: record.accessToken },
1851
+ deps,
1852
+ signal
1853
+ );
1854
+ } catch (error) {
1855
+ signal?.throwIfAborted();
1856
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
1857
+ }
1858
+ const code = answerError(answer);
1859
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
1860
+ return { status: "refused", failure: SESSION_REVOKED };
1861
+ if (answer.status === 401 || answer.status === 403)
1862
+ return {
1863
+ status: "refused",
1864
+ failure: environmentFailure(
1865
+ new MachineAuthError("rejected", "rejected", true),
1866
+ context.apiUrl
1867
+ )
1868
+ };
1869
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1870
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
1871
+ return { status: "unavailable" };
1872
+ return {
1873
+ status: "ok",
1874
+ record: {
1875
+ ...record,
1876
+ accessToken: token.accessToken,
1877
+ expiresAt: token.expiresAt,
1878
+ refreshAfter: token.refreshAfter,
1879
+ displayName: token.displayName
1880
+ }
1881
+ };
1882
+ }
1883
+ function exchangeRefusal(answer, repository) {
1884
+ if (answer.status === 404) return CHALLENGE_GONE;
1885
+ if (answer.status !== 409) return void 0;
1886
+ switch (answerError(answer)) {
1887
+ case "identity_mismatch":
1888
+ return rejectionFailure("identity_mismatch", repository);
1889
+ case "challenge_rejected":
1890
+ return rejectionFailure(answer.value?.reason, repository);
1891
+ case "challenge_expired":
1892
+ return CHALLENGE_WINDOW_PASSED;
1893
+ case "challenge_already_exchanged":
1894
+ return failure(
1895
+ "challenge_already_exchanged",
1896
+ "this session's identity check was already exchanged for a token this VM does not hold",
1897
+ NEW_SESSION_REMEDY
1898
+ );
1899
+ case "challenge_pending":
1900
+ return failure(
1901
+ "webhook_timeout",
1902
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
1903
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1904
+ );
1905
+ default:
1906
+ return void 0;
1907
+ }
1908
+ }
1909
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
1910
+ let answer;
1911
+ try {
1912
+ answer = await environmentRequest(
1913
+ "POST",
1914
+ SESSION_IDENTITY_ROUTES.token,
1915
+ { challengeId: challenge.challengeId },
1916
+ deps,
1917
+ signal
1918
+ );
1919
+ } catch (error) {
1920
+ signal?.throwIfAborted();
1921
+ return environmentFailure(error, context.apiUrl);
1922
+ }
1923
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
1924
+ const login = answer.value?.githubLogin;
1925
+ return {
1926
+ status: "link_required",
1927
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
1928
+ challengeId: challenge.challengeId,
1929
+ challengeExpiresAt: challenge.challengeExpiresAt
1930
+ };
1931
+ }
1932
+ const refused = exchangeRefusal(
1933
+ answer,
1934
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
1935
+ );
1936
+ if (refused) return refused;
1937
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1938
+ if (!token) {
1939
+ if (answer.status === 401 || answer.status === 403)
1940
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1941
+ return answer.status >= 500 ? environmentFailure(
1942
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1943
+ context.apiUrl
1944
+ ) : SERVER_CONTRACT_FAILURE;
1945
+ }
1946
+ return recordFor(
1947
+ context,
1948
+ token,
1949
+ { githubLogin: challenge.githubLogin, repositoryRoot },
1950
+ deps,
1951
+ signal
1952
+ );
1953
+ }
1954
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
1955
+ const env = deps.env ?? process.env;
1956
+ const repository = githubRepositoryFullName(root);
1957
+ if (!repository)
1958
+ return failure(
1959
+ "repository_unidentified",
1960
+ "this checkout does not name its GitHub repository",
1961
+ "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"
1962
+ );
1963
+ const branch = currentBranch(root);
1964
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
1965
+ return failure(
1966
+ "not_session_branch",
1967
+ `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`,
1968
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
1969
+ );
1970
+ attempt.branch = branch;
1971
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
1972
+ if (!baseSha) {
1973
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
1974
+ baseSha = head.stdout.trim();
1975
+ if (!head.ok || !SHA.test(baseSha))
1976
+ return failure(
1977
+ "no_commit",
1978
+ "this checkout has no commit to create the session branch at",
1979
+ NEW_SESSION_REMEDY
1980
+ );
1981
+ }
1982
+ const published = await git(
1983
+ root,
1984
+ [
1985
+ "for-each-ref",
1986
+ "--count=1",
1987
+ "--format=%(refname)",
1988
+ "--contains",
1989
+ baseSha,
1990
+ "refs/remotes/origin/"
1991
+ ],
1992
+ signal
1993
+ );
1994
+ if (!published.ok || published.stdout.trim() === "")
1995
+ return failure(
1996
+ "unpublished_commits",
1997
+ `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`,
1998
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
1999
+ );
2000
+ attempt.baseSha = baseSha;
2001
+ const remote = await git(
2002
+ root,
2003
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2004
+ signal
2005
+ );
2006
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2007
+ if (remote.ok && recorded) {
2008
+ Object.assign(attempt, recorded);
2009
+ return { ...recorded, repository };
2010
+ }
2011
+ if (remote.ok)
2012
+ return failure(
2013
+ "branch_exists",
2014
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2015
+ NEW_SESSION_REMEDY
2016
+ );
2017
+ if (remote.code !== 2)
2018
+ return failure(
2019
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2020
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2021
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2022
+ );
2023
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2024
+ Object.assign(attempt, recorded);
2025
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2026
+ }
2027
+ let answer;
2028
+ try {
2029
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2030
+ answer = await environmentRequest(
2031
+ "POST",
2032
+ SESSION_IDENTITY_ROUTES.challenge,
2033
+ {
2034
+ repositoryFullName: repository,
2035
+ claudeSessionId: context.sessionId,
2036
+ branch,
2037
+ baseSha,
2038
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2039
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2040
+ },
2041
+ deps,
2042
+ signal
2043
+ );
2044
+ } catch (error) {
2045
+ signal?.throwIfAborted();
2046
+ return environmentFailure(error, context.apiUrl);
2047
+ }
2048
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2049
+ return failure(
2050
+ "repository_not_connected",
2051
+ `${repository} is not connected to Primitive`,
2052
+ CLOUD_GITHUB_CONNECT_REMEDY
2053
+ );
2054
+ if (answer.status === 401 || answer.status === 403)
2055
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2056
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2057
+ return failure(
2058
+ "challenge_open",
2059
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2060
+ `wait five minutes, then ${RETRY_REMEDY}`
2061
+ );
2062
+ if (answer.status === 429)
2063
+ return failure(
2064
+ "too_many_challenges",
2065
+ "too many sessions of this cloud environment are being identified at once",
2066
+ `wait a few minutes, then ${RETRY_REMEDY}`
2067
+ );
2068
+ const challengeId = answer.value?.challengeId;
2069
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2070
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2071
+ return answer.status >= 500 ? environmentFailure(
2072
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2073
+ context.apiUrl
2074
+ ) : SERVER_CONTRACT_FAILURE;
2075
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2076
+ attempt.challengeId = challengeId;
2077
+ attempt.challengeExpiresAt = challengeExpiresAt;
2078
+ return pushSessionBranch(
2079
+ root,
2080
+ repository,
2081
+ branch,
2082
+ baseSha,
2083
+ { challengeId, challengeExpiresAt },
2084
+ signal
2085
+ );
2086
+ }
2087
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2088
+ const push = await git(
2089
+ root,
2090
+ [
2091
+ "-c",
2092
+ "core.hooksPath=/dev/null",
2093
+ "-c",
2094
+ "push.followTags=false",
2095
+ "-c",
2096
+ "push.recurseSubmodules=no",
2097
+ "-c",
2098
+ "push.gpgSign=false",
2099
+ "-c",
2100
+ "push.pushOption=",
2101
+ "push",
2102
+ "--no-verify",
2103
+ "--no-follow-tags",
2104
+ "--no-recurse-submodules",
2105
+ "--no-signed",
2106
+ "--quiet",
2107
+ "origin",
2108
+ `${baseSha}:refs/heads/${branch}`
2109
+ ],
2110
+ signal
2111
+ );
2112
+ if (!push.ok)
2113
+ return push.timedOut ? failure(
2114
+ "push_timeout",
2115
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2116
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2117
+ ) : failure(
2118
+ "push_refused",
2119
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2120
+ `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}`
2121
+ );
2122
+ return { ...challenge, repository };
2123
+ }
2124
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2125
+ let context;
2126
+ try {
2127
+ context = sessionContext(deps);
2128
+ } catch (error) {
2129
+ return failure(
2130
+ "environment_credential_invalid",
2131
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2132
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2133
+ );
874
2134
  }
875
- return { path: join4(home, ".config", "prim"), source: "default" };
2135
+ if ("status" in context) return context;
2136
+ const ctx = context;
2137
+ const startedAt2 = Date.now();
2138
+ prepareMachineMetadataDirectory(ctx.directory);
2139
+ return withFileLock(
2140
+ ctx.lockPath,
2141
+ async () => {
2142
+ const record = readToken(ctx);
2143
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2144
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2145
+ if (record) {
2146
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2147
+ if (refreshed.status === "ok") {
2148
+ writeToken(ctx, refreshed.record);
2149
+ return identified(refreshed.record, true);
2150
+ }
2151
+ if (refreshed.status === "refused") {
2152
+ rmSync5(ctx.tokenPath, { force: true });
2153
+ writeState(ctx, {
2154
+ sessionId: ctx.sessionId,
2155
+ status: "failed",
2156
+ code: refreshed.failure.code,
2157
+ cause: refreshed.failure.cause,
2158
+ remedy: refreshed.failure.remedy,
2159
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2160
+ at: Date.now()
2161
+ });
2162
+ return refreshed.failure;
2163
+ }
2164
+ if (!forced && tokenValid(record)) return identified(record, true);
2165
+ }
2166
+ const state = readState(ctx);
2167
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2168
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2169
+ if (!options.explicit) {
2170
+ if (!root || !(record || state))
2171
+ return failure(
2172
+ "not_identified",
2173
+ "this session has not identified who started it yet",
2174
+ RETRY_REMEDY
2175
+ );
2176
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2177
+ } else if (state && state.at >= startedAt2) {
2178
+ return outcomeFromState(state);
2179
+ }
2180
+ if (!root)
2181
+ return failure(
2182
+ "repository_missing",
2183
+ "this is not a git repository",
2184
+ "run it in the repository the session cloned"
2185
+ );
2186
+ const attempt = { root };
2187
+ const remember = (outcome) => {
2188
+ writeState(ctx, {
2189
+ sessionId: ctx.sessionId,
2190
+ status: outcome.status,
2191
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2192
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2193
+ githubLogin: outcome.githubLogin
2194
+ },
2195
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2196
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2197
+ repositoryRoot: root,
2198
+ branch: attempt.branch ?? state?.branch,
2199
+ baseSha: attempt.baseSha ?? state?.baseSha,
2200
+ at: Date.now()
2201
+ });
2202
+ return outcome;
2203
+ };
2204
+ let challenge;
2205
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2206
+ attempt.challengeId = state.challengeId;
2207
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2208
+ attempt.branch = state.branch;
2209
+ attempt.baseSha = state.baseSha;
2210
+ challenge = {
2211
+ challengeId: state.challengeId,
2212
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2213
+ repository: githubRepositoryFullName(root) ?? "the repository"
2214
+ };
2215
+ } else if (state?.status === "link_required" && state.challengeId) {
2216
+ attempt.challengeId = state.challengeId;
2217
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2218
+ const exchanged2 = await exchangeChallenge(
2219
+ ctx,
2220
+ {
2221
+ challengeId: state.challengeId,
2222
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2223
+ githubLogin: state.githubLogin
2224
+ },
2225
+ root,
2226
+ deps,
2227
+ options.signal
2228
+ );
2229
+ if ("status" in exchanged2) return remember(exchanged2);
2230
+ writeToken(ctx, exchanged2);
2231
+ return identified(exchanged2, false);
2232
+ } else if (!options.explicit) {
2233
+ return state ? outcomeFromState(state) : failure(
2234
+ "not_identified",
2235
+ "this session has not identified who started it yet",
2236
+ RETRY_REMEDY
2237
+ );
2238
+ } else {
2239
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2240
+ if ("status" in pushed) return remember(pushed);
2241
+ challenge = pushed;
2242
+ }
2243
+ const verified = await pollChallenge(
2244
+ ctx.apiUrl,
2245
+ challenge.challengeId,
2246
+ challenge.repository,
2247
+ // A hook process waits only briefly for a late notice.
2248
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2249
+ options.signal
2250
+ );
2251
+ if ("status" in verified) return remember(verified);
2252
+ const exchanged = await exchangeChallenge(
2253
+ ctx,
2254
+ { ...challenge, githubLogin: verified.githubLogin },
2255
+ root,
2256
+ deps,
2257
+ options.signal
2258
+ );
2259
+ if ("status" in exchanged) return remember(exchanged);
2260
+ writeToken(ctx, exchanged);
2261
+ return identified(exchanged, false);
2262
+ },
2263
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2264
+ );
876
2265
  }
877
- function primConfigDirectory(options = {}) {
878
- return resolvePrimConfigDirectory(options).path;
2266
+ async function acquireSessionCredential(options = {}, deps = {}) {
2267
+ const cached2 = cachedSessionCredential(deps);
2268
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2269
+ if (cached2 && fresh && !options.force) return cached2;
2270
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2271
+ let outcome;
2272
+ try {
2273
+ outcome = await ensureSessionIdentity(
2274
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2275
+ deps
2276
+ );
2277
+ } catch (error) {
2278
+ options.signal?.throwIfAborted();
2279
+ if (error instanceof MachineAuthError) throw error;
2280
+ throw new MachineAuthError(
2281
+ "identity_unavailable",
2282
+ "Identifying who started this cloud session is still in progress; retry shortly."
2283
+ );
2284
+ }
2285
+ if (outcome.status === "ok") return outcome.credential;
2286
+ throw new MachineAuthError(
2287
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2288
+ sessionIdentityMessage(outcome)
2289
+ );
879
2290
  }
880
2291
 
881
2292
  // src/lib/machine-credentials.ts
882
- var require2 = createRequire(import.meta.url);
2293
+ function sessionScoped(deps) {
2294
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2295
+ }
2296
+ var require3 = createRequire2(import.meta.url);
883
2297
  var SERVICE = "ai.primitive.prim.machine";
884
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2298
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
885
2299
  var PROFILE_FILE = "machine_profile.json";
886
- var RENEW_BEFORE_MS = 6e4;
2300
+ var RENEW_BEFORE_MS2 = 6e4;
887
2301
  var cached;
888
2302
  function configurationDirectory(deps) {
889
2303
  return deps.directory ?? primConfigDirectory({ env: deps.env });
890
2304
  }
891
2305
  function apiUrlFor(deps) {
892
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2306
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
893
2307
  }
894
- function hash(value) {
895
- return createHash2("sha256").update(value).digest("hex");
2308
+ function hash2(value) {
2309
+ return createHash5("sha256").update(value).digest("hex");
896
2310
  }
897
2311
  function recordPath(directory, generation) {
898
- return join5(directory, `machine_${generation}.json`);
2312
+ return join9(directory, `machine_${generation}.json`);
899
2313
  }
900
2314
  function storageKey(directory, generation) {
901
- return `${hash(directory)}:${generation}`;
2315
+ return `${hash2(directory)}:${generation}`;
902
2316
  }
903
2317
  function environmentContextPath(deps, clientId) {
904
- return join5(
2318
+ return join9(
905
2319
  configurationDirectory(deps),
906
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2320
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
907
2321
  );
908
2322
  }
909
2323
  function writeEnvironmentContext(credential, deps) {
@@ -961,27 +2375,33 @@ function readEnvironmentContext(environment, deps) {
961
2375
  return void 0;
962
2376
  }
963
2377
  }
964
- function keyringEntry(key) {
965
- let directory = dirname4(fileURLToPath2(import.meta.url));
2378
+ function keyringLoaderPath(start, options = {}) {
2379
+ let directory = start;
966
2380
  for (let depth = 0; depth < 5; depth++) {
967
- const loader = join5(directory, "native", "keyring.cjs");
968
- if (existsSync3(loader)) {
969
- const module2 = require2(loader);
970
- return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
971
- }
972
- directory = dirname4(directory);
2381
+ const loader = join9(directory, "native", "keyring.cjs");
2382
+ if (existsSync5(loader)) return loader;
2383
+ directory = dirname7(directory);
973
2384
  }
974
- const module = require2("@napi-rs/keyring");
2385
+ try {
2386
+ createRequire2(join9(start, "noop.js")).resolve("@napi-rs/keyring");
2387
+ return void 0;
2388
+ } catch {
2389
+ return selectedHookRuntimeKeyringLoader(options);
2390
+ }
2391
+ }
2392
+ function keyringEntry(key) {
2393
+ const loader = keyringLoaderPath(dirname7(fileURLToPath3(import.meta.url)));
2394
+ const module = require3(loader ?? "@napi-rs/keyring");
975
2395
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
976
2396
  }
977
2397
  function protectPath(path, directory) {
978
2398
  if (process.platform !== "win32") {
979
- chmodSync(path, directory ? 448 : 384);
2399
+ chmodSync2(path, directory ? 448 : 384);
980
2400
  return;
981
2401
  }
982
2402
  const encodedPath = Buffer.from(path).toString("base64");
983
2403
  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)`;
984
- execFileSync(
2404
+ execFileSync2(
985
2405
  "powershell.exe",
986
2406
  [
987
2407
  "-NoProfile",
@@ -993,8 +2413,8 @@ function protectPath(path, directory) {
993
2413
  );
994
2414
  }
995
2415
  function ensureDirectory(directory) {
996
- mkdirSync3(directory, { recursive: true, mode: 448 });
997
- if (lstatSync2(directory).isSymbolicLink())
2416
+ mkdirSync4(directory, { recursive: true, mode: 448 });
2417
+ if (lstatSync4(directory).isSymbolicLink())
998
2418
  throw new MachineAuthError(
999
2419
  "unsafe_storage",
1000
2420
  "Credential directory must not be a symbolic link."
@@ -1006,17 +2426,20 @@ function writePrivate(path, value) {
1006
2426
  `, { mode: 384 });
1007
2427
  protectPath(path, false);
1008
2428
  }
2429
+ function readMachineMetadata(path) {
2430
+ return readPrivate(path);
2431
+ }
1009
2432
  function readPrivate(path) {
1010
2433
  let raw;
1011
2434
  try {
1012
- const stat = lstatSync2(path);
2435
+ const stat = lstatSync4(path);
1013
2436
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1014
2437
  throw new MachineAuthError(
1015
2438
  "unsafe_storage",
1016
2439
  "Machine credential files must be owner-only regular files."
1017
2440
  );
1018
2441
  }
1019
- raw = readFileSync4(path, "utf8");
2442
+ raw = readFileSync6(path, "utf8");
1020
2443
  } catch (error) {
1021
2444
  if (error.code === "ENOENT") return void 0;
1022
2445
  throw error;
@@ -1061,7 +2484,7 @@ function parseProfile(value) {
1061
2484
  };
1062
2485
  }
1063
2486
  function readMachineProfile(deps = {}) {
1064
- const value = readPrivate(join5(configurationDirectory(deps), PROFILE_FILE));
2487
+ const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
1065
2488
  return value === void 0 ? void 0 : parseProfile(value);
1066
2489
  }
1067
2490
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -1070,20 +2493,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
1070
2493
  var brokerKeys = /* @__PURE__ */ new Map();
1071
2494
  function networkSecretBrokerKey(deps, clientId) {
1072
2495
  const directory = configurationDirectory(deps);
1073
- const path = join5(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2496
+ const path = join9(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
1074
2497
  const known = brokerKeys.get(path);
1075
2498
  if (known) return known;
1076
2499
  ensureDirectory(directory);
1077
2500
  const read = () => {
1078
2501
  try {
1079
- const stat = lstatSync2(path);
2502
+ const stat = lstatSync4(path);
1080
2503
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
1081
2504
  throw new MachineAuthError(
1082
2505
  "unsafe_storage",
1083
2506
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
1084
2507
  true
1085
2508
  );
1086
- const value = readFileSync4(path, "utf8").trim();
2509
+ const value = readFileSync6(path, "utf8").trim();
1087
2510
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
1088
2511
  } catch (error) {
1089
2512
  if (error.code === "ENOENT") return void 0;
@@ -1102,16 +2525,16 @@ function networkSecretBrokerKey(deps, clientId) {
1102
2525
  `The machine broker key at ${path} is damaged. Delete it and retry.`,
1103
2526
  true
1104
2527
  );
1105
- const staged = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}`;
2528
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
1106
2529
  try {
1107
- writeFileSync3(staged, `${randomBytes2(32).toString("hex")}
2530
+ writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
1108
2531
  `, { mode: 384, flag: "wx" });
1109
2532
  protectPath(staged, false);
1110
2533
  linkSync(staged, path);
1111
2534
  } catch (error) {
1112
2535
  if (error.code !== "EEXIST") throw error;
1113
2536
  } finally {
1114
- rmSync4(staged, { force: true });
2537
+ rmSync6(staged, { force: true });
1115
2538
  }
1116
2539
  }
1117
2540
  const key = read()?.key;
@@ -1144,7 +2567,7 @@ function environmentCredentials(deps) {
1144
2567
  "conflicting_credentials",
1145
2568
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
1146
2569
  );
1147
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2570
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1148
2571
  const credentials = {
1149
2572
  clientId,
1150
2573
  generation,
@@ -1165,12 +2588,12 @@ function environmentCredentials(deps) {
1165
2588
  return {
1166
2589
  clientId,
1167
2590
  clientSecret,
1168
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2591
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1169
2592
  };
1170
2593
  }
1171
2594
  function hasMachineConfiguration(deps = {}) {
1172
2595
  const env = deps.env ?? process.env;
1173
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join5(configurationDirectory(deps), PROFILE_FILE));
2596
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join9(configurationDirectory(deps), PROFILE_FILE));
1174
2597
  if (configured && env.PRIM_TOKEN?.trim()) {
1175
2598
  throw new MachineAuthError(
1176
2599
  "conflicting_credentials",
@@ -1182,6 +2605,7 @@ function hasMachineConfiguration(deps = {}) {
1182
2605
  }
1183
2606
  function machineContext(deps = {}) {
1184
2607
  if (!hasMachineConfiguration(deps)) return void 0;
2608
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1185
2609
  const environment = environmentCredentials(deps);
1186
2610
  if (environment) {
1187
2611
  if (environmentTerminal === environment.generation) return void 0;
@@ -1196,6 +2620,7 @@ function machineContext(deps = {}) {
1196
2620
  return profile;
1197
2621
  }
1198
2622
  function cachedMachineCredential(deps = {}) {
2623
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1199
2624
  const context = machineContext(deps);
1200
2625
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1201
2626
  }
@@ -1204,7 +2629,7 @@ function machineSessionEnded(deps = {}) {
1204
2629
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1205
2630
  if (!generation) return false;
1206
2631
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1207
- return readPrivate(join5(configurationDirectory(deps), "machine_terminal.json")) === generation;
2632
+ return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
1208
2633
  }
1209
2634
  var environmentTerminal;
1210
2635
  var NETWORK_REJECTION_PAUSE_MS = 3e4;
@@ -1268,6 +2693,7 @@ async function persistRecord(record, deps, signal) {
1268
2693
  }
1269
2694
  async function acquireMachineCredential(options = {}, deps = {}) {
1270
2695
  if (!hasMachineConfiguration(deps)) return void 0;
2696
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1271
2697
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1272
2698
  const apiUrl = apiUrlFor(deps);
1273
2699
  const environment = environmentCredentials(deps);
@@ -1296,7 +2722,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1296
2722
  }
1297
2723
  }
1298
2724
  return withFileLock(
1299
- join5(directory2, "credentials.lock"),
2725
+ join9(directory2, "credentials.lock"),
1300
2726
  async () => {
1301
2727
  if (machineSessionEnded(deps))
1302
2728
  throw new MachineAuthError(
@@ -1304,7 +2730,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1304
2730
  rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1305
2731
  true
1306
2732
  );
1307
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2733
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1308
2734
  return cached;
1309
2735
  if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
1310
2736
  throw networkRejection.error;
@@ -1378,7 +2804,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1378
2804
  const contextPath = environmentContextPath(deps, environment.clientId);
1379
2805
  try {
1380
2806
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1381
- rmSync4(contextPath, { force: true });
2807
+ rmSync6(contextPath, { force: true });
1382
2808
  } catch {
1383
2809
  }
1384
2810
  throw error;
@@ -1388,7 +2814,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1388
2814
  const contextPath = environmentContextPath(deps, environment.clientId);
1389
2815
  try {
1390
2816
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1391
- rmSync4(contextPath, { force: true });
2817
+ rmSync6(contextPath, { force: true });
1392
2818
  } catch {
1393
2819
  }
1394
2820
  }
@@ -1402,7 +2828,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1402
2828
  const expected = machineContext(deps);
1403
2829
  const directory = configurationDirectory(deps);
1404
2830
  return withFileLock(
1405
- join5(directory, "credentials.lock"),
2831
+ join9(directory, "credentials.lock"),
1406
2832
  async () => {
1407
2833
  const profile = readMachineProfile(deps);
1408
2834
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1417,7 +2843,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1417
2843
  true
1418
2844
  );
1419
2845
  let record = await loadRecord(profile, deps, signal);
1420
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2846
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1421
2847
  try {
1422
2848
  const { tokens, identity } = await withMachineCooldown(
1423
2849
  directory,
@@ -1452,7 +2878,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1452
2878
  await persistRecord(record, deps, signal);
1453
2879
  } catch (error) {
1454
2880
  if (error instanceof MachineAuthError && error.terminal)
1455
- writePrivate(join5(directory, "machine_terminal.json"), profile.generation);
2881
+ writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
1456
2882
  throw error;
1457
2883
  }
1458
2884
  }
@@ -1482,13 +2908,19 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
1482
2908
  });
1483
2909
  }
1484
2910
  function machineJournalBucket(identity) {
1485
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2911
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1486
2912
  }
1487
2913
  function identityPending(actor) {
1488
2914
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1489
2915
  }
1490
2916
  function machinePendingBucket(identity) {
1491
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
2917
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
2918
+ }
2919
+ function prepareMachineMetadataDirectory(directory) {
2920
+ ensureDirectory(directory);
2921
+ }
2922
+ function writeMachineMetadata(path, value) {
2923
+ writePrivate(path, value);
1492
2924
  }
1493
2925
 
1494
2926
  // src/lib/machine-broker.ts
@@ -1503,14 +2935,14 @@ var FORWARD_TIMEOUT_MS = 3e4;
1503
2935
  var FORWARD_METHODS = ["GET", "POST", "DELETE"];
1504
2936
  var IDLE_MS = 5 * 6e4;
1505
2937
  function descriptorPath(directory, generation) {
1506
- return join6(directory, `machine_broker_${generation}.json`);
2938
+ return join10(directory, `machine_broker_${generation}.json`);
1507
2939
  }
1508
2940
  function readDescriptor(path) {
1509
2941
  try {
1510
- const stat = lstatSync3(path);
2942
+ const stat = lstatSync5(path);
1511
2943
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1512
2944
  return void 0;
1513
- const data = JSON.parse(readFileSync5(path, "utf8"));
2945
+ const data = JSON.parse(readFileSync7(path, "utf8"));
1514
2946
  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;
1515
2947
  } catch {
1516
2948
  return void 0;
@@ -1523,7 +2955,7 @@ function matches(left, right) {
1523
2955
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
1524
2956
  }
1525
2957
  function tokenHash(token) {
1526
- return token ? createHash3("sha256").update(token).digest("hex") : void 0;
2958
+ return token ? createHash6("sha256").update(token).digest("hex") : void 0;
1527
2959
  }
1528
2960
  async function brokerRequest(descriptor, environment, options) {
1529
2961
  const body = JSON.stringify({
@@ -1600,7 +3032,7 @@ async function acquireBrokerCredential(options) {
1600
3032
  async function ensureBroker(options) {
1601
3033
  const path = descriptorPath(options.directory, options.environment.generation);
1602
3034
  return withFileLock(
1603
- join6(options.directory, "machine-broker.lock"),
3035
+ join10(options.directory, "machine-broker.lock"),
1604
3036
  async () => {
1605
3037
  const current = readDescriptor(path);
1606
3038
  if (current) {
@@ -1613,14 +3045,14 @@ async function ensureBroker(options) {
1613
3045
  options.signal.throwIfAborted();
1614
3046
  }
1615
3047
  }
1616
- const bundled = fileURLToPath3(import.meta.url);
1617
- const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
3048
+ const bundled = fileURLToPath4(import.meta.url);
3049
+ const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
1618
3050
  if (!entry)
1619
3051
  throw new MachineAuthError(
1620
3052
  "broker_unavailable",
1621
3053
  "Reinstall Prim to restore its machine credential broker."
1622
3054
  );
1623
- await new Promise((resolve3, reject) => {
3055
+ await new Promise((resolve4, reject) => {
1624
3056
  const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
1625
3057
  detached: true,
1626
3058
  stdio: ["ignore", "ignore", "ignore", "ipc"],
@@ -1635,7 +3067,7 @@ async function ensureBroker(options) {
1635
3067
  if (error) child.kill();
1636
3068
  if (child.connected) child.disconnect();
1637
3069
  child.unref();
1638
- error ? reject(error) : resolve3();
3070
+ error ? reject(error) : resolve4();
1639
3071
  };
1640
3072
  const abort = () => finish(
1641
3073
  new MachineAuthError(
@@ -1817,7 +3249,7 @@ async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
1817
3249
  }
1818
3250
  async function credentialResult(apiUrl, data, signal) {
1819
3251
  try {
1820
- const current = cachedMachineCredential();
3252
+ const current = cachedMachineCredential({ localEnvironment: true });
1821
3253
  const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
1822
3254
  const credential = await acquireMachineCredential(
1823
3255
  { force, signal },
@@ -1915,7 +3347,7 @@ async function startMachineBroker() {
1915
3347
  const directory = primConfigDirectory();
1916
3348
  const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
1917
3349
  const path = descriptorPath(directory, environment.generation);
1918
- const nonce = randomBytes3(32).toString("hex");
3350
+ const nonce = randomBytes4(32).toString("hex");
1919
3351
  const server = createBrokerServer({
1920
3352
  environment,
1921
3353
  apiUrl,
@@ -1926,14 +3358,14 @@ async function startMachineBroker() {
1926
3358
  clearTimeout(idle);
1927
3359
  server.closeAllConnections();
1928
3360
  server.close();
1929
- if (readDescriptor(path)?.nonce === nonce) rmSync5(path, { force: true });
3361
+ if (readDescriptor(path)?.nonce === nonce) rmSync7(path, { force: true });
1930
3362
  };
1931
3363
  const idle = setTimeout(close, IDLE_MS);
1932
3364
  process.once("SIGTERM", close);
1933
3365
  process.once("SIGINT", close);
1934
- await new Promise((resolve3, reject) => {
3366
+ await new Promise((resolve4, reject) => {
1935
3367
  server.once("error", reject);
1936
- server.listen(0, "127.0.0.1", resolve3);
3368
+ server.listen(0, "127.0.0.1", resolve4);
1937
3369
  });
1938
3370
  const address = server.address();
1939
3371
  if (!address || typeof address === "string") throw new Error("Invalid broker address");
@@ -1944,27 +3376,27 @@ async function startMachineBroker() {
1944
3376
  }
1945
3377
 
1946
3378
  // src/daemon/principal.ts
1947
- import { createHash as createHash5 } from "crypto";
3379
+ import { createHash as createHash8 } from "crypto";
1948
3380
 
1949
3381
  // src/lib/credentials.ts
1950
- import { createHash as createHash4 } from "crypto";
1951
- import { readFileSync as readFileSync6 } from "fs";
1952
- import { join as join7 } from "path";
3382
+ import { createHash as createHash7 } from "crypto";
3383
+ import { readFileSync as readFileSync8 } from "fs";
3384
+ import { join as join11 } from "path";
1953
3385
  var CONFIG_DIRECTORY = primConfigDirectory();
1954
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1955
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1956
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1957
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1958
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1959
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1960
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1961
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3386
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
3387
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
3388
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
3389
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
3390
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
3391
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
3392
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
3393
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
1962
3394
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1963
3395
  var CREDENTIAL_MIGRATION_VERSION = 1;
1964
3396
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1965
3397
  function readTrimmed(path) {
1966
3398
  try {
1967
- const value = readFileSync6(path, "utf8").trim();
3399
+ const value = readFileSync8(path, "utf8").trim();
1968
3400
  return value || void 0;
1969
3401
  } catch {
1970
3402
  return void 0;
@@ -1986,22 +3418,22 @@ function resolveAuthCredential(options = {}) {
1986
3418
  );
1987
3419
  if (metadata.state === "legacy_broker") {
1988
3420
  if (metadata.metadata) {
1989
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1990
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3421
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3422
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1991
3423
  return void 0;
1992
3424
  }
1993
3425
  }
1994
3426
  return { token: stored, source: "token_file" };
1995
3427
  }
1996
3428
  if (metadata.state === "invalid") return void 0;
1997
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1998
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3429
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3430
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1999
3431
  return void 0;
2000
3432
  }
2001
3433
  return { token: stored, source: "token_file" };
2002
3434
  }
2003
3435
  function credentialFingerprint(value) {
2004
- return createHash4("sha256").update(value).digest("hex");
3436
+ return createHash7("sha256").update(value).digest("hex");
2005
3437
  }
2006
3438
  function parseLegacyBrokerCredentialMetadata(value) {
2007
3439
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -2021,7 +3453,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
2021
3453
  function readBoundedCredentialJson(path) {
2022
3454
  let raw;
2023
3455
  try {
2024
- raw = readFileSync6(path, "utf8");
3456
+ raw = readFileSync8(path, "utf8");
2025
3457
  } catch (error) {
2026
3458
  return error.code === "ENOENT" ? void 0 : null;
2027
3459
  }
@@ -2098,25 +3530,25 @@ var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
2098
3530
  function boundedClaim(value) {
2099
3531
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
2100
3532
  }
2101
- function sha256(value) {
2102
- return createHash5("sha256").update(value).digest("hex");
3533
+ function sha2562(value) {
3534
+ return createHash8("sha256").update(value).digest("hex");
2103
3535
  }
2104
3536
  function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
2105
3537
  if (hasMachineConfiguration()) {
2106
3538
  const machine = machineContext();
2107
3539
  return machine ? `${machine.generation}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}` : void 0;
2108
3540
  }
2109
- return token ? sha256(token) : void 0;
3541
+ return token ? sha2562(token) : void 0;
2110
3542
  }
2111
3543
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
2112
3544
  if (hasMachineConfiguration()) {
2113
3545
  const machine = machineContext();
2114
3546
  return machine ? {
2115
- principalId: sha256(
3547
+ principalId: sha2562(
2116
3548
  `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
2117
3549
  ),
2118
3550
  organizationId: machine.workosOrganizationId,
2119
- credentialFingerprint: sha256(machine.generation)
3551
+ credentialFingerprint: sha2562(machine.generation)
2120
3552
  } : void 0;
2121
3553
  }
2122
3554
  if (!token) return void 0;
@@ -2126,9 +3558,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
2126
3558
  if (!(subject && organizationId)) return void 0;
2127
3559
  const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
2128
3560
  return {
2129
- principalId: sha256(`${issuer}\0${subject}`),
3561
+ principalId: sha2562(`${issuer}\0${subject}`),
2130
3562
  organizationId,
2131
- credentialFingerprint: sha256(token)
3563
+ credentialFingerprint: sha2562(token)
2132
3564
  };
2133
3565
  }
2134
3566
  function isDaemonPrincipal(value) {
@@ -2182,10 +3614,10 @@ function parseDaemonResponseEnvelope(value) {
2182
3614
  }
2183
3615
 
2184
3616
  // src/daemon/server.ts
2185
- import { chmodSync as chmodSync8, existsSync as existsSync12, mkdirSync as mkdirSync10, readFileSync as readFileSync15, unlinkSync as unlinkSync3 } from "fs";
3617
+ import { chmodSync as chmodSync9, existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync16, unlinkSync as unlinkSync3 } from "fs";
2186
3618
  import { createServer as createServer2 } from "net";
2187
- import { join as join20 } from "path";
2188
- import { fileURLToPath as fileURLToPath4 } from "url";
3619
+ import { join as join23 } from "path";
3620
+ import { fileURLToPath as fileURLToPath5 } from "url";
2189
3621
 
2190
3622
  // src/decisions/identity.ts
2191
3623
  var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
@@ -2265,14 +3697,14 @@ function publicDecisionResponse(value) {
2265
3697
  }
2266
3698
 
2267
3699
  // src/client.ts
2268
- import { createHash as createHash6 } from "crypto";
2269
- import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
2270
- import { dirname as dirname5 } from "path";
3700
+ import { createHash as createHash9 } from "crypto";
3701
+ import { chmodSync as chmodSync4, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
3702
+ import { dirname as dirname8 } from "path";
2271
3703
 
2272
3704
  // src/daemon/client-instance-id.ts
2273
- import { randomBytes as randomBytes4 } from "crypto";
2274
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
2275
- import { join as join8 } from "path";
3705
+ import { randomBytes as randomBytes5 } from "crypto";
3706
+ import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync9 } from "fs";
3707
+ import { join as join12 } from "path";
2276
3708
  var CONFIG_DIRECTORY_MODE = 448;
2277
3709
  var INSTANCE_FILE_MODE = 384;
2278
3710
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -2285,17 +3717,17 @@ function isClientInstanceId(value) {
2285
3717
  }
2286
3718
  function ensurePrivateConfigDirectory(configDir) {
2287
3719
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
2288
- const metadata = lstatSync4(configDir);
3720
+ const metadata = lstatSync6(configDir);
2289
3721
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
2290
3722
  throw new Error("prim config path must be a private directory");
2291
3723
  }
2292
- chmodSync2(configDir, CONFIG_DIRECTORY_MODE);
3724
+ chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
2293
3725
  syncDirectory(configDir);
2294
3726
  }
2295
3727
  function readExisting(path) {
2296
3728
  let metadata;
2297
3729
  try {
2298
- metadata = lstatSync4(path);
3730
+ metadata = lstatSync6(path);
2299
3731
  } catch (error) {
2300
3732
  if (error.code === "ENOENT") {
2301
3733
  return;
@@ -2305,11 +3737,11 @@ function readExisting(path) {
2305
3737
  if (!metadata.isFile() || metadata.isSymbolicLink()) {
2306
3738
  throw new Error("stored client instance identity is invalid");
2307
3739
  }
2308
- chmodSync2(path, INSTANCE_FILE_MODE);
3740
+ chmodSync3(path, INSTANCE_FILE_MODE);
2309
3741
  if (metadata.size > MAX_STORED_BYTES) {
2310
3742
  throw new Error("stored client instance identity is invalid");
2311
3743
  }
2312
- const raw = readFileSync7(path, "utf8");
3744
+ const raw = readFileSync9(path, "utf8");
2313
3745
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
2314
3746
  if (raw !== value && raw !== `${value}
2315
3747
  ` || !isClientInstanceId(value)) {
@@ -2323,8 +3755,8 @@ function atomicWrite(path, value) {
2323
3755
  }
2324
3756
  async function getOrCreateClientInstanceId(options) {
2325
3757
  const configDir = options.configDir;
2326
- const path = join8(configDir, "client_instance_id");
2327
- const lockPath = join8(configDir, "client-instance.lock");
3758
+ const path = join12(configDir, "client_instance_id");
3759
+ const lockPath = join12(configDir, "client-instance.lock");
2328
3760
  ensurePrivateConfigDirectory(configDir);
2329
3761
  return withFileLock(
2330
3762
  lockPath,
@@ -2333,7 +3765,7 @@ async function getOrCreateClientInstanceId(options) {
2333
3765
  if (existing !== void 0) {
2334
3766
  return existing;
2335
3767
  }
2336
- const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
3768
+ const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
2337
3769
  "base64url"
2338
3770
  )}`;
2339
3771
  if (!isClientInstanceId(generated)) {
@@ -2368,60 +3800,18 @@ async function ingestUploaderHeaders() {
2368
3800
  return headers;
2369
3801
  }
2370
3802
 
2371
- // src/lib/terminal-safe.ts
2372
- function replaceIsolatedSurrogates(value) {
2373
- let out = "";
2374
- for (let index = 0; index < value.length; index += 1) {
2375
- const unit = value.charCodeAt(index);
2376
- if (unit >= 55296 && unit <= 56319) {
2377
- const next = value.charCodeAt(index + 1);
2378
- if (next >= 56320 && next <= 57343) {
2379
- out += value[index] + value[index + 1];
2380
- index += 1;
2381
- } else {
2382
- out += "\uFFFD";
2383
- }
2384
- } else if (unit >= 56320 && unit <= 57343) {
2385
- out += "\uFFFD";
2386
- } else {
2387
- out += value[index];
2388
- }
2389
- }
2390
- return out;
2391
- }
2392
- function isUnsafeTerminalCodePoint(point) {
2393
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
2394
- const bidiOrZeroWidth = point === 173 || // soft hyphen
2395
- point === 1564 || // Arabic letter mark
2396
- point === 6158 || // Mongolian vowel separator
2397
- point >= 8203 && point <= 8207 || // zero-width + directional marks
2398
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
2399
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
2400
- point >= 65529 && point <= 65531 || // interlinear annotation controls
2401
- point === 65279 || // zero-width no-break space / BOM
2402
- point >= 917504 && point <= 917631;
2403
- return c0OrC1 || bidiOrZeroWidth;
2404
- }
2405
- function terminalSafeText(value) {
2406
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
2407
- }
2408
- function terminalSafeLine(value) {
2409
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
2410
- }
2411
- var stripControlChars = terminalSafeText;
2412
-
2413
3803
  // src/client.ts
2414
3804
  var CONFIG_DIR_MODE = 448;
2415
3805
  var CREDENTIAL_FILE_MODE = 384;
2416
3806
  var REFRESH_THRESHOLD_MS = 6e4;
2417
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3807
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
2418
3808
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
2419
3809
  function authExpiredMessage() {
2420
3810
  return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
2421
3811
  }
2422
3812
  function readTrimmed2(path) {
2423
3813
  try {
2424
- const value = readFileSync8(path, "utf8").trim();
3814
+ const value = readFileSync10(path, "utf8").trim();
2425
3815
  return value || void 0;
2426
3816
  } catch {
2427
3817
  return void 0;
@@ -2431,23 +3821,23 @@ function getSiteUrl() {
2431
3821
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
2432
3822
  }
2433
3823
  function getSiteUrlForEnvironment(primApiUrl) {
2434
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3824
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
2435
3825
  }
2436
3826
  function expiresAtFor(token, expiresIn) {
2437
3827
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
2438
3828
  }
2439
3829
  function ensureConfigDirectory() {
2440
- const directory = dirname5(TOKEN_FILE_PATH);
2441
- mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
2442
- chmodSync3(directory, CONFIG_DIR_MODE);
3830
+ const directory = dirname8(TOKEN_FILE_PATH);
3831
+ mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
3832
+ chmodSync4(directory, CONFIG_DIR_MODE);
2443
3833
  }
2444
3834
  function atomicWrite2(path, content) {
2445
3835
  ensureConfigDirectory();
2446
3836
  atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
2447
3837
  }
2448
3838
  function removeCredentialFile(path) {
2449
- if (!existsSync4(path)) return false;
2450
- rmSync6(path, { force: true });
3839
+ if (!existsSync6(path)) return false;
3840
+ rmSync8(path, { force: true });
2451
3841
  return true;
2452
3842
  }
2453
3843
  function getTokenExpiresAt() {
@@ -2462,23 +3852,23 @@ function isTokenExpiringSoon(credential) {
2462
3852
  const expiresAt = getTokenExpiresAt();
2463
3853
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
2464
3854
  }
2465
- function refreshFingerprint(refreshToken2) {
2466
- return createHash6("sha256").update(refreshToken2).digest("hex");
3855
+ function refreshFingerprint(refreshToken3) {
3856
+ return createHash9("sha256").update(refreshToken3).digest("hex");
2467
3857
  }
2468
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3858
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
2469
3859
  return {
2470
3860
  version: 1,
2471
3861
  family: "legacy_broker",
2472
3862
  accessTokenHash: refreshFingerprint(accessToken),
2473
- refreshTokenHash: refreshFingerprint(refreshToken2)
3863
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2474
3864
  };
2475
3865
  }
2476
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3866
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
2477
3867
  const hashes = {
2478
3868
  accessTokenHash: refreshFingerprint(accessToken),
2479
- refreshTokenHash: refreshFingerprint(refreshToken2)
3869
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2480
3870
  };
2481
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3871
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
2482
3872
  }
2483
3873
  function writeCredentialMigrationSentinel() {
2484
3874
  atomicWrite2(
@@ -2490,11 +3880,11 @@ function writeCredentialMigrationSentinel() {
2490
3880
  `
2491
3881
  );
2492
3882
  }
2493
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
2494
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3883
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3884
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
2495
3885
  return { state: "invalid" };
2496
3886
  }
2497
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3887
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2498
3888
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
2499
3889
  return { state: "invalid" };
2500
3890
  }
@@ -2511,17 +3901,17 @@ function preserveMarkerlessLegacyGeneration() {
2511
3901
  const metadata = readStoredCredentialMetadata();
2512
3902
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
2513
3903
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
2514
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
2515
- if (!(accessToken && refreshToken2)) return;
2516
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3904
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3905
+ if (!(accessToken && refreshToken3)) return;
3906
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2517
3907
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2518
3908
  `);
2519
3909
  }
2520
3910
  function terminalFingerprint() {
2521
3911
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2522
3912
  }
2523
- function writeTerminalFingerprint(refreshToken2) {
2524
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3913
+ function writeTerminalFingerprint(refreshToken3) {
3914
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2525
3915
  `);
2526
3916
  }
2527
3917
  function clearTerminalFingerprint() {
@@ -2530,20 +3920,20 @@ function clearTerminalFingerprint() {
2530
3920
  function isSessionEnded() {
2531
3921
  if (hasMachineConfiguration()) return machineSessionEnded();
2532
3922
  if (resolveAuthCredential()?.source !== "token_file") return false;
2533
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3923
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2534
3924
  const ended = terminalFingerprint();
2535
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3925
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2536
3926
  }
2537
3927
  function withCredentialLock(operation, options = {}) {
2538
3928
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2539
3929
  }
2540
3930
  function commitCredentialsUnlocked(credentials) {
2541
3931
  const accessToken = credentials.accessToken.trim();
2542
- const refreshToken2 = credentials.refreshToken.trim();
2543
- if (!accessToken || !refreshToken2) {
3932
+ const refreshToken3 = credentials.refreshToken.trim();
3933
+ if (!accessToken || !refreshToken3) {
2544
3934
  throw new Error("OAuth credentials require both access and refresh tokens");
2545
3935
  }
2546
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3936
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2547
3937
  if (credentials.metadata !== void 0) {
2548
3938
  preserveMarkerlessLegacyGeneration();
2549
3939
  writeCredentialMigrationSentinel();
@@ -2551,10 +3941,10 @@ function commitCredentialsUnlocked(credentials) {
2551
3941
  `);
2552
3942
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2553
3943
  `);
2554
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3944
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2555
3945
  `);
2556
3946
  } else {
2557
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3947
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2558
3948
  `);
2559
3949
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2560
3950
  `);
@@ -2591,15 +3981,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2591
3981
  `
2592
3982
  );
2593
3983
  }
2594
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3984
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2595
3985
  const current = readStoredCredentialMetadata();
2596
3986
  if (expected.state === "legacy_broker") {
2597
3987
  if (current.state !== "legacy_broker") return false;
2598
3988
  if (!expected.metadata) return current.metadata === void 0;
2599
- 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;
3989
+ 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;
2600
3990
  }
2601
3991
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2602
- 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;
3992
+ 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;
2603
3993
  }
2604
3994
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2605
3995
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2768,7 +4158,7 @@ async function performTokenRefresh(options = {}) {
2768
4158
  );
2769
4159
  }
2770
4160
  var _refreshInFlight;
2771
- function refreshToken(options = {}) {
4161
+ function refreshToken2(options = {}) {
2772
4162
  if (hasMachineConfiguration())
2773
4163
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2774
4164
  if (_refreshInFlight) return _refreshInFlight;
@@ -2906,7 +4296,7 @@ async function machineClient(options = {}, management = false) {
2906
4296
  if (response.status === 401)
2907
4297
  throw new HttpError(
2908
4298
  401,
2909
- 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(
4299
+ 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(
2910
4300
  "Machine access was rejected. Ask your administrator to check or rotate its credentials."
2911
4301
  )
2912
4302
  );
@@ -2927,7 +4317,7 @@ async function request2(method, path, body, options) {
2927
4317
  let refreshAttempted = false;
2928
4318
  if (credential && isTokenExpiringSoon(credential)) {
2929
4319
  refreshAttempted = true;
2930
- const token = await refreshToken({
4320
+ const token = await refreshToken2({
2931
4321
  signal: options?.signal,
2932
4322
  quiet: options?.quietRefresh
2933
4323
  });
@@ -2946,7 +4336,7 @@ async function request2(method, path, body, options) {
2946
4336
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2947
4337
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2948
4338
  refreshAttempted = true;
2949
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4339
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2950
4340
  }
2951
4341
  if (retryToken) {
2952
4342
  _cachedCredential = {
@@ -2970,7 +4360,7 @@ async function getPinnedClient(options = {}) {
2970
4360
  const siteUrl = getSiteUrl();
2971
4361
  let credential = selectedCredential();
2972
4362
  if (credential && isTokenExpiringSoon(credential)) {
2973
- const token2 = await refreshToken({
4363
+ const token2 = await refreshToken2({
2974
4364
  signal: options.signal,
2975
4365
  quiet: options.quietRefresh
2976
4366
  });
@@ -2988,66 +4378,66 @@ async function getPinnedClient(options = {}) {
2988
4378
  }
2989
4379
 
2990
4380
  // src/flusher.ts
2991
- import { createReadStream, renameSync as renameSync3, statSync as statSync2, unlinkSync } from "fs";
2992
- import { dirname as dirname10, join as join16 } from "path";
4381
+ import { createReadStream, renameSync as renameSync4, statSync as statSync3, unlinkSync } from "fs";
4382
+ import { dirname as dirname12, join as join19 } from "path";
2993
4383
 
2994
4384
  // src/dead-letter.ts
2995
- import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
4385
+ import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
2996
4386
  import {
2997
- constants as constants2,
2998
- chmodSync as chmodSync4,
4387
+ constants as constants3,
4388
+ chmodSync as chmodSync5,
2999
4389
  closeSync as closeSync2,
3000
- existsSync as existsSync5,
4390
+ existsSync as existsSync7,
3001
4391
  fchmodSync as fchmodSync2,
3002
4392
  fsyncSync as fsyncSync2,
3003
- mkdirSync as mkdirSync5,
4393
+ mkdirSync as mkdirSync6,
3004
4394
  openSync as openSync2,
3005
- renameSync as renameSync2,
3006
- rmSync as rmSync7,
3007
- writeFileSync as writeFileSync4
4395
+ renameSync as renameSync3,
4396
+ rmSync as rmSync9,
4397
+ writeFileSync as writeFileSync5
3008
4398
  } from "fs";
3009
- import { dirname as dirname6, join as join10 } from "path";
4399
+ import { dirname as dirname9, join as join14 } from "path";
3010
4400
  var DIRECTORY_MODE2 = 448;
3011
4401
  var FILE_MODE2 = 384;
3012
4402
  var DEAD_LETTER_DIRNAME = "dead-letter";
3013
4403
  function deadLetterDirectoryForRotation(flushingPath) {
3014
- return join10(dirname6(flushingPath), DEAD_LETTER_DIRNAME);
4404
+ return join14(dirname9(flushingPath), DEAD_LETTER_DIRNAME);
3015
4405
  }
3016
4406
  function deadLetterPathForRawLine(flushingPath, rawLine) {
3017
- const quarantineId = createHash7("sha256").update(rawLine).digest("hex");
3018
- return join10(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
4407
+ const quarantineId = createHash10("sha256").update(rawLine).digest("hex");
4408
+ return join14(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
3019
4409
  }
3020
4410
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
3021
4411
  const directory = deadLetterDirectoryForRotation(flushingPath);
3022
- mkdirSync5(directory, { recursive: true, mode: DIRECTORY_MODE2 });
3023
- chmodSync4(directory, DIRECTORY_MODE2);
3024
- persistDirectory(dirname6(directory));
4412
+ mkdirSync6(directory, { recursive: true, mode: DIRECTORY_MODE2 });
4413
+ chmodSync5(directory, DIRECTORY_MODE2);
4414
+ persistDirectory(dirname9(directory));
3025
4415
  return directory;
3026
4416
  }
3027
4417
  function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
3028
- if (existsSync5(path)) {
4418
+ if (existsSync7(path)) {
3029
4419
  persistDirectory(directory);
3030
4420
  return;
3031
4421
  }
3032
- const temporaryPath = join10(
4422
+ const temporaryPath = join14(
3033
4423
  directory,
3034
- `.${quarantineId}.${String(process.pid)}.${randomBytes5(8).toString("hex")}.tmp`
4424
+ `.${quarantineId}.${String(process.pid)}.${randomBytes6(8).toString("hex")}.tmp`
3035
4425
  );
3036
- const flags = constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW;
4426
+ const flags = constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW;
3037
4427
  try {
3038
4428
  const fd = openSync2(temporaryPath, flags, FILE_MODE2);
3039
4429
  try {
3040
4430
  fchmodSync2(fd, FILE_MODE2);
3041
- writeFileSync4(fd, `${JSON.stringify(record)}
4431
+ writeFileSync5(fd, `${JSON.stringify(record)}
3042
4432
  `, "utf8");
3043
4433
  fsyncSync2(fd);
3044
4434
  } finally {
3045
4435
  closeSync2(fd);
3046
4436
  }
3047
- renameSync2(temporaryPath, path);
4437
+ renameSync3(temporaryPath, path);
3048
4438
  persistDirectory(directory);
3049
4439
  } finally {
3050
- rmSync7(temporaryPath, { force: true });
4440
+ rmSync9(temporaryPath, { force: true });
3051
4441
  }
3052
4442
  }
3053
4443
  function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
@@ -3056,12 +4446,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
3056
4446
  const serializedMove = JSON.stringify(move);
3057
4447
  const record = {
3058
4448
  version: 1,
3059
- quarantineId: createHash7("sha256").update(serializedMove).digest("hex"),
4449
+ quarantineId: createHash10("sha256").update(serializedMove).digest("hex"),
3060
4450
  quarantinedAt: now(),
3061
4451
  reason,
3062
4452
  move
3063
4453
  };
3064
- const path = join10(directory, `${record.quarantineId}.json`);
4454
+ const path = join14(directory, `${record.quarantineId}.json`);
3065
4455
  persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
3066
4456
  return record;
3067
4457
  }
@@ -3072,7 +4462,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
3072
4462
  const record = {
3073
4463
  version: 1,
3074
4464
  recordKind: "raw_line_v1",
3075
- quarantineId: createHash7("sha256").update(bytes).digest("hex"),
4465
+ quarantineId: createHash10("sha256").update(bytes).digest("hex"),
3076
4466
  quarantinedAt: now(),
3077
4467
  reason: "invalid_move",
3078
4468
  rawLineEncoding: "base64",
@@ -3091,14 +4481,14 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
3091
4481
 
3092
4482
  // src/drain-progress.ts
3093
4483
  import {
3094
- chmodSync as chmodSync5,
3095
- existsSync as existsSync6,
3096
- readFileSync as readFileSync9,
3097
- readdirSync as readdirSync2,
3098
- rmSync as rmSync8,
4484
+ chmodSync as chmodSync6,
4485
+ existsSync as existsSync8,
4486
+ readFileSync as readFileSync11,
4487
+ readdirSync as readdirSync3,
4488
+ rmSync as rmSync10,
3099
4489
  rmdirSync
3100
4490
  } from "fs";
3101
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
4491
+ import { basename as basename3, dirname as dirname10, join as join15 } from "path";
3102
4492
  var DIRECTORY_MODE3 = 448;
3103
4493
  var FILE_MODE3 = 384;
3104
4494
  var DRAIN_PROGRESS_DIRNAME = "drain-progress";
@@ -3107,10 +4497,10 @@ function rotationIdentity(stat) {
3107
4497
  return { size: stat.size, ino: stat.ino, dev: stat.dev };
3108
4498
  }
3109
4499
  function drainProgressDirectory(flushingPath) {
3110
- return join11(dirname7(flushingPath), DRAIN_PROGRESS_DIRNAME);
4500
+ return join15(dirname10(flushingPath), DRAIN_PROGRESS_DIRNAME);
3111
4501
  }
3112
4502
  function drainProgressPath(flushingPath) {
3113
- return join11(drainProgressDirectory(flushingPath), `${basename2(flushingPath)}.json`);
4503
+ return join15(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
3114
4504
  }
3115
4505
  function isByteCount(value) {
3116
4506
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -3118,7 +4508,7 @@ function isByteCount(value) {
3118
4508
  function drainResumeOffset(flushingPath, rotation) {
3119
4509
  let parsed;
3120
4510
  try {
3121
- parsed = JSON.parse(readFileSync9(drainProgressPath(flushingPath), "utf8"));
4511
+ parsed = JSON.parse(readFileSync11(drainProgressPath(flushingPath), "utf8"));
3122
4512
  } catch {
3123
4513
  return 0;
3124
4514
  }
@@ -3134,7 +4524,7 @@ function drainResumeOffset(flushingPath, rotation) {
3134
4524
  function writeDrainCheckpoint(flushingPath, checkpoint) {
3135
4525
  const directory = drainProgressDirectory(flushingPath);
3136
4526
  ensureDurableDirectory(directory, DIRECTORY_MODE3);
3137
- chmodSync5(directory, DIRECTORY_MODE3);
4527
+ chmodSync6(directory, DIRECTORY_MODE3);
3138
4528
  atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
3139
4529
  `, {
3140
4530
  mode: FILE_MODE3
@@ -3151,24 +4541,24 @@ function removeEmptyDirectory(directory) {
3151
4541
  }
3152
4542
  }
3153
4543
  function removeDrainCheckpoint(flushingPath) {
3154
- rmSync8(drainProgressPath(flushingPath), { force: true });
4544
+ rmSync10(drainProgressPath(flushingPath), { force: true });
3155
4545
  removeEmptyDirectory(drainProgressDirectory(flushingPath));
3156
4546
  }
3157
4547
  function sweepOrphanedDrainCheckpoints(bucketDirectory) {
3158
- const directory = join11(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
4548
+ const directory = join15(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
3159
4549
  let names;
3160
4550
  try {
3161
- names = readdirSync2(directory);
4551
+ names = readdirSync3(directory);
3162
4552
  } catch {
3163
4553
  return;
3164
4554
  }
3165
4555
  for (const name of names) {
3166
4556
  const rotation = CHECKPOINT_NAME.exec(name)?.[1];
3167
- if (rotation === void 0 || existsSync6(join11(bucketDirectory, rotation))) {
4557
+ if (rotation === void 0 || existsSync8(join15(bucketDirectory, rotation))) {
3168
4558
  continue;
3169
4559
  }
3170
4560
  try {
3171
- rmSync8(join11(directory, name), { force: true });
4561
+ rmSync10(join15(directory, name), { force: true });
3172
4562
  } catch {
3173
4563
  }
3174
4564
  }
@@ -29865,38 +31255,38 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29865
31255
 
29866
31256
  // src/lib/activation.ts
29867
31257
  import { execFileSync as execFileSync4 } from "child_process";
29868
- import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
31258
+ import { existsSync as existsSync10, readFileSync as readFileSync13 } from "fs";
29869
31259
  import { homedir as homedir2 } from "os";
29870
- import { join as join14 } from "path";
31260
+ import { join as join17 } from "path";
29871
31261
 
29872
31262
  // src/lib/cloud-prepared.ts
29873
- import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync10, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
29874
- import { join as join12 } from "path";
31263
+ import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync12, rmSync as rmSync11, writeFileSync as writeFileSync6 } from "fs";
31264
+ import { join as join16 } from "path";
29875
31265
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
29876
31266
  function cloudPreparedPath(env = process.env) {
29877
- return join12(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
31267
+ return join16(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
29878
31268
  }
29879
31269
  function isPreparedCloudSession(env = process.env) {
29880
31270
  if (!isClaudeCloudSession(env)) return false;
29881
31271
  try {
29882
- return existsSync7(cloudPreparedPath(env));
31272
+ return existsSync9(cloudPreparedPath(env));
29883
31273
  } catch {
29884
31274
  return false;
29885
31275
  }
29886
31276
  }
29887
31277
 
29888
31278
  // src/lib/demo-pause.ts
29889
- import { execFileSync as execFileSync2 } from "child_process";
31279
+ import { execFileSync as execFileSync3 } from "child_process";
29890
31280
  var DEMO_PAUSE_MS = 30 * 6e4;
29891
31281
  var PAUSE_KEY = "prim.demoPause";
29892
- var GIT_TIMEOUT_MS = 1e3;
29893
- function git(cwd, args) {
31282
+ var GIT_TIMEOUT_MS3 = 1e3;
31283
+ function git2(cwd, args) {
29894
31284
  try {
29895
- return execFileSync2("git", args, {
31285
+ return execFileSync3("git", args, {
29896
31286
  cwd,
29897
31287
  encoding: "utf-8",
29898
31288
  stdio: ["ignore", "pipe", "ignore"],
29899
- timeout: GIT_TIMEOUT_MS
31289
+ timeout: GIT_TIMEOUT_MS3
29900
31290
  });
29901
31291
  } catch {
29902
31292
  return void 0;
@@ -29904,10 +31294,10 @@ function git(cwd, args) {
29904
31294
  }
29905
31295
  function setLocal(cwd, key, value) {
29906
31296
  try {
29907
- execFileSync2(
31297
+ execFileSync3(
29908
31298
  "git",
29909
31299
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
29910
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
31300
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
29911
31301
  );
29912
31302
  } catch (error) {
29913
31303
  if (value !== null || error.status !== 5) throw error;
@@ -29921,7 +31311,7 @@ function parsePause(value) {
29921
31311
  function readCaptureConfig(cwd) {
29922
31312
  let active;
29923
31313
  let pause;
29924
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
31314
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
29925
31315
  for (const line of out.split("\n")) {
29926
31316
  const space = line.indexOf(" ");
29927
31317
  const key = line.slice(0, space).toLowerCase();
@@ -29946,121 +31336,13 @@ function healDemoPause(cwd, pause, options = {}) {
29946
31336
  }
29947
31337
  }
29948
31338
 
29949
- // src/lib/git.ts
29950
- import { execFileSync as execFileSync3 } from "child_process";
29951
- import { createHash as createHash8 } from "crypto";
29952
- import { lstatSync as lstatSync5, readFileSync as readFileSync11, realpathSync } from "fs";
29953
- import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, join as join13, relative, resolve as resolve2, sep } from "path";
29954
- var GIT_TIMEOUT_MS2 = 1e3;
29955
- var MAX_SETTINGS_BYTES = 1024 * 1024;
29956
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
29957
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
29958
- function gitToplevel(cwd) {
29959
- try {
29960
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
29961
- cwd,
29962
- encoding: "utf-8",
29963
- stdio: ["ignore", "pipe", "ignore"],
29964
- timeout: GIT_TIMEOUT_MS2
29965
- }).trim();
29966
- } catch {
29967
- return null;
29968
- }
29969
- }
29970
- function gitValue(cwd, args) {
29971
- try {
29972
- const value = execFileSync3("git", args, {
29973
- cwd,
29974
- encoding: "utf-8",
29975
- stdio: ["ignore", "pipe", "ignore"],
29976
- timeout: GIT_TIMEOUT_MS2
29977
- }).trim();
29978
- return value || void 0;
29979
- } catch {
29980
- return void 0;
29981
- }
29982
- }
29983
- function parseGithubRepositoryName(path) {
29984
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
29985
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
29986
- return null;
29987
- }
29988
- return `${parts[0]}/${parts[1]}`;
29989
- }
29990
- function githubRepositoryFromRemote(remote) {
29991
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
29992
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29993
- remote
29994
- );
29995
- const path = match?.[1] ?? match?.[2];
29996
- return path ? parseGithubRepositoryName(path) : null;
29997
- }
29998
- function checkoutSettingsText(repoRoot) {
29999
- const path = join13(repoRoot, ".claude", "settings.json");
30000
- try {
30001
- if (!lstatSync5(join13(repoRoot, ".claude")).isDirectory()) return null;
30002
- const stat = lstatSync5(path);
30003
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
30004
- return readFileSync11(path, "utf8");
30005
- } catch {
30006
- return null;
30007
- }
30008
- }
30009
- function checkoutDeclaration(repoRoot, name) {
30010
- const text = checkoutSettingsText(repoRoot);
30011
- if (text === null) return null;
30012
- let parsed;
30013
- try {
30014
- parsed = JSON.parse(text);
30015
- } catch {
30016
- return null;
30017
- }
30018
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
30019
- const value = typeof env === "object" && env !== null ? env[name] : void 0;
30020
- return typeof value === "string" ? value : null;
30021
- }
30022
- function declaredGithubRepository(repoRoot) {
30023
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
30024
- return value === null ? null : parseGithubRepositoryName(value.trim());
30025
- }
30026
- function githubRepositoryFullName(cwd) {
30027
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
30028
- if (remote) {
30029
- const fromOrigin = githubRepositoryFromRemote(remote);
30030
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
30031
- }
30032
- const root = gitToplevel(cwd);
30033
- return root ? declaredGithubRepository(root) : null;
30034
- }
30035
- function normalizeOriginRemote(remote) {
30036
- const value = remote.trim();
30037
- if (!value) return void 0;
30038
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
30039
- if (scp?.host && scp.path) {
30040
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30041
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
30042
- }
30043
- try {
30044
- const url = new URL(value);
30045
- url.username = "";
30046
- url.password = "";
30047
- url.search = "";
30048
- url.hash = "";
30049
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30050
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
30051
- return void 0;
30052
- } catch {
30053
- return void 0;
30054
- }
30055
- }
30056
-
30057
31339
  // src/lib/activation.ts
30058
31340
  var PRIM_ACTIVE_KEY = "prim.active";
30059
31341
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
30060
31342
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
30061
31343
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
30062
31344
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
30063
- var GIT_TIMEOUT_MS3 = 1e3;
31345
+ var GIT_TIMEOUT_MS4 = 1e3;
30064
31346
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
30065
31347
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
30066
31348
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -30070,7 +31352,7 @@ function repoActiveFlag(cwd, strict = false) {
30070
31352
  cwd,
30071
31353
  encoding: "utf-8",
30072
31354
  stdio: ["ignore", "pipe", "ignore"],
30073
- timeout: GIT_TIMEOUT_MS3
31355
+ timeout: GIT_TIMEOUT_MS4
30074
31356
  }).trim();
30075
31357
  if (value === "true") return "true";
30076
31358
  if (value === "false") return "false";
@@ -30091,7 +31373,7 @@ function localGitConfigValue(cwd, key) {
30091
31373
  cwd,
30092
31374
  encoding: "utf-8",
30093
31375
  stdio: ["ignore", "pipe", "ignore"],
30094
- timeout: GIT_TIMEOUT_MS3
31376
+ timeout: GIT_TIMEOUT_MS4
30095
31377
  }).trim();
30096
31378
  return value || void 0;
30097
31379
  } catch {
@@ -30102,7 +31384,7 @@ function setLocalGitConfigValue(cwd, key, value) {
30102
31384
  execFileSync4("git", ["config", "--local", key, value], {
30103
31385
  cwd,
30104
31386
  stdio: ["ignore", "ignore", "pipe"],
30105
- timeout: GIT_TIMEOUT_MS3
31387
+ timeout: GIT_TIMEOUT_MS4
30106
31388
  });
30107
31389
  }
30108
31390
  function repoSyncId(cwd) {
@@ -30123,10 +31405,10 @@ function repositoryBindingState(cwd) {
30123
31405
  function projectPrimInstallAt(root) {
30124
31406
  if (root === null || root === homedir2()) return false;
30125
31407
  for (const rel of PROJECT_INSTALL_FILES) {
30126
- const path = join14(root, rel);
30127
- if (existsSync8(path)) {
31408
+ const path = join17(root, rel);
31409
+ if (existsSync10(path)) {
30128
31410
  try {
30129
- const content = readFileSync12(path, "utf-8");
31411
+ const content = readFileSync13(path, "utf-8");
30130
31412
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
30131
31413
  } catch {
30132
31414
  }
@@ -30535,17 +31817,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
30535
31817
  import {
30536
31818
  appendFileSync,
30537
31819
  closeSync as closeSync3,
30538
- existsSync as existsSync9,
31820
+ existsSync as existsSync11,
30539
31821
  fstatSync,
30540
- mkdirSync as mkdirSync7,
31822
+ mkdirSync as mkdirSync8,
30541
31823
  openSync as openSync3,
30542
31824
  opendirSync,
30543
- readFileSync as readFileSync13,
31825
+ readFileSync as readFileSync14,
30544
31826
  readSync,
30545
- readdirSync as readdirSync3
31827
+ readdirSync as readdirSync4
30546
31828
  } from "fs";
30547
- import { dirname as dirname9, join as join15 } from "path";
30548
- var JOURNAL_DIR = join15(primConfigDirectory(), "moves");
31829
+ import { dirname as dirname11, join as join18 } from "path";
31830
+ var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
30549
31831
  var JOURNAL_BASENAME = "journal.ndjson";
30550
31832
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
30551
31833
  var PENDING_STATS_MAX_FILES = 128;
@@ -30557,7 +31839,7 @@ function envSlug(apiUrl) {
30557
31839
  return slug;
30558
31840
  }
30559
31841
  function currentEnvDir() {
30560
- return join15(JOURNAL_DIR, envSlug(getSiteUrl()));
31842
+ return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
30561
31843
  }
30562
31844
  function parseMoves(content) {
30563
31845
  const moves = [];
@@ -30575,15 +31857,15 @@ function parseMoves(content) {
30575
31857
  function listBuckets() {
30576
31858
  const out = [];
30577
31859
  const envDir = currentEnvDir();
30578
- if (!existsSync9(envDir)) {
31860
+ if (!existsSync11(envDir)) {
30579
31861
  return out;
30580
31862
  }
30581
- for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
31863
+ for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
30582
31864
  if (!entry.isDirectory()) {
30583
31865
  continue;
30584
31866
  }
30585
- const path = join15(envDir, entry.name, JOURNAL_BASENAME);
30586
- if (existsSync9(path)) {
31867
+ const path = join18(envDir, entry.name, JOURNAL_BASENAME);
31868
+ if (existsSync11(path)) {
30587
31869
  out.push({ bucket: entry.name, path });
30588
31870
  }
30589
31871
  }
@@ -30645,7 +31927,7 @@ function parseFlushingPid(name) {
30645
31927
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
30646
31928
  }
30647
31929
  function listFlushingInDir(dir, bucket, options = {}) {
30648
- if (!existsSync9(dir)) {
31930
+ if (!existsSync11(dir)) {
30649
31931
  return [];
30650
31932
  }
30651
31933
  const out = [];
@@ -30659,7 +31941,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
30659
31941
  entry = entries.readSync();
30660
31942
  continue;
30661
31943
  }
30662
- const path = join15(dir, entry.name);
31944
+ const path = join18(dir, entry.name);
30663
31945
  let sample;
30664
31946
  try {
30665
31947
  sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
@@ -30686,18 +31968,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
30686
31968
  }
30687
31969
  function listFlushing(options = {}) {
30688
31970
  const envDir = currentEnvDir();
30689
- if (!existsSync9(envDir)) {
31971
+ if (!existsSync11(envDir)) {
30690
31972
  return [];
30691
31973
  }
30692
31974
  const out = [];
30693
31975
  let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
30694
31976
  const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
30695
- for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
31977
+ for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
30696
31978
  if (out.length >= maxFiles) {
30697
31979
  break;
30698
31980
  }
30699
31981
  if (entry.isDirectory()) {
30700
- const found = listFlushingInDir(join15(envDir, entry.name), entry.name, {
31982
+ const found = listFlushingInDir(join18(envDir, entry.name), entry.name, {
30701
31983
  sampleBytes: remainingBytes,
30702
31984
  maxFiles: maxFiles - out.length
30703
31985
  });
@@ -30712,12 +31994,12 @@ function listFlushing(options = {}) {
30712
31994
  }
30713
31995
  function sweepOrphanedDrainProgress() {
30714
31996
  const envDir = currentEnvDir();
30715
- if (!existsSync9(envDir)) {
31997
+ if (!existsSync11(envDir)) {
30716
31998
  return;
30717
31999
  }
30718
- for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
32000
+ for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
30719
32001
  if (entry.isDirectory()) {
30720
- sweepOrphanedDrainCheckpoints(join15(envDir, entry.name));
32002
+ sweepOrphanedDrainCheckpoints(join18(envDir, entry.name));
30721
32003
  }
30722
32004
  }
30723
32005
  }
@@ -30870,7 +32152,7 @@ async function* rawJournalLines(input, offset) {
30870
32152
  }
30871
32153
  var drainProgressWarned = false;
30872
32154
  async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
30873
- const rotation = rotationIdentity(statSync2(flushingPath));
32155
+ const rotation = rotationIdentity(statSync3(flushingPath));
30874
32156
  const resumeAt = drainResumeOffset(flushingPath, rotation);
30875
32157
  const recordProgress = (end) => {
30876
32158
  if (end === void 0 || end >= rotation.size) {
@@ -30997,7 +32279,7 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
30997
32279
  async function drainPath(path, client2, binding, onProgress) {
30998
32280
  const tmpPath = `${path}.flushing.${String(Date.now())}.${String(process.pid)}`;
30999
32281
  try {
31000
- renameSync3(path, tmpPath);
32282
+ renameSync4(path, tmpPath);
31001
32283
  } catch (err) {
31002
32284
  if (err.code === "ENOENT") {
31003
32285
  return { flushed: 0, quarantined: 0 };
@@ -31045,12 +32327,12 @@ async function recoverOrphans(candidates, options) {
31045
32327
  if (summary.failedBuckets.has(file.bucket)) {
31046
32328
  continue;
31047
32329
  }
31048
- const { counts, failure } = await settleDrain((onProgress) => drain(file.path, onProgress));
32330
+ const { counts, failure: failure2 } = await settleDrain((onProgress) => drain(file.path, onProgress));
31049
32331
  summary.flushed += counts.flushed;
31050
32332
  summary.quarantined += counts.quarantined;
31051
- if (failure) {
32333
+ if (failure2) {
31052
32334
  summary.failedDrainFlushed += counts.flushed;
31053
- summary.errors.push(failure.error);
32335
+ summary.errors.push(failure2.error);
31054
32336
  summary.failedBuckets.add(file.bucket);
31055
32337
  }
31056
32338
  }
@@ -31109,14 +32391,14 @@ async function flushOnce() {
31109
32391
  if (recovered.failedBuckets.has(bucket)) {
31110
32392
  continue;
31111
32393
  }
31112
- const { counts, failure } = await settleDrain(
32394
+ const { counts, failure: failure2 } = await settleDrain(
31113
32395
  (onProgress) => drainPath(path, client2, binding, onProgress)
31114
32396
  );
31115
32397
  total += counts.flushed;
31116
32398
  quarantined += counts.quarantined;
31117
- if (failure) {
32399
+ if (failure2) {
31118
32400
  failedDrainFlushed += counts.flushed;
31119
- errors.push(failure.error);
32401
+ errors.push(failure2.error);
31120
32402
  }
31121
32403
  }
31122
32404
  if (errors.length > 0) {
@@ -31131,7 +32413,7 @@ async function flushOnce() {
31131
32413
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
31132
32414
  }
31133
32415
  var flushInFlight;
31134
- var FLUSH_LOCK_PATH = join16(dirname10(JOURNAL_DIR), ".flush.lock");
32416
+ var FLUSH_LOCK_PATH = join19(dirname12(JOURNAL_DIR), ".flush.lock");
31135
32417
  var FLUSH_LOCK_TIMEOUT_MS = 250;
31136
32418
  function isFlushLockContended(error) {
31137
32419
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -31286,8 +32568,8 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
31286
32568
  var STATUSLINE_INGESTION_CACHE_TTL_MS = 3e4;
31287
32569
  var STATUSLINE_INGESTION_CACHE_MAX_ENTRIES = 256;
31288
32570
  var StatuslineIngestionCache = class {
31289
- constructor(resolve3, options = {}) {
31290
- this.resolve = resolve3;
32571
+ constructor(resolve4, options = {}) {
32572
+ this.resolve = resolve4;
31291
32573
  this.#now = options.now ?? Date.now;
31292
32574
  this.#ttlMs = options.ttlMs ?? STATUSLINE_INGESTION_CACHE_TTL_MS;
31293
32575
  this.#maxEntries = options.maxEntries ?? STATUSLINE_INGESTION_CACHE_MAX_ENTRIES;
@@ -31333,8 +32615,8 @@ var StatuslineIngestionCache = class {
31333
32615
 
31334
32616
  // src/daemon/client.ts
31335
32617
  import { createConnection } from "net";
31336
- import { join as join17 } from "path";
31337
- var SOCK_PATH = join17(primConfigDirectory(), "sock");
32618
+ import { join as join20 } from "path";
32619
+ var SOCK_PATH = join20(primConfigDirectory(), "sock");
31338
32620
  var DEFAULT_TIMEOUT_MS2 = 250;
31339
32621
  var nextRequestId = 1;
31340
32622
  function daemonRequest(method, params = {}, opts = {}) {
@@ -31347,7 +32629,7 @@ function daemonRequest(method, params = {}, opts = {}) {
31347
32629
  ...caller ? { caller } : {}
31348
32630
  };
31349
32631
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
31350
- return new Promise((resolve3) => {
32632
+ return new Promise((resolve4) => {
31351
32633
  let settled = false;
31352
32634
  let socket;
31353
32635
  let buffer = Buffer.alloc(0);
@@ -31362,7 +32644,7 @@ function daemonRequest(method, params = {}, opts = {}) {
31362
32644
  } catch {
31363
32645
  }
31364
32646
  }
31365
- resolve3(value);
32647
+ resolve4(value);
31366
32648
  };
31367
32649
  const timer = setTimeout(() => settle(null), timeoutMs);
31368
32650
  timer.unref();
@@ -31424,7 +32706,7 @@ function daemonRequest(method, params = {}, opts = {}) {
31424
32706
  }
31425
32707
 
31426
32708
  // src/daemon/decision-digest-cache.ts
31427
- import { randomBytes as randomBytes6 } from "crypto";
32709
+ import { randomBytes as randomBytes7 } from "crypto";
31428
32710
  var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
31429
32711
  var DECISION_DIGEST_CACHE_LIMIT = 100;
31430
32712
  var DECISION_DIGEST_CACHE_WINDOW = "24h";
@@ -31454,7 +32736,7 @@ function errorMessage(error) {
31454
32736
  return error instanceof Error ? error.message : String(error);
31455
32737
  }
31456
32738
  function privatePageToken() {
31457
- return randomBytes6(16).toString("hex");
32739
+ return randomBytes7(16).toString("hex");
31458
32740
  }
31459
32741
  var DecisionDigestCache = class {
31460
32742
  constructor(load, now = Date.now, options = {}) {
@@ -31605,8 +32887,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
31605
32887
  }
31606
32888
 
31607
32889
  // src/daemon/health.ts
31608
- import { chmodSync as chmodSync6, existsSync as existsSync10, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
31609
- import { dirname as dirname11, join as join18 } from "path";
32890
+ import { chmodSync as chmodSync7, existsSync as existsSync12, mkdirSync as mkdirSync9, renameSync as renameSync5, writeFileSync as writeFileSync7 } from "fs";
32891
+ import { dirname as dirname13, join as join21 } from "path";
31610
32892
  var CONFIG_DIR_MODE2 = 448;
31611
32893
  var HEALTH_FILE_MODE = 384;
31612
32894
  var INGESTION_SLA_MS = 3e4;
@@ -31614,7 +32896,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
31614
32896
  var HEARTBEAT_RETRY_CAP_MS = 3e4;
31615
32897
  var INGESTION_RETRY_BASE_MS = 5e3;
31616
32898
  var INGESTION_RETRY_CAP_MS = 15e3;
31617
- var DAEMON_HEALTH_PATH = join18(primConfigDirectory(), "daemon-health.json");
32899
+ var DAEMON_HEALTH_PATH = join21(primConfigDirectory(), "daemon-health.json");
31618
32900
  function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
31619
32901
  return {
31620
32902
  schemaVersion: 1,
@@ -31655,37 +32937,37 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
31655
32937
  return retryDelayMs(consecutiveFailures, INGESTION_RETRY_CAP_MS, random);
31656
32938
  }
31657
32939
  function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
31658
- const dir = dirname11(path);
31659
- if (!existsSync10(dir)) {
31660
- mkdirSync8(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
32940
+ const dir = dirname13(path);
32941
+ if (!existsSync12(dir)) {
32942
+ mkdirSync9(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
31661
32943
  }
31662
- const tmp = join18(dir, `.${process.pid}.daemon-health.tmp`);
31663
- writeFileSync6(tmp, `${JSON.stringify(state, null, 2)}
32944
+ const tmp = join21(dir, `.${process.pid}.daemon-health.tmp`);
32945
+ writeFileSync7(tmp, `${JSON.stringify(state, null, 2)}
31664
32946
  `, { mode: HEALTH_FILE_MODE });
31665
- chmodSync6(tmp, HEALTH_FILE_MODE);
31666
- renameSync4(tmp, path);
32947
+ chmodSync7(tmp, HEALTH_FILE_MODE);
32948
+ renameSync5(tmp, path);
31667
32949
  }
31668
32950
 
31669
32951
  // src/daemon/instance-lock.ts
31670
32952
  import { randomUUID as randomUUID3 } from "crypto";
31671
32953
  import {
31672
- chmodSync as chmodSync7,
31673
- existsSync as existsSync11,
31674
- mkdirSync as mkdirSync9,
31675
- readFileSync as readFileSync14,
31676
- renameSync as renameSync5,
31677
- rmSync as rmSync10,
31678
- statSync as statSync3,
32954
+ chmodSync as chmodSync8,
32955
+ existsSync as existsSync13,
32956
+ mkdirSync as mkdirSync10,
32957
+ readFileSync as readFileSync15,
32958
+ renameSync as renameSync6,
32959
+ rmSync as rmSync12,
32960
+ statSync as statSync4,
31679
32961
  unlinkSync as unlinkSync2,
31680
- writeFileSync as writeFileSync7
32962
+ writeFileSync as writeFileSync8
31681
32963
  } from "fs";
31682
- import { join as join19 } from "path";
32964
+ import { join as join22 } from "path";
31683
32965
  var DIR_MODE = 448;
31684
32966
  var FILE_MODE4 = 384;
31685
32967
  var DAEMON_STARTUP_GRACE_MS = 5e3;
31686
32968
  function readLockRecord(path) {
31687
32969
  try {
31688
- const value = JSON.parse(readFileSync14(path, "utf-8"));
32970
+ const value = JSON.parse(readFileSync15(path, "utf-8"));
31689
32971
  if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
31690
32972
  return value;
31691
32973
  }
@@ -31695,23 +32977,23 @@ function readLockRecord(path) {
31695
32977
  }
31696
32978
  function numericPid(path) {
31697
32979
  try {
31698
- const pid = Number(readFileSync14(path, "utf-8").trim());
32980
+ const pid = Number(readFileSync15(path, "utf-8").trim());
31699
32981
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
31700
32982
  } catch {
31701
32983
  return;
31702
32984
  }
31703
32985
  }
31704
32986
  function readDaemonOwner(configDir) {
31705
- return readLockRecord(join19(configDir, "daemon.lock", "owner.json"));
32987
+ return readLockRecord(join22(configDir, "daemon.lock", "owner.json"));
31706
32988
  }
31707
32989
  function readDaemonPid(configDir) {
31708
- const path = join19(configDir, "daemon.pid");
32990
+ const path = join22(configDir, "daemon.pid");
31709
32991
  const pid = numericPid(path);
31710
32992
  if (pid === void 0) {
31711
32993
  return;
31712
32994
  }
31713
32995
  try {
31714
- return { pid, mtimeMs: statSync3(path).mtimeMs };
32996
+ return { pid, mtimeMs: statSync4(path).mtimeMs };
31715
32997
  } catch {
31716
32998
  return;
31717
32999
  }
@@ -31720,16 +33002,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31720
33002
  const pid = opts.pid ?? process.pid;
31721
33003
  const now = opts.now ?? Date.now();
31722
33004
  const isAlive = opts.isAlive ?? processIsAlive;
31723
- const lockDir = join19(configDir, "daemon.lock");
31724
- const ownerPath2 = join19(lockDir, "owner.json");
31725
- const pidPath = join19(configDir, "daemon.pid");
33005
+ const lockDir = join22(configDir, "daemon.lock");
33006
+ const ownerPath2 = join22(lockDir, "owner.json");
33007
+ const pidPath = join22(configDir, "daemon.pid");
31726
33008
  const instanceId2 = randomUUID3();
31727
- if (!existsSync11(configDir)) {
31728
- mkdirSync9(configDir, { recursive: true, mode: DIR_MODE });
33009
+ if (!existsSync13(configDir)) {
33010
+ mkdirSync10(configDir, { recursive: true, mode: DIR_MODE });
31729
33011
  }
31730
33012
  for (; ; ) {
31731
33013
  try {
31732
- mkdirSync9(lockDir, { mode: DIR_MODE });
33014
+ mkdirSync10(lockDir, { mode: DIR_MODE });
31733
33015
  break;
31734
33016
  } catch (err) {
31735
33017
  if (err.code !== "EEXIST") {
@@ -31742,7 +33024,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31742
33024
  if (!existing) {
31743
33025
  let mtimeMs;
31744
33026
  try {
31745
- mtimeMs = statSync3(lockDir).mtimeMs;
33027
+ mtimeMs = statSync4(lockDir).mtimeMs;
31746
33028
  } catch (statErr) {
31747
33029
  if (statErr.code === "ENOENT") {
31748
33030
  continue;
@@ -31755,8 +33037,8 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31755
33037
  }
31756
33038
  const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
31757
33039
  try {
31758
- renameSync5(lockDir, stale);
31759
- rmSync10(stale, { recursive: true, force: true });
33040
+ renameSync6(lockDir, stale);
33041
+ rmSync12(stale, { recursive: true, force: true });
31760
33042
  } catch (renameErr) {
31761
33043
  if (renameErr.code !== "ENOENT") {
31762
33044
  throw renameErr;
@@ -31773,16 +33055,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31773
33055
  instanceId: instanceId2
31774
33056
  };
31775
33057
  const record = { pid, instanceId: instanceId2, startedAt: now };
31776
- writeFileSync7(ownerPath2, `${JSON.stringify(record)}
33058
+ writeFileSync8(ownerPath2, `${JSON.stringify(record)}
31777
33059
  `, { mode: FILE_MODE4 });
31778
- chmodSync7(ownerPath2, FILE_MODE4);
33060
+ chmodSync8(ownerPath2, FILE_MODE4);
31779
33061
  const legacyPid = numericPid(pidPath);
31780
33062
  if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
31781
- rmSync10(lockDir, { recursive: true, force: true });
33063
+ rmSync12(lockDir, { recursive: true, force: true });
31782
33064
  throw new Error(`daemon already running (pid=${String(legacyPid)})`);
31783
33065
  }
31784
- writeFileSync7(pidPath, String(pid), { mode: FILE_MODE4 });
31785
- chmodSync7(pidPath, FILE_MODE4);
33066
+ writeFileSync8(pidPath, String(pid), { mode: FILE_MODE4 });
33067
+ chmodSync8(pidPath, FILE_MODE4);
31786
33068
  return ownership2;
31787
33069
  }
31788
33070
  function ownsDaemonInstance(ownership2) {
@@ -31812,7 +33094,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
31812
33094
  }
31813
33095
  }
31814
33096
  }
31815
- rmSync10(ownership2.lockDir, { recursive: true, force: true });
33097
+ rmSync12(ownership2.lockDir, { recursive: true, force: true });
31816
33098
  if (cleanupError) {
31817
33099
  throw cleanupError;
31818
33100
  }
@@ -31867,7 +33149,7 @@ function normalizePresenceHeartbeatResponse(value) {
31867
33149
  }
31868
33150
 
31869
33151
  // src/daemon/statusline-protocol.ts
31870
- import { isAbsolute as isAbsolute4 } from "path";
33152
+ import { isAbsolute as isAbsolute5 } from "path";
31871
33153
  var STATUSLINE_PROTOCOL_PREFIX = Buffer.from("prim-statusline-v1\0", "utf8");
31872
33154
  var STATUSLINE_REQUEST_MAX_BYTES = 64 * 1024;
31873
33155
  var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
@@ -31896,7 +33178,7 @@ function parseStatuslineRequest(buffer) {
31896
33178
  try {
31897
33179
  const cwd = utf8Decoder.decode(buffer.subarray(STATUSLINE_PROTOCOL_PREFIX.length, cwdEnd));
31898
33180
  const primApiUrl = utf8Decoder.decode(buffer.subarray(cwdEnd + 1, apiUrlEnd));
31899
- if (!cwd || !isAbsolute4(cwd)) {
33181
+ if (!cwd || !isAbsolute5(cwd)) {
31900
33182
  return { state: "invalid" };
31901
33183
  }
31902
33184
  return { state: "complete", request: { cwd, primApiUrl } };
@@ -31907,7 +33189,7 @@ function parseStatuslineRequest(buffer) {
31907
33189
 
31908
33190
  // src/daemon/server.ts
31909
33191
  var CONFIG_DIR = primConfigDirectory();
31910
- var SOCK_PATH2 = join20(CONFIG_DIR, "sock");
33192
+ var SOCK_PATH2 = join23(CONFIG_DIR, "sock");
31911
33193
  var CONFIG_DIR_MODE3 = 448;
31912
33194
  var SOCKET_MODE = 384;
31913
33195
  var MAX_SOCKET_CONNECTIONS = 64;
@@ -31975,8 +33257,8 @@ function resolveRuntimeVersion() {
31975
33257
  return process.env.PRIM_RUNTIME_VERSION;
31976
33258
  }
31977
33259
  try {
31978
- const here = fileURLToPath4(new URL(".", import.meta.url));
31979
- const pkg = JSON.parse(readFileSync15(join20(here, "..", "..", "package.json"), "utf-8"));
33260
+ const here = fileURLToPath5(new URL(".", import.meta.url));
33261
+ const pkg = JSON.parse(readFileSync16(join23(here, "..", "..", "package.json"), "utf-8"));
31980
33262
  return pkg.version ?? "unknown";
31981
33263
  } catch {
31982
33264
  return "unknown";
@@ -32015,8 +33297,8 @@ function assertCallerPrincipalMatches(caller) {
32015
33297
  return credentialKey;
32016
33298
  }
32017
33299
  function ensureDaemonDirectoryPermissions() {
32018
- mkdirSync10(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
32019
- chmodSync8(CONFIG_DIR, CONFIG_DIR_MODE3);
33300
+ mkdirSync11(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
33301
+ chmodSync9(CONFIG_DIR, CONFIG_DIR_MODE3);
32020
33302
  }
32021
33303
  function persistHealth() {
32022
33304
  refreshDaemonHealth(daemonHealth, Date.now());
@@ -32102,7 +33384,7 @@ async function takeOwnership() {
32102
33384
  (pid) => pid !== void 0 && processIsAlive(pid)
32103
33385
  )
32104
33386
  );
32105
- if (existsSync12(SOCK_PATH2) || candidatePids.size > 0) {
33387
+ if (existsSync14(SOCK_PATH2) || candidatePids.size > 0) {
32106
33388
  const snapshot = await daemonRequest(
32107
33389
  "status_snapshot",
32108
33390
  {},
@@ -32247,7 +33529,7 @@ async function ensureTokenFresh() {
32247
33529
  }
32248
33530
  if (Date.now() >= expiresAt - TOKEN_REFRESH_THRESHOLD_MS) {
32249
33531
  try {
32250
- await refreshToken({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
33532
+ await refreshToken2({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
32251
33533
  } catch {
32252
33534
  }
32253
33535
  }
@@ -32647,7 +33929,7 @@ function startSocketServer() {
32647
33929
  });
32648
33930
  socketServer.listen(SOCK_PATH2, () => {
32649
33931
  try {
32650
- chmodSync8(SOCK_PATH2, SOCKET_MODE);
33932
+ chmodSync9(SOCK_PATH2, SOCKET_MODE);
32651
33933
  } catch (err) {
32652
33934
  shutdown(EXIT_CRASH, `[prim-daemon] failed to secure socket: ${errorMessage2(err)}`);
32653
33935
  return;