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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
  3. package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
  4. package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
  5. package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
  6. package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
  7. package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
  8. package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
  9. package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
  10. package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
  11. package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
  12. package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
  13. package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
  14. package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
  15. package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
  16. package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
  17. package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
  19. package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
  20. package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
  21. package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
  22. package/dist/daemon/server.js +1311 -364
  23. package/dist/hook-runtime/daemon/server.js +1311 -364
  24. package/dist/hook-runtime/hooks/post-commit.js +395 -242
  25. package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
  27. package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
  29. package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
  30. package/dist/hook-runtime/hooks/session-end.js +369 -216
  31. package/dist/hook-runtime/hooks/session-start.js +1209 -219
  32. package/dist/hook-runtime/index.js +2406 -1036
  33. package/dist/hook-runtime/statusline-main.js +360 -207
  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 +63 -20
  42. package/dist/index.js +387 -43
  43. package/dist/statusline-main.js +360 -207
  44. package/package.json +1 -1
@@ -63,33 +63,33 @@ import {
63
63
  readFileSync as readFileSync17,
64
64
  unlinkSync as unlinkSync2
65
65
  } from "fs";
66
- import { basename as basename4, dirname as dirname11, isAbsolute as isAbsolute5, join as join18 } from "path";
66
+ import { basename as basename4, dirname as dirname11, isAbsolute as isAbsolute5, join as join19 } from "path";
67
67
  import { fileURLToPath as fileURLToPath4 } from "url";
68
68
 
69
69
  // src/binding.ts
70
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
71
- import { dirname as dirname5, join as join8 } from "path";
70
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
71
+ import { dirname as dirname6, join as join10 } from "path";
72
72
 
73
73
  // src/lib/credentials.ts
74
- import { createHash as createHash4 } from "crypto";
75
- import { readFileSync as readFileSync6 } from "fs";
76
- import { join as join7 } from "path";
74
+ import { createHash as createHash6 } from "crypto";
75
+ import { readFileSync as readFileSync7 } from "fs";
76
+ import { join as join9 } from "path";
77
77
 
78
78
  // src/lib/machine-credentials.ts
79
- import { execFileSync } from "child_process";
80
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
79
+ import { execFileSync as execFileSync2 } from "child_process";
80
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
81
81
  import {
82
82
  chmodSync,
83
83
  existsSync as existsSync3,
84
84
  linkSync,
85
- lstatSync as lstatSync3,
85
+ lstatSync as lstatSync4,
86
86
  mkdirSync as mkdirSync3,
87
- readFileSync as readFileSync5,
88
- rmSync as rmSync5,
87
+ readFileSync as readFileSync6,
88
+ rmSync as rmSync6,
89
89
  writeFileSync as writeFileSync3
90
90
  } from "fs";
91
91
  import { createRequire } from "module";
92
- import { dirname as dirname4, join as join6 } from "path";
92
+ import { dirname as dirname5, join as join8 } from "path";
93
93
  import { fileURLToPath as fileURLToPath3 } from "url";
94
94
 
95
95
  // src/lib/atomic-file.ts
@@ -173,6 +173,8 @@ import { Readable } from "stream";
173
173
  function isClaudeCloudSession(env = process.env) {
174
174
  return env.CLAUDE_CODE_REMOTE === "true";
175
175
  }
