@primitive.ai/prim 0.1.0-alpha.102 → 0.1.0-alpha.103

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.
@@ -52,8 +52,8 @@ var require_ucs2length = __commonJS({
52
52
  });
53
53
 
54
54
  // src/hooks/post-tool-use.ts
55
- import { readFileSync as readFileSync16 } from "fs";
56
- import { dirname as dirname12, join as join18 } from "path";
55
+ import { readFileSync as readFileSync17 } from "fs";
56
+ import { dirname as dirname12, join as join19 } from "path";
57
57
  import { fileURLToPath as fileURLToPath2 } from "url";
58
58
 
59
59
  // src/binding.ts
@@ -435,17 +435,373 @@ function resolveOrg(args) {
435
435
  return { orgId: void 0, source: "unbound" };
436
436
  }
437
437
 
438
+ // src/demo/isolation.ts
439
+ import { existsSync as existsSync4 } from "fs";
440
+
441
+ // src/demo/state.ts
442
+ import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
443
+ import { existsSync as existsSync3, lstatSync, readFileSync as readFileSync4, readdirSync } from "fs";
444
+ import { join as join5, resolve } from "path";
445
+
446
+ // src/lib/atomic-file.ts
447
+ import { randomUUID } from "crypto";
448
+ import {
449
+ constants,
450
+ closeSync,
451
+ fchmodSync,
452
+ fsyncSync,
453
+ mkdirSync,
454
+ openSync,
455
+ renameSync,
456
+ rmSync,
457
+ writeFileSync
458
+ } from "fs";
459
+ import { dirname as dirname2 } from "path";
460
+ var DEFAULT_FILE_MODE = 438;
461
+ function syncDirectory(path) {
462
+ const fd = openSync(path, constants.O_RDONLY);
463
+ try {
464
+ fsyncSync(fd);
465
+ } finally {
466
+ closeSync(fd);
467
+ }
468
+ }
469
+ function syncCreatedParentChain(firstCreatedParent, parent) {
470
+ const createdDirectories = [];
471
+ let current = parent;
472
+ while (current !== firstCreatedParent) {
473
+ createdDirectories.push(current);
474
+ const next = dirname2(current);
475
+ if (next === current) {
476
+ throw new Error("recursive mkdir returned a path outside the target parent chain");
477
+ }
478
+ current = next;
479
+ }
480
+ createdDirectories.push(firstCreatedParent);
481
+ syncDirectory(dirname2(firstCreatedParent));
482
+ for (const directory of createdDirectories.reverse().slice(0, -1)) {
483
+ syncDirectory(directory);
484
+ }
485
+ }
486
+ function ensureDurableDirectory(path, mode) {
487
+ const firstCreatedParent = mkdirSync(path, { recursive: true, mode });
488
+ if (firstCreatedParent) {
489
+ syncCreatedParentChain(firstCreatedParent, path);
490
+ }
491
+ }
492
+ function atomicWriteFile(target, content, options = {}) {
493
+ const parent = dirname2(target);
494
+ if (options.ensureParent) {
495
+ ensureDurableDirectory(parent);
496
+ }
497
+ const temporaryPath = `${target}.${randomUUID()}.tmp`;
498
+ let temporaryCreated = false;
499
+ try {
500
+ const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
501
+ const fd = openSync(temporaryPath, flags, options.mode ?? DEFAULT_FILE_MODE);
502
+ temporaryCreated = true;
503
+ try {
504
+ if (options.mode !== void 0) fchmodSync(fd, options.mode);
505
+ writeFileSync(fd, content);
506
+ fsyncSync(fd);
507
+ } finally {
508
+ closeSync(fd);
509
+ }
510
+ options.validate?.(temporaryPath);
511
+ renameSync(temporaryPath, target);
512
+ syncDirectory(parent);
513
+ } catch (error) {
514
+ if (temporaryCreated) {
515
+ try {
516
+ rmSync(temporaryPath, { force: true });
517
+ } catch {
518
+ }
519
+ }
520
+ throw error;
521
+ }
522
+ }
523
+
524
+ // src/lib/file-lock.ts
525
+ import { randomBytes } from "crypto";
526
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
527
+ import { dirname as dirname3, join as join4 } from "path";
528
+
529
+ // src/lib/process-liveness.ts
530
+ function processIsAlive(pid, probe = process.kill) {
531
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false;
532
+ try {
533
+ probe(pid, 0);
534
+ return true;
535
+ } catch (error) {
536
+ return error.code === "EPERM";
537
+ }
538
+ }
539
+
540
+ // src/lib/file-lock.ts
541
+ var DEFAULT_TIMEOUT_MS = 3e4;
542
+ var DEFAULT_POLL_MS = 50;
543
+ var DEFAULT_INIT_GRACE_MS = 2e3;
544
+ var DIRECTORY_MODE = 448;
545
+ var FILE_MODE = 384;
546
+ function ownerPath(lockDir) {
547
+ return join4(lockDir, "owner.json");
548
+ }
549
+ function readOwner(lockDir) {
550
+ try {
551
+ const owner = JSON.parse(readFileSync3(ownerPath(lockDir), "utf8"));
552
+ if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
553
+ return null;
554
+ }
555
+ return owner;
556
+ } catch {
557
+ return null;
558
+ }
559
+ }
560
+ function sameOwner(a, b) {
561
+ return a?.pid === b.pid && a.nonce === b.nonce && a.createdAt === b.createdAt;
562
+ }
563
+ function tryTakeLock(lockDir, now) {
564
+ try {
565
+ mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
566
+ } catch (error) {
567
+ if (error.code === "EEXIST") return null;
568
+ throw error;
569
+ }
570
+ const owner = {
571
+ pid: process.pid,
572
+ nonce: randomBytes(16).toString("hex"),
573
+ createdAt: now
574
+ };
575
+ try {
576
+ writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
577
+ `, {
578
+ encoding: "utf8",
579
+ mode: FILE_MODE,
580
+ flag: "wx"
581
+ });
582
+ return owner;
583
+ } catch (error) {
584
+ rmSync2(lockDir, { recursive: true, force: true });
585
+ throw error;
586
+ }
587
+ }
588
+ function recoverStaleLock(lockDir, now, alive, initGraceMs) {
589
+ const owner = readOwner(lockDir);
590
+ if (owner) {
591
+ if (alive(owner.pid)) return false;
592
+ if (!sameOwner(readOwner(lockDir), owner)) return false;
593
+ rmSync2(lockDir, { recursive: true, force: true });
594
+ return true;
595
+ }
596
+ try {
597
+ const before = statSync(lockDir).mtimeMs;
598
+ if (now - before < initGraceMs) return false;
599
+ if (readOwner(lockDir)) return false;
600
+ if (statSync(lockDir).mtimeMs !== before) return false;
601
+ rmSync2(lockDir, { recursive: true, force: true });
602
+ return true;
603
+ } catch {
604
+ return true;
605
+ }
606
+ }
607
+ function abortError(signal) {
608
+ if (signal.reason instanceof Error) return signal.reason;
609
+ const error = new Error("The operation was aborted");
610
+ error.name = "AbortError";
611
+ return error;
612
+ }
613
+ function throwIfAborted(signal) {
614
+ if (signal?.aborted) throw abortError(signal);
615
+ }
616
+ async function defaultSleep(ms, signal) {
617
+ if (!signal) {
618
+ await new Promise((resolve7) => setTimeout(resolve7, ms));
619
+ return;
620
+ }
621
+ throwIfAborted(signal);
622
+ await new Promise((resolve7, reject) => {
623
+ const timer = setTimeout(() => {
624
+ signal.removeEventListener("abort", onAbort);
625
+ resolve7();
626
+ }, ms);
627
+ const onAbort = () => {
628
+ clearTimeout(timer);
629
+ reject(abortError(signal));
630
+ };
631
+ signal.addEventListener("abort", onAbort, { once: true });
632
+ });
633
+ }
634
+ var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
635
+ function defaultSleepSync(ms) {
636
+ Atomics.wait(syncSleeper, 0, 0, ms);
637
+ }
638
+ function withFileLockSync(lockDir, operation, options = {}) {
639
+ mkdirSync2(dirname3(lockDir), { recursive: true, mode: DIRECTORY_MODE });
640
+ const nowMs = options.nowMs ?? Date.now;
641
+ const alive = options.processAlive ?? processIsAlive;
642
+ const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
643
+ let owner = null;
644
+ while (!owner) {
645
+ const now = nowMs();
646
+ owner = tryTakeLock(lockDir, now);
647
+ if (owner) break;
648
+ recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
649
+ if (now >= deadline) {
650
+ throw new Error(`timed out waiting for file lock ${lockDir}`);
651
+ }
652
+ (options.sleep ?? defaultSleepSync)(options.pollMs ?? DEFAULT_POLL_MS);
653
+ }
654
+ try {
655
+ return operation();
656
+ } finally {
657
+ if (sameOwner(readOwner(lockDir), owner)) {
658
+ rmSync2(lockDir, { recursive: true, force: true });
659
+ }
660
+ }
661
+ }
662
+ async function withFileLock(lockDir, operation, options = {}) {
663
+ mkdirSync2(dirname3(lockDir), { recursive: true, mode: DIRECTORY_MODE });
664
+ const nowMs = options.nowMs ?? Date.now;
665
+ const alive = options.processAlive ?? processIsAlive;
666
+ const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
667
+ let owner = null;
668
+ while (!owner) {
669
+ throwIfAborted(options.signal);
670
+ const now = nowMs();
671
+ owner = tryTakeLock(lockDir, now);
672
+ if (owner) break;
673
+ recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
674
+ if (now >= deadline) {
675
+ throw new Error(`timed out waiting for file lock ${lockDir}`);
676
+ }
677
+ if (options.sleep) {
678
+ await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
679
+ throwIfAborted(options.signal);
680
+ } else {
681
+ await defaultSleep(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
682
+ }
683
+ }
684
+ try {
685
+ throwIfAborted(options.signal);
686
+ return await operation();
687
+ } finally {
688
+ if (sameOwner(readOwner(lockDir), owner)) {
689
+ rmSync2(lockDir, { recursive: true, force: true });
690
+ }
691
+ }
692
+ }
693
+
694
+ // src/demo/state.ts
695
+ var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
696
+ var demoDirectory = () => join5(primConfigDirectory(), "demo");
697
+ var runPath = (id) => {
698
+ if (!RUN_ID.test(id)) throw new Error("invalid demo run ID");
699
+ return join5(demoDirectory(), "runs", `${id}.json`);
700
+ };
701
+ function readDemoJson(path) {
702
+ const stat = lstatSync(path);
703
+ if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
704
+ return JSON.parse(readFileSync4(path, "utf8"));
705
+ }
706
+ function saveDemoJson(path, value) {
707
+ atomicWriteFile(path, `${JSON.stringify(value)}
708
+ `, { mode: 384, ensureParent: true });
709
+ }
710
+ function readRun(id) {
711
+ const run = readDemoJson(runPath(id));
712
+ if (run.version !== 1 || run.id !== id || !["prepared", "proposal", "conflict", "completed", "skipped"].includes(run.stage) || typeof run.terminal !== "boolean" || !Array.isArray(run.launcher) || run.launcher.length !== 2 || run.launcher.some((value) => typeof value !== "string" || !value.startsWith("/")) || run.agent !== void 0 && !["claude_code", "codex", "cursor", "hermes"].includes(run.agent)) {
713
+ throw new Error("invalid demo run state");
714
+ }
715
+ return run;
716
+ }
717
+ var saveRun = (run) => saveDemoJson(runPath(run.id), run);
718
+ var lockRun = (id, action) => withFileLockSync(`${runPath(id)}.lock`, () => action(readRun(id)), { timeoutMs: 500 });
719
+ var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
720
+ function demoCommand(run, action, choice) {
721
+ return [
722
+ ...run.launcher,
723
+ "demo",
724
+ action,
725
+ run.id,
726
+ ...choice === void 0 ? [] : ["--choice", choice]
727
+ ].map(quote).join(" ");
728
+ }
729
+ function sessionKey(agent, session) {
730
+ return createHash2("sha256").update(`${agent}\0${session}`).digest("hex");
731
+ }
732
+ function exclusionPath(key) {
733
+ if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
734
+ return join5(demoDirectory(), "excluded-sessions", `${key}.json`);
735
+ }
736
+ function sessionExcluded(agent, session) {
737
+ if (typeof session !== "string" || !session) return false;
738
+ const path = exclusionPath(sessionKey(agent, session));
739
+ if (!existsSync3(path)) return false;
740
+ const record = readDemoJson(path);
741
+ if (typeof record.runId !== "string" || !RUN_ID.test(record.runId)) {
742
+ throw new Error("invalid demo capture exclusion");
743
+ }
744
+ return true;
745
+ }
746
+
747
+ // src/demo/isolation.ts
748
+ function observeDemoInvocation(envelope, agent, checkExclusion = true) {
749
+ const session = typeof envelope.session_id === "string" && envelope.session_id ? envelope.session_id : agent === "hermes" ? envelope.extra?.session_key : void 0;
750
+ let invocation = false;
751
+ if (envelope.hook_event_name === "PreToolUse" && typeof session === "string" && session) {
752
+ const tool = agent === "cursor" ? "Shell" : agent === "hermes" ? "terminal" : "Bash";
753
+ const input = envelope.tool_input;
754
+ const command = input?.command;
755
+ if (envelope.tool_name === tool && typeof command === "string" && command.length < 8192) {
756
+ const ids = command.match(
757
+ /[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/gu
758
+ );
759
+ if (ids?.length === 1 && existsSync4(runPath(ids[0]))) {
760
+ invocation = lockRun(ids[0], (run) => {
761
+ const actions = [
762
+ ["start"],
763
+ ["confirm"],
764
+ ["resolve", "repository"],
765
+ ["resolve", "local-storage"],
766
+ ["skip"]
767
+ ];
768
+ const match = actions.find(
769
+ ([action, choice]) => demoCommand(run, action, choice) === command
770
+ );
771
+ if (run.terminal || !match) {
772
+ return false;
773
+ }
774
+ if (match[0] === "skip") return true;
775
+ const key = sessionKey(agent, session);
776
+ if (run.agent && run.agent !== agent || run.binding && run.binding !== key) {
777
+ run.acknowledgment = void 0;
778
+ saveRun(run);
779
+ return false;
780
+ }
781
+ saveDemoJson(exclusionPath(key), { runId: run.id });
782
+ run.binding = key;
783
+ run.agent = agent;
784
+ run.acknowledgment = { command, at: Date.now() };
785
+ saveRun(run);
786
+ return true;
787
+ });
788
+ }
789
+ }
790
+ }
791
+ return { invocation, excluded: checkExclusion && sessionExcluded(agent, session) };
792
+ }
793
+
438
794
  // src/lib/activation.ts
439
795
  import { execFileSync as execFileSync2 } from "child_process";
440
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
796
+ import { existsSync as existsSync5, readFileSync as readFileSync5 } from "fs";
441
797
  import { homedir as homedir2 } from "os";
442
- import { join as join4 } from "path";
798
+ import { join as join6 } from "path";
443
799
 
444
800
  // src/lib/git.ts
445
801
  import { execFileSync } from "child_process";
446
- import { createHash as createHash2 } from "crypto";
447
- import { lstatSync, realpathSync } from "fs";
448
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
802
+ import { createHash as createHash3 } from "crypto";
803
+ import { lstatSync as lstatSync2, realpathSync } from "fs";
804
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute2, relative, resolve as resolve2, sep } from "path";
449
805
  var GIT_TIMEOUT_MS = 1e3;
450
806
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
451
807
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
@@ -500,13 +856,13 @@ function canonicalGitRoot(cwd) {
500
856
  }
501
857
  }
502
858
  function relatedWorktreeTarget(path, cwd, origin) {
503
- let parent = dirname2(resolve(cwd, path));
859
+ let parent = dirname4(resolve2(cwd, path));
504
860
  while (true) {
505
861
  try {
506
862
  realpathSync.native(parent);
507
863
  break;
508
864
  } catch {
509
- const next = dirname2(parent);
865
+ const next = dirname4(parent);
510
866
  if (next === parent) return null;
511
867
  parent = next;
512
868
  }
@@ -516,7 +872,7 @@ function relatedWorktreeTarget(path, cwd, origin) {
516
872
  const common = (root) => {
517
873
  const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
518
874
  try {
519
- return value ? realpathSync.native(resolve(root, value)) : void 0;
875
+ return value ? realpathSync.native(resolve2(root, value)) : void 0;
520
876
  } catch {
521
877
  return void 0;
522
878
  }
@@ -546,7 +902,7 @@ function normalizeOriginRemote(remote) {
546
902
  }
547
903
  }
548
904
  function opaqueRepoKey(source, value) {
549
- return `repo_v1_${createHash2("sha256").update(`${source}\0${value}`).digest("hex")}`;
905
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
550
906
  }
551
907
  function resolveRepositoryContext(cwd = process.cwd()) {
552
908
  const top = gitToplevel(cwd);
@@ -555,7 +911,7 @@ function resolveRepositoryContext(cwd = process.cwd()) {
555
911
  try {
556
912
  repoRoot = realpathSync.native(top);
557
913
  } catch {
558
- repoRoot = resolve(top);
914
+ repoRoot = resolve2(top);
559
915
  }
560
916
  const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
561
917
  const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
@@ -584,12 +940,12 @@ function nearestExistingAncestor(path) {
584
940
  let cursor = path;
585
941
  while (true) {
586
942
  try {
587
- lstatSync(cursor);
943
+ lstatSync2(cursor);
588
944
  break;
589
945
  } catch (error) {
590
946
  const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
591
947
  if (code !== "ENOENT" && code !== "ENOTDIR") return null;
592
- const parent = dirname2(cursor);
948
+ const parent = dirname4(cursor);
593
949
  if (parent === cursor) return null;
594
950
  suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
595
951
  cursor = parent;
@@ -605,10 +961,10 @@ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
605
961
  if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
606
962
  return { ok: false, reason: "invalid_path" };
607
963
  }
608
- const absolute = resolve(baseDir, filePath);
964
+ const absolute = resolve2(baseDir, filePath);
609
965
  const resolved = nearestExistingAncestor(absolute);
610
966
  if (!resolved) return { ok: false, reason: "invalid_path" };
611
- const target = resolve(resolved.real, ...resolved.suffix);
967
+ const target = resolve2(resolved.real, ...resolved.suffix);
612
968
  const rel = relative(context.repoRoot, target);
613
969
  if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
614
970
  if (isAbsolute2(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
@@ -619,10 +975,10 @@ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
619
975
  function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
620
976
  if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
621
977
  return null;
622
- const absolute = resolve(cwd, filePath);
978
+ const absolute = resolve2(cwd, filePath);
623
979
  let target;
624
980
  try {
625
- const stat = lstatSync(absolute);
981
+ const stat = lstatSync2(absolute);
626
982
  if (!stat.isFile() || stat.isSymbolicLink()) return null;
627
983
  target = realpathSync.native(absolute);
628
984
  } catch (error) {
@@ -630,9 +986,9 @@ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonical
630
986
  return null;
631
987
  }
632
988
  try {
633
- const parent = realpathSync.native(dirname2(absolute));
634
- if (!lstatSync(parent).isDirectory()) return null;
635
- target = resolve(parent, basename(absolute));
989
+ const parent = realpathSync.native(dirname4(absolute));
990
+ if (!lstatSync2(parent).isDirectory()) return null;
991
+ target = resolve2(parent, basename(absolute));
636
992
  } catch {
637
993
  return null;
638
994
  }
@@ -720,10 +1076,10 @@ function hasProjectPrimInstall(cwd) {
720
1076
  const root = gitToplevel(cwd);
721
1077
  if (root === null || root === homedir2()) return false;
722
1078
  for (const rel of PROJECT_INSTALL_FILES) {
723
- const path = join4(root, rel);
724
- if (existsSync2(path)) {
1079
+ const path = join6(root, rel);
1080
+ if (existsSync5(path)) {
725
1081
  try {
726
- const content = readFileSync3(path, "utf-8");
1082
+ const content = readFileSync5(path, "utf-8");
727
1083
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
728
1084
  } catch {
729
1085
  }
@@ -742,235 +1098,14 @@ function decisionIngestionStatus(cwd) {
742
1098
  }
743
1099
 
744
1100
  // src/client.ts
745
- import { createHash as createHash3 } from "crypto";
746
- import { chmodSync as chmodSync2, existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync7, rmSync as rmSync3 } from "fs";
1101
+ import { createHash as createHash4 } from "crypto";
1102
+ import { chmodSync as chmodSync2, existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync8, rmSync as rmSync3 } from "fs";
747
1103
  import { dirname as dirname6 } from "path";
748
1104
 
749
- // src/lib/atomic-file.ts
750
- import { randomUUID } from "crypto";
751
- import {
752
- constants,
753
- closeSync,
754
- fchmodSync,
755
- fsyncSync,
756
- mkdirSync,
757
- openSync,
758
- renameSync,
759
- rmSync,
760
- writeFileSync
761
- } from "fs";
762
- import { dirname as dirname3 } from "path";
763
- var DEFAULT_FILE_MODE = 438;
764
- function syncDirectory(path) {
765
- const fd = openSync(path, constants.O_RDONLY);
766
- try {
767
- fsyncSync(fd);
768
- } finally {
769
- closeSync(fd);
770
- }
771
- }
772
- function syncCreatedParentChain(firstCreatedParent, parent) {
773
- const createdDirectories = [];
774
- let current = parent;
775
- while (current !== firstCreatedParent) {
776
- createdDirectories.push(current);
777
- const next = dirname3(current);
778
- if (next === current) {
779
- throw new Error("recursive mkdir returned a path outside the target parent chain");
780
- }
781
- current = next;
782
- }
783
- createdDirectories.push(firstCreatedParent);
784
- syncDirectory(dirname3(firstCreatedParent));
785
- for (const directory of createdDirectories.reverse().slice(0, -1)) {
786
- syncDirectory(directory);
787
- }
788
- }
789
- function ensureDurableDirectory(path, mode) {
790
- const firstCreatedParent = mkdirSync(path, { recursive: true, mode });
791
- if (firstCreatedParent) {
792
- syncCreatedParentChain(firstCreatedParent, path);
793
- }
794
- }
795
- function atomicWriteFile(target, content, options = {}) {
796
- const parent = dirname3(target);
797
- if (options.ensureParent) {
798
- ensureDurableDirectory(parent);
799
- }
800
- const temporaryPath = `${target}.${randomUUID()}.tmp`;
801
- let temporaryCreated = false;
802
- try {
803
- const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
804
- const fd = openSync(temporaryPath, flags, options.mode ?? DEFAULT_FILE_MODE);
805
- temporaryCreated = true;
806
- try {
807
- if (options.mode !== void 0) fchmodSync(fd, options.mode);
808
- writeFileSync(fd, content);
809
- fsyncSync(fd);
810
- } finally {
811
- closeSync(fd);
812
- }
813
- options.validate?.(temporaryPath);
814
- renameSync(temporaryPath, target);
815
- syncDirectory(parent);
816
- } catch (error) {
817
- if (temporaryCreated) {
818
- try {
819
- rmSync(temporaryPath, { force: true });
820
- } catch {
821
- }
822
- }
823
- throw error;
824
- }
825
- }
826
-
827
- // src/lib/file-lock.ts
828
- import { randomBytes } from "crypto";
829
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
830
- import { dirname as dirname4, join as join5 } from "path";
831
-
832
- // src/lib/process-liveness.ts
833
- function processIsAlive(pid, probe = process.kill) {
834
- if (!Number.isSafeInteger(pid) || pid <= 0) return false;
835
- try {
836
- probe(pid, 0);
837
- return true;
838
- } catch (error) {
839
- return error.code === "EPERM";
840
- }
841
- }
842
-
843
- // src/lib/file-lock.ts
844
- var DEFAULT_TIMEOUT_MS = 3e4;
845
- var DEFAULT_POLL_MS = 50;
846
- var DEFAULT_INIT_GRACE_MS = 2e3;
847
- var DIRECTORY_MODE = 448;
848
- var FILE_MODE = 384;
849
- function ownerPath(lockDir) {
850
- return join5(lockDir, "owner.json");
851
- }
852
- function readOwner(lockDir) {
853
- try {
854
- const owner = JSON.parse(readFileSync4(ownerPath(lockDir), "utf8"));
855
- if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
856
- return null;
857
- }
858
- return owner;
859
- } catch {
860
- return null;
861
- }
862
- }
863
- function sameOwner(a, b) {
864
- return a?.pid === b.pid && a.nonce === b.nonce && a.createdAt === b.createdAt;
865
- }
866
- function tryTakeLock(lockDir, now) {
867
- try {
868
- mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
869
- } catch (error) {
870
- if (error.code === "EEXIST") return null;
871
- throw error;
872
- }
873
- const owner = {
874
- pid: process.pid,
875
- nonce: randomBytes(16).toString("hex"),
876
- createdAt: now
877
- };
878
- try {
879
- writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
880
- `, {
881
- encoding: "utf8",
882
- mode: FILE_MODE,
883
- flag: "wx"
884
- });
885
- return owner;
886
- } catch (error) {
887
- rmSync2(lockDir, { recursive: true, force: true });
888
- throw error;
889
- }
890
- }
891
- function recoverStaleLock(lockDir, now, alive, initGraceMs) {
892
- const owner = readOwner(lockDir);
893
- if (owner) {
894
- if (alive(owner.pid)) return false;
895
- if (!sameOwner(readOwner(lockDir), owner)) return false;
896
- rmSync2(lockDir, { recursive: true, force: true });
897
- return true;
898
- }
899
- try {
900
- const before = statSync(lockDir).mtimeMs;
901
- if (now - before < initGraceMs) return false;
902
- if (readOwner(lockDir)) return false;
903
- if (statSync(lockDir).mtimeMs !== before) return false;
904
- rmSync2(lockDir, { recursive: true, force: true });
905
- return true;
906
- } catch {
907
- return true;
908
- }
909
- }
910
- function abortError(signal) {
911
- if (signal.reason instanceof Error) return signal.reason;
912
- const error = new Error("The operation was aborted");
913
- error.name = "AbortError";
914
- return error;
915
- }
916
- function throwIfAborted(signal) {
917
- if (signal?.aborted) throw abortError(signal);
918
- }
919
- async function defaultSleep(ms, signal) {
920
- if (!signal) {
921
- await new Promise((resolve6) => setTimeout(resolve6, ms));
922
- return;
923
- }
924
- throwIfAborted(signal);
925
- await new Promise((resolve6, reject) => {
926
- const timer = setTimeout(() => {
927
- signal.removeEventListener("abort", onAbort);
928
- resolve6();
929
- }, ms);
930
- const onAbort = () => {
931
- clearTimeout(timer);
932
- reject(abortError(signal));
933
- };
934
- signal.addEventListener("abort", onAbort, { once: true });
935
- });
936
- }
937
- var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
938
- async function withFileLock(lockDir, operation, options = {}) {
939
- mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
940
- const nowMs = options.nowMs ?? Date.now;
941
- const alive = options.processAlive ?? processIsAlive;
942
- const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
943
- let owner = null;
944
- while (!owner) {
945
- throwIfAborted(options.signal);
946
- const now = nowMs();
947
- owner = tryTakeLock(lockDir, now);
948
- if (owner) break;
949
- recoverStaleLock(lockDir, now, alive, options.initGraceMs ?? DEFAULT_INIT_GRACE_MS);
950
- if (now >= deadline) {
951
- throw new Error(`timed out waiting for file lock ${lockDir}`);
952
- }
953
- if (options.sleep) {
954
- await options.sleep(options.pollMs ?? DEFAULT_POLL_MS);
955
- throwIfAborted(options.signal);
956
- } else {
957
- await defaultSleep(options.pollMs ?? DEFAULT_POLL_MS, options.signal);
958
- }
959
- }
960
- try {
961
- throwIfAborted(options.signal);
962
- return await operation();
963
- } finally {
964
- if (sameOwner(readOwner(lockDir), owner)) {
965
- rmSync2(lockDir, { recursive: true, force: true });
966
- }
967
- }
968
- }
969
-
970
1105
  // src/daemon/client-instance-id.ts
