@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
@@ -60,27 +60,36 @@ import {
60
60
  fstatSync as fstatSync2,
61
61
  lstatSync as lstatSync7,
62
62
  openSync as openSync4,
63
- readFileSync as readFileSync15,
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 join16 } 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, randomUUID as randomUUID2 } from "crypto";
81
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
79
+ import { execFileSync as execFileSync2 } from "child_process";
80
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
81
+ import {
82
+ chmodSync,
83
+ existsSync as existsSync3,
84
+ linkSync,
85
+ lstatSync as lstatSync4,
86
+ mkdirSync as mkdirSync3,
87
+ readFileSync as readFileSync6,
88
+ rmSync as rmSync6,
89
+ writeFileSync as writeFileSync3
90
+ } from "fs";
82
91
  import { createRequire } from "module";
83
- import { dirname as dirname4, join as join6 } from "path";
92
+ import { dirname as dirname5, join as join8 } from "path";
84
93
  import { fileURLToPath as fileURLToPath3 } from "url";
85
94
 
86
95
  // src/lib/atomic-file.ts
@@ -156,6 +165,17 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
156
165
  "fi; fi; "
157
166
  ].join("");
158
167
 
168
+ // src/lib/loopback-fetch.ts
169
+ import { request } from "http";
170
+ import { Readable } from "stream";
171
+
172
+ // src/lib/cloud-env.ts
173
+ function isClaudeCloudSession(env = process.env) {
174
+ return env.CLAUDE_CODE_REMOTE === "true";
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}.`;
178
+
159
179
  // src/lib/workos-connect.ts
160
180
  var DISCOVERY_MAX_BYTES = 16 * 1024;
161
181
  var WORKOS_CONNECT_RESPONSE_MAX_BYTES = 64 * 1024;
@@ -331,31 +351,331 @@ function primConfigDirectory(options = {}) {
331
351
 
332
352
  // src/lib/machine-broker.ts
333
353
  var MAX_RESPONSE_BYTES = 96 * 1024;
354
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
355
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
356
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
334
357
  var IDLE_MS = 5 * 6e4;
335
358
 
336
359
  // src/lib/machine-retry.ts
337
360
  import { createHash as createHash2 } from "crypto";
338
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
361
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
339
362
  import { join as join5 } from "path";
363
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
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
+ );
340
657
 
341
658
  // src/lib/machine-credentials.ts
659
+ function sessionScoped(deps) {
660
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
661
+ }
342
662
  var require2 = createRequire(import.meta.url);
343
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
663
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
344
664
  var PROFILE_FILE = "machine_profile.json";
345
665
  var cached;
346
666
  function configurationDirectory(deps) {
347
667
  return deps.directory ?? primConfigDirectory({ env: deps.env });
348
668
  }
349
669
  function apiUrlFor(deps) {
350
- 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);
351
671
  }
352
- function hash(value) {
353
- return createHash3("sha256").update(value).digest("hex");
672
+ function hash2(value) {
673
+ return createHash5("sha256").update(value).digest("hex");
354
674
  }
355
675
  function environmentContextPath(deps, clientId) {
356
- return join6(
676
+ return join8(
357
677
  configurationDirectory(deps),
358
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
678
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
359
679
  );
360
680
  }
361
681
  function readEnvironmentContext(environment, deps) {
@@ -379,17 +699,47 @@ function readEnvironmentContext(environment, deps) {
379
699
  return void 0;
380
700
  }
381
701
  }
702
+ function protectPath(path, directory) {
703
+ if (process.platform !== "win32") {
704
+ chmodSync(path, directory ? 448 : 384);
705
+ return;
706
+ }
707
+ const encodedPath = Buffer.from(path).toString("base64");
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)`;
709
+ execFileSync2(
710
+ "powershell.exe",
711
+ [
712
+ "-NoProfile",
713
+ "-NonInteractive",
714
+ "-EncodedCommand",
715
+ Buffer.from(script, "utf16le").toString("base64")
716
+ ],
717
+ { stdio: "pipe", encoding: "utf8", windowsHide: true }
718
+ );
719
+ }
720
+ function ensureDirectory(directory) {
721
+ mkdirSync3(directory, { recursive: true, mode: 448 });
722
+ if (lstatSync4(directory).isSymbolicLink())
723
+ throw new MachineAuthError(
724
+ "unsafe_storage",
725
+ "Credential directory must not be a symbolic link."
726
+ );
727
+ protectPath(directory, true);
728
+ }
729
+ function readMachineMetadata(path) {
730
+ return readPrivate(path);
731
+ }
382
732
  function readPrivate(path) {
383
733
  let raw;
384
734
  try {
385
- const stat = lstatSync3(path);
735
+ const stat = lstatSync4(path);
386
736
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
387
737
  throw new MachineAuthError(
388
738
  "unsafe_storage",
389
739
  "Machine credential files must be owner-only regular files."
390
740
  );
391
741
  }
392
- raw = readFileSync5(path, "utf8");
742
+ raw = readFileSync6(path, "utf8");
393
743
  } catch (error) {
394
744
  if (error.code === "ENOENT") return void 0;
395
745
  throw error;
@@ -434,13 +784,101 @@ function parseProfile(value) {
434
784
  };
435
785
  }