176
+ 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';
177
+ 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}.`;
176
178
 
177
179
  // src/lib/workos-connect.ts
178
180
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -360,24 +362,320 @@ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rm
360
362
  import { join as join5 } from "path";
361
363
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
362
364
 
365
+ // src/lib/session-identity.ts
366
+ import { execFile } from "child_process";
367
+ import { createHash as createHash4 } from "crypto";
368
+ import { rmSync as rmSync5 } from "fs";
369
+ import { join as join7 } from "path";
370
+ import { promisify } from "util";
371
+
372
+ // src/lib/git.ts
373
+ import { execFileSync } from "child_process";
374
+ import { createHash as createHash3 } from "crypto";
375
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
376
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
377
+ var GIT_TIMEOUT_MS = 1e3;
378
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
379
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
380
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
381
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
382
+ function gitChildEnvironment(env = process.env) {
383
+ return Object.fromEntries(
384
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
385
+ );
386
+ }
387
+ function gitToplevel(cwd) {
388
+ try {
389
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
390
+ cwd,
391
+ encoding: "utf-8",
392
+ stdio: ["ignore", "pipe", "ignore"],
393
+ timeout: GIT_TIMEOUT_MS,
394
+ env: gitChildEnvironment()
395
+ }).trim();
396
+ } catch {
397
+ return null;
398
+ }
399
+ }
400
+ function gitValue(cwd, args) {
401
+ try {
402
+ const value = execFileSync("git", args, {
403
+ cwd,
404
+ encoding: "utf-8",
405
+ stdio: ["ignore", "pipe", "ignore"],
406
+ timeout: GIT_TIMEOUT_MS,
407
+ env: gitChildEnvironment()
408
+ }).trim();
409
+ return value || void 0;
410
+ } catch {
411
+ return void 0;
412
+ }
413
+ }
414
+ function parseGithubRepositoryName(path) {
415
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
416
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
417
+ return null;
418
+ }
419
+ return `${parts[0]}/${parts[1]}`;
420
+ }
421
+ function githubRepositoryFromRemote(remote) {
422
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
423
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
424
+ remote
425
+ );
426
+ const path = match?.[1] ?? match?.[2];
427
+ return path ? parseGithubRepositoryName(path) : null;
428
+ }
429
+ function checkoutSettingsText(repoRoot) {
430
+ const path = join6(repoRoot, ".claude", "settings.json");
431
+ try {
432
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
433
+ const stat = lstatSync3(path);
434
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
435
+ return readFileSync5(path, "utf8");
436
+ } catch {
437
+ return null;
438
+ }
439
+ }
440
+ function checkoutDeclaration(repoRoot, name) {
441
+ const text = checkoutSettingsText(repoRoot);
442
+ if (text === null) return null;
443
+ let parsed;
444
+ try {
445
+ parsed = JSON.parse(text);
446
+ } catch {
447
+ return null;
448
+ }
449
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
450
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
451
+ return typeof value === "string" ? value : null;
452
+ }
453
+ function declaredGithubRepository(repoRoot) {
454
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
455
+ return value === null ? null : parseGithubRepositoryName(value.trim());
456
+ }
457
+ function githubRepositoryFullName(cwd) {
458
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
459
+ if (remote) {
460
+ const fromOrigin = githubRepositoryFromRemote(remote);
461
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
462
+ }
463
+ const root = gitToplevel(cwd);
464
+ return root ? declaredGithubRepository(root) : null;
465
+ }
466
+ function normalizeOriginRemote(remote) {
467
+ const value = remote.trim();
468
+ if (!value) return void 0;
469
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
470
+ if (scp?.host && scp.path) {
471
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
472
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
473
+ }
474
+ try {
475
+ const url = new URL(value);
476
+ url.username = "";
477
+ url.password = "";
478
+ url.search = "";
479
+ url.hash = "";
480
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
481
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
482
+ return void 0;
483
+ } catch {
484
+ return void 0;
485
+ }
486
+ }
487
+ function opaqueRepoKey(source, value) {
488
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
489
+ }
490
+ function resolveRepositoryContext(cwd = process.cwd()) {
491
+ const top = gitToplevel(cwd);
492
+ if (!top) return null;
493
+ let repoRoot;
494
+ try {
495
+ repoRoot = realpathSync.native(top);
496
+ } catch {
497
+ repoRoot = resolve(top);
498
+ }
499
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
500
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
501
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
502
+ if (normalizedOrigin) {
503
+ return {
504
+ repoRoot,
505
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
506
+ identitySource: "origin",
507
+ repoFullName
508
+ };
509
+ }
510
+ if (repoFullName) {
511
+ return {
512
+ repoRoot,
513
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
514
+ identitySource: "declared",
515
+ repoFullName
516
+ };
517
+ }
518
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
519
+ if (roots && roots.length > 0) {
520
+ return {
521
+ repoRoot,
522
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
523
+ identitySource: "root_commit",
524
+ repoFullName
525
+ };
526
+ }
527
+ return { repoRoot, repoFullName };
528
+ }
529
+
530
+ // src/lib/session-identity.ts
531
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
532
+ var SESSION_IDENTITY_VALUE = "session";
533
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
534
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
535
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
536
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
537
+ var RENEW_BEFORE_MS = 6e4;
538
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
539
+ var RESPONSE_MAX_BYTES = 64 * 1024;
540
+ function sessionIdentityRequested(env = process.env) {
541
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
542
+ }
543
+ function sessionIdentityMode(deps = {}) {
544
+ const env = deps.env ?? process.env;
545
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
546
+ }
547
+ function failure(code, cause, remedy) {
548
+ return { status: "failed", code, cause, remedy };
549
+ }
550
+ var NEW_SESSION_REMEDY = "start a new cloud session";
551
+ var SESSION_REVOKED = failure(
552
+ "session_revoked",
553
+ "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",
554
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
555
+ );
556
+ var CHALLENGE_WINDOW_PASSED = failure(
557
+ "challenge_expired",
558
+ "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)",
559
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
560
+ );
561
+ var CHALLENGE_GONE = failure(
562
+ "challenge_not_found",
563
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
564
+ NEW_SESSION_REMEDY
565
+ );
566
+ function hash(value) {
567
+ return createHash4("sha256").update(value).digest("hex");
568
+ }
569
+ function sessionContext(deps) {
570
+ const env = deps.env ?? process.env;
571
+ const environment = environmentCredentials(deps);
572
+ if (!environment)
573
+ return failure(
574
+ "environment_credential_missing",
575
+ "the cloud environment has no environment credential",
576
+ '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'
577
+ );
578
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
579
+ if (!sessionId || !SESSION_ID.test(sessionId))
580
+ return failure(
581
+ "session_id_missing",
582
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
583
+ NEW_SESSION_REMEDY
584
+ );
585
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
586
+ const directory = deps.directory ?? primConfigDirectory({ env });
587
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
588
+ return {
589
+ directory,
590
+ apiUrl,
591
+ clientId: environment.clientId,
592
+ generation: environment.generation,
593
+ sessionId,
594
+ tokenPath: join7(directory, `session_identity_${key}.json`),
595
+ statePath: join7(directory, `session_identity_${key}.state.json`),
596
+ lockPath: join7(directory, "session-identity.lock")
597
+ };
598
+ }
599
+ function readRecord(path) {
600
+ try {
601
+ const value = readMachineMetadata(path);
602
+ return value === void 0 ? void 0 : machineRecord(value);
603
+ } catch {
604
+ return void 0;
605
+ }
606
+ }
607
+ function finiteNumber(value) {
608
+ return typeof value === "number" && Number.isFinite(value);
609
+ }
610
+ function readToken(context) {
611
+ const data = readRecord(context.tokenPath);
612
+ 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))
613
+ return void 0;
614
+ const identity = data.identity;
615
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
616
+ return void 0;
617
+ return data;
618
+ }
619
+ function tokenValid(record, now = Date.now()) {
620
+ return now < record.expiresAt - RENEW_BEFORE_MS;
621
+ }
622
+ function toCredential(record) {
623
+ return {
624
+ issuer: record.issuer,
625
+ audience: record.audience,
626
+ ...record.identity,
627
+ accessToken: record.accessToken,
628
+ expiresAt: record.expiresAt,
629
+ apiUrl: record.apiUrl,
630
+ generation: record.generation,
631
+ storage: "environment",
632
+ session: {
633
+ userId: record.userId,
634
+ displayName: record.displayName,
635
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
636
+ refreshAfter: record.refreshAfter
637
+ }
638
+ };
639
+ }
640
+ function cachedSessionCredential(deps = {}) {
641
+ if (!sessionIdentityMode(deps)) return void 0;
642
+ let context;
643
+ try {
644
+ context = sessionContext(deps);
645
+ } catch {
646
+ return void 0;
647
+ }
648
+ if ("status" in context) return void 0;
649
+ const record = readToken(context);
650
+ return record && tokenValid(record) ? toCredential(record) : void 0;
651
+ }
652
+ var SERVER_CONTRACT_FAILURE = failure(
653
+ "server_contract",
654
+ "Primitive's answer did not identify the linked member",
655
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
656
+ );
657
+
363
658
  // src/lib/machine-credentials.ts
659
+ function sessionScoped(deps) {
660
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
661
+ }
364
662
  var require2 = createRequire(import.meta.url);
365
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
663
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
366
664
  var PROFILE_FILE = "machine_profile.json";
367
665
  var cached;
368
666
  function configurationDirectory(deps) {
369
667
  return deps.directory ?? primConfigDirectory({ env: deps.env });
370
668
  }
371
669
  function apiUrlFor(deps) {
372
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
670
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
373
671
  }
374
- function hash(value) {
375
- return createHash3("sha256").update(value).digest("hex");
672
+ function hash2(value) {
673
+ return createHash5("sha256").update(value).digest("hex");
376
674
  }
377
675
  function environmentContextPath(deps, clientId) {
378
- return join6(
676
+ return join8(
379
677
  configurationDirectory(deps),
380
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
678
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
381
679
  );
382
680
  }
383
681
  function readEnvironmentContext(environment, deps) {
@@ -408,7 +706,7 @@ function protectPath(path, directory) {
408
706
  }
409
707
  const encodedPath = Buffer.from(path).toString("base64");
410
708
  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)`;