971
1106
  import { randomBytes as randomBytes2 } from "crypto";
972
- import { chmodSync, lstatSync as lstatSync2, readFileSync as readFileSync5 } from "fs";
973
- import { join as join6 } from "path";
1107
+ import { chmodSync, lstatSync as lstatSync3, readFileSync as readFileSync6 } from "fs";
1108
+ import { join as join7 } from "path";
974
1109
  var CONFIG_DIRECTORY_MODE = 448;
975
1110
  var INSTANCE_FILE_MODE = 384;
976
1111
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -983,7 +1118,7 @@ function isClientInstanceId(value) {
983
1118
  }
984
1119
  function ensurePrivateConfigDirectory(configDir) {
985
1120
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
986
- const metadata = lstatSync2(configDir);
1121
+ const metadata = lstatSync3(configDir);
987
1122
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
988
1123
  throw new Error("prim config path must be a private directory");
989
1124
  }
@@ -993,7 +1128,7 @@ function ensurePrivateConfigDirectory(configDir) {
993
1128
  function readExisting(path) {
994
1129
  let metadata;
995
1130
  try {
996
- metadata = lstatSync2(path);
1131
+ metadata = lstatSync3(path);
997
1132
  } catch (error) {
998
1133
  if (error.code === "ENOENT") {
999
1134
  return;
@@ -1007,7 +1142,7 @@ function readExisting(path) {
1007
1142
  if (metadata.size > MAX_STORED_BYTES) {
1008
1143
  throw new Error("stored client instance identity is invalid");
1009
1144
  }
1010
- const raw = readFileSync5(path, "utf8");
1145
+ const raw = readFileSync6(path, "utf8");
1011
1146
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
1012
1147
  if (raw !== value && raw !== `${value}
1013
1148
  ` || !isClientInstanceId(value)) {
@@ -1021,8 +1156,8 @@ function atomicWrite(path, value) {
1021
1156
  }
1022
1157
  async function getOrCreateClientInstanceId(options) {
1023
1158
  const configDir = options.configDir;
1024
- const path = join6(configDir, "client_instance_id");
1025
- const lockPath = join6(configDir, "client-instance.lock");
1159
+ const path = join7(configDir, "client_instance_id");
1160
+ const lockPath = join7(configDir, "client-instance.lock");
1026
1161
  ensurePrivateConfigDirectory(configDir);
1027
1162
  return withFileLock(
1028
1163
  lockPath,
@@ -1045,8 +1180,8 @@ async function getOrCreateClientInstanceId(options) {
1045
1180
  }
1046
1181
 
1047
1182
  // src/lib/bin-path.ts
1048
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
1049
- import { dirname as dirname5, isAbsolute as isAbsolute3, join as join7 } from "path";
1183
+ import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
1184
+ import { dirname as dirname5, isAbsolute as isAbsolute3, join as join8 } from "path";
1050
1185
  import { fileURLToPath } from "url";
1051
1186
  var PKG_NAME = "@primitive.ai/prim";
1052
1187
  var ROOT_WALK_LIMIT = 6;
@@ -1058,10 +1193,10 @@ function locateRoot() {
1058
1193
  }
1059
1194
  let dir = dirname5(fileURLToPath(import.meta.url));
1060
1195
  for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
1061
- const manifestPath = join7(dir, "package.json");
1062
- if (existsSync4(manifestPath)) {
1196
+ const manifestPath = join8(dir, "package.json");
1197
+ if (existsSync6(manifestPath)) {
1063
1198
  try {
1064
- const manifest = JSON.parse(readFileSync6(manifestPath, "utf-8"));
1199
+ const manifest = JSON.parse(readFileSync7(manifestPath, "utf-8"));
1065
1200
  if (manifest.name === PKG_NAME && manifest.bin) {
1066
1201
  resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
1067
1202
  return resolvedRoot;
@@ -1185,7 +1320,7 @@ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1185
1320
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
1186
1321
  function readTrimmed2(path) {
1187
1322
  try {
1188
- const value = readFileSync7(path, "utf8").trim();
1323
+ const value = readFileSync8(path, "utf8").trim();
1189
1324
  return value || void 0;
1190
1325
  } catch {
1191
1326
  return void 0;
@@ -1210,7 +1345,7 @@ function atomicWrite2(path, content) {
1210
1345
  atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
1211
1346
  }
1212
1347
  function removeCredentialFile(path) {
1213
- if (!existsSync5(path)) return false;
1348
+ if (!existsSync7(path)) return false;
1214
1349
  rmSync3(path, { force: true });
1215
1350
  return true;
1216
1351
  }
@@ -1226,7 +1361,7 @@ function isTokenExpiringSoon(credential) {
1226
1361
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
1227
1362
  }
1228
1363
  function refreshFingerprint(refreshToken2) {
1229
- return createHash3("sha256").update(refreshToken2).digest("hex");
1364
+ return createHash4("sha256").update(refreshToken2).digest("hex");
1230
1365
  }
1231
1366
  function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
1232
1367
  return {
@@ -20454,7 +20589,7 @@ function scheduleCollectScopeRefresh(cwd, collectScopeVersion, dependencies = de
20454
20589
 
20455
20590
  // src/lib/workspace-id.ts
20456
20591
  import { execFileSync as execFileSync3 } from "child_process";
20457
- import { randomUUID as randomUUID2 } from "crypto";
20592
+ import { randomUUID as randomUUID3 } from "crypto";
20458
20593
  import {
20459
20594
  constants as constants2,
20460
20595
  chmodSync as chmodSync3,
@@ -20462,16 +20597,16 @@ import {
20462
20597
  fchmodSync as fchmodSync2,
20463
20598
  fsyncSync as fsyncSync2,
20464
20599
  linkSync,
20465
- lstatSync as lstatSync3,
20600
+ lstatSync as lstatSync4,
20466
20601
  mkdirSync as mkdirSync4,
20467
20602
  openSync as openSync2,
20468
- readFileSync as readFileSync8,
20603
+ readFileSync as readFileSync9,
20469
20604
  statSync as statSync2,
20470
20605
  unlinkSync,
20471
20606
  writeFileSync as writeFileSync3
20472
20607
  } from "fs";
20473
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join9, resolve as resolve3 } from "path";
20474
- var WORKSPACE_ID_RELATIVE_PATH = join9("prim", "workspace-id");
20608
+ import { dirname as dirname7, isAbsolute as isAbsolute4, join as join10, resolve as resolve4 } from "path";
20609
+ var WORKSPACE_ID_RELATIVE_PATH = join10("prim", "workspace-id");
20475
20610
  var MAX_ANCESTORS = 64;
20476
20611
  var MAX_GIT_FILE_BYTES = 4096;
20477
20612
  var MAX_ID_FILE_BYTES = 128;
@@ -20517,7 +20652,7 @@ function resolveWorkspaceIdPath(cwd) {
20517
20652
  }
20518
20653
  return {
20519
20654
  status: "resolved",
20520
- path: isAbsolute4(gitPath) ? resolve3(gitPath) : resolve3(cwd, gitPath)
20655
+ path: isAbsolute4(gitPath) ? resolve4(gitPath) : resolve4(cwd, gitPath)
20521
20656
  };
20522
20657
  } catch (error) {
20523
20658
  const code = errorCode(error);
@@ -20528,21 +20663,21 @@ function resolveWorkspaceIdPath(cwd) {
20528
20663
  }
20529
20664
  }
20530
20665
  function resolveFromFilesystem(cwd) {
20531
- let current = resolve3(cwd);
20666
+ let current = resolve4(cwd);
20532
20667
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
20533
- const dotGit = join9(current, ".git");
20668
+ const dotGit = join10(current, ".git");
20534
20669
  try {
20535
- const stat = lstatSync3(dotGit);
20670
+ const stat = lstatSync4(dotGit);
20536
20671
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
20537
- return join9(dotGit, WORKSPACE_ID_RELATIVE_PATH);
20672
+ return join10(dotGit, WORKSPACE_ID_RELATIVE_PATH);
20538
20673
  }
20539
20674
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
20540
- const contents = readFileSync8(dotGit, "utf8");
20675
+ const contents = readFileSync9(dotGit, "utf8");
20541
20676
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
20542
20677
  if (match?.[1]) {
20543
- const gitDirectory = isAbsolute4(match[1]) ? resolve3(match[1]) : resolve3(current, match[1]);
20678
+ const gitDirectory = isAbsolute4(match[1]) ? resolve4(match[1]) : resolve4(current, match[1]);
20544
20679
  if (isGitDirectory(gitDirectory)) {
20545
- return join9(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
20680
+ return join10(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
20546
20681
  }
20547
20682
  }
20548
20683
  }
@@ -20561,7 +20696,7 @@ function resolveFromFilesystem(cwd) {
20561
20696
  }
20562
20697
  function isGitDirectory(path) {
20563
20698
  try {
20564
- return statSync2(join9(path, "HEAD")).isFile();
20699
+ return statSync2(join10(path, "HEAD")).isFile();
20565
20700
  } catch {
20566
20701
  return false;
20567
20702
  }
@@ -20569,7 +20704,7 @@ function isGitDirectory(path) {
20569
20704
  function inspectPath(path) {
20570
20705
  let stat;
20571
20706
  try {
20572
- stat = lstatSync3(path);
20707
+ stat = lstatSync4(path);
20573
20708
  } catch (error) {
20574
20709
  const code = errorCode(error);
20575
20710
  if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing", path };
@@ -20580,7 +20715,7 @@ function inspectPath(path) {
20580
20715
  return { status: "corrupt", path, reason: "invalid_content" };
20581
20716
  }
20582
20717
  try {
20583
- const contents = readFileSync8(path, "utf8");
20718
+ const contents = readFileSync9(path, "utf8");
20584
20719
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
20585
20720
  if ((contents === workspaceId || contents === `${workspaceId}
20586
20721
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -20598,8 +20733,8 @@ function inspectPath(path) {
20598
20733
  }
20599
20734
  function createWorkspaceId(path) {
20600
20735
  const parent = dirname7(path);
20601
- const workspaceId = randomUUID2();
20602
- const temporaryPath = join9(parent, `.workspace-id-${process.pid}-${randomUUID2()}.tmp`);
20736
+ const workspaceId = randomUUID3();
20737
+ const temporaryPath = join10(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
20603
20738
  let temporaryCreated = false;
20604
20739
  let publishing = false;
20605
20740
  try {
@@ -20669,33 +20804,33 @@ function parseAgent(argv) {
20669
20804
  }
20670
20805
 
20671
20806
  // src/hooks/codex-context.ts
20672
- import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
20807
+ import { createHash as createHash6, randomBytes as randomBytes4 } from "crypto";
20673
20808
  import {
20674
20809
  chmodSync as chmodSync4,
20675
- existsSync as existsSync6,
20810
+ existsSync as existsSync8,
20676
20811
  mkdirSync as mkdirSync5,
20677
- readFileSync as readFileSync9,
20678
- readdirSync,
20812
+ readFileSync as readFileSync10,
20813
+ readdirSync as readdirSync2,
20679
20814
  renameSync as renameSync2,
20680
20815
  rmSync as rmSync4,
20681
20816
  statSync as statSync3,
20682
20817
  unlinkSync as unlinkSync2,
20683
20818
  writeFileSync as writeFileSync4
20684
20819
  } from "fs";
20685
- import { join as join11 } from "path";
20820
+ import { join as join12 } from "path";
20686
20821
 
20687
20822
  // src/daemon/client.ts
20688
20823
  import { createConnection } from "net";
20689
- import { join as join10 } from "path";
20824
+ import { join as join11 } from "path";
20690
20825
 
20691
20826
  // src/daemon/principal.ts
20692
- import { createHash as createHash4 } from "crypto";
20827
+ import { createHash as createHash5 } from "crypto";
20693
20828
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
20694
20829
  function boundedClaim(value) {
20695
20830
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
20696
20831
  }
20697
20832
  function sha256(value) {
20698
- return createHash4("sha256").update(value).digest("hex");
20833
+ return createHash5("sha256").update(value).digest("hex");
20699
20834
  }
20700
20835
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
20701
20836
  if (!token) return void 0;
@@ -20736,7 +20871,7 @@ function parseDaemonResponseEnvelope(value) {
20736
20871
  }
20737
20872
 
20738
20873
  // src/daemon/client.ts
20739
- var SOCK_PATH = join10(primConfigDirectory(), "sock");
20874
+ var SOCK_PATH = join11(primConfigDirectory(), "sock");
20740
20875
  var DEFAULT_TIMEOUT_MS2 = 250;
20741
20876
  var nextRequestId = 1;
20742
20877
  function daemonRequest(method, params = {}, opts = {}) {
@@ -20749,7 +20884,7 @@ function daemonRequest(method, params = {}, opts = {}) {
20749
20884
  ...caller ? { caller } : {}
20750
20885
  };
20751
20886
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
20752
- return new Promise((resolve6) => {
20887
+ return new Promise((resolve7) => {
20753
20888
  let settled = false;
20754
20889
  let socket;
20755
20890
  let buffer = Buffer.alloc(0);
@@ -20764,7 +20899,7 @@ function daemonRequest(method, params = {}, opts = {}) {
20764
20899
  } catch {
20765
20900
  }
20766
20901
  }
20767
- resolve6(value);
20902
+ resolve7(value);
20768
20903
  };
20769
20904
  const timer = setTimeout(() => settle(null), timeoutMs);
20770
20905
  timer.unref();
@@ -21037,10 +21172,10 @@ function appendCodexContext(output, context) {
21037
21172
  return next;
21038
21173
  }
21039
21174
  function stateRoot(namespace) {
21040
- return join11(primConfigDirectory(), namespace, "decision-digests");
21175
+ return join12(primConfigDirectory(), namespace, "decision-digests");
21041
21176
  }
21042
21177
  function draftStateRoot(namespace) {
21043
- return join11(primConfigDirectory(), namespace, "decision-draft-deliveries");
21178
+ return join12(primConfigDirectory(), namespace, "decision-draft-deliveries");
21044
21179
  }
21045
21180
  function workspaceFor(cwd) {
21046
21181
  try {
@@ -21051,13 +21186,13 @@ function workspaceFor(cwd) {
21051
21186
  }
21052
21187
  function statePath(args) {
21053
21188
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
21054
- const key = createHash5("sha256").update(identity).digest("hex");
21055
- return join11(stateRoot(args.namespace), `${key}.json`);
21189
+ const key = createHash6("sha256").update(identity).digest("hex");
21190
+ return join12(stateRoot(args.namespace), `${key}.json`);
21056
21191
  }
21057
21192
  function draftStatePath(args) {
21058
21193
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
21059
- const key = createHash5("sha256").update(identity).digest("hex");
21060
- return join11(draftStateRoot(args.namespace), `${key}.json`);
21194
+ const key = createHash6("sha256").update(identity).digest("hex");
21195
+ return join12(draftStateRoot(args.namespace), `${key}.json`);
21061
21196
  }
21062
21197
  function parseState(value) {
21063
21198
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -21096,17 +21231,17 @@ function parseDraftState(value) {
21096
21231
  };
21097
21232
  }
21098
21233
  function readState(path) {
21099
- if (!existsSync6(path)) return void 0;
21234
+ if (!existsSync8(path)) return void 0;
21100
21235
  try {
21101
- return parseState(JSON.parse(readFileSync9(path, "utf8")));
21236
+ return parseState(JSON.parse(readFileSync10(path, "utf8")));
21102
21237
  } catch {
21103
21238
  return void 0;
21104
21239
  }
21105
21240
  }
21106
21241
  function readDraftState(path) {
21107
- if (!existsSync6(path)) return void 0;
21242
+ if (!existsSync8(path)) return void 0;
21108
21243
  try {
21109
- return parseDraftState(JSON.parse(readFileSync9(path, "utf8")));
21244
+ return parseDraftState(JSON.parse(readFileSync10(path, "utf8")));
21110
21245
  } catch {
21111
21246
  return void 0;
21112
21247
  }
@@ -21114,7 +21249,7 @@ function readDraftState(path) {
21114
21249
  function writeStateFile(path, directory, state) {
21115
21250
  mkdirSync5(directory, { recursive: true, mode: 448 });
21116
21251
  chmodSync4(directory, 448);
21117
- const temporary = join11(
21252
+ const temporary = join12(
21118
21253
  directory,
21119
21254
  `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes4(8).toString("hex")}`
21120
21255
  );
@@ -21135,17 +21270,17 @@ function writeStateFile(path, directory, state) {
21135
21270
  }
21136
21271
  }
21137
21272
  function cleanupStateFiles(directory, now) {
21138
- if (!existsSync6(directory)) return;
21273
+ if (!existsSync8(directory)) return;
21139
21274
  let names;
21140
21275
  try {
21141
- names = readdirSync(directory);
21276
+ names = readdirSync2(directory);
21142
21277
  } catch {
21143
21278
  return;
21144
21279
  }
21145
21280
  const files = [];
21146
21281
  const residue = [];
21147
21282
  for (const name of names) {
21148
- const path = join11(directory, name);
21283
+ const path = join12(directory, name);
21149
21284
  try {
21150
21285
  const mtimeMs = statSync3(path).mtimeMs;
21151
21286
  if (name.endsWith(".json")) {
@@ -21450,23 +21585,23 @@ async function prepareCodexContext(options) {
21450
21585
  }
21451
21586
 
21452
21587
  // src/commands/cursor-install.ts
21453
- import { existsSync as existsSync9, readFileSync as readFileSync12 } from "fs";
21588
+ import { existsSync as existsSync11, readFileSync as readFileSync13 } from "fs";
21454
21589
  import { homedir as homedir4 } from "os";
21455
- import { isAbsolute as isAbsolute6, join as join14 } from "path";
21590
+ import { isAbsolute as isAbsolute6, join as join15 } from "path";
21456
21591
 
21457
21592
  // src/lib/hook-runtime.ts
21458
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
21593
+ import { createHash as createHash7, randomBytes as randomBytes5 } from "crypto";
21459
21594
  import {
21460
21595
  constants as constants3,
21461
21596
  accessSync,
21462
21597
  chmodSync as chmodSync5,
21463
21598
  copyFileSync,
21464
- existsSync as existsSync7,
21465
- lstatSync as lstatSync4,
21599
+ existsSync as existsSync9,
21600
+ lstatSync as lstatSync5,
21466
21601
  mkdirSync as mkdirSync6,
21467
21602
  mkdtempSync,
21468
- readFileSync as readFileSync10,
21469
- readdirSync as readdirSync2,
21603
+ readFileSync as readFileSync11,
21604
+ readdirSync as readdirSync3,
21470
21605
  realpathSync as realpathSync2,
21471
21606
  renameSync as renameSync3,
21472
21607
  rmSync as rmSync5,
@@ -21474,7 +21609,7 @@ import {
21474
21609
  utimesSync,
21475
21610
  writeFileSync as writeFileSync5
21476
21611
  } from "fs";
21477
- import { delimiter, dirname as dirname8, isAbsolute as isAbsolute5, join as join12, resolve as resolve4 } from "path";
21612
+ import { delimiter, dirname as dirname8, isAbsolute as isAbsolute5, join as join13, resolve as resolve5 } from "path";
21478
21613
 
21479
21614
  // src/lib/git-hook-contract.ts
21480
21615
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -21567,9 +21702,9 @@ exec "$prim_node" "$prim_entry" "$@"
21567
21702
  `;
21568
21703
 
21569
21704
  // src/commands/claude-install.ts
21570
- import { existsSync as existsSync8, readFileSync as readFileSync11 } from "fs";
21705
+ import { existsSync as existsSync10, readFileSync as readFileSync12 } from "fs";
21571
21706
  import { homedir as homedir3 } from "os";
21572
- import { join as join13 } from "path";
21707
+ import { join as join14 } from "path";
21573
21708
  var CAPTURE_BIN = "prim-hook";
21574
21709
  var GATE_BIN = "prim-pre-tool-use";
21575
21710
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -21578,7 +21713,7 @@ var SESSION_END_BIN = "prim-session-end";
21578
21713
  var STATUSLINE_BIN = "prim-statusline";
21579
21714
  var STATUSLINE_ARGS = "";
21580
21715
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
21581
- var USER_SCOPE_PATH = join13(homedir3(), ".claude", "settings.json");
21716
+ var USER_SCOPE_PATH = join14(homedir3(), ".claude", "settings.json");
21582
21717
  function projectRoot() {
21583
21718
  return gitToplevel() ?? process.cwd();
21584
21719
  }
@@ -21657,20 +21792,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
21657
21792
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
21658
21793
  if (explicit && isAbsolute6(explicit)) return explicit;
21659
21794
  const xdg = env.XDG_CONFIG_HOME?.trim();
21660
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join14(xdg, "cursor");
21661
- return join14(home, ".cursor");
21795
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join15(xdg, "cursor");
21796
+ return join15(home, ".cursor");
21662
21797
  }
21663
21798
  function cursorHooksPath(scope, root = projectRoot()) {
21664
- return scope === "user" ? join14(cursorConfigDirectory(), "hooks.json") : join14(root, ".cursor", "hooks.json");
21799
+ return scope === "user" ? join15(cursorConfigDirectory(), "hooks.json") : join15(root, ".cursor", "hooks.json");
21665
21800
  }
21666
21801
  function plainObject(value) {
21667
21802
  return typeof value === "object" && value !== null && !Array.isArray(value);
21668
21803
  }
21669
21804
  function readCursorHooks(path) {
21670
- if (!existsSync9(path)) return {};
21805
+ if (!existsSync11(path)) return {};
21671
21806
  let parsed;
21672
21807
  try {
21673
- parsed = JSON.parse(readFileSync12(path, "utf8"));
21808
+ parsed = JSON.parse(readFileSync13(path, "utf8"));
21674
21809
  } catch {
21675
21810
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
21676
21811
  }
@@ -21890,8 +22025,8 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
21890
22025
  }
21891
22026
 
21892
22027
  // src/hooks/redact.ts
21893
- import { existsSync as existsSync10, readFileSync as readFileSync13, statSync as statSync5 } from "fs";
21894
- import { join as join15 } from "path";
22028
+ import { existsSync as existsSync12, readFileSync as readFileSync14, statSync as statSync5 } from "fs";
22029
+ import { join as join16 } from "path";
21895
22030
  import { Worker } from "worker_threads";
21896
22031
  var USER_HOME_RULES = [
21897
22032
  {
@@ -21967,15 +22102,15 @@ function normalizedWorkspaceFlags(value) {
21967
22102
  return [...new Set(`g${requested}`)].sort().join("");
21968
22103
  }
21969
22104
  function loadWorkspaceRules(cwd) {
21970
- const path = join15(cwd, WORKSPACE_FILE2);
21971
- if (!existsSync10(path)) return [];
22105
+ const path = join16(cwd, WORKSPACE_FILE2);
22106
+ if (!existsSync12(path)) return [];
21972
22107
  let cfg;
21973
22108
  try {
21974
22109
  if (statSync5(path).size > MAX_WORKSPACE_CONFIG_BYTES) {
21975
22110
  debugRedaction(`ignoring oversized ${WORKSPACE_FILE2}`);
21976
22111
  return [];
21977
22112
  }
21978
- cfg = JSON.parse(readFileSync13(path, "utf-8"));
22113
+ cfg = JSON.parse(readFileSync14(path, "utf-8"));
21979
22114
  } catch {
21980
22115
  debugRedaction(`ignoring unparseable ${WORKSPACE_FILE2}`);
21981
22116
  return [];
@@ -22094,7 +22229,7 @@ function applyWorkspaceRules(value, rules) {
22094
22229
  flags: pattern.flags,
22095
22230
  reason
22096
22231
  }));
22097
- return new Promise((resolve6) => {
22232
+ return new Promise((resolve7) => {
22098
22233
  let worker;
22099
22234
  try {
22100
22235
  worker = new Worker(WORKSPACE_REDACTION_WORKER, {
@@ -22102,7 +22237,7 @@ function applyWorkspaceRules(value, rules) {
22102
22237
  workerData: { value, rules: serialized }
22103
22238
  });
22104
22239
  } catch {
22105
- resolve6(redactEveryString(value, "workspace-rule-failed"));
22240
+ resolve7(redactEveryString(value, "workspace-rule-failed"));
22106
22241
  return;
22107
22242
  }
22108
22243
  let settled = false;
@@ -22111,7 +22246,7 @@ function applyWorkspaceRules(value, rules) {
22111
22246
  settled = true;
22112
22247
  clearTimeout(timer);
22113
22248
  void worker.terminate();
22114
- resolve6(result);
22249
+ resolve7(result);
22115
22250
  };
22116
22251
  const failClosed = () => finish2(redactEveryString(value, "workspace-rule-failed"));
22117
22252
  const timer = setTimeout(failClosed, WORKSPACE_RULE_TIMEOUT_MS);
@@ -26682,7 +26817,7 @@ function enrichHookPayloadWithFileRefs(args) {
26682
26817
  // src/hooks/hook-stdin.ts
26683
26818
  var DEFAULT_MAX_BYTES = 1024 * 1024;
26684
26819
  function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
26685
- return new Promise((resolve6, reject) => {
26820
+ return new Promise((resolve7, reject) => {
26686
26821
  const chunks = [];
26687
26822
  let bytes = 0;
26688
26823
  let settled = false;
@@ -26694,7 +26829,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
26694
26829
  process.stdin.removeAllListeners("end");
26695
26830
  process.stdin.removeAllListeners("error");
26696
26831
  if (error) reject(error);
26697
- else resolve6(Buffer.concat(chunks, bytes).toString("utf-8"));
26832
+ else resolve7(Buffer.concat(chunks, bytes).toString("utf-8"));
26698
26833
  };
26699
26834
  const timer = setTimeout(() => finish2(new Error("stdin read timeout")), timeoutMs);
26700
26835
  process.stdin.on("data", (chunk) => {
@@ -26711,9 +26846,9 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
26711
26846
  }
26712
26847
 
26713
26848
  // src/hooks/normalize.ts
26714
- import { createHash as createHash7 } from "crypto";
26849
+ import { createHash as createHash8 } from "crypto";
26715
26850
  import { realpathSync as realpathSync3 } from "fs";
26716
- import { isAbsolute as isAbsolute8, resolve as resolve5 } from "path";
26851
+ import { isAbsolute as isAbsolute8, resolve as resolve6 } from "path";
26717
26852
  var HERMES_EVENT_MAP = {
26718
26853
  on_session_start: "SessionStart",
26719
26854
  on_session_end: "SessionEnd",
@@ -26756,7 +26891,7 @@ function requiredId(value, field) {
26756
26891
  }
26757
26892
  function cursorToolUseId(value) {
26758
26893
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
26759
- return `cursor:tool:v1:${createHash7("sha256").update(value).digest("hex")}`;
26894
+ return `cursor:tool:v1:${createHash8("sha256").update(value).digest("hex")}`;
26760
26895
  }
26761
26896
  function workspaceCandidates(value) {
26762
26897
  if (!Array.isArray(value)) return [];
@@ -26770,7 +26905,7 @@ function pathIdentity(path) {
26770
26905
  try {
26771
26906
  return realpathSync3.native(path);
26772
26907
  } catch {
26773
- return resolve5(path);
26908
+ return resolve6(path);
26774
26909
  }
26775
26910
  }
26776
26911
  function resolveCursorCwd(parsed) {
@@ -26795,7 +26930,7 @@ function resolveCursorCwd(parsed) {
26795
26930
  if (rawToolCwd && !isAbsolute8(rawToolCwd) && !base) {
26796
26931
  throw new TypeError("relative Cursor tool cwd has no workspace base");
26797
26932
  }
26798
- const toolCwd = rawToolCwd ? pathIdentity(isAbsolute8(rawToolCwd) ? rawToolCwd : resolve5(base, rawToolCwd)) : void 0;
26933
+ const toolCwd = rawToolCwd ? pathIdentity(isAbsolute8(rawToolCwd) ? rawToolCwd : resolve6(base, rawToolCwd)) : void 0;
26799
26934
  const selected = toolCwd ?? envelopeCwd ?? (roots.length === 1 ? roots[0] : expectedRepo);
26800
26935
  if (!selected) {
26801
26936
  throw new TypeError("Cursor hook envelope has no unambiguous workspace");
@@ -26853,7 +26988,7 @@ function normalizeEnvelope(parsed, agent) {
26853
26988
  ]);
26854
26989
  return {
26855
26990
  ...parsed,
26856
- tool_use_id: `codex:fallback:v1:${createHash7("sha256").update(stableToolIdentity).digest("hex")}`
26991
+ tool_use_id: `codex:fallback:v1:${createHash8("sha256").update(stableToolIdentity).digest("hex")}`
26857
26992
  };
26858
26993
  }
26859
26994
  return parsed;
@@ -26901,30 +27036,30 @@ function requireDurableIngestAcknowledgement(value, expected, cwd = process.cwd(
26901
27036
  import {
26902
27037
  appendFileSync,
26903
27038
  closeSync as closeSync3,
26904
- existsSync as existsSync12,
27039
+ existsSync as existsSync14,
26905
27040
  fstatSync,
26906
27041
  mkdirSync as mkdirSync7,
26907
27042
  openSync as openSync3,
26908
27043
  opendirSync,
26909
- readFileSync as readFileSync15,
27044
+ readFileSync as readFileSync16,
26910
27045
  readSync,
26911
- readdirSync as readdirSync4
27046
+ readdirSync as readdirSync5
26912
27047
  } from "fs";
26913
- import { dirname as dirname11, join as join17 } from "path";
27048
+ import { dirname as dirname11, join as join18 } from "path";
26914
27049
 
26915
27050
  // src/drain-progress.ts
26916
27051
  import {
26917
27052
  chmodSync as chmodSync6,
26918
- existsSync as existsSync11,
26919
- readFileSync as readFileSync14,
26920
- readdirSync as readdirSync3,
27053
+ existsSync as existsSync13,
27054
+ readFileSync as readFileSync15,
27055
+ readdirSync as readdirSync4,
26921
27056
  rmSync as rmSync6,
26922
27057
  rmdirSync
26923
27058
  } from "fs";
26924
- import { basename as basename2, dirname as dirname10, join as join16 } from "path";
27059
+ import { basename as basename2, dirname as dirname10, join as join17 } from "path";
26925
27060
 
26926
27061
  // src/journal.ts
26927
- var JOURNAL_DIR = join17(primConfigDirectory(), "moves");
27062
+ var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
26928
27063
  var UNBOUND_BUCKET = "_unbound";
26929
27064
  var JOURNAL_BASENAME = "journal.ndjson";
26930
27065
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -26936,7 +27071,7 @@ function envSlug(apiUrl) {
26936
27071
  return slug;
26937
27072
  }
26938
27073
  function currentEnvDir() {
26939
- return join17(JOURNAL_DIR, envSlug(getSiteUrl()));
27074
+ return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
26940
27075
  }
26941
27076
  var DIR_MODE = 448;
26942
27077
  var FILE_MODE2 = 384;
@@ -26944,7 +27079,7 @@ var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
26944
27079
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
26945
27080
  function appendMoveToPath(path, move) {
26946
27081
  const dir = dirname11(path);
26947
- if (!existsSync12(dir)) {
27082
+ if (!existsSync14(dir)) {
26948
27083
  mkdirSync7(dir, { recursive: true, mode: DIR_MODE });
26949
27084
  }
26950
27085
  appendFileSync(path, `${JSON.stringify(move)}
@@ -26952,10 +27087,10 @@ function appendMoveToPath(path, move) {
26952
27087
  }
26953
27088
  function bucketDir(orgId) {
26954
27089
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
26955
- return join17(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
27090
+ return join18(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
26956
27091
  }
26957
27092
  function journalPath(orgId) {
26958
- return join17(bucketDir(orgId), JOURNAL_BASENAME);
27093
+ return join18(bucketDir(orgId), JOURNAL_BASENAME);
26959
27094
  }
26960
27095
  function appendMove(move, orgId) {
26961
27096
  appendMoveToPath(journalPath(orgId), move);
@@ -26975,7 +27110,7 @@ async function deliverPostToolMove(move, orgId) {
26975
27110
  }
26976
27111
 
26977
27112
  // src/hooks/prim-hook-core.ts
26978
- import { createHash as createHash8, randomUUID as randomUUID3 } from "crypto";
27113
+ import { createHash as createHash9, randomUUID as randomUUID4 } from "crypto";
26979
27114
  import { platform } from "os";
26980
27115
 
26981
27116
  // src/protocol/move.ts
@@ -27049,9 +27184,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
27049
27184
  const toolOutcome = toolOutcomeFor(parsed, agent);
27050
27185
  let moveId;
27051
27186
  if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
27052
- moveId = `posttool:v1:${createHash8("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
27187
+ moveId = `posttool:v1:${createHash9("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
27053
27188
  } else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
27054
- moveId = `posttool:fallback:v1:${createHash8("sha256").update(
27189
+ moveId = `posttool:fallback:v1:${createHash9("sha256").update(
27055
27190
  JSON.stringify([
27056
27191
  agent,
27057
27192
  sessionId,
@@ -27062,7 +27197,7 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
27062
27197
  ])
27063
27198
  ).digest("hex")}`;
27064
27199
  } else {
27065
- moveId = randomUUID3();
27200
+ moveId = randomUUID4();
27066
27201
  }
27067
27202
  return {
27068
27203
  moveId,
@@ -27127,19 +27262,19 @@ function editingToolsFor(agent) {
27127
27262
  var here = dirname12(fileURLToPath2(import.meta.url));
27128
27263
  function resolveCliVersion() {
27129
27264
  try {
27130
- const pkg = JSON.parse(readFileSync16(join18(here, "..", "..", "package.json"), "utf-8"));
27265
+ const pkg = JSON.parse(readFileSync17(join19(here, "..", "..", "package.json"), "utf-8"));
27131
27266
  return pkg.version ?? "unknown";
27132
27267
  } catch {
27133
27268
  return "unknown";
27134
27269
  }
27135
27270
  }
27136
27271
  async function emit(output = {}) {
27137
- return await new Promise((resolve6) => {
27272
+ return await new Promise((resolve7) => {
27138
27273
  try {
27139
27274
  process.stdout.write(`${JSON.stringify(output)}
27140
- `, (error) => resolve6(!error));
27275
+ `, (error) => resolve7(!error));
27141
27276
  } catch {
27142
- resolve6(false);
27277
+ resolve7(false);
27143
27278
  }
27144
27279
  });
27145
27280
  }
@@ -27194,6 +27329,10 @@ async function main() {
27194
27329
  return;
27195
27330
  }
27196
27331
  parsed = normalizeEnvelope(incoming, agent);
27332
+ if (observeDemoInvocation(parsed, agent).excluded) {
27333
+ await emit();
27334
+ return;
27335
+ }
27197
27336
  } catch {
27198
27337
  await emit();
27199
27338
  return;