@primitive.ai/prim 0.1.0-alpha.126 → 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 (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
@@ -54,25 +54,34 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/hooks/post-commit.ts
56
56
  import { execFileSync as execFileSync7, spawn as spawn2 } from "child_process";
57
- import { lstatSync as lstatSync7, readFileSync as readFileSync16 } from "fs";
58
- import { basename as basename4, dirname as dirname12, isAbsolute as isAbsolute5, join as join17 } from "path";
57
+ import { lstatSync as lstatSync7, readFileSync as readFileSync18 } from "fs";
58
+ import { basename as basename4, dirname as dirname12, isAbsolute as isAbsolute5, join as join20 } from "path";
59
59
  import { fileURLToPath as fileURLToPath4 } from "url";
60
60
 
61
61
  // src/binding.ts
62
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
63
- import { dirname as dirname5, join as join8 } from "path";
62
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
63
+ import { dirname as dirname6, join as join10 } from "path";
64
64
 
65
65
  // src/lib/credentials.ts
66
- import { createHash as createHash4 } from "crypto";
67
- import { readFileSync as readFileSync6 } from "fs";
68
- import { join as join7 } from "path";
66
+ import { createHash as createHash6 } from "crypto";
67
+ import { readFileSync as readFileSync7 } from "fs";
68
+ import { join as join9 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
- import { execFileSync } from "child_process";
72
- import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
73
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
71
+ import { execFileSync as execFileSync2 } from "child_process";
72
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
73
+ import {
74
+ chmodSync,
75
+ existsSync as existsSync3,
76
+ linkSync,
77
+ lstatSync as lstatSync4,
78
+ mkdirSync as mkdirSync3,
79
+ readFileSync as readFileSync6,
80
+ rmSync as rmSync6,
81
+ writeFileSync as writeFileSync3
82
+ } from "fs";
74
83
  import { createRequire } from "module";
75
- import { dirname as dirname4, join as join6 } from "path";
84
+ import { dirname as dirname5, join as join8 } from "path";
76
85
  import { fileURLToPath as fileURLToPath3 } from "url";
77
86
 
78
87
  // src/lib/atomic-file.ts
@@ -212,6 +221,17 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
212
221
  "fi; fi; "
213
222
  ].join("");
214
223
 
224
+ // src/lib/loopback-fetch.ts
225
+ import { request } from "http";
226
+ import { Readable } from "stream";
227
+
228
+ // src/lib/cloud-env.ts
229
+ function isClaudeCloudSession(env = process.env) {
230
+ return env.CLAUDE_CODE_REMOTE === "true";
231
+ }
232
+ 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';
233
+ 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}.`;
234
+
215
235
  // src/lib/workos-connect.ts
216
236
  var DISCOVERY_MAX_BYTES = 16 * 1024;
217
237
  var WORKOS_CONNECT_RESPONSE_MAX_BYTES = 64 * 1024;
@@ -387,31 +407,331 @@ function primConfigDirectory(options = {}) {
387
407
 
388
408
  // src/lib/machine-broker.ts
389
409
  var MAX_RESPONSE_BYTES = 96 * 1024;
410
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
411
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
412
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
390
413
  var IDLE_MS = 5 * 6e4;
391
414
 
392
415
  // src/lib/machine-retry.ts
393
416
  import { createHash as createHash2 } from "crypto";
394
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
417
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
395
418
  import { join as join5 } from "path";
419
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
420
+
421
+ // src/lib/session-identity.ts
422
+ import { execFile } from "child_process";
423
+ import { createHash as createHash4 } from "crypto";
424
+ import { rmSync as rmSync5 } from "fs";
425
+ import { join as join7 } from "path";
426
+ import { promisify } from "util";
427
+
428
+ // src/lib/git.ts
429
+ import { execFileSync } from "child_process";
430
+ import { createHash as createHash3 } from "crypto";
431
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
432
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
433
+ var GIT_TIMEOUT_MS = 1e3;
434
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
435
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
436
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
437
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
438
+ function gitChildEnvironment(env = process.env) {
439
+ return Object.fromEntries(
440
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
441
+ );
442
+ }
443
+ function gitToplevel(cwd) {
444
+ try {
445
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
446
+ cwd,
447
+ encoding: "utf-8",
448
+ stdio: ["ignore", "pipe", "ignore"],
449
+ timeout: GIT_TIMEOUT_MS,
450
+ env: gitChildEnvironment()
451
+ }).trim();
452
+ } catch {
453
+ return null;
454
+ }
455
+ }
456
+ function gitValue(cwd, args) {
457
+ try {
458
+ const value = execFileSync("git", args, {
459
+ cwd,
460
+ encoding: "utf-8",
461
+ stdio: ["ignore", "pipe", "ignore"],
462
+ timeout: GIT_TIMEOUT_MS,
463
+ env: gitChildEnvironment()
464
+ }).trim();
465
+ return value || void 0;
466
+ } catch {
467
+ return void 0;
468
+ }
469
+ }
470
+ function parseGithubRepositoryName(path) {
471
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
472
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
473
+ return null;
474
+ }
475
+ return `${parts[0]}/${parts[1]}`;
476
+ }
477
+ function githubRepositoryFromRemote(remote) {
478
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
479
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
480
+ remote
481
+ );
482
+ const path = match?.[1] ?? match?.[2];
483
+ return path ? parseGithubRepositoryName(path) : null;
484
+ }
485
+ function checkoutSettingsText(repoRoot) {
486
+ const path = join6(repoRoot, ".claude", "settings.json");
487
+ try {
488
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
489
+ const stat = lstatSync3(path);
490
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
491
+ return readFileSync5(path, "utf8");
492
+ } catch {
493
+ return null;
494
+ }
495
+ }
496
+ function checkoutDeclaration(repoRoot, name) {
497
+ const text = checkoutSettingsText(repoRoot);
498
+ if (text === null) return null;
499
+ let parsed;
500
+ try {
501
+ parsed = JSON.parse(text);
502
+ } catch {
503
+ return null;
504
+ }
505
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
506
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
507
+ return typeof value === "string" ? value : null;
508
+ }
509
+ function declaredGithubRepository(repoRoot) {
510
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
511
+ return value === null ? null : parseGithubRepositoryName(value.trim());
512
+ }
513
+ function githubRepositoryFullName(cwd) {
514
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
515
+ if (remote) {
516
+ const fromOrigin = githubRepositoryFromRemote(remote);
517
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
518
+ }
519
+ const root = gitToplevel(cwd);
520
+ return root ? declaredGithubRepository(root) : null;
521
+ }
522
+ function normalizeOriginRemote(remote) {
523
+ const value = remote.trim();
524
+ if (!value) return void 0;
525
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
526
+ if (scp?.host && scp.path) {
527
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
528
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
529
+ }
530
+ try {
531
+ const url = new URL(value);
532
+ url.username = "";
533
+ url.password = "";
534
+ url.search = "";
535
+ url.hash = "";
536
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
537
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
538
+ return void 0;
539
+ } catch {
540
+ return void 0;
541
+ }
542
+ }
543
+ function opaqueRepoKey(source, value) {
544
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
545
+ }
546
+ function resolveRepositoryContext(cwd = process.cwd()) {
547
+ const top = gitToplevel(cwd);
548
+ if (!top) return null;
549
+ let repoRoot;
550
+ try {
551
+ repoRoot = realpathSync.native(top);
552
+ } catch {
553
+ repoRoot = resolve(top);
554
+ }
555
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
556
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
557
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
558
+ if (normalizedOrigin) {
559
+ return {
560
+ repoRoot,
561
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
562
+ identitySource: "origin",
563
+ repoFullName
564
+ };
565
+ }
566
+ if (repoFullName) {
567
+ return {
568
+ repoRoot,
569
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
570
+ identitySource: "declared",
571
+ repoFullName
572
+ };
573
+ }
574
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
575
+ if (roots && roots.length > 0) {
576
+ return {
577
+ repoRoot,
578
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
579
+ identitySource: "root_commit",
580
+ repoFullName
581
+ };
582
+ }
583
+ return { repoRoot, repoFullName };
584
+ }
585
+
586
+ // src/lib/session-identity.ts
587
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
588
+ var SESSION_IDENTITY_VALUE = "session";
589
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
590
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
591
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
592
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
593
+ var RENEW_BEFORE_MS = 6e4;
594
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
595
+ var RESPONSE_MAX_BYTES = 64 * 1024;
596
+ function sessionIdentityRequested(env = process.env) {
597
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
598
+ }
599
+ function sessionIdentityMode(deps = {}) {
600
+ const env = deps.env ?? process.env;
601
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
602
+ }
603
+ function failure(code, cause, remedy) {
604
+ return { status: "failed", code, cause, remedy };
605
+ }
606
+ var NEW_SESSION_REMEDY = "start a new cloud session";
607
+ var SESSION_REVOKED = failure(
608
+ "session_revoked",
609
+ "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",
610
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
611
+ );
612
+ var CHALLENGE_WINDOW_PASSED = failure(
613
+ "challenge_expired",
614
+ "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)",
615
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
616
+ );
617
+ var CHALLENGE_GONE = failure(
618
+ "challenge_not_found",
619
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
620
+ NEW_SESSION_REMEDY
621
+ );
622
+ function hash(value) {
623
+ return createHash4("sha256").update(value).digest("hex");
624
+ }
625
+ function sessionContext(deps) {
626
+ const env = deps.env ?? process.env;
627
+ const environment = environmentCredentials(deps);
628
+ if (!environment)
629
+ return failure(
630
+ "environment_credential_missing",
631
+ "the cloud environment has no environment credential",
632
+ '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'
633
+ );
634
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
635
+ if (!sessionId || !SESSION_ID.test(sessionId))
636
+ return failure(
637
+ "session_id_missing",
638
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
639
+ NEW_SESSION_REMEDY
640
+ );
641
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
642
+ const directory = deps.directory ?? primConfigDirectory({ env });
643
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
644
+ return {
645
+ directory,
646
+ apiUrl,
647
+ clientId: environment.clientId,
648
+ generation: environment.generation,
649
+ sessionId,
650
+ tokenPath: join7(directory, `session_identity_${key}.json`),
651
+ statePath: join7(directory, `session_identity_${key}.state.json`),
652
+ lockPath: join7(directory, "session-identity.lock")
653
+ };
654
+ }
655
+ function readRecord(path) {
656
+ try {
657
+ const value = readMachineMetadata(path);
658
+ return value === void 0 ? void 0 : machineRecord(value);
659
+ } catch {
660
+ return void 0;
661
+ }
662
+ }
663
+ function finiteNumber(value) {
664
+ return typeof value === "number" && Number.isFinite(value);
665
+ }
666
+ function readToken(context) {
667
+ const data = readRecord(context.tokenPath);
668
+ 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))
669
+ return void 0;
670
+ const identity = data.identity;
671
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
672
+ return void 0;
673
+ return data;
674
+ }
675
+ function tokenValid(record, now = Date.now()) {
676
+ return now < record.expiresAt - RENEW_BEFORE_MS;
677
+ }
678
+ function toCredential(record) {
679
+ return {
680
+ issuer: record.issuer,
681
+ audience: record.audience,
682
+ ...record.identity,
683
+ accessToken: record.accessToken,
684
+ expiresAt: record.expiresAt,
685
+ apiUrl: record.apiUrl,
686
+ generation: record.generation,
687
+ storage: "environment",
688
+ session: {
689
+ userId: record.userId,
690
+ displayName: record.displayName,
691
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
692
+ refreshAfter: record.refreshAfter
693
+ }
694
+ };
695
+ }
696
+ function cachedSessionCredential(deps = {}) {
697
+ if (!sessionIdentityMode(deps)) return void 0;
698
+ let context;
699
+ try {
700
+ context = sessionContext(deps);
701
+ } catch {
702
+ return void 0;
703
+ }
704
+ if ("status" in context) return void 0;
705
+ const record = readToken(context);
706
+ return record && tokenValid(record) ? toCredential(record) : void 0;
707
+ }
708
+ var SERVER_CONTRACT_FAILURE = failure(
709
+ "server_contract",
710
+ "Primitive's answer did not identify the linked member",
711
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
712
+ );
396
713
 
397
714
  // src/lib/machine-credentials.ts
715
+ function sessionScoped(deps) {
716
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
717
+ }
398
718
  var require2 = createRequire(import.meta.url);
399
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
719
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
400
720
  var PROFILE_FILE = "machine_profile.json";
401
721
  var cached;
402
722
  function configurationDirectory(deps) {
403
723
  return deps.directory ?? primConfigDirectory({ env: deps.env });
404
724
  }
405
725
  function apiUrlFor(deps) {
406
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
726
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
407
727
  }
408
- function hash(value) {
409
- return createHash3("sha256").update(value).digest("hex");
728
+ function hash2(value) {
729
+ return createHash5("sha256").update(value).digest("hex");
410
730
  }
411
731
  function environmentContextPath(deps, clientId) {
412
- return join6(
732
+ return join8(
413
733
  configurationDirectory(deps),
414
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
734
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
415
735
  );
416
736
  }
417
737
  function readEnvironmentContext(environment, deps) {
@@ -435,17 +755,47 @@ function readEnvironmentContext(environment, deps) {
435
755
  return void 0;
436
756
  }
437
757
  }
758
+ function protectPath(path, directory) {
759
+ if (process.platform !== "win32") {
760
+ chmodSync(path, directory ? 448 : 384);
761
+ return;
762
+ }
763
+ const encodedPath = Buffer.from(path).toString("base64");
764
+ 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)`;
765
+ execFileSync2(
766
+ "powershell.exe",
767
+ [
768
+ "-NoProfile",
769
+ "-NonInteractive",
770
+ "-EncodedCommand",
771
+ Buffer.from(script, "utf16le").toString("base64")
772
+ ],
773
+ { stdio: "pipe", encoding: "utf8", windowsHide: true }
774
+ );
775
+ }
776
+ function ensureDirectory(directory) {
777
+ mkdirSync3(directory, { recursive: true, mode: 448 });
778
+ if (lstatSync4(directory).isSymbolicLink())
779
+ throw new MachineAuthError(
780
+ "unsafe_storage",
781
+ "Credential directory must not be a symbolic link."
782
+ );
783
+ protectPath(directory, true);
784
+ }
785
+ function readMachineMetadata(path) {
786
+ return readPrivate(path);
787
+ }
438
788
  function readPrivate(path) {
439
789
  let raw;
440
790
  try {
441
- const stat = lstatSync3(path);
791
+ const stat = lstatSync4(path);
442
792
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
443
793
  throw new MachineAuthError(
444
794
  "unsafe_storage",
445
795
  "Machine credential files must be owner-only regular files."
446
796
  );
447
797
  }
448
- raw = readFileSync5(path, "utf8");
798
+ raw = readFileSync6(path, "utf8");
449
799
  } catch (error) {
450
800
  if (error.code === "ENOENT") return void 0;
451
801
  throw error;
@@ -490,13 +840,101 @@ function parseProfile(value) {
490
840
  };
491
841
  }