436
786
  function readMachineProfile(deps = {}) {
437
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
787
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
438
788
  return value === void 0 ? void 0 : parseProfile(value);
439
789
  }
790
+ var NETWORK_SECRET_AUTH = "network-secret";
791
+ var NETWORK_TOKEN_AUTH = "network-token";
792
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
793
+ var brokerKeys = /* @__PURE__ */ new Map();
794
+ function networkSecretBrokerKey(deps, clientId) {
795
+ const directory = configurationDirectory(deps);
796
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
797
+ const known = brokerKeys.get(path);
798
+ if (known) return known;
799
+ ensureDirectory(directory);
800
+ const read = () => {
801
+ try {
802
+ const stat = lstatSync4(path);
803
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
804
+ throw new MachineAuthError(
805
+ "unsafe_storage",
806
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
807
+ true
808
+ );
809
+ const value = readFileSync6(path, "utf8").trim();
810
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
811
+ } catch (error) {
812
+ if (error.code === "ENOENT") return void 0;
813
+ throw error;
814
+ }
815
+ };
816
+ for (let attempt = 0; attempt < 2; attempt += 1) {
817
+ const existing = read();
818
+ if (existing?.key) {
819
+ brokerKeys.set(path, existing.key);
820
+ return existing.key;
821
+ }
822
+ if (existing)
823
+ throw new MachineAuthError(
824
+ "unsafe_storage",
825
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
826
+ true
827
+ );
828
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
829
+ try {
830
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
831
+ `, { mode: 384, flag: "wx" });
832
+ protectPath(staged, false);
833
+ linkSync(staged, path);
834
+ } catch (error) {
835
+ if (error.code !== "EEXIST") throw error;
836
+ } finally {
837
+ rmSync6(staged, { force: true });
838
+ }
839
+ }
840
+ const key = read()?.key;
841
+ if (!key)
842
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
843
+ brokerKeys.set(path, key);
844
+ return key;
845
+ }
440
846
  function environmentCredentials(deps) {
441
847
  const env = deps.env ?? process.env;
442
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
443
- if (clientId === void 0 && clientSecret === void 0) return void 0;
848
+ const {
849
+ PRIM_M2M_CLIENT_ID: clientId,
850
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
851
+ PRIM_M2M_CLIENT_AUTH: auth
852
+ } = env;
853
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
854
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
855
+ throw new MachineAuthError(
856
+ "incomplete_machine_credentials",
857
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
858
+ );
859
+ if (auth !== void 0) {
860
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
861
+ throw new MachineAuthError(
862
+ "incomplete_machine_credentials",
863
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
864
+ );
865
+ if (clientSecret !== void 0)
866
+ throw new MachineAuthError(
867
+ "conflicting_credentials",
868
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
869
+ );
870
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
871
+ const credentials = {
872
+ clientId,
873
+ generation,
874
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
875
+ };
876
+ Object.defineProperty(credentials, "clientSecret", {
877
+ enumerable: true,
878
+ get: () => networkSecretBrokerKey(deps, clientId)
879
+ });
880
+ return credentials;
881
+ }
444
882
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
445
883
  throw new MachineAuthError(
446
884
  "incomplete_machine_credentials",
@@ -450,12 +888,12 @@ function environmentCredentials(deps) {
450
888
  return {
451
889
  clientId,
452
890
  clientSecret,
453
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
891
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
454
892
  };
455
893
  }
456
894
  function hasMachineConfiguration(deps = {}) {
457
895
  const env = deps.env ?? process.env;
458
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== 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));
459
897
  if (configured && env.PRIM_TOKEN?.trim()) {
460
898
  throw new MachineAuthError(
461
899
  "conflicting_credentials",
@@ -467,6 +905,7 @@ function hasMachineConfiguration(deps = {}) {
467
905
  }
468
906
  function machineContext(deps = {}) {
469
907
  if (!hasMachineConfiguration(deps)) return void 0;
908
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
470
909
  const environment = environmentCredentials(deps);
471
910
  if (environment) {
472
911
  if (environmentTerminal === environment.generation) return void 0;
@@ -481,6 +920,7 @@ function machineContext(deps = {}) {
481
920
  return profile;
482
921
  }
483
922
  function cachedMachineCredential(deps = {}) {
923
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
484
924
  const context = machineContext(deps);
485
925
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
486
926
  }
@@ -502,25 +942,31 @@ function machineCaptureActor(deps = {}) {
502
942
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
503
943
  }
504
944
  function machineJournalBucket(identity) {
505
- 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}` : ""}`)}`;
946
+ }
947
+ function identityPending(actor) {
948
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
949
+ }
950
+ function machinePendingBucket(identity) {
951
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
506
952
  }
507
953
 
508
954
  // src/lib/credentials.ts
509
955
  var CONFIG_DIRECTORY = primConfigDirectory();
510
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
511
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
512
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
513
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
514
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
515
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
516
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
517
- 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");
518
964
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
519
965
  var CREDENTIAL_MIGRATION_VERSION = 1;
520
966
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
521
967
  function readTrimmed(path) {
522
968
  try {
523
- const value = readFileSync6(path, "utf8").trim();
969
+ const value = readFileSync7(path, "utf8").trim();
524
970
  return value || void 0;
525
971
  } catch {
526
972
  return void 0;
@@ -529,7 +975,7 @@ function readTrimmed(path) {
529
975
  function resolveAuthCredential(options = {}) {
530
976
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
531
977
  const machine = cachedMachineCredential({ env: options.env });
532
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
978
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
533
979
  }
534
980
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
535
981
  if (envToken) return { token: envToken, source: "environment" };
@@ -557,7 +1003,7 @@ function resolveAuthCredential(options = {}) {
557
1003
  return { token: stored, source: "token_file" };
558
1004
  }
559
1005
  function credentialFingerprint(value) {
560
- return createHash4("sha256").update(value).digest("hex");
1006
+ return createHash6("sha256").update(value).digest("hex");
561
1007
  }
562
1008
  function parseLegacyBrokerCredentialMetadata(value) {
563
1009
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -577,7 +1023,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
577
1023
  function readBoundedCredentialJson(path) {
578
1024
  let raw;
579
1025
  try {
580
- raw = readFileSync6(path, "utf8");
1026
+ raw = readFileSync7(path, "utf8");
581
1027
  } catch (error) {
582
1028
  return error.code === "ENOENT" ? void 0 : null;
583
1029
  }
@@ -650,14 +1096,14 @@ function jwtOrganizationId(token) {
650
1096
 
651
1097
  // src/binding.ts
652
1098
  var PRIM_CONFIG_DIR = primConfigDirectory();
653
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
1099
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
654
1100
  var WORKSPACE_FILE = ".prim/workspace.json";
655
1101
  function readJsonSafe(path) {
656
1102
  if (!existsSync4(path)) {
657
1103
  return;
658
1104
  }
659
1105
  try {
660
- return JSON.parse(readFileSync7(path, "utf-8"));
1106
+ return JSON.parse(readFileSync8(path, "utf-8"));
661
1107
  } catch {
662
1108
  return;
663
1109
  }
@@ -666,17 +1112,17 @@ function fromSessionMarker(sessionId) {
666
1112
  if (!sessionId) {
667
1113
  return;
668
1114
  }
669
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
1115
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
670
1116
  return marker?.orgId;
671
1117
  }
672
1118
  function fromWorkspaceFile(startDir) {
673
1119
  let dir = startDir;
674
1120
  while (true) {
675
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
1121
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
676
1122
  if (config?.orgId) {
677
1123
  return config.orgId;
678
1124
  }
679
- const parent = dirname5(dir);
1125
+ const parent = dirname6(dir);
680
1126
  if (parent === dir) {
681
1127
  return;
682
1128
  }
@@ -717,21 +1163,21 @@ import {
717
1163
  mkdirSync as mkdirSync5,
718
1164
  openSync as openSync2,
719
1165
  opendirSync,
720
- readFileSync as readFileSync11,
1166
+ readFileSync as readFileSync12,
721
1167
  readSync,
722
- readdirSync as readdirSync2
1168
+ readdirSync as readdirSync3
723
1169
  } from "fs";
724
- import { dirname as dirname8, join as join12 } from "path";
1170
+ import { dirname as dirname9, join as join14 } from "path";
725
1171
 
726
1172
  // src/client.ts
727
- import { createHash as createHash5 } from "crypto";
728
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
729
- 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";
730
1176
 
731
1177
  // src/daemon/client-instance-id.ts
732
- import { randomBytes as randomBytes3 } from "crypto";
733
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
734
- import { join as join9 } from "path";
1178
+ import { randomBytes as randomBytes4 } from "crypto";
1179
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
1180
+ import { join as join11 } from "path";
735
1181
  var INSTANCE_BODY_CHARS = 43;
736
1182
  var INSTANCE_PREFIX = "pci_";
737
1183
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -740,12 +1186,12 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
740
1186
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
741
1187
 
742
1188
  // src/client.ts
743
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1189
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
744
1190
  function getSiteUrl() {
745
1191
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
746
1192
  }
747
1193
  function getSiteUrlForEnvironment(primApiUrl) {
748
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1194
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
749
1195
  }
750
1196
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
751
1197
 
@@ -753,15 +1199,15 @@ var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
753
1199
  import {
754
1200
  chmodSync as chmodSync4,
755
1201
  existsSync as existsSync6,
756
- readFileSync as readFileSync10,
757
- readdirSync,
758
- rmSync as rmSync7,
1202
+ readFileSync as readFileSync11,
1203
+ readdirSync as readdirSync2,
1204
+ rmSync as rmSync8,
759
1205
  rmdirSync
760
1206
  } from "fs";
761
- 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";
762
1208
 
763
1209
  // src/journal.ts
764
- var JOURNAL_DIR = join12(primConfigDirectory(), "moves");
1210
+ var JOURNAL_DIR = join14(primConfigDirectory(), "moves");
765
1211
  var UNBOUND_BUCKET = "_unbound";
766
1212
  var JOURNAL_BASENAME = "journal.ndjson";
767
1213
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -773,14 +1219,14 @@ function envSlug(apiUrl) {
773
1219
  return slug;
774
1220
  }
775
1221
  function currentEnvDir() {
776
- return join12(JOURNAL_DIR, envSlug(getSiteUrl()));
1222
+ return join14(JOURNAL_DIR, envSlug(getSiteUrl()));
777
1223
  }
778
1224
  var DIR_MODE = 448;
779
1225
  var FILE_MODE = 384;
780
1226
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
781
1227
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
782
1228
  function appendMoveToPath(path, move) {
783
- const dir = dirname8(path);
1229
+ const dir = dirname9(path);
784
1230
  if (!existsSync7(dir)) {
785
1231
  mkdirSync5(dir, { recursive: true, mode: DIR_MODE });
786
1232
  }
@@ -789,37 +1235,54 @@ function appendMoveToPath(path, move) {
789
1235
  }
790
1236
  function bucketDir(orgId) {
791
1237
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
792
- return join12(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
1238
+ return join14(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
793
1239
  }
794
1240
  function journalPath(orgId) {
795
- return join12(bucketDir(orgId), JOURNAL_BASENAME);
1241
+ return join14(bucketDir(orgId), JOURNAL_BASENAME);
796
1242
  }
797
1243
  function appendMove(move, orgId) {
798
1244
  const actor = machineCaptureActor();
799
1245
  const captured = actor ? { ...move, captureActor: actor } : move;
800
- appendMoveToPath(journalPath(actor ? machineJournalBucket(actor) : orgId), captured);
1246
+ const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
1247
+ appendMoveToPath(journalPath(bucket), captured);
801
1248
  return captured;
802
1249
  }
803
1250
  var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
804
1251
 
805
1252
  // src/lib/activation.ts
806
1253
  import { execFileSync as execFileSync4 } from "child_process";
807
- import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
1254
+ import { existsSync as existsSync9, readFileSync as readFileSync14 } from "fs";
808
1255
  import { homedir as homedir2 } from "os";
809
- import { join as join13 } from "path";
1256
+ import { join as join16 } from "path";
1257
+
1258
+ // src/lib/cloud-prepared.ts
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";
1261
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
1262
+ function cloudPreparedPath(env = process.env) {
1263
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1264
+ }
1265
+ function isPreparedCloudSession(env = process.env) {
1266
+ if (!isClaudeCloudSession(env)) return false;
1267
+ try {
1268
+ return existsSync8(cloudPreparedPath(env));
1269
+ } catch {
1270
+ return false;
1271
+ }
1272
+ }
810
1273
 
811
1274
  // src/lib/demo-pause.ts
812
- import { execFileSync as execFileSync2 } from "child_process";
1275
+ import { execFileSync as execFileSync3 } from "child_process";
813
1276
  var DEMO_PAUSE_MS = 30 * 6e4;
814
1277
  var PAUSE_KEY = "prim.demoPause";
815
- var GIT_TIMEOUT_MS = 1e3;
1278
+ var GIT_TIMEOUT_MS2 = 1e3;
816
1279
  function git(cwd, args) {
817
1280
  try {
818
- return execFileSync2("git", args, {
1281
+ return execFileSync3("git", args, {
819
1282
  cwd,
820
1283
  encoding: "utf-8",
821
1284
  stdio: ["ignore", "pipe", "ignore"],
822
- timeout: GIT_TIMEOUT_MS
1285
+ timeout: GIT_TIMEOUT_MS2
823
1286
  });
824
1287
  } catch {
825
1288
  return void 0;
@@ -827,10 +1290,10 @@ function git(cwd, args) {
827
1290
  }
828
1291
  function setLocal(cwd, key, value) {
829
1292
  try {
830
- execFileSync2(
1293
+ execFileSync3(
831
1294
  "git",
832
1295
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
833
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1296
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
834
1297
  );
835
1298
  } catch (error) {
836
1299
  if (value !== null || error.status !== 5) throw error;
@@ -869,111 +1332,9 @@ function healDemoPause(cwd, pause, options = {}) {
869
1332
  }
870
1333
  }
871
1334
 
872
- // src/lib/git.ts
873
- import { execFileSync as execFileSync3 } from "child_process";
874
- import { createHash as createHash6 } from "crypto";
875
- import { lstatSync as lstatSync5, realpathSync } from "fs";
876
- import { basename as basename3, dirname as dirname9, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
877
- var GIT_TIMEOUT_MS2 = 1e3;
878
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
879
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
880
- function gitToplevel(cwd) {
881
- try {
882
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
883
- cwd,
884
- encoding: "utf-8",
885
- stdio: ["ignore", "pipe", "ignore"],
886
- timeout: GIT_TIMEOUT_MS2
887
- }).trim();
888
- } catch {
889
- return null;
890
- }
891
- }
892
- function gitValue(cwd, args) {
893
- try {
894
- const value = execFileSync3("git", args, {
895
- cwd,
896
- encoding: "utf-8",
897
- stdio: ["ignore", "pipe", "ignore"],
898
- timeout: GIT_TIMEOUT_MS2
899
- }).trim();
900
- return value || void 0;
901
- } catch {
902
- return void 0;
903
- }
904
- }
905
- function githubRepositoryFullName(cwd) {
906
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
907
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
908
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
909
- remote
910
- );
911
- const path = match?.[1] ?? match?.[2];
912
- if (!path) return null;
913
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
914
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
915
- return null;
916
- }
917
- return `${parts[0]}/${parts[1]}`;
918
- }
919
- function normalizeOriginRemote(remote) {
920
- const value = remote.trim();
921
- if (!value) return void 0;
922
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
923
- if (scp?.host && scp.path) {
924
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
925
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
926
- }
927
- try {
928
- const url = new URL(value);
929
- url.username = "";
930
- url.password = "";
931
- url.search = "";
932
- url.hash = "";
933
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
934
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
935
- return void 0;
936
- } catch {
937
- return void 0;
938
- }
939
- }
940
- function opaqueRepoKey(source, value) {
941
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
942
- }
943
- function resolveRepositoryContext(cwd = process.cwd()) {
944
- const top = gitToplevel(cwd);
945
- if (!top) return null;
946
- let repoRoot;
947
- try {
948
- repoRoot = realpathSync.native(top);
949
- } catch {
950
- repoRoot = resolve2(top);
951
- }
952
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
953
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
954
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
955
- if (normalizedOrigin) {
956
- return {
957
- repoRoot,
958
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
959
- identitySource: "origin",
960
- repoFullName
961
- };
962
- }
963
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
964
- if (roots && roots.length > 0) {
965
- return {
966
- repoRoot,
967
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
968
- identitySource: "root_commit",
969
- repoFullName
970
- };
971
- }
972
- return { repoRoot, repoFullName };
973
- }
974
-
975
1335
  // src/lib/activation.ts
976
1336
  var PRIM_ACTIVE_KEY = "prim.active";
1337
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
977
1338
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
978
1339
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
979
1340
  var GIT_TIMEOUT_MS3 = 1e3;
@@ -1020,14 +1381,13 @@ function repoSyncId(cwd) {
1020
1381
  const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
1021
1382
  return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
1022
1383
  }
1023
- function hasProjectPrimInstall(cwd) {
1024
- const root = gitToplevel(cwd);
1384
+ function projectPrimInstallAt(root) {
1025
1385
  if (root === null || root === homedir2()) return false;
1026
1386
  for (const rel of PROJECT_INSTALL_FILES) {
1027
- const path = join13(root, rel);
1028
- if (existsSync8(path)) {
1387
+ const path = join16(root, rel);
1388
+ if (existsSync9(path)) {
1029
1389
  try {
1030
- const content = readFileSync12(path, "utf-8");
1390
+ const content = readFileSync14(path, "utf-8");
1031
1391
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
1032
1392
  } catch {
1033
1393
  }
@@ -1035,12 +1395,27 @@ function hasProjectPrimInstall(cwd) {
1035
1395
  }
1036
1396
  return false;
1037
1397
  }
1398
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
1399
+ function declaresInactiveAt(root) {
1400
+ if (root === null || root === homedir2()) return false;
1401
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
1402
+ const text = checkoutSettingsText(root);
1403
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
1404
+ try {
1405
+ JSON.parse(text);
1406
+ return false;
1407
+ } catch {
1408
+ return true;
1409
+ }
1410
+ }
1038
1411
  function isRepoActiveForCapture(cwd, options = {}) {
1039
1412
  let { active: flag, pause } = readCaptureConfig(cwd);
1040
1413
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
1041
1414
  if (flag === "true") return true;
1042
1415
  if (flag === "false") return false;
1043
- return hasProjectPrimInstall(cwd);
1416
+ const root = gitToplevel(cwd);
1417
+ if (declaresInactiveAt(root)) return false;
1418
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
1044
1419
  }
1045
1420
 
1046
1421
  // src/generated/cli-http-v1.validators.js
@@ -28026,17 +28401,17 @@ import {
28026
28401
  closeSync as closeSync3,
28027
28402
  fchmodSync as fchmodSync2,
28028
28403
  fsyncSync as fsyncSync2,
28029
- linkSync,
28404
+ linkSync as linkSync2,
28030
28405
  lstatSync as lstatSync6,
28031
- mkdirSync as mkdirSync6,
28406
+ mkdirSync as mkdirSync7,
28032
28407
  openSync as openSync3,
28033
- readFileSync as readFileSync13,
28408
+ readFileSync as readFileSync15,
28034
28409
  statSync as statSync2,
28035
28410
  unlinkSync,
28036
- writeFileSync as writeFileSync3
28411
+ writeFileSync as writeFileSync5
28037
28412
  } from "fs";
28038
- import { dirname as dirname10, isAbsolute as isAbsolute4, join as join14, resolve as resolve3 } from "path";
28039
- var WORKSPACE_ID_RELATIVE_PATH = join14("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");
28040
28415
  var MAX_ANCESTORS = 64;
28041
28416
  var MAX_GIT_FILE_BYTES = 4096;
28042
28417
  var MAX_ID_FILE_BYTES = 128;
@@ -28095,19 +28470,19 @@ function resolveWorkspaceIdPath(cwd) {
28095
28470
  function resolveFromFilesystem(cwd) {
28096
28471
  let current = resolve3(cwd);
28097
28472
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
28098
- const dotGit = join14(current, ".git");
28473
+ const dotGit = join17(current, ".git");
28099
28474
  try {
28100
28475
  const stat = lstatSync6(dotGit);
28101
28476
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
28102
- return join14(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28477
+ return join17(dotGit, WORKSPACE_ID_RELATIVE_PATH);
28103
28478
  }
28104
28479
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
28105
- const contents = readFileSync13(dotGit, "utf8");
28480
+ const contents = readFileSync15(dotGit, "utf8");
28106
28481
  const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
28107
28482
  if (match?.[1]) {
28108
28483
  const gitDirectory = isAbsolute4(match[1]) ? resolve3(match[1]) : resolve3(current, match[1]);
28109
28484
  if (isGitDirectory(gitDirectory)) {
28110
- return join14(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28485
+ return join17(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
28111
28486
  }
28112
28487
  }
28113
28488
  }
@@ -28126,7 +28501,7 @@ function resolveFromFilesystem(cwd) {
28126
28501
  }
28127
28502
  function isGitDirectory(path) {
28128
28503
  try {
28129
- return statSync2(join14(path, "HEAD")).isFile();
28504
+ return statSync2(join17(path, "HEAD")).isFile();
28130
28505
  } catch {
28131
28506
  return false;
28132
28507
  }
@@ -28145,7 +28520,7 @@ function inspectPath(path) {
28145
28520
  return { status: "corrupt", path, reason: "invalid_content" };
28146
28521
  }
28147
28522
  try {
28148
- const contents = readFileSync13(path, "utf8");
28523
+ const contents = readFileSync15(path, "utf8");
28149
28524
  const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
28150
28525
  if ((contents === workspaceId || contents === `${workspaceId}
28151
28526
  `) && isCanonicalWorkspaceId(workspaceId)) {
@@ -28164,11 +28539,11 @@ function inspectPath(path) {
28164
28539
  function createWorkspaceId(path) {
28165
28540
  const parent = dirname10(path);
28166
28541
  const workspaceId = randomUUID3();
28167
- const temporaryPath = join14(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28542
+ const temporaryPath = join17(parent, `.workspace-id-${process.pid}-${randomUUID3()}.tmp`);
28168
28543
  let temporaryCreated = false;
28169
28544
  let publishing = false;
28170
28545
  try {
28171
- mkdirSync6(parent, { recursive: true, mode: 448 });
28546
+ mkdirSync7(parent, { recursive: true, mode: 448 });
28172
28547
  chmodSync5(parent, 448);
28173
28548
  const fd = openSync3(
28174
28549
  temporaryPath,
@@ -28177,7 +28552,7 @@ function createWorkspaceId(path) {
28177
28552
  );
28178
28553
  temporaryCreated = true;
28179
28554
  try {
28180
- writeFileSync3(fd, `${workspaceId}
28555
+ writeFileSync5(fd, `${workspaceId}
28181
28556
  `, "utf8");
28182
28557
  fchmodSync2(fd, 384);
28183
28558
  fsyncSync2(fd);
@@ -28185,7 +28560,7 @@ function createWorkspaceId(path) {
28185
28560
  closeSync3(fd);
28186
28561
  }
28187
28562
  publishing = true;
28188
- linkSync(temporaryPath, path);
28563
+ linkSync2(temporaryPath, path);
28189
28564
  return { status: "ready", workspaceId, path, created: true };
28190
28565
  } catch (error) {
28191
28566
  if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
@@ -28224,7 +28599,7 @@ function errorCode(error) {
28224
28599
  }
28225
28600
 
28226
28601
  // src/hooks/prim-hook-core.ts
28227
- import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
28602
+ import { createHash as createHash8, randomUUID as randomUUID4 } from "crypto";
28228
28603
  import { platform } from "os";
28229
28604
 
28230
28605
  // src/protocol/move.ts
@@ -28232,8 +28607,8 @@ var LEGACY_ENVELOPE_VERSION = 1;
28232
28607
  var ENVELOPE_VERSION = LEGACY_ENVELOPE_VERSION;
28233
28608
 
28234
28609
  // src/hooks/redact.ts
28235
- import { existsSync as existsSync9, readFileSync as readFileSync14, statSync as statSync3 } from "fs";
28236
- import { join as join15 } from "path";
28610
+ import { existsSync as existsSync10, readFileSync as readFileSync16, statSync as statSync3 } from "fs";
28611
+ import { join as join18 } from "path";
28237
28612
  import { Worker } from "worker_threads";
28238
28613
  var USER_HOME_RULES = [
28239
28614
  {
@@ -28277,6 +28652,11 @@ var DEFAULT_RULES = [
28277
28652
  pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
28278
28653
  reason: "aws-secret"
28279
28654
  },
28655
+ {
28656
+ // `prim auth enroll --print-env` output an agent may write into a file.
28657
+ pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
28658
+ reason: "prim-m2m-secret"
28659
+ },
28280
28660
  { pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
28281
28661
  {
28282
28662
  pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
@@ -28380,7 +28760,7 @@ function toRewriteMove(rewrite, cliVersion, cwd, context) {
28380
28760
  const moves = [];
28381
28761
  for (let offset = 0; offset < pairs.length; offset += MAX_REWRITE_PAIRS_PER_MOVE) {
28382
28762
  const sortedPairs = pairs.slice(offset, offset + MAX_REWRITE_PAIRS_PER_MOVE);
28383
- 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")}`;
28384
28764
  moves.push({
28385
28765
  moveId,
28386
28766
  capturedAt: observedAt,
@@ -28452,7 +28832,7 @@ function rewritePairsFromLauncher(env = process.env, now = Date.now()) {
28452
28832
  if (!privatePairsFileStat(openStat, now) || openStat.dev !== pathStat.dev || openStat.ino !== pathStat.ino) {
28453
28833
  return;
28454
28834
  }
28455
- const bytes = readFileSync15(fd);
28835
+ const bytes = readFileSync17(fd);
28456
28836
  if (bytes.length !== openStat.size) return;
28457
28837
  let text;
28458
28838
  try {
@@ -28508,14 +28888,14 @@ function validBranch(value) {
28508
28888
  }
28509
28889
  function resolveCliVersion() {
28510
28890
  try {
28511
- const pkg = JSON.parse(readFileSync15(join16(here, "..", "..", "package.json"), "utf-8"));
28891
+ const pkg = JSON.parse(readFileSync17(join19(here, "..", "..", "package.json"), "utf-8"));
28512
28892
  return pkg.version ?? "unknown";
28513
28893
  } catch {
28514
28894
  return "unknown";
28515
28895
  }
28516
28896
  }
28517
28897
  function spawnBackgroundFlush() {
28518
- const entry = join16(here, "..", "index.js");
28898
+ const entry = join19(here, "..", "index.js");
28519
28899
  spawn2(process.execPath, [entry, "moves", "flush"], {
28520
28900
  detached: true,
28521
28901
  stdio: "ignore",