411
- execFileSync(
709
+ execFileSync2(
412
710
  "powershell.exe",
413
711
  [
414
712
  "-NoProfile",
@@ -421,24 +719,27 @@ function protectPath(path, directory) {
421
719
  }
422
720
  function ensureDirectory(directory) {
423
721
  mkdirSync3(directory, { recursive: true, mode: 448 });
424
- if (lstatSync3(directory).isSymbolicLink())
722
+ if (lstatSync4(directory).isSymbolicLink())
425
723
  throw new MachineAuthError(
426
724
  "unsafe_storage",
427
725
  "Credential directory must not be a symbolic link."
428
726
  );
429
727
  protectPath(directory, true);
430
728
  }
729
+ function readMachineMetadata(path) {
730
+ return readPrivate(path);
731
+ }
431
732
  function readPrivate(path) {
432
733
  let raw;
433
734
  try {
434
- const stat = lstatSync3(path);
735
+ const stat = lstatSync4(path);
435
736
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
436
737
  throw new MachineAuthError(
437
738
  "unsafe_storage",
438
739
  "Machine credential files must be owner-only regular files."
439
740
  );
440
741
  }
441
- raw = readFileSync5(path, "utf8");
742
+ raw = readFileSync6(path, "utf8");
442
743
  } catch (error) {
443
744
  if (error.code === "ENOENT") return void 0;
444
745
  throw error;
@@ -483,7 +784,7 @@ function parseProfile(value) {
483
784
  };
484
785
  }
485
786
  function readMachineProfile(deps = {}) {
486
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
787
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
487
788
  return value === void 0 ? void 0 : parseProfile(value);
488
789
  }
489
790
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -492,20 +793,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
492
793
  var brokerKeys = /* @__PURE__ */ new Map();
493
794
  function networkSecretBrokerKey(deps, clientId) {
494
795
  const directory = configurationDirectory(deps);
495
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
796
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
496
797
  const known = brokerKeys.get(path);
497
798
  if (known) return known;
498
799
  ensureDirectory(directory);
499
800
  const read = () => {
500
801
  try {
501
- const stat = lstatSync3(path);
802
+ const stat = lstatSync4(path);
502
803
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
503
804
  throw new MachineAuthError(
504
805
  "unsafe_storage",
505
806
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
506
807
  true
507
808
  );
508
- const value = readFileSync5(path, "utf8").trim();
809
+ const value = readFileSync6(path, "utf8").trim();
509
810
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
510
811
  } catch (error) {
511
812
  if (error.code === "ENOENT") return void 0;
@@ -533,7 +834,7 @@ function networkSecretBrokerKey(deps, clientId) {
533
834
  } catch (error) {
534
835
  if (error.code !== "EEXIST") throw error;
535
836
  } finally {
536
- rmSync5(staged, { force: true });
837
+ rmSync6(staged, { force: true });
537
838
  }
538
839
  }
539
840
  const key = read()?.key;
@@ -566,7 +867,7 @@ function environmentCredentials(deps) {
566
867
  "conflicting_credentials",
567
868
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
568
869
  );
569
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
870
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
570
871
  const credentials = {
571
872
  clientId,
572
873
  generation,
@@ -587,12 +888,12 @@ function environmentCredentials(deps) {
587
888
  return {
588
889
  clientId,
589
890
  clientSecret,
590
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
891
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
591
892
  };
592
893
  }
593
894
  function hasMachineConfiguration(deps = {}) {
594
895
  const env = deps.env ?? process.env;
595
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
896
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
596
897
  if (configured && env.PRIM_TOKEN?.trim()) {
597
898
  throw new MachineAuthError(
598
899
  "conflicting_credentials",
@@ -604,6 +905,7 @@ function hasMachineConfiguration(deps = {}) {
604
905
  }
605
906
  function machineContext(deps = {}) {
606
907
  if (!hasMachineConfiguration(deps)) return void 0;
908
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
607
909
  const environment = environmentCredentials(deps);
608
910
  if (environment) {
609
911
  if (environmentTerminal === environment.generation) return void 0;
@@ -618,6 +920,7 @@ function machineContext(deps = {}) {
618
920
  return profile;
619
921
  }
620
922
  function cachedMachineCredential(deps = {}) {
923
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
621
924
  const context = machineContext(deps);
622
925
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
623
926
  }
@@ -639,31 +942,31 @@ function machineCaptureActor(deps = {}) {
639
942
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
640
943
  }
641
944
  function machineJournalBucket(identity) {
642
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
945
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
643
946
  }
644
947
  function identityPending(actor) {
645
948
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
646
949
  }
647
950
  function machinePendingBucket(identity) {
648
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
951
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
649
952
  }
650
953
 
651
954
  // src/lib/credentials.ts
652
955
  var CONFIG_DIRECTORY = primConfigDirectory();
653
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
654
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
655
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
656
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
657
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
658
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
659
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
660
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
956
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
957
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
958
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
959
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
960
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
961
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
962
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
963
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
661
964
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
662
965
  var CREDENTIAL_MIGRATION_VERSION = 1;
663
966
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
664
967
  function readTrimmed(path) {
665
968
  try {
666
- const value = readFileSync6(path, "utf8").trim();
969
+ const value = readFileSync7(path, "utf8").trim();
667
970
  return value || void 0;
668
971
  } catch {
669
972
  return void 0;
@@ -700,7 +1003,7 @@ function resolveAuthCredential(options = {}) {
700
1003
  return { token: stored, source: "token_file" };
701
1004
  }
702
1005
  function credentialFingerprint(value) {
703
- return createHash4("sha256").update(value).digest("hex");
1006
+ return createHash6("sha256").update(value).digest("hex");
704
1007
  }
705
1008
  function parseLegacyBrokerCredentialMetadata(value) {
706
1009
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -720,7 +1023,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
720
1023
  function readBoundedCredentialJson(path) {
721
1024
  let raw;
722
1025
  try {
723
- raw = readFileSync6(path, "utf8");
1026
+ raw = readFileSync7(path, "utf8");
724
1027
  } catch (error) {
725
1028
  return error.code === "ENOENT" ? void 0 : null;
726
1029
  }
@@ -793,14 +1096,14 @@ function jwtOrganizationId(token) {
793
1096
 
794
1097
  // src/binding.ts
795
1098
  var PRIM_CONFIG_DIR = primConfigDirectory();
796
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
1099
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
797
1100
  var WORKSPACE_FILE = ".prim/workspace.json";
798
1101
  function readJsonSafe(path) {
799
1102
  if (!existsSync4(path)) {
800
1103
  return;
801
1104
  }
802
1105
  try {
803
- return JSON.parse(readFileSync7(path, "utf-8"));
1106
+ return JSON.parse(readFileSync8(path, "utf-8"));
804
1107
  } catch {
805
1108
  return;
806
1109
  }
@@ -809,17 +1112,17 @@ function fromSessionMarker(sessionId) {
809
1112
  if (!sessionId) {
810
1113
  return;
811
1114
  }
812
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
1115
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
813
1116
  return marker?.orgId;
814
1117
  }
815
1118
  function fromWorkspaceFile(startDir) {
816
1119
  let dir = startDir;
817
1120
  while (true) {
818
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
1121
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
819
1122
  if (config?.orgId) {
820
1123
  return config.orgId;
821
1124
  }
822
- const parent = dirname5(dir);
1125
+ const parent = dirname6(dir);
823
1126
  if (parent === dir) {
824
1127
  return;
825
1128
  }
@@ -860,21 +1163,21 @@ import {
860
1163
  mkdirSync as mkdirSync5,
861
1164
  openSync as openSync2,
862
1165
  opendirSync,
863
- readFileSync as readFileSync11,
1166
+ readFileSync as readFileSync12,
864
1167
  readSync,
865
1168
  readdirSync as readdirSync3
866
1169
  } from "fs";
867
- import { dirname as dirname8, join as join12 } from "path";
1170
+ import { dirname as dirname9, join as join14 } from "path";
868
1171
 
869
1172
  // src/client.ts
870
- import { createHash as createHash5 } from "crypto";
871
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
872
- import { dirname as dirname6 } from "path";
1173
+ import { createHash as createHash7 } from "crypto";
1174
+ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync7 } from "fs";
1175
+ import { dirname as dirname7 } from "path";
873
1176
 
874
1177
  // src/daemon/client-instance-id.ts
875
1178
  import { randomBytes as randomBytes4 } from "crypto";
876
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
877
- import { join as join9 } from "path";
1179
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
1180
+ import { join as join11 } from "path";
878
1181
  var INSTANCE_BODY_CHARS = 43;
879
1182
  var INSTANCE_PREFIX = "pci_";
880
1183
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -883,12 +1186,12 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
883
1186
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
884
1187
 
885
1188
  // src/client.ts
886
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1189
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
887
1190
  function getSiteUrl() {
888
1191
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
889
1192
  }
890
1193
  function getSiteUrlForEnvironment(primApiUrl) {
891
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1194
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
892
1195
  }
893
1196
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
894
1197
 
@@ -896,15 +1199,15 @@ var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
896
1199
  import {
897
1200
  chmodSync as chmodSync4,
898
1201
  existsSync as existsSync6,
899
- readFileSync as readFileSync10,
1202
+ readFileSync as readFileSync11,
900
1203
  readdirSync as readdirSync2,
901
- rmSync as rmSync7,
1204
+ rmSync as rmSync8,
902
1205
  rmdirSync
903
1206
  } from "fs";
904
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
1207
+ import { basename as basename3, dirname as dirname8, join as join13 } from "path";
905
1208
 
906
1209
  // src/journal.ts
907
- var JOURNAL_DIR = join12(primConfigDirectory(), "moves");
1210
+ var JOURNAL_DIR = join14(primConfigDirectory(), "moves");
908
1211
  var UNBOUND_BUCKET = "_unbound";
909
1212
  var JOURNAL_BASENAME = "journal.ndjson";
910
1213
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -916,14 +1219,14 @@ function envSlug(apiUrl) {
916
1219
  return slug;
917
1220
  }
918
1221
  function currentEnvDir() {
919
- return join12(JOURNAL_DIR, envSlug(getSiteUrl()));
1222
+ return join14(JOURNAL_DIR, envSlug(getSiteUrl()));
920
1223
  }
921
1224
  var DIR_MODE = 448;
922
1225
  var FILE_MODE = 384;
923
1226
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
924
1227
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
925
1228
  function appendMoveToPath(path, move) {
926
- const dir = dirname8(path);
1229
+ const dir = dirname9(path);
927
1230
  if (!existsSync7(dir)) {
928
1231
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
929
1232
  }
@@ -932,10 +1235,10 @@ function appendMoveToPath(path, move) {
932
1235
  }
933
1236
  function bucketDir(orgId) {
934
1237
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
935
- return join12(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
1238
+ return join14(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
936
1239
  }
937
1240
  function journalPath(orgId) {
938
- return join12(bucketDir(orgId), JOURNAL_BASENAME);
1241
+ return join14(bucketDir(orgId), JOURNAL_BASENAME);
939
1242
  }
940
1243
  function appendMove(move, orgId) {
941
1244
  const actor = machineCaptureActor();
@@ -950,14 +1253,14 @@ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
950
1253
  import { execFileSync as execFileSync4 } from "child_process";
951
1254
  import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
952
1255
  import { homedir as homedir2 } from "os";
953
- import { join as join15 } from "path";
1256
+ import { join as join16 } from "path";
954
1257
 
955
1258
  // src/lib/cloud-prepared.ts
956
- import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync12, rmSync as rmSync8, writeFileSync as writeFileSync4 } from "fs";
957
- import { join as join13 } from "path";
1259
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9, writeFileSync as writeFileSync4 } from "fs";
1260
+ import { join as join15 } from "path";
958
1261
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
959
1262
  function cloudPreparedPath(env = process.env) {
960
- return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1263
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
961
1264
  }
962
1265
  function isPreparedCloudSession(env = process.env) {
963
1266
  if (!isClaudeCloudSession(env)) return false;
@@ -969,17 +1272,17 @@ function isPreparedCloudSession(env = process.env) {
969
1272
  }
970
1273
 
971
1274
  // src/lib/demo-pause.ts
972
- import { execFileSync as execFileSync2 } from "child_process";
1275
+ import { execFileSync as execFileSync3 } from "child_process";
973
1276
  var DEMO_PAUSE_MS = 30 * 6e4;
974
1277
  var PAUSE_KEY = "prim.demoPause";
975
- var GIT_TIMEOUT_MS = 1e3;
1278
+ var GIT_TIMEOUT_MS2 = 1e3;
976
1279
  function git(cwd, args) {
977
1280
  try {
978
- return execFileSync2("git", args, {
1281
+ return execFileSync3("git", args, {
979
1282
  cwd,
980
1283
  encoding: "utf-8",
981
1284
  stdio: ["ignore", "pipe", "ignore"],
982
- timeout: GIT_TIMEOUT_MS
1285
+ timeout: GIT_TIMEOUT_MS2
983
1286
  });
984
1287
  } catch {
985
1288
  return void 0;
@@ -987,10 +1290,10 @@ function git(cwd, args) {
987
1290
  }
988
1291
  function setLocal(cwd, key, value) {
989
1292
  try {
990
- execFileSync2(
1293
+ execFileSync3(
991
1294
  "git",
992
1295
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
993
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1296
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
994
1297
  );
995
1298
  } catch (error) {
996
1299
  if (value !== null || error.status !== 5) throw error;
@@ -1029,156 +1332,6 @@ function healDemoPause(cwd, pause, options = {}) {
1029
1332
  }
1030
1333
  }
1031
1334
 
1032
- // src/lib/git.ts
1033
- import { execFileSync as execFileSync3 } from "child_process";
1034
- import { createHash as createHash6 } from "crypto";
1035
- import { lstatSync as lstatSync5, readFileSync as readFileSync13, realpathSync } from "fs";
1036
- import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute3, join as join14, relative, resolve as resolve2, sep } from "path";
1037
- var GIT_TIMEOUT_MS2 = 1e3;
1038
- var MAX_SETTINGS_BYTES = 1024 * 1024;
1039
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1040
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1041
- function gitToplevel(cwd) {
1042
- try {
1043
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
1044
- cwd,
1045
- encoding: "utf-8",
1046
- stdio: ["ignore", "pipe", "ignore"],
1047
- timeout: GIT_TIMEOUT_MS2
1048
- }).trim();
1049
- } catch {
1050
- return null;
1051
- }
1052
- }
1053
- function gitValue(cwd, args) {
1054
- try {
1055
- const value = execFileSync3("git", args, {
1056
- cwd,
1057
- encoding: "utf-8",
1058
- stdio: ["ignore", "pipe", "ignore"],
1059
- timeout: GIT_TIMEOUT_MS2
1060
- }).trim();
1061
- return value || void 0;
1062
- } catch {
1063
- return void 0;
1064
- }
1065
- }
1066
- function parseGithubRepositoryName(path) {
1067
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1068
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1069
- return null;
1070
- }
1071
- return `${parts[0]}/${parts[1]}`;
1072
- }
1073
- function githubRepositoryFromRemote(remote) {
1074
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1075
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1076
- remote
1077
- );
1078
- const path = match?.[1] ?? match?.[2];
1079
- return path ? parseGithubRepositoryName(path) : null;
1080
- }
1081
- function checkoutSettingsText(repoRoot) {
1082
- const path = join14(repoRoot, ".claude", "settings.json");
1083
- try {
1084
- if (!lstatSync5(join14(repoRoot, ".claude")).isDirectory()) return null;
1085
- const stat = lstatSync5(path);
1086
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1087
- return readFileSync13(path, "utf8");
1088
- } catch {
1089
- return null;
1090
- }
1091
- }
1092
- function checkoutDeclaration(repoRoot, name) {
1093
- const text = checkoutSettingsText(repoRoot);
1094
- if (text === null) return null;
1095
- let parsed;
1096
- try {
1097
- parsed = JSON.parse(text);
1098
- } catch {
1099
- return null;
1100
- }
1101
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1102
- const value = typeof env === "object" && env !== null ? env[name] : void 0;
1103
- return typeof value === "string" ? value : null;
1104
- }
1105
- function declaredGithubRepository(repoRoot) {
1106
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1107
- return value === null ? null : parseGithubRepositoryName(value.trim());
1108
- }
1109
- function githubRepositoryFullName(cwd) {
1110
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1111
- if (remote) {
1112
- const fromOrigin = githubRepositoryFromRemote(remote);
1113
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1114
- }
1115
- const root = gitToplevel(cwd);
1116
- return root ? declaredGithubRepository(root) : null;
1117
- }
1118
- function normalizeOriginRemote(remote) {
1119
- const value = remote.trim();
1120
- if (!value) return void 0;
1121
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1122
- if (scp?.host && scp.path) {
1123
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1124
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1125
- }
1126
- try {
1127
- const url = new URL(value);
1128
- url.username = "";
1129
- url.password = "";
1130
- url.search = "";
1131
- url.hash = "";
1132
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1133
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1134
- return void 0;
1135
- } catch {
1136
- return void 0;
1137
- }
1138
- }
1139
- function opaqueRepoKey(source, value) {
1140
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
1141
- }
1142
- function resolveRepositoryContext(cwd = process.cwd()) {
1143
- const top = gitToplevel(cwd);
1144
- if (!top) return null;
1145
- let repoRoot;
1146
- try {
1147
- repoRoot = realpathSync.native(top);
1148
- } catch {
1149
- repoRoot = resolve2(top);
1150
- }
1151
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1152
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1153
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1154
- if (normalizedOrigin) {
1155
- return {
1156
- repoRoot,
1157
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
1158
- identitySource: "origin",
1159
- repoFullName
1160
- };
1161
- }
1162
- if (repoFullName) {
1163
- return {
1164
- repoRoot,
1165
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1166
- identitySource: "declared",
1167
- repoFullName
1168
- };
1169
- }
1170
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1171
- if (roots && roots.length > 0) {
1172
- return {
1173
- repoRoot,
1174
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1175
- identitySource: "root_commit",
1176
- repoFullName
1177
- };
1178
- }
1179
- return { repoRoot, repoFullName };
1180
- }
1181
-
1182
1335
  // src/lib/activation.ts
1183
1336
  var PRIM_ACTIVE_KEY = "prim.active";
1184
1337
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1231,7 +1384,7 @@ function repoSyncId(cwd) {
1231
1384
  function projectPrimInstallAt(root) {
1232
1385
  if (root === null || root === homedir2()) return false;
1233
1386
  for (const rel of PROJECT_INSTALL_FILES) {
1234
- const path = join15(root, rel);
1387
+ const path = join16(root, rel);
1235
1388
  if (existsSync9(path)) {
1236
1389
  try {
1237
1390
  const content = readFileSync14(path, "utf-8");
@@ -28257,8 +28410,8 @@ import {
28257
28410
  unlinkSync,
28258
28411
  writeFileSync as writeFileSync5
28259
28412
  } from "fs";
28260
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join16, resolve as resolve3 } from "path";
28261
- var WORKSPACE_ID_RELATIVE_PATH = join16("prim", "workspace-id");
28413
+ import { dirname as dirname10, isAbsolute as isAbsolute4, join as join17, resolve as resolve3 } from "path";
28414
+ var WORKSPACE_ID_RELATIVE_PATH = join17("prim", "workspace-id");
28262
28415
  var MAX_ANCESTORS = 64;
28263
28416
  var MAX_GIT_FILE_BYTES = 4096;
28264
28417
  var MAX_ID_FILE_BYTES = 128;
@@ -28317,11 +28470,11 @@ function resolveWorkspaceIdPath(cwd) {
28317
28470
  function resolveFromFilesystem(cwd) {
28318
28471
  let current = resolve3(cwd);
28319
28472
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
28320
- const dotGit = join16(current, ".git");
28473
+ const dotGit = join17(current, ".git");
28321
28474
  try {
28322
28475
  const stat = lstatSync6(dotGit);
28323
28476
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
28324
- return join16(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28477
+ return join17(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28325
28478
  }
28326
28479
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
28327
28480
  const contents = readFileSync15(dotGit, "utf8");
@@ -28329,7 +28482,7 @@ function resolveFromFilesystem(cwd) {
28329
28482
  if (match?.[1]) {
28330
28483
  const gitDirectory = isAbsolute4(match[1]) ? resolve3(match[1]) : resolve3(current, match[1]);
28331
28484
  if (isGitDirectory(gitDirectory)) {
28332
- return join16(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28485
+ return join17(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28333
28486
  }
28334
28487
  }
28335
28488
  }
@@ -28348,7 +28501,7 @@ function resolveFromFilesystem(cwd) {
28348
28501
  }
28349
28502
  function isGitDirectory(path) {
28350
28503
  try {
28351
- return statSync2(join16(path, "HEAD")).isFile();
28504
+ return statSync2(join17(path, "HEAD")).isFile();
28352
28505
  } catch {
28353
28506
  return false;
28354
28507
  }
@@ -28386,7 +28539,7 @@ function inspectPath(path) {
28386
28539
  function createWorkspaceId(path) {
28387
28540
  const parent = dirname10(path);
28388
28541
  const workspaceId = randomUUID3();
28389
- const temporaryPath = join16(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28542
+ const temporaryPath = join17(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28390
28543
  let temporaryCreated = false;
28391
28544
  let publishing = false;
28392
28545
  try {
@@ -28446,7 +28599,7 @@ function errorCode(error) {
28446
28599
  }
28447
28600
 
28448
28601
  // src/hooks/prim-hook-core.ts
28449
- import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
28602
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto";
28450
28603
  import { platform } from "os";
28451
28604
 
28452
28605
  // src/protocol/move.ts
@@ -28455,7 +28608,7 @@ var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
28455
28608
 
28456
28609
  // src/hooks/redact.ts
28457
28610
  import { existsSync as existsSync10, readFileSync as readFileSync16, statSync as statSync3 } from "fs";
28458
- import { join as join17 } from "path";
28611
+ import { join as join18 } from "path";
28459
28612
  import { Worker } from "worker_threads";
28460
28613
  var USER_HOME_RULES = [
28461
28614
  {
@@ -28607,7 +28760,7 @@ function toRewriteMove(rewrite, cliVersion, cwd, context) {
28607
28760
  const moves = [];
28608
28761
  for (let offset = 0; offset < pairs.length; offset += MAX_REWRITE_PAIRS_PER_MOVE) {
28609
28762
  const sortedPairs = pairs.slice(offset, offset + MAX_REWRITE_PAIRS_PER_MOVE);
28610
- const moveId = `rewrite:v1:${createHash7("sha256").update(JSON.stringify(["rewrite:v1", repoSyncId2, workspaceId, rewrite.source, sortedPairs])).digest("hex")}`;
28763
+ const moveId = `rewrite:v1:${createHash8("sha256").update(JSON.stringify(["rewrite:v1", repoSyncId2, workspaceId, rewrite.source, sortedPairs])).digest("hex")}`;
28611
28764
  moves.push({
28612
28765
  moveId,
28613
28766
  capturedAt: observedAt,
@@ -28735,14 +28888,14 @@ function validBranch(value) {
28735
28888
  }
28736
28889
  function resolveCliVersion() {
28737
28890
  try {
28738
- const pkg = JSON.parse(readFileSync17(join18(here, "..", "..", "package.json"), "utf-8"));
28891
+ const pkg = JSON.parse(readFileSync17(join19(here, "..", "..", "package.json"), "utf-8"));
28739
28892
  return pkg.version ?? "unknown";
28740
28893
  } catch {
28741
28894
  return "unknown";
28742
28895
  }
28743
28896
  }
28744
28897
  function spawnBackgroundFlush() {
28745
- const entry = join18(here, "..", "index.js");
28898
+ const entry = join19(here, "..", "index.js");
28746
28899
  spawn2(process.execPath, [entry, "moves", "flush"], {
28747
28900
  detached: true,
28748
28901
  stdio: "ignore",