492
842
  function readMachineProfile(deps = {}) {
493
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
843
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
494
844
  return value === void 0 ? void 0 : parseProfile(value);
495
845
  }
846
+ var NETWORK_SECRET_AUTH = "network-secret";
847
+ var NETWORK_TOKEN_AUTH = "network-token";
848
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
849
+ var brokerKeys = /* @__PURE__ */ new Map();
850
+ function networkSecretBrokerKey(deps, clientId) {
851
+ const directory = configurationDirectory(deps);
852
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
853
+ const known = brokerKeys.get(path);
854
+ if (known) return known;
855
+ ensureDirectory(directory);
856
+ const read = () => {
857
+ try {
858
+ const stat = lstatSync4(path);
859
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
860
+ throw new MachineAuthError(
861
+ "unsafe_storage",
862
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
863
+ true
864
+ );
865
+ const value = readFileSync6(path, "utf8").trim();
866
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
867
+ } catch (error) {
868
+ if (error.code === "ENOENT") return void 0;
869
+ throw error;
870
+ }
871
+ };
872
+ for (let attempt = 0; attempt < 2; attempt += 1) {
873
+ const existing = read();
874
+ if (existing?.key) {
875
+ brokerKeys.set(path, existing.key);
876
+ return existing.key;
877
+ }
878
+ if (existing)
879
+ throw new MachineAuthError(
880
+ "unsafe_storage",
881
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
882
+ true
883
+ );
884
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
885
+ try {
886
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
887
+ `, { mode: 384, flag: "wx" });
888
+ protectPath(staged, false);
889
+ linkSync(staged, path);
890
+ } catch (error) {
891
+ if (error.code !== "EEXIST") throw error;
892
+ } finally {
893
+ rmSync6(staged, { force: true });
894
+ }
895
+ }
896
+ const key = read()?.key;
897
+ if (!key)
898
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
899
+ brokerKeys.set(path, key);
900
+ return key;
901
+ }
496
902
  function environmentCredentials(deps) {
497
903
  const env = deps.env ?? process.env;
498
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
499
- if (clientId === void 0 && clientSecret === void 0) return void 0;
904
+ const {
905
+ PRIM_M2M_CLIENT_ID: clientId,
906
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
907
+ PRIM_M2M_CLIENT_AUTH: auth
908
+ } = env;
909
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
910
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
911
+ throw new MachineAuthError(
912
+ "incomplete_machine_credentials",
913
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
914
+ );
915
+ if (auth !== void 0) {
916
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
917
+ throw new MachineAuthError(
918
+ "incomplete_machine_credentials",
919
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
920
+ );
921
+ if (clientSecret !== void 0)
922
+ throw new MachineAuthError(
923
+ "conflicting_credentials",
924
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
925
+ );
926
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
927
+ const credentials = {
928
+ clientId,
929
+ generation,
930
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
931
+ };
932
+ Object.defineProperty(credentials, "clientSecret", {
933
+ enumerable: true,
934
+ get: () => networkSecretBrokerKey(deps, clientId)
935
+ });
936
+ return credentials;
937
+ }
500
938
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
501
939
  throw new MachineAuthError(
502
940
  "incomplete_machine_credentials",
@@ -506,12 +944,12 @@ function environmentCredentials(deps) {
506
944
  return {
507
945
  clientId,
508
946
  clientSecret,
509
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
947
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
510
948
  };
511
949
  }
512
950
  function hasMachineConfiguration(deps = {}) {
513
951
  const env = deps.env ?? process.env;
514
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
952
+ 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));
515
953
  if (configured && env.PRIM_TOKEN?.trim()) {
516
954
  throw new MachineAuthError(
517
955
  "conflicting_credentials",
@@ -523,6 +961,7 @@ function hasMachineConfiguration(deps = {}) {
523
961
  }
524
962
  function machineContext(deps = {}) {
525
963
  if (!hasMachineConfiguration(deps)) return void 0;
964
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
526
965
  const environment = environmentCredentials(deps);
527
966
  if (environment) {
528
967
  if (environmentTerminal === environment.generation) return void 0;
@@ -537,6 +976,7 @@ function machineContext(deps = {}) {
537
976
  return profile;
538
977
  }
539
978
  function cachedMachineCredential(deps = {}) {
979
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
540
980
  const context = machineContext(deps);
541
981
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
542
982
  }
@@ -558,25 +998,31 @@ function machineCaptureActor(deps = {}) {
558
998
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
559
999
  }
560
1000
  function machineJournalBucket(identity) {
561
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1001
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1002
+ }
1003
+ function identityPending(actor) {
1004
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1005
+ }
1006
+ function machinePendingBucket(identity) {
1007
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
562
1008
  }
563
1009
 
564
1010
  // src/lib/credentials.ts
565
1011
  var CONFIG_DIRECTORY = primConfigDirectory();
566
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
567
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
568
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
569
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
570
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
571
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
572
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
573
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
1012
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
1013
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
1014
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
1015
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
1016
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
1017
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
1018
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
1019
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
574
1020
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
575
1021
  var CREDENTIAL_MIGRATION_VERSION = 1;
576
1022
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
577
1023
  function readTrimmed(path) {
578
1024
  try {
579
- const value = readFileSync6(path, "utf8").trim();
1025
+ const value = readFileSync7(path, "utf8").trim();
580
1026
  return value || void 0;
581
1027
  } catch {
582
1028
  return void 0;
@@ -585,7 +1031,7 @@ function readTrimmed(path) {
585
1031
  function resolveAuthCredential(options = {}) {
586
1032
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
587
1033
  const machine = cachedMachineCredential({ env: options.env });
588
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
1034
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
589
1035
  }
590
1036
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
591
1037
  if (envToken) return { token: envToken, source: "environment" };
@@ -613,7 +1059,7 @@ function resolveAuthCredential(options = {}) {
613
1059
  return { token: stored, source: "token_file" };
614
1060
  }
615
1061
  function credentialFingerprint(value) {
616
- return createHash4("sha256").update(value).digest("hex");
1062
+ return createHash6("sha256").update(value).digest("hex");
617
1063
  }
618
1064
  function parseLegacyBrokerCredentialMetadata(value) {
619
1065
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -633,7 +1079,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
633
1079
  function readBoundedCredentialJson(path) {
634
1080
  let raw;
635
1081
  try {
636
- raw = readFileSync6(path, "utf8");
1082
+ raw = readFileSync7(path, "utf8");
637
1083
  } catch (error) {
638
1084
  return error.code === "ENOENT" ? void 0 : null;
639
1085
  }
@@ -706,14 +1152,14 @@ function jwtOrganizationId(token) {
706
1152
 
707
1153
  // src/binding.ts
708
1154
  var PRIM_CONFIG_DIR = primConfigDirectory();
709
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
1155
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
710
1156
  var WORKSPACE_FILE = ".prim/workspace.json";
711
1157
  function readJsonSafe(path) {
712
1158
  if (!existsSync4(path)) {
713
1159
  return;
714
1160
  }
715
1161
  try {
716
- return JSON.parse(readFileSync7(path, "utf-8"));
1162
+ return JSON.parse(readFileSync8(path, "utf-8"));
717
1163
  } catch {
718
1164
  return;
719
1165
  }
@@ -722,17 +1168,17 @@ function fromSessionMarker(sessionId) {
722
1168
  if (!sessionId) {
723
1169
  return;
724
1170
  }
725
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
1171
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
726
1172
  return marker?.orgId;
727
1173
  }
728
1174
  function fromWorkspaceFile(startDir) {
729
1175
  let dir = startDir;
730
1176
  while (true) {
731
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
1177
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
732
1178
  if (config?.orgId) {
733
1179
  return config.orgId;
734
1180
  }
735
- const parent = dirname5(dir);
1181
+ const parent = dirname6(dir);
736
1182
  if (parent === dir) {
737
1183
  return;
738
1184
  }
@@ -773,21 +1219,21 @@ import {
773
1219
  mkdirSync as mkdirSync5,
774
1220
  openSync as openSync2,
775
1221
  opendirSync,
776
- readFileSync as readFileSync11,
1222
+ readFileSync as readFileSync12,
777
1223
  readSync,
778
- readdirSync as readdirSync2
1224
+ readdirSync as readdirSync3
779
1225
  } from "fs";
780
- import { dirname as dirname8, join as join12 } from "path";
1226
+ import { dirname as dirname9, join as join14 } from "path";
781
1227
 
782
1228
  // src/client.ts
783
- import { createHash as createHash5 } from "crypto";
784
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
785
- import { dirname as dirname6 } from "path";
1229
+ import { createHash as createHash7 } from "crypto";
1230
+ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync7 } from "fs";
1231
+ import { dirname as dirname7 } from "path";
786
1232
 
787
1233
  // src/daemon/client-instance-id.ts
788
- import { randomBytes as randomBytes3 } from "crypto";
789
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
790
- import { join as join9 } from "path";
1234
+ import { randomBytes as randomBytes4 } from "crypto";
1235
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
1236
+ import { join as join11 } from "path";
791
1237
  var INSTANCE_BODY_CHARS = 43;
792
1238
  var INSTANCE_PREFIX = "pci_";
793
1239
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -796,12 +1242,12 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
796
1242
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
797
1243
 
798
1244
  // src/client.ts
799
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1245
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
800
1246
  function getSiteUrl() {
801
1247
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
802
1248
  }
803
1249
  function getSiteUrlForEnvironment(primApiUrl) {
804
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1250
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
805
1251
  }
806
1252
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
807
1253
 
@@ -809,15 +1255,15 @@ var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
809
1255
  import {
810
1256
  chmodSync as chmodSync4,
811
1257
  existsSync as existsSync6,
812
- readFileSync as readFileSync10,
813
- readdirSync,
814
- rmSync as rmSync7,
1258
+ readFileSync as readFileSync11,
1259
+ readdirSync as readdirSync2,
1260
+ rmSync as rmSync8,
815
1261
  rmdirSync
816
1262
  } from "fs";
817
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
1263
+ import { basename as basename3, dirname as dirname8, join as join13 } from "path";
818
1264
 
819
1265
  // src/journal.ts
820
- var JOURNAL_DIR = join12(primConfigDirectory(), "moves");
1266
+ var JOURNAL_DIR = join14(primConfigDirectory(), "moves");
821
1267
  var UNBOUND_BUCKET = "_unbound";
822
1268
  var JOURNAL_BASENAME = "journal.ndjson";
823
1269
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -829,14 +1275,14 @@ function envSlug(apiUrl) {
829
1275
  return slug;
830
1276
  }
831
1277
  function currentEnvDir() {
832
- return join12(JOURNAL_DIR, envSlug(getSiteUrl()));
1278
+ return join14(JOURNAL_DIR, envSlug(getSiteUrl()));
833
1279
  }
834
1280
  var DIR_MODE = 448;
835
1281
  var FILE_MODE = 384;
836
1282
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
837
1283
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
838
1284
  function appendMoveToPath(path, move) {
839
- const dir = dirname8(path);
1285
+ const dir = dirname9(path);
840
1286
  if (!existsSync7(dir)) {
841
1287
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
842
1288
  }
@@ -845,37 +1291,54 @@ function appendMoveToPath(path, move) {
845
1291
  }
846
1292
  function bucketDir(orgId) {
847
1293
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
848
- return join12(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
1294
+ return join14(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
849
1295
  }
850
1296
  function journalPath(orgId) {
851
- return join12(bucketDir(orgId), JOURNAL_BASENAME);
1297
+ return join14(bucketDir(orgId), JOURNAL_BASENAME);
852
1298
  }
853
1299
  function appendMove(move, orgId) {
854
1300
  const actor = machineCaptureActor();
855
1301
  const captured = actor ? { ...move, captureActor: actor } : move;
856
- appendMoveToPath(journalPath(actor ? machineJournalBucket(actor) : orgId), captured);
1302
+ const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
1303
+ appendMoveToPath(journalPath(bucket), captured);
857
1304
  return captured;
858
1305
  }
859
1306
  var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
860
1307
 
861
1308
  // src/lib/activation.ts
862
1309
  import { execFileSync as execFileSync4 } from "child_process";
863
- import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
1310
+ import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
864
1311
  import { homedir as homedir2 } from "os";
865
- import { join as join13 } from "path";
1312
+ import { join as join16 } from "path";
1313
+
1314
+ // src/lib/cloud-prepared.ts
1315
+ import { existsSync as existsSync8, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync9, writeFileSync as writeFileSync4 } from "fs";
1316
+ import { join as join15 } from "path";
1317
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
1318
+ function cloudPreparedPath(env = process.env) {
1319
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1320
+ }
1321
+ function isPreparedCloudSession(env = process.env) {
1322
+ if (!isClaudeCloudSession(env)) return false;
1323
+ try {
1324
+ return existsSync8(cloudPreparedPath(env));
1325
+ } catch {
1326
+ return false;
1327
+ }
1328
+ }
866
1329
 
867
1330
  // src/lib/demo-pause.ts
868
- import { execFileSync as execFileSync2 } from "child_process";
1331
+ import { execFileSync as execFileSync3 } from "child_process";
869
1332
  var DEMO_PAUSE_MS = 30 * 6e4;
870
1333
  var PAUSE_KEY = "prim.demoPause";
871
- var GIT_TIMEOUT_MS = 1e3;
1334
+ var GIT_TIMEOUT_MS2 = 1e3;
872
1335
  function git(cwd, args) {
873
1336
  try {
874
- return execFileSync2("git", args, {
1337
+ return execFileSync3("git", args, {
875
1338
  cwd,
876
1339
  encoding: "utf-8",
877
1340
  stdio: ["ignore", "pipe", "ignore"],
878
- timeout: GIT_TIMEOUT_MS
1341
+ timeout: GIT_TIMEOUT_MS2
879
1342
  });
880
1343
  } catch {
881
1344
  return void 0;
@@ -883,10 +1346,10 @@ function git(cwd, args) {
883
1346
  }
884
1347
  function setLocal(cwd, key, value) {
885
1348
  try {
886
- execFileSync2(
1349
+ execFileSync3(
887
1350
  "git",
888
1351
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
889
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1352
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
890
1353
  );
891
1354
  } catch (error) {
892
1355
  if (value !== null || error.status !== 5) throw error;
@@ -925,111 +1388,9 @@ function healDemoPause(cwd, pause, options = {}) {
925
1388
  }
926
1389
  }
927
1390
 
928
- // src/lib/git.ts
929
- import { execFileSync as execFileSync3 } from "child_process";
930
- import { createHash as createHash6 } from "crypto";
931
- import { lstatSync as lstatSync5, realpathSync } from "fs";
932
- import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
933
- var GIT_TIMEOUT_MS2 = 1e3;
934
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
935
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
936
- function gitToplevel(cwd) {
937
- try {
938
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
939
- cwd,
940
- encoding: "utf-8",
941
- stdio: ["ignore", "pipe", "ignore"],
942
- timeout: GIT_TIMEOUT_MS2
943
- }).trim();
944
- } catch {
945
- return null;
946
- }
947
- }
948
- function gitValue(cwd, args) {
949
- try {
950
- const value = execFileSync3("git", args, {
951
- cwd,
952
- encoding: "utf-8",
953
- stdio: ["ignore", "pipe", "ignore"],
954
- timeout: GIT_TIMEOUT_MS2
955
- }).trim();
956
- return value || void 0;
957
- } catch {
958
- return void 0;
959
- }
960
- }
961
- function githubRepositoryFullName(cwd) {
962
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
963
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
964
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
965
- remote
966
- );
967
- const path = match?.[1] ?? match?.[2];
968
- if (!path) return null;
969
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
970
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
971
- return null;
972
- }
973
- return `${parts[0]}/${parts[1]}`;
974
- }
975
- function normalizeOriginRemote(remote) {
976
- const value = remote.trim();
977
- if (!value) return void 0;
978
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
979
- if (scp?.host && scp.path) {
980
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
981
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
982
- }
983
- try {
984
- const url = new URL(value);
985
- url.username = "";
986
- url.password = "";
987
- url.search = "";
988
- url.hash = "";
989
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
990
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
991
- return void 0;
992
- } catch {
993
- return void 0;
994
- }
995
- }
996
- function opaqueRepoKey(source, value) {
997
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
998
- }
999
- function resolveRepositoryContext(cwd = process.cwd()) {
1000
- const top = gitToplevel(cwd);
1001
- if (!top) return null;
1002
- let repoRoot;
1003
- try {
1004
- repoRoot = realpathSync.native(top);
1005
- } catch {
1006
- repoRoot = resolve2(top);
1007
- }
1008
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1009
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1010
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1011
- if (normalizedOrigin) {
1012
- return {
1013
- repoRoot,
1014
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
1015
- identitySource: "origin",
1016
- repoFullName
1017
- };
1018
- }
1019
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1020
- if (roots && roots.length > 0) {
1021
- return {
1022
- repoRoot,
1023
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1024
- identitySource: "root_commit",
1025
- repoFullName
1026
- };
1027
- }
1028
- return { repoRoot, repoFullName };
1029
- }
1030
-
1031
1391
  // src/lib/activation.ts
1032
1392
  var PRIM_ACTIVE_KEY = "prim.active";
1393
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
1033
1394
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
1034
1395
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
1035
1396
  var GIT_TIMEOUT_MS3 = 1e3;
@@ -1076,14 +1437,13 @@ function repoSyncId(cwd) {
1076
1437
  const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
1077
1438
  return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
1078
1439
  }
1079
- function hasProjectPrimInstall(cwd) {
1080
- const root = gitToplevel(cwd);
1440
+ function projectPrimInstallAt(root) {
1081
1441
  if (root === null || root === homedir2()) return false;
1082
1442
  for (const rel of PROJECT_INSTALL_FILES) {
1083
- const path = join13(root, rel);
1084
- if (existsSync8(path)) {
1443
+ const path = join16(root, rel);
1444
+ if (existsSync9(path)) {
1085
1445
  try {
1086
- const content = readFileSync12(path, "utf-8");
1446
+ const content = readFileSync14(path, "utf-8");
1087
1447
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
1088
1448
  } catch {
1089
1449
  }
@@ -1091,12 +1451,27 @@ function hasProjectPrimInstall(cwd) {
1091
1451
  }
1092
1452
  return false;
1093
1453
  }
1454
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
1455
+ function declaresInactiveAt(root) {
1456
+ if (root === null || root === homedir2()) return false;
1457
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
1458
+ const text = checkoutSettingsText(root);
1459
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
1460
+ try {
1461
+ JSON.parse(text);
1462
+ return false;
1463
+ } catch {
1464
+ return true;
1465
+ }
1466
+ }
1094
1467
  function isRepoActiveForCapture(cwd, options = {}) {
1095
1468
  let { active: flag, pause } = readCaptureConfig(cwd);
1096
1469
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
1097
1470
  if (flag === "true") return true;
1098
1471
  if (flag === "false") return false;
1099
- return hasProjectPrimInstall(cwd);
1472
+ const root = gitToplevel(cwd);
1473
+ if (declaresInactiveAt(root)) return false;
1474
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
1100
1475
  }
1101
1476
 
1102
1477
  // src/generated/cli-http-v1.validators.js
@@ -28069,8 +28444,8 @@ function cachedCollectScopeAdmits(cwd, facts) {
28069
28444
 
28070
28445
  // src/lib/commit-heartbeat.ts
28071
28446
  import { execFileSync as execFileSync5 } from "child_process";
28072
- import { mkdirSync as mkdirSync6, readFileSync as readFileSync13, readdirSync as readdirSync3, unlinkSync } from "fs";
28073
- import { dirname as dirname10, join as join14, resolve as resolve3 } from "path";
28447
+ import { mkdirSync as mkdirSync7, readFileSync as readFileSync15, readdirSync as readdirSync4, unlinkSync } from "fs";
28448
+ import { dirname as dirname10, join as join17, resolve as resolve3 } from "path";
28074
28449
  var FIRED_DIR = "prim/post-commit-fired";
28075
28450
  var GIT_TIMEOUT_MS4 = 1e3;
28076
28451
  var MAX_STAMP_BYTES = 1024;
@@ -28088,8 +28463,8 @@ function gitPath(cwd, relative2) {
28088
28463
  return resolve3(cwd, value);
28089
28464
  }
28090
28465
  function ensurePrivateParent(path) {
28091
- mkdirSync6(dirname10(dirname10(path)), { recursive: true, mode: 448 });
28092
- mkdirSync6(dirname10(path), { recursive: true, mode: 448 });
28466
+ mkdirSync7(dirname10(dirname10(path)), { recursive: true, mode: 448 });
28467
+ mkdirSync7(dirname10(path), { recursive: true, mode: 448 });
28093
28468
  }
28094
28469
  function writeStamp(path, at) {
28095
28470
  ensurePrivateParent(path);
@@ -28098,7 +28473,7 @@ function writeStamp(path, at) {
28098
28473
  }
28099
28474
  function readStampAt(path) {
28100
28475
  try {
28101
- const raw = readFileSync13(path, "utf8");
28476
+ const raw = readFileSync15(path, "utf8");
28102
28477
  if (raw.length > MAX_STAMP_BYTES) return void 0;
28103
28478
  const parsed = JSON.parse(raw);
28104
28479
  return typeof parsed.at === "number" && Number.isSafeInteger(parsed.at) && parsed.at > 0 ? parsed.at : void 0;
@@ -28110,11 +28485,11 @@ function recordPostCommitFired(cwd, sha, now = Date.now()) {
28110
28485
  if (!sha || !FULL_SHA_RE.test(sha)) return;
28111
28486
  try {
28112
28487
  const dir = gitPath(cwd, FIRED_DIR);
28113
- writeStamp(join14(dir, sha), now);
28114
- const names = readdirSync3(dir).filter((name) => FULL_SHA_RE.test(name));
28488
+ writeStamp(join17(dir, sha), now);
28489
+ const names = readdirSync4(dir).filter((name) => FULL_SHA_RE.test(name));
28115
28490
  if (names.length <= MAX_FIRED_STAMPS + PRUNE_SLACK) return;
28116
- const stale = names.map((name) => ({ name, at: readStampAt(join14(dir, name)) ?? 0 })).sort((left, right) => right.at - left.at || left.name.localeCompare(right.name)).slice(MAX_FIRED_STAMPS);
28117
- for (const { name } of stale) unlinkSync(join14(dir, name));
28491
+ const stale = names.map((name) => ({ name, at: readStampAt(join17(dir, name)) ?? 0 })).sort((left, right) => right.at - left.at || left.name.localeCompare(right.name)).slice(MAX_FIRED_STAMPS);
28492
+ for (const { name } of stale) unlinkSync(join17(dir, name));
28118
28493
  } catch {
28119
28494
  }
28120
28495
  }
@@ -28134,17 +28509,17 @@ import {
28134
28509
  closeSync as closeSync3,
28135
28510
  fchmodSync as fchmodSync2,
28136
28511
  fsyncSync as fsyncSync2,
28137
- linkSync,
28512
+ linkSync as linkSync2,
28138
28513
  lstatSync as lstatSync6,
28139
- mkdirSync as mkdirSync7,
28514
+ mkdirSync as mkdirSync8,
28140
28515
  openSync as openSync3,
28141
- readFileSync as readFileSync14,
28516
+ readFileSync as readFileSync16,
28142
28517
  statSync as statSync2,
28143
28518
  unlinkSync as unlinkSync2,
28144
- writeFileSync as writeFileSync3
28519
+ writeFileSync as writeFileSync5
28145
28520
  } from "fs";
28146
- import { dirname as dirname11, isAbsolute as isAbsolute4, join as join15, resolve as resolve4 } from "path";
28147
- var WORKSPACE_ID_RELATIVE_PATH = join15("prim", "workspace-id");
28521
+ import { dirname as dirname11, isAbsolute as isAbsolute4, join as join18, resolve as resolve4 } from "path";
28522
+ var WORKSPACE_ID_RELATIVE_PATH = join18("prim", "workspace-id");
28148
28523
  var MAX_ANCESTORS = 64;
28149
28524
  var MAX_GIT_FILE_BYTES = 4096;
28150
28525
  var MAX_ID_FILE_BYTES = 128;
@@ -28203,19 +28578,19 @@ function resolveWorkspaceIdPath(cwd) {
28203
28578
  function resolveFromFilesystem(cwd) {
28204
28579
  let current = resolve4(cwd);
28205
28580
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
28206
- const dotGit = join15(current, ".git");
28581
+ const dotGit = join18(current, ".git");
28207
28582
  try {
28208
28583
  const stat = lstatSync6(dotGit);
28209
28584
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
28210
- return join15(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28585
+ return join18(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28211
28586
  }
28212
28587
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
28213
- const contents = readFileSync14(dotGit, "utf8");
28588
+ const contents = readFileSync16(dotGit, "utf8");
28214
28589
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
28215
28590
  if (match?.[1]) {
28216
28591
  const gitDirectory = isAbsolute4(match[1]) ? resolve4(match[1]) : resolve4(current, match[1]);
28217
28592
  if (isGitDirectory(gitDirectory)) {
28218
- return join15(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28593
+ return join18(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28219
28594
  }
28220
28595
  }
28221
28596
  }
@@ -28234,7 +28609,7 @@ function resolveFromFilesystem(cwd) {
28234
28609
  }
28235
28610
  function isGitDirectory(path) {
28236
28611
  try {
28237
- return statSync2(join15(path, "HEAD")).isFile();
28612
+ return statSync2(join18(path, "HEAD")).isFile();
28238
28613
  } catch {
28239
28614
  return false;
28240
28615
  }
@@ -28253,7 +28628,7 @@ function inspectPath(path) {
28253
28628
  return { status: "corrupt", path, reason: "invalid_content" };
28254
28629
  }
28255
28630
  try {
28256
- const contents = readFileSync14(path, "utf8");
28631
+ const contents = readFileSync16(path, "utf8");
28257
28632
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
28258
28633
  if ((contents === workspaceId || contents === `${workspaceId}
28259
28634
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -28272,11 +28647,11 @@ function inspectPath(path) {
28272
28647
  function createWorkspaceId(path) {
28273
28648
  const parent = dirname11(path);
28274
28649
  const workspaceId = randomUUID3();
28275
- const temporaryPath = join15(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28650
+ const temporaryPath = join18(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28276
28651
  let temporaryCreated = false;
28277
28652
  let publishing = false;
28278
28653
  try {
28279
- mkdirSync7(parent, { recursive: true, mode: 448 });
28654
+ mkdirSync8(parent, { recursive: true, mode: 448 });
28280
28655
  chmodSync5(parent, 448);
28281
28656
  const fd = openSync3(
28282
28657
  temporaryPath,
@@ -28285,7 +28660,7 @@ function createWorkspaceId(path) {
28285
28660
  );
28286
28661
  temporaryCreated = true;
28287
28662
  try {
28288
- writeFileSync3(fd, `${workspaceId}
28663
+ writeFileSync5(fd, `${workspaceId}
28289
28664
  `, "utf8");
28290
28665
  fchmodSync2(fd, 384);
28291
28666
  fsyncSync2(fd);
@@ -28293,7 +28668,7 @@ function createWorkspaceId(path) {
28293
28668
  closeSync3(fd);
28294
28669
  }
28295
28670
  publishing = true;
28296
- linkSync(temporaryPath, path);
28671
+ linkSync2(temporaryPath, path);
28297
28672
  return { status: "ready", workspaceId, path, created: true };
28298
28673
  } catch (error) {
28299
28674
  if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
@@ -28332,7 +28707,7 @@ function errorCode(error) {
28332
28707
  }
28333
28708
 
28334
28709
  // src/hooks/prim-hook-core.ts
28335
- import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
28710
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto";
28336
28711
  import { platform } from "os";
28337
28712
 
28338
28713
  // src/protocol/move.ts
@@ -28341,8 +28716,8 @@ var AGENT_ENVELOPE_VERSION = 3;
28341
28716
  var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
28342
28717
 
28343
28718
  // src/hooks/redact.ts
28344
- import { existsSync as existsSync9, readFileSync as readFileSync15, statSync as statSync3 } from "fs";
28345
- import { join as join16 } from "path";
28719
+ import { existsSync as existsSync10, readFileSync as readFileSync17, statSync as statSync3 } from "fs";
28720
+ import { join as join19 } from "path";
28346
28721
  import { Worker } from "worker_threads";
28347
28722
  var USER_HOME_RULES = [
28348
28723
  {
@@ -28386,6 +28761,11 @@ var DEFAULT_RULES = [
28386
28761
  pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
28387
28762
  reason: "aws-secret"
28388
28763
  },
28764
+ {
28765
+ // `prim auth enroll --print-env` output an agent may write into a file.
28766
+ pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
28767
+ reason: "prim-m2m-secret"
28768
+ },
28389
28769
  { pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
28390
28770
  {
28391
28771
  pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
@@ -28480,7 +28860,7 @@ function toCommitMove(commit, cliVersion, cwd, context = {}) {
28480
28860
  const validatedAttribution = validatedWorkspaceId ? attribution : void 0;
28481
28861
  const validatedCapturedAt = typeof capturedAt === "number" && Number.isSafeInteger(capturedAt) && capturedAt > 0 ? capturedAt : Date.now();
28482
28862
  const fullSha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/u.test(commit.sha);
28483
- const moveId = validatedRepoSyncId && validatedWorkspaceId && fullSha ? `commit:v2:${createHash7("sha256").update(
28863
+ const moveId = validatedRepoSyncId && validatedWorkspaceId && fullSha ? `commit:v2:${createHash8("sha256").update(
28484
28864
  JSON.stringify(["commit:v2", validatedRepoSyncId, validatedWorkspaceId, commit.sha])
28485
28865
  ).digest("hex")}` : `commit:v2:unscoped:${randomUUID4()}`;
28486
28866
  const base = {
@@ -28612,14 +28992,14 @@ function readCommit() {
28612
28992
  }
28613
28993
  function resolveCliVersion() {
28614
28994
  try {
28615
- const pkg = JSON.parse(readFileSync16(join17(here, "..", "..", "package.json"), "utf-8"));
28995
+ const pkg = JSON.parse(readFileSync18(join20(here, "..", "..", "package.json"), "utf-8"));
28616
28996
  return pkg.version ?? "unknown";
28617
28997
  } catch {
28618
28998
  return "unknown";
28619
28999
  }
28620
29000
  }
28621
29001
  function spawnBackgroundFlush() {
28622
- const entry = join17(here, "..", "index.js");
29002
+ const entry = join20(here, "..", "index.js");
28623
29003
  spawn2(process.execPath, [entry, "moves", "flush"], {
28624
29004
  detached: true,
28625
29005
  stdio: "ignore",