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

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 +140 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
  4. package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
  5. package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
  6. package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
  7. package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
  8. package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
  9. package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
  10. package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
  11. package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
  12. package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
  13. package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
  14. package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
  15. package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
  16. package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
  17. package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
  18. package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
  19. package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
  20. package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
  21. package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
  22. package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
  23. package/dist/daemon/server.js +805 -218
  24. package/dist/hook-runtime/daemon/server.js +805 -218
  25. package/dist/hook-runtime/hooks/post-commit.js +286 -59
  26. package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
  27. package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
  28. package/dist/hook-runtime/hooks/pre-commit.js +536 -88
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
  30. package/dist/hook-runtime/hooks/prim-hook.js +642 -167
  31. package/dist/hook-runtime/hooks/session-end.js +263 -47
  32. package/dist/hook-runtime/hooks/session-start.js +1103 -476
  33. package/dist/hook-runtime/index.js +3645 -2120
  34. package/dist/hook-runtime/statusline-main.js +257 -29
  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 +15 -15
  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 +49 -18
  43. package/dist/index.js +1014 -271
  44. package/dist/statusline-main.js +257 -29
  45. package/package.json +1 -1
@@ -123,6 +123,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
123
123
  'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
124
124
  "fi; fi; "
125
125
  ].join("");
126
+ var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
126
127
  function stableHookCommand(bin, args = "") {
127
128
  if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
128
129
  throw new Error("invalid stable hook command");
@@ -134,11 +135,18 @@ function stableHookCommand(bin, args = "") {
134
135
  `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
135
136
  PRIM_CONFIG_SHELL_RESOLVER,
136
137
  `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
137
- 'exec "$prim_launcher" "$@"'
138
+ LAUNCHER_EXEC
138
139
  ].join("");
139
140
  const suffix = args ? ` ${args}` : "";
140
141
  return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
141
142
  }
143
+ function quietWithoutLauncher(command) {
144
+ if (!command.includes(LAUNCHER_EXEC)) throw new Error("not a stable hook command");
145
+ return command.replace(
146
+ LAUNCHER_EXEC,
147
+ () => `[ -e "$prim_launcher" ] || [ -L "$prim_launcher" ] || exit 0; ${LAUNCHER_EXEC}`
148
+ );
149
+ }
142
150
  function detachedHookShimCommand(bin, args = "") {
143
151
  return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
144
152
  }
@@ -186,14 +194,30 @@ function hookCommandResolutions(commands, bins) {
186
194
  return resolutions;
187
195
  }
188
196
 
197
+ // src/lib/cloud-env.ts
198
+ function isClaudeCloudSession(env = process.env) {
199
+ return env.CLAUDE_CODE_REMOTE === "true";
200
+ }
201
+ function insideClaudeCode(env = process.env) {
202
+ return env.CLAUDECODE === "1";
203
+ }
204
+ var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
205
+ 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';
206
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
207
+ function cloudSetupPointer(message, env = process.env) {
208
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
209
+ }
210
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
211
+
189
212
  // src/lib/git.ts
190
213
  import { execFileSync } from "child_process";
191
214
  import { createHash } from "crypto";
192
- import { lstatSync, realpathSync } from "fs";
193
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
215
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
216
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
194
217
  var GIT_TIMEOUT_MS = 1e3;
218
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
195
219
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
196
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
220
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
197
221
  function gitToplevel(cwd) {
198
222
  try {
199
223
  return execFileSync("git", ["rev-parse", "--show-toplevel"], {
@@ -240,19 +264,77 @@ function gitValue(cwd, args) {
240
264
  function currentBranch(cwd) {
241
265
  return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
242
266
  }
243
- function githubRepositoryFullName(cwd) {
244
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
245
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
267
+ function parseGithubRepositoryName(path) {
268
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
269
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
270
+ return null;
271
+ }
272
+ return `${parts[0]}/${parts[1]}`;
273
+ }
274
+ function githubRepositoryFromRemote(remote) {
275
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
246
276
  const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
247
277
  remote
248
278
  );
249
279
  const path = match?.[1] ?? match?.[2];
250
- if (!path) return null;
251
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
252
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
280
+ return path ? parseGithubRepositoryName(path) : null;
281
+ }
282
+ function originIdentifiesRepository(cwd) {
283
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
284
+ return remote !== void 0 && Boolean(githubRepositoryFromRemote(remote) || normalizeOriginRemote(remote));
285
+ }
286
+ function originGithubRepository(cwd) {
287
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
288
+ return remote ? githubRepositoryFromRemote(remote) : null;
289
+ }
290
+ function isGitIgnored(cwd, path) {
291
+ try {
292
+ execFileSync("git", ["check-ignore", "--quiet", "--", path], {
293
+ cwd,
294
+ stdio: ["ignore", "ignore", "ignore"],
295
+ timeout: GIT_TIMEOUT_MS
296
+ });
297
+ return true;
298
+ } catch {
299
+ return false;
300
+ }
301
+ }
302
+ function checkoutSettingsText(repoRoot) {
303
+ const path = join2(repoRoot, ".claude", "settings.json");
304
+ try {
305
+ if (!lstatSync(join2(repoRoot, ".claude")).isDirectory()) return null;
306
+ const stat = lstatSync(path);
307
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
308
+ return readFileSync2(path, "utf8");
309
+ } catch {
253
310
  return null;
254
311
  }
255
- return `${parts[0]}/${parts[1]}`;
312
+ }
313
+ function checkoutDeclaration(repoRoot, name) {
314
+ const text = checkoutSettingsText(repoRoot);
315
+ if (text === null) return null;
316
+ let parsed;
317
+ try {
318
+ parsed = JSON.parse(text);
319
+ } catch {
320
+ return null;
321
+ }
322
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
323
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
324
+ return typeof value === "string" ? value : null;
325
+ }
326
+ function declaredGithubRepository(repoRoot) {
327
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
328
+ return value === null ? null : parseGithubRepositoryName(value.trim());
329
+ }
330
+ function githubRepositoryFullName(cwd) {
331
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
332
+ if (remote) {
333
+ const fromOrigin = githubRepositoryFromRemote(remote);
334
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
335
+ }
336
+ const root = gitToplevel(cwd);
337
+ return root ? declaredGithubRepository(root) : null;
256
338
  }
257
339
  function canonicalGitRoot(cwd) {
258
340
  try {
@@ -331,6 +413,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
331
413
  repoFullName
332
414
  };
333
415
  }
416
+ if (repoFullName) {
417
+ return {
418
+ repoRoot,
419
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
420
+ identitySource: "declared",
421
+ repoFullName
422
+ };
423
+ }
334
424
  const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
335
425
  if (roots && roots.length > 0) {
336
426
  return {
@@ -419,9 +509,77 @@ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
419
509
 
420
510
  // src/lib/activation.ts
421
511
  import { execFileSync as execFileSync3 } from "child_process";
422
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
512
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
513
+ import { homedir as homedir2 } from "os";
514
+ import { join as join5 } from "path";
515
+
516
+ // src/lib/cloud-prepared.ts
517
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
518
+ import { join as join4 } from "path";
519
+
520
+ // src/lib/paths.ts
423
521
  import { homedir } from "os";
424
- import { join as join2 } from "path";
522
+ import { isAbsolute as isAbsolute3, join as join3, normalize } from "path";
523
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
524
+ function absolutePath(value, variable) {
525
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
526
+ throw new Error(`${variable} contains unsafe characters`);
527
+ }
528
+ if (!value || value.trim() !== value || !isAbsolute3(value)) return;
529
+ const normalized = normalize(value);
530
+ return normalized === value ? value : void 0;
531
+ }
532
+ function resolvePrimConfigDirectory(options = {}) {
533
+ const env = options.env ?? process.env;
534
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
535
+ if (explicit) return { path: explicit, source: "explicit" };
536
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
537
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
538
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
539
+ if (!home) {
540
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
541
+ }
542
+ return { path: join3(home, ".config", "prim"), source: "default" };
543
+ }
544
+ function primConfigDirectory(options = {}) {
545
+ return resolvePrimConfigDirectory(options).path;
546
+ }
547
+
548
+ // src/lib/cloud-prepared.ts
549
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
550
+ var CLOUD_PREPARED_VERSION = "1";
551
+ var SESSION_ORIGIN = "session";
552
+ function cloudPreparedPath(env = process.env) {
553
+ return join4(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
554
+ }
555
+ function markCloudPrepared(env = process.env, origin = "image") {
556
+ const directory = primConfigDirectory({ env });
557
+ mkdirSync(directory, { recursive: true, mode: 448 });
558
+ writeFileSync(
559
+ cloudPreparedPath(env),
560
+ `${CLOUD_PREPARED_VERSION}${origin === "session" ? ` ${SESSION_ORIGIN}` : ""}
561
+ `,
562
+ { mode: 384 }
563
+ );
564
+ }
565
+ function preparedInSession(env = process.env) {
566
+ try {
567
+ return readFileSync3(cloudPreparedPath(env), "utf8").trim().split(/\s+/u)[1] === SESSION_ORIGIN;
568
+ } catch {
569
+ return false;
570
+ }
571
+ }
572
+ function clearCloudPrepared(env = process.env) {
573
+ rmSync(cloudPreparedPath(env), { force: true });
574
+ }
575
+ function isPreparedCloudSession(env = process.env) {
576
+ if (!isClaudeCloudSession(env)) return false;
577
+ try {
578
+ return existsSync2(cloudPreparedPath(env));
579
+ } catch {
580
+ return false;
581
+ }
582
+ }
425
583
 
426
584
  // src/lib/demo-pause.ts
427
585
  import { execFileSync as execFileSync2 } from "child_process";
@@ -515,6 +673,8 @@ function healDemoPause(cwd, pause, options = {}) {
515
673
 
516
674
  // src/lib/activation.ts
517
675
  var PRIM_ACTIVE_KEY = "prim.active";
676
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
677
+ var PRIM_ACTIVE_IMPLICIT_KEY = "prim.activeImplicit";
518
678
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
519
679
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
520
680
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
@@ -610,14 +770,30 @@ function repositoryBindingState(cwd) {
610
770
  if (marker !== void 0) return "invalid";
611
771
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
612
772
  }
773
+ function unsetLocalGitConfigValue(cwd, key) {
774
+ try {
775
+ execFileSync3("git", ["config", "--local", "--unset-all", key], {
776
+ cwd,
777
+ stdio: ["ignore", "ignore", "pipe"],
778
+ timeout: GIT_TIMEOUT_MS3
779
+ });
780
+ } catch (error) {
781
+ if (typeof error === "object" && error !== null && "status" in error && error.status === 5) {
782
+ return;
783
+ }
784
+ throw error;
785
+ }
786
+ }
613
787
  function hasProjectPrimInstall(cwd) {
614
- const root = gitToplevel(cwd);
615
- if (root === null || root === homedir()) return false;
788
+ return projectPrimInstallAt(gitToplevel(cwd));
789
+ }
790
+ function projectPrimInstallAt(root) {
791
+ if (root === null || root === homedir2()) return false;
616
792
  for (const rel of PROJECT_INSTALL_FILES) {
617
- const path = join2(root, rel);
618
- if (existsSync2(path)) {
793
+ const path = join5(root, rel);
794
+ if (existsSync3(path)) {
619
795
  try {
620
- const content = readFileSync2(path, "utf-8");
796
+ const content = readFileSync4(path, "utf-8");
621
797
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
622
798
  } catch {
623
799
  }
@@ -625,12 +801,56 @@ function hasProjectPrimInstall(cwd) {
625
801
  }
626
802
  return false;
627
803
  }
804
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
805
+ function declaresInactive(cwd) {
806
+ return declaresInactiveAt(gitToplevel(cwd));
807
+ }
808
+ function declaresInactiveAt(root) {
809
+ if (root === null || root === homedir2()) return false;
810
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
811
+ const text = checkoutSettingsText(root);
812
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
813
+ try {
814
+ JSON.parse(text);
815
+ return false;
816
+ } catch {
817
+ return true;
818
+ }
819
+ }
820
+ function markActivationImplicit(cwd) {
821
+ try {
822
+ setLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY, "true");
823
+ } catch {
824
+ }
825
+ }
826
+ function markActivationExplicit(cwd) {
827
+ unsetLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY);
828
+ }
829
+ function explicitlyActive(cwd) {
830
+ return repoActiveFlag(cwd) === "true" && !(localGitConfigValue(cwd, PRIM_ACTIVE_KEY) === "true" && localGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY) === "true");
831
+ }
832
+ function withdrawImplicitActivation(cwd) {
833
+ try {
834
+ const root = gitToplevel(cwd);
835
+ if (root === null) return false;
836
+ if (localGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY) !== "true") return false;
837
+ if (localGitConfigValue(root, PRIM_ACTIVE_KEY) !== "true" || !declaresInactiveAt(root))
838
+ return false;
839
+ unsetLocalGitConfigValue(root, PRIM_ACTIVE_KEY);
840
+ unsetLocalGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY);
841
+ return true;
842
+ } catch {
843
+ return false;
844
+ }
845
+ }
628
846
  function isRepoActiveForCapture(cwd, options = {}) {
629
847
  let { active: flag, pause } = readCaptureConfig(cwd);
630
848
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
631
849
  if (flag === "true") return true;
632
850
  if (flag === "false") return false;
633
- return hasProjectPrimInstall(cwd);
851
+ const root = gitToplevel(cwd);
852
+ if (declaresInactiveAt(root)) return false;
853
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
634
854
  }
635
855
  function decisionIngestionStatus(cwd) {
636
856
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -643,11 +863,11 @@ import {
643
863
  closeSync,
644
864
  fchmodSync,
645
865
  fsyncSync,
646
- mkdirSync,
866
+ mkdirSync as mkdirSync2,
647
867
  openSync,
648
868
  renameSync,
649
- rmSync,
650
- writeFileSync
869
+ rmSync as rmSync2,
870
+ writeFileSync as writeFileSync2
651
871
  } from "fs";
652
872
  import { dirname as dirname3 } from "path";
653
873
  var DEFAULT_FILE_MODE = 438;
@@ -686,7 +906,7 @@ function syncCreatedParentChain(firstCreatedParent, parent) {
686
906
  }
687
907
  }
688
908
  function ensureDurableDirectory(path, mode) {
689
- const firstCreatedParent = mkdirSync(path, { recursive: true, mode });
909
+ const firstCreatedParent = mkdirSync2(path, { recursive: true, mode });
690
910
  if (firstCreatedParent) {
691
911
  syncCreatedParentChain(firstCreatedParent, path);
692
912
  }
@@ -704,7 +924,7 @@ function atomicWriteFile(target, content, options = {}) {
704
924
  temporaryCreated = true;
705
925
  try {
706
926
  if (options.mode !== void 0) fchmodSync(fd, options.mode);
707
- writeFileSync(fd, content);
927
+ writeFileSync2(fd, content);
708
928
  fsyncSync(fd);
709
929
  } finally {
710
930
  closeSync(fd);
@@ -715,7 +935,7 @@ function atomicWriteFile(target, content, options = {}) {
715
935
  } catch (error) {
716
936
  if (temporaryCreated) {
717
937
  try {
718
- rmSync(temporaryPath, { force: true });
938
+ rmSync2(temporaryPath, { force: true });
719
939
  } catch {
720
940
  }
721
941
  }
@@ -736,19 +956,19 @@ function processIsAlive(pid, probe = process.kill) {
736
956
 
737
957
  // src/lib/file-lock.ts
738
958
  import { randomBytes } from "crypto";
739
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync3, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
740
- import { dirname as dirname4, join as join3 } from "path";
959
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync3, statSync, writeFileSync as writeFileSync3 } from "fs";
960
+ import { dirname as dirname4, join as join6 } from "path";
741
961
  var DEFAULT_TIMEOUT_MS = 3e4;
742
962
  var DEFAULT_POLL_MS = 50;
743
963
  var DEFAULT_INIT_GRACE_MS = 2e3;
744
964
  var DIRECTORY_MODE = 448;
745
965
  var FILE_MODE = 384;
746
966
  function ownerPath(lockDir) {
747
- return join3(lockDir, "owner.json");
967
+ return join6(lockDir, "owner.json");
748
968
  }
749
969
  function readOwner(lockDir) {
750
970
  try {
751
- const owner = JSON.parse(readFileSync3(ownerPath(lockDir), "utf8"));
971
+ const owner = JSON.parse(readFileSync5(ownerPath(lockDir), "utf8"));
752
972
  if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
753
973
  return null;
754
974
  }
@@ -762,7 +982,7 @@ function sameOwner(a, b) {
762
982
  }
763
983
  function tryTakeLock(lockDir, now) {
764
984
  try {
765
- mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
985
+ mkdirSync3(lockDir, { mode: DIRECTORY_MODE });
766
986
  } catch (error) {
767
987
  if (error.code === "EEXIST") return null;
768
988
  throw error;
@@ -773,7 +993,7 @@ function tryTakeLock(lockDir, now) {
773
993
  createdAt: now
774
994
  };
775
995
  try {
776
- writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
996
+ writeFileSync3(ownerPath(lockDir), `${JSON.stringify(owner)}
777
997
  `, {
778
998
  encoding: "utf8",
779
999
  mode: FILE_MODE,
@@ -781,7 +1001,7 @@ function tryTakeLock(lockDir, now) {
781
1001
  });
782
1002
  return owner;
783
1003
  } catch (error) {
784
- rmSync2(lockDir, { recursive: true, force: true });
1004
+ rmSync3(lockDir, { recursive: true, force: true });
785
1005
  throw error;
786
1006
  }
787
1007
  }
@@ -790,7 +1010,7 @@ function recoverStaleLock(lockDir, now, alive, initGraceMs) {
790
1010
  if (owner) {
791
1011
  if (alive(owner.pid)) return false;
792
1012
  if (!sameOwner(readOwner(lockDir), owner)) return false;
793
- rmSync2(lockDir, { recursive: true, force: true });
1013
+ rmSync3(lockDir, { recursive: true, force: true });
794
1014
  return true;
795
1015
  }
796
1016
  try {
@@ -798,7 +1018,7 @@ function recoverStaleLock(lockDir, now, alive, initGraceMs) {
798
1018
  if (now - before < initGraceMs) return false;
799
1019
  if (readOwner(lockDir)) return false;
800
1020
  if (statSync(lockDir).mtimeMs !== before) return false;
801
- rmSync2(lockDir, { recursive: true, force: true });
1021
+ rmSync3(lockDir, { recursive: true, force: true });
802
1022
  return true;
803
1023
  } catch {
804
1024
  return true;
@@ -836,7 +1056,7 @@ function defaultSleepSync(ms) {
836
1056
  Atomics.wait(syncSleeper, 0, 0, ms);
837
1057
  }
838
1058
  function withFileLockSync(lockDir, operation, options = {}) {
839
- mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1059
+ mkdirSync3(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
840
1060
  const nowMs = options.nowMs ?? Date.now;
841
1061
  const alive = options.processAlive ?? processIsAlive;
842
1062
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -855,12 +1075,12 @@ function withFileLockSync(lockDir, operation, options = {}) {
855
1075
  return operation();
856
1076
  } finally {
857
1077
  if (sameOwner(readOwner(lockDir), owner)) {
858
- rmSync2(lockDir, { recursive: true, force: true });
1078
+ rmSync3(lockDir, { recursive: true, force: true });
859
1079
  }
860
1080
  }
861
1081
  }
862
1082
  async function withFileLock(lockDir, operation, options = {}) {
863
- mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1083
+ mkdirSync3(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
864
1084
  const nowMs = options.nowMs ?? Date.now;
865
1085
  const alive = options.processAlive ?? processIsAlive;
866
1086
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -886,7 +1106,7 @@ async function withFileLock(lockDir, operation, options = {}) {
886
1106
  return await operation();
887
1107
  } finally {
888
1108
  if (sameOwner(readOwner(lockDir), owner)) {
889
- rmSync2(lockDir, { recursive: true, force: true });
1109
+ rmSync3(lockDir, { recursive: true, force: true });
890
1110
  }
891
1111
  }
892
1112
  }
@@ -1242,9 +1462,19 @@ function parseMachineConfiguration(value) {
1242
1462
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
1243
1463
  };
1244
1464
  }
1465
+ function rejectedCredentialsMessage(message, env = process.env) {
1466
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
1467
+ }
1245
1468
  function machineSignal(signal) {
1246
1469
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1247
1470
  }
1471
+ function hostOf(url) {
1472
+ try {
1473
+ return new URL(url).hostname;
1474
+ } catch {
1475
+ return "Primitive";
1476
+ }
1477
+ }
1248
1478
  async function fetchMachine(url, options, fetchImpl) {
1249
1479
  try {
1250
1480
  return await fetchImpl(url, options);
@@ -1252,7 +1482,9 @@ async function fetchMachine(url, options, fetchImpl) {
1252
1482
  options.signal?.throwIfAborted();
1253
1483
  throw new MachineAuthError(
1254
1484
  "authentication_unavailable",
1255
- "Machine authentication is temporarily unavailable. Check the connection and retry."
1485
+ // A cloud VM reaches only the hosts its environment allows, and both of
1486
+ // Primitive's are blocked by default: name the one that failed.
1487
+ isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
1256
1488
  );
1257
1489
  }
1258
1490
  }
@@ -1279,8 +1511,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
1279
1511
  );
1280
1512
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
1281
1513
  }
1282
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
1283
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1514
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
1515
+ const network = options.secretInjection === "network";
1516
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
1284
1517
  throw new MachineAuthError(
1285
1518
  "invalid_credentials",
1286
1519
  "A machine client ID and secret are required.",
@@ -1294,11 +1527,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1294
1527
  redirect: "error",
1295
1528
  signal: machineSignal(signal),
1296
1529
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
1297
- body: new URLSearchParams({
1298
- grant_type: "client_credentials",
1299
- client_id: clientId,
1300
- client_secret: clientSecret
1301
- })
1530
+ // With a network secret the agent proxy authenticates the client with
1531
+ // HTTP Basic (client_secret_basic); the body carries no credential.
1532
+ body: new URLSearchParams(
1533
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
1534
+ )
1302
1535
  },
1303
1536
  fetchImpl
1304
1537
  );
@@ -1306,7 +1539,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1306
1539
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
1307
1540
  throw new MachineAuthError(
1308
1541
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
1309
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
1542
+ terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
1543
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
1544
+ ) : "The machine token service is temporarily unavailable.",
1310
1545
  terminal,
1311
1546
  terminal ? void 0 : machineRetryAt(response)
1312
1547
  );
@@ -1326,6 +1561,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1326
1561
  } catch {
1327
1562
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
1328
1563
  }
1564
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
1565
+ throw new MachineAuthError(
1566
+ "token_client_mismatch",
1567
+ "The token service issued a token for another machine client."
1568
+ );
1329
1569
  if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
1330
1570
  throw new MachineAuthError(
1331
1571
  "token_identity_mismatch",
@@ -1371,74 +1611,131 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
1371
1611
  const terminal = response.status === 401 || response.status === 403;
1372
1612
  throw new MachineAuthError(
1373
1613
  terminal ? "machine_access_rejected" : "verification_unavailable",
1374
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
1614
+ terminal ? rejectedCredentialsMessage(
1615
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
1616
+ ) : "Machine verification is temporarily unavailable.",
1375
1617
  terminal
1376
1618
  );
1377
1619
  }
1378
1620
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
1379
1621
  }
1380
-
1381
- // src/lib/paths.ts
1382
- import { homedir as homedir2 } from "os";
1383
- import { isAbsolute as isAbsolute3, join as join4, normalize } from "path";
1384
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
1385
- function absolutePath(value, variable) {
1386
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
1387
- throw new Error(`${variable} contains unsafe characters`);
1388
- }
1389
- if (!value || value.trim() !== value || !isAbsolute3(value)) return;
1390
- const normalized = normalize(value);
1391
- return normalized === value ? value : void 0;
1392
- }
1393
- function resolvePrimConfigDirectory(options = {}) {
1394
- const env = options.env ?? process.env;
1395
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
1396
- if (explicit) return { path: explicit, source: "explicit" };
1397
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
1398
- if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
1399
- const home = absolutePath(options.homeDir ?? homedir2(), "HOME");
1400
- if (!home) {
1401
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
1622
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
1623
+ const rejected = () => new MachineAuthError(
1624
+ "network_token_rejected",
1625
+ `Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
1626
+ true
1627
+ );
1628
+ if (status === 401 || status === 403) throw rejected();
1629
+ if (status < 200 || status > 299)
1630
+ throw new MachineAuthError(
1631
+ "verification_unavailable",
1632
+ "Machine verification is temporarily unavailable."
1633
+ );
1634
+ let data;
1635
+ try {
1636
+ data = machineRecord(value);
1637
+ } catch {
1638
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
1402
1639
  }
1403
- return { path: join4(home, ".config", "prim"), source: "default" };
1640
+ if (data.authenticated !== true) throw rejected();
1641
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
1642
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
1643
+ throw new MachineAuthError(
1644
+ "network_secret_mismatch",
1645
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
1646
+ true
1647
+ );
1648
+ return parseMachineIdentity(data, clientId);
1404
1649
  }
1405
- function primConfigDirectory(options = {}) {
1406
- return resolvePrimConfigDirectory(options).path;
1650
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
1651
+ const response = await fetchMachine(
1652
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
1653
+ { redirect: "error", signal: machineSignal(signal) },
1654
+ fetchImpl
1655
+ );
1656
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
1657
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
1407
1658
  }
1408
1659
 
1409
1660
  // src/lib/machine-credentials.ts
1410
1661
  import { execFileSync as execFileSync4 } from "child_process";
1411
- import { createHash as createHash4, randomUUID as randomUUID2 } from "crypto";
1412
- import { chmodSync, existsSync as existsSync4, lstatSync as lstatSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync6, rmSync as rmSync5 } from "fs";
1662
+ import { createHash as createHash4, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
1663
+ import {
1664
+ chmodSync,
1665
+ existsSync as existsSync5,
1666
+ linkSync,
1667
+ lstatSync as lstatSync4,
1668
+ mkdirSync as mkdirSync4,
1669
+ readFileSync as readFileSync8,
1670
+ rmSync as rmSync6,
1671
+ writeFileSync as writeFileSync4
1672
+ } from "fs";
1413
1673
  import { createRequire } from "module";
1414
- import { dirname as dirname5, join as join7 } from "path";
1674
+ import { dirname as dirname5, join as join9 } from "path";
1415
1675
  import { fileURLToPath as fileURLToPath3 } from "url";
1416
1676
 
1417
1677
  // src/lib/machine-broker.ts
1418
1678
  import { spawn } from "child_process";
1419
1679
  import { createHash as createHash2, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
1420
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync3 } from "fs";
1680
+ import { lstatSync as lstatSync2, readFileSync as readFileSync6, rmSync as rmSync4 } from "fs";
1421
1681
  import { createServer } from "http";
1422
- import { basename as basename2, join as join5 } from "path";
1682
+ import { basename as basename2, join as join7 } from "path";
1423
1683
  import { fileURLToPath as fileURLToPath2 } from "url";
1684
+
1685
+ // src/lib/loopback-fetch.ts
1686
+ import { request } from "http";
1687
+ import { Readable } from "stream";
1688
+ function loopbackFetch(url, init = {}) {
1689
+ const target = new URL(url);
1690
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
1691
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
1692
+ return new Promise((resolve2, reject) => {
1693
+ const outgoing = request(
1694
+ target,
1695
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
1696
+ (incoming) => {
1697
+ try {
1698
+ const headers = new Headers();
1699
+ for (const [name, value] of Object.entries(incoming.headers))
1700
+ if (typeof value === "string") headers.set(name, value);
1701
+ const status = incoming.statusCode ?? 502;
1702
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
1703
+ resolve2(new Response(body, { status, headers }));
1704
+ } catch (error) {
1705
+ incoming.destroy();
1706
+ reject(error);
1707
+ }
1708
+ }
1709
+ );
1710
+ outgoing.once("error", reject);
1711
+ outgoing.end(init.body);
1712
+ });
1713
+ }
1714
+
1715
+ // src/lib/machine-broker.ts
1424
1716
  var MAX_RESPONSE_BYTES = 96 * 1024;
1717
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
1718
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
1719
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
1720
+ var FORWARD_REQUEST_PROOF = "forward-request";
1721
+ var FORWARD_ANSWER_PROOF = "forward-answer";
1425
1722
  var IDLE_MS = 5 * 6e4;
1426
1723
  function descriptorPath(directory, generation) {
1427
- return join5(directory, `machine_broker_${generation}.json`);
1724
+ return join7(directory, `machine_broker_${generation}.json`);
1428
1725
  }
1429
1726
  function readDescriptor(path) {
1430
1727
  try {
1431
1728
  const stat = lstatSync2(path);
1432
1729
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1433
1730
  return void 0;
1434
- const data = JSON.parse(readFileSync4(path, "utf8"));
1731
+ const data = JSON.parse(readFileSync6(path, "utf8"));
1435
1732
  return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
1436
1733
  } catch {
1437
1734
  return void 0;
1438
1735
  }
1439
1736
  }
1440
- function signature(secret, nonce, body) {
1441
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
1737
+ function signature(secret, nonce, body, purpose) {
1738
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
1442
1739
  }
1443
1740
  function matches(left, right) {
1444
1741
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -1453,10 +1750,9 @@ async function brokerRequest(descriptor, environment, options) {
1453
1750
  observedTokenHash: tokenHash(options.observedToken),
1454
1751
  timestamp: Date.now()
1455
1752
  });
1456
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1753
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1457
1754
  method: "POST",
1458
1755
  body,
1459
- redirect: "error",
1460
1756
  signal: options.signal,
1461
1757
  headers: {
1462
1758
  "Content-Type": "application/json",
@@ -1487,6 +1783,15 @@ async function brokerRequest(descriptor, environment, options) {
1487
1783
  );
1488
1784
  return credential;
1489
1785
  }
1786
+ function brokerEnvironment(options) {
1787
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
1788
+ return {
1789
+ ...options.env,
1790
+ PRIM_API_URL: options.apiUrl,
1791
+ PRIM_CONFIG_DIR: options.directory,
1792
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
1793
+ };
1794
+ }
1490
1795
  async function acquireBrokerCredential(options) {
1491
1796
  const path = descriptorPath(options.directory, options.environment.generation);
1492
1797
  const existing = readDescriptor(path);
@@ -1498,15 +1803,28 @@ async function acquireBrokerCredential(options) {
1498
1803
  if (error instanceof MachineAuthError) throw error;
1499
1804
  }
1500
1805
  }
1501
- const descriptor = await withFileLock(
1502
- join5(options.directory, "machine-broker.lock"),
1806
+ const descriptor = await ensureBroker(options);
1807
+ try {
1808
+ return await brokerRequest(descriptor, options.environment, options);
1809
+ } catch (error) {
1810
+ options.signal.throwIfAborted();
1811
+ if (error instanceof MachineAuthError) throw error;
1812
+ throw new MachineAuthError(
1813
+ "broker_unavailable",
1814
+ "Machine credential broker is unavailable. Retry the command."
1815
+ );
1816
+ }
1817
+ }
1818
+ async function ensureBroker(options) {
1819
+ const path = descriptorPath(options.directory, options.environment.generation);
1820
+ return withFileLock(
1821
+ join7(options.directory, "machine-broker.lock"),
1503
1822
  async () => {
1504
1823
  const current = readDescriptor(path);
1505
1824
  if (current) {
1506
1825
  try {
1507
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
1508
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
1509
- redirect: "error"
1826
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
1827
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
1510
1828
  });
1511
1829
  if (response.ok && await response.text() === current.nonce) return current;
1512
1830
  } catch {
@@ -1525,7 +1843,7 @@ async function acquireBrokerCredential(options) {
1525
1843
  detached: true,
1526
1844
  stdio: ["ignore", "ignore", "ignore", "ipc"],
1527
1845
  windowsHide: true,
1528
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
1846
+ env: brokerEnvironment(options)
1529
1847
  });
1530
1848
  let settled = false;
1531
1849
  const finish = (error) => {
@@ -1577,31 +1895,118 @@ async function acquireBrokerCredential(options) {
1577
1895
  },
1578
1896
  { signal: options.signal }
1579
1897
  );
1898
+ }
1899
+ async function forwardOnce(descriptor, environment, request2, signal) {
1900
+ const body = JSON.stringify({
1901
+ generation: environment.generation,
1902
+ timestamp: Date.now(),
1903
+ method: request2.method,
1904
+ path: request2.path,
1905
+ headers: request2.headers ?? {},
1906
+ ...request2.body === void 0 ? {} : { body: request2.body }
1907
+ });
1908
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
1909
+ method: "POST",
1910
+ body,
1911
+ signal,
1912
+ headers: {
1913
+ "Content-Type": "application/json",
1914
+ "X-Prim-Proof": signature(
1915
+ environment.clientSecret,
1916
+ descriptor.nonce,
1917
+ body,
1918
+ FORWARD_REQUEST_PROOF
1919
+ )
1920
+ }
1921
+ });
1922
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
1923
+ if (typeof envelope.body !== "string" || !matches(
1924
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
1925
+ envelope.proof
1926
+ ))
1927
+ throw new MachineAuthError(
1928
+ "broker_unavailable",
1929
+ "Machine credential broker could not be authenticated. Retry the command."
1930
+ );
1931
+ const data = machineRecord(JSON.parse(envelope.body));
1932
+ if (data.error) {
1933
+ const error = machineRecord(data.error);
1934
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
1935
+ }
1936
+ const status = data.status;
1937
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
1938
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
1939
+ const headers = new Headers();
1940
+ for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
1941
+ if (typeof value === "string") headers.set(name, value);
1942
+ const text = typeof data.body === "string" ? data.body : "";
1943
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
1944
+ }
1945
+ async function forwardBrokerRequest(options) {
1946
+ const path = descriptorPath(options.directory, options.environment.generation);
1947
+ const unavailable = () => new MachineAuthError(
1948
+ "broker_unavailable",
1949
+ "Machine credential broker is unavailable. Retry the command."
1950
+ );
1951
+ const existing = readDescriptor(path);
1952
+ if (existing) {
1953
+ try {
1954
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
1955
+ } catch (error) {
1956
+ options.signal.throwIfAborted();
1957
+ if (error instanceof MachineAuthError) throw error;
1958
+ if (error.code !== "ECONNREFUSED") throw unavailable();
1959
+ }
1960
+ }
1961
+ const descriptor = await ensureBroker(options);
1580
1962
  try {
1581
- return await brokerRequest(descriptor, options.environment, options);
1963
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
1582
1964
  } catch (error) {
1583
1965
  options.signal.throwIfAborted();
1584
1966
  if (error instanceof MachineAuthError) throw error;
1585
- throw new MachineAuthError(
1586
- "broker_unavailable",
1587
- "Machine credential broker is unavailable. Retry the command."
1588
- );
1967
+ throw unavailable();
1589
1968
  }
1590
1969
  }
1591
1970
 
1592
1971
  // src/lib/machine-retry.ts
1593
1972
  import { createHash as createHash3 } from "crypto";
1594
- import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync4 } from "fs";
1595
- import { join as join6 } from "path";
1596
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request) {
1973
+ import { lstatSync as lstatSync3, readFileSync as readFileSync7, readdirSync, rmSync as rmSync5 } from "fs";
1974
+ import { join as join8 } from "path";
1975
+ function clearMachineCooldowns(directory) {
1976
+ let names;
1977
+ try {
1978
+ names = readdirSync(directory);
1979
+ } catch {
1980
+ return;
1981
+ }
1982
+ for (const name of names) {
1983
+ if (!/^machine_retry_[0-9a-f]{64}\.json$/u.test(name)) continue;
1984
+ const path = join8(directory, name);
1985
+ try {
1986
+ const state = JSON.parse(readFileSync7(path, "utf8"));
1987
+ if (state.serverRetryAfter === true) continue;
1988
+ } catch {
1989
+ }
1990
+ try {
1991
+ rmSync5(path, { force: true });
1992
+ } catch {
1993
+ }
1994
+ }
1995
+ }
1996
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
1997
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
1998
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
1597
1999
  signal?.throwIfAborted();
1598
2000
  const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
1599
- const path = join6(directory, `machine_retry_${key}.json`);
1600
- let state = { failures: 0, retryAt: 0 };
2001
+ const path = join8(directory, `machine_retry_${key}.json`);
2002
+ let state = {
2003
+ failures: 0,
2004
+ retryAt: 0
2005
+ };
1601
2006
  try {
1602
2007
  const stat = lstatSync3(path);
1603
2008
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
1604
- const data = JSON.parse(readFileSync5(path, "utf8"));
2009
+ const data = JSON.parse(readFileSync7(path, "utf8"));
1605
2010
  if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
1606
2011
  throw new Error("Invalid retry state");
1607
2012
  state = data;
@@ -1612,13 +2017,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request)
1612
2017
  if (state.retryAt > Date.now())
1613
2018
  throw new MachineAuthError(
1614
2019
  "token_service_unavailable",
1615
- "Machine authentication is cooling down after a temporary failure. Retry later.",
2020
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
2021
+ // Cloud setup keeps this wait too, so pointing at it would loop.
2022
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
2023
+ ) : (
2024
+ // The cooldown hides the failure that started it; cloud setup
2025
+ // retries at once and names the cause.
2026
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
2027
+ ),
1616
2028
  false,
1617
2029
  state.retryAt
1618
2030
  );
1619
2031
  try {
1620
- const result = await request();
1621
- rmSync4(path, { force: true });
2032
+ const result = await request2();
2033
+ rmSync5(path, { force: true });
1622
2034
  return result;
1623
2035
  } catch (error) {
1624
2036
  if (!signal?.aborted && error instanceof MachineAuthError && [
@@ -1629,8 +2041,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request)
1629
2041
  ].includes(error.code)) {
1630
2042
  const failures = Math.min(16, state.failures + 1);
1631
2043
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
1632
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
1633
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
2044
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
2045
+ atomicWriteFile(
2046
+ path,
2047
+ JSON.stringify({
2048
+ failures,
2049
+ retryAt,
2050
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
2051
+ }),
2052
+ { mode: 384 }
2053
+ );
1634
2054
  throw new MachineAuthError(error.code, error.message, false, retryAt);
1635
2055
  }
1636
2056
  throw error;
@@ -1654,13 +2074,13 @@ function hash(value) {
1654
2074
  return createHash4("sha256").update(value).digest("hex");
1655
2075
  }
1656
2076
  function recordPath(directory, generation) {
1657
- return join7(directory, `machine_${generation}.json`);
2077
+ return join9(directory, `machine_${generation}.json`);
1658
2078
  }
1659
2079
  function storageKey(directory, generation) {
1660
2080
  return `${hash(directory)}:${generation}`;
1661
2081
  }
1662
2082
  function environmentContextPath(deps, clientId) {
1663
- return join7(
2083
+ return join9(
1664
2084
  configurationDirectory(deps),
1665
2085
  `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1666
2086
  );
@@ -1723,8 +2143,8 @@ function readEnvironmentContext(environment, deps) {
1723
2143
  function keyringEntry(key) {
1724
2144
  let directory = dirname5(fileURLToPath3(import.meta.url));
1725
2145
  for (let depth = 0; depth < 5; depth++) {
1726
- const loader = join7(directory, "native", "keyring.cjs");
1727
- if (existsSync4(loader)) {
2146
+ const loader = join9(directory, "native", "keyring.cjs");
2147
+ if (existsSync5(loader)) {
1728
2148
  const module2 = require2(loader);
1729
2149
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1730
2150
  }
@@ -1752,7 +2172,7 @@ function protectPath(path, directory) {
1752
2172
  );
1753
2173
  }
1754
2174
  function ensureDirectory(directory) {
1755
- mkdirSync3(directory, { recursive: true, mode: 448 });
2175
+ mkdirSync4(directory, { recursive: true, mode: 448 });
1756
2176
  if (lstatSync4(directory).isSymbolicLink())
1757
2177
  throw new MachineAuthError(
1758
2178
  "unsafe_storage",
@@ -1775,7 +2195,7 @@ function readPrivate(path) {
1775
2195
  "Machine credential files must be owner-only regular files."
1776
2196
  );
1777
2197
  }
1778
- raw = readFileSync6(path, "utf8");
2198
+ raw = readFileSync8(path, "utf8");
1779
2199
  } catch (error) {
1780
2200
  if (error.code === "ENOENT") return void 0;
1781
2201
  throw error;
@@ -1820,13 +2240,101 @@ function parseProfile(value) {
1820
2240
  };
1821
2241
  }
1822
2242
  function readMachineProfile(deps = {}) {
1823
- const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
2243
+ const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
1824
2244
  return value === void 0 ? void 0 : parseProfile(value);
1825
2245
  }
2246
+ var NETWORK_SECRET_AUTH = "network-secret";
2247
+ var NETWORK_TOKEN_AUTH = "network-token";
2248
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2249
+ var brokerKeys = /* @__PURE__ */ new Map();
2250
+ function networkSecretBrokerKey(deps, clientId) {
2251
+ const directory = configurationDirectory(deps);
2252
+ const path = join9(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2253
+ const known = brokerKeys.get(path);
2254
+ if (known) return known;
2255
+ ensureDirectory(directory);
2256
+ const read = () => {
2257
+ try {
2258
+ const stat = lstatSync4(path);
2259
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2260
+ throw new MachineAuthError(
2261
+ "unsafe_storage",
2262
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2263
+ true
2264
+ );
2265
+ const value = readFileSync8(path, "utf8").trim();
2266
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2267
+ } catch (error) {
2268
+ if (error.code === "ENOENT") return void 0;
2269
+ throw error;
2270
+ }
2271
+ };
2272
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2273
+ const existing = read();
2274
+ if (existing?.key) {
2275
+ brokerKeys.set(path, existing.key);
2276
+ return existing.key;
2277
+ }
2278
+ if (existing)
2279
+ throw new MachineAuthError(
2280
+ "unsafe_storage",
2281
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2282
+ true
2283
+ );
2284
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
2285
+ try {
2286
+ writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
2287
+ `, { mode: 384, flag: "wx" });
2288
+ protectPath(staged, false);
2289
+ linkSync(staged, path);
2290
+ } catch (error) {
2291
+ if (error.code !== "EEXIST") throw error;
2292
+ } finally {
2293
+ rmSync6(staged, { force: true });
2294
+ }
2295
+ }
2296
+ const key = read()?.key;
2297
+ if (!key)
2298
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2299
+ brokerKeys.set(path, key);
2300
+ return key;
2301
+ }
1826
2302
  function environmentCredentials(deps) {
1827
2303
  const env = deps.env ?? process.env;
1828
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
1829
- if (clientId === void 0 && clientSecret === void 0) return void 0;
2304
+ const {
2305
+ PRIM_M2M_CLIENT_ID: clientId,
2306
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2307
+ PRIM_M2M_CLIENT_AUTH: auth
2308
+ } = env;
2309
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2310
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2311
+ throw new MachineAuthError(
2312
+ "incomplete_machine_credentials",
2313
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2314
+ );
2315
+ if (auth !== void 0) {
2316
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2317
+ throw new MachineAuthError(
2318
+ "incomplete_machine_credentials",
2319
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2320
+ );
2321
+ if (clientSecret !== void 0)
2322
+ throw new MachineAuthError(
2323
+ "conflicting_credentials",
2324
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2325
+ );
2326
+ const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2327
+ const credentials = {
2328
+ clientId,
2329
+ generation,
2330
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2331
+ };
2332
+ Object.defineProperty(credentials, "clientSecret", {
2333
+ enumerable: true,
2334
+ get: () => networkSecretBrokerKey(deps, clientId)
2335
+ });
2336
+ return credentials;
2337
+ }
1830
2338
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1831
2339
  throw new MachineAuthError(
1832
2340
  "incomplete_machine_credentials",
@@ -1841,7 +2349,7 @@ function environmentCredentials(deps) {
1841
2349
  }
1842
2350
  function hasMachineConfiguration(deps = {}) {
1843
2351
  const env = deps.env ?? process.env;
1844
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync4(join7(configurationDirectory(deps), PROFILE_FILE));
2352
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join9(configurationDirectory(deps), PROFILE_FILE));
1845
2353
  if (configured && env.PRIM_TOKEN?.trim()) {
1846
2354
  throw new MachineAuthError(
1847
2355
  "conflicting_credentials",
@@ -1875,9 +2383,11 @@ function machineSessionEnded(deps = {}) {
1875
2383
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1876
2384
  if (!generation) return false;
1877
2385
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1878
- return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
2386
+ return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
1879
2387
  }
1880
2388
  var environmentTerminal;
2389
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2390
+ var networkRejection;
1881
2391
  async function loadRecord(profile, deps, signal) {
1882
2392
  const directory = configurationDirectory(deps);
1883
2393
  let value;
@@ -1946,7 +2456,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
1946
2456
  const directory = configurationDirectory(deps);
1947
2457
  ensureDirectory(directory);
1948
2458
  return withFileLock(
1949
- join7(directory, "credentials.lock"),
2459
+ join9(directory, "credentials.lock"),
1950
2460
  async () => {
1951
2461
  const { configuration, tokens, identity } = await withMachineCooldown(
1952
2462
  directory,
@@ -2002,11 +2512,11 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
2002
2512
  profile = { ...profile, storage: "file" };
2003
2513
  await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
2004
2514
  }
2005
- writePrivate(join7(directory, PROFILE_FILE), profile);
2006
- rmSync5(join7(directory, "machine_terminal.json"), { force: true });
2515
+ writePrivate(join9(directory, PROFILE_FILE), profile);
2516
+ rmSync6(join9(directory, "machine_terminal.json"), { force: true });
2007
2517
  cached = { ...profile, ...tokens };
2008
2518
  if (previous) {
2009
- writePrivate(join7(directory, "machine_retired.json"), [...retired, previous]);
2519
+ writePrivate(join9(directory, "machine_retired.json"), [...retired, previous]);
2010
2520
  }
2011
2521
  await cleanupRetired(deps, signal);
2012
2522
  return profile;
@@ -2020,6 +2530,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2020
2530
  const apiUrl = apiUrlFor(deps);
2021
2531
  const environment = environmentCredentials(deps);
2022
2532
  if (environment) {
2533
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
2023
2534
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
2024
2535
  const directory2 = configurationDirectory(deps);
2025
2536
  ensureDirectory(directory2);
@@ -2037,22 +2548,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2037
2548
  writeEnvironmentContext(cached, deps);
2038
2549
  return cached;
2039
2550
  } catch (error) {
2040
- if (error instanceof MachineAuthError && error.terminal)
2551
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
2041
2552
  environmentTerminal = environment.generation;
2042
2553
  throw error;
2043
2554
  }
2044
2555
  }
2045
2556
  return withFileLock(
2046
- join7(directory2, "credentials.lock"),
2557
+ join9(directory2, "credentials.lock"),
2047
2558
  async () => {
2048
2559
  if (machineSessionEnded(deps))
2049
2560
  throw new MachineAuthError(
2050
2561
  "machine_credentials_rejected",
2051
- "Rotate the injected machine credentials.",
2562
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
2052
2563
  true
2053
2564
  );
2054
2565
  if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2055
2566
  return cached;
2567
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2568
+ throw networkRejection.error;
2056
2569
  try {
2057
2570
  const { configuration, tokens, identity } = await withMachineCooldown(
2058
2571
  directory2,
@@ -2061,13 +2574,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2061
2574
  signal,
2062
2575
  async () => {
2063
2576
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2577
+ if (environment.tokenInjection) {
2578
+ const identity3 = await verifyInjectedMachineIdentity(
2579
+ apiUrl,
2580
+ environment.clientId,
2581
+ signal,
2582
+ deps.fetch
2583
+ );
2584
+ const tokens3 = {
2585
+ accessToken: "",
2586
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2587
+ };
2588
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2589
+ }
2064
2590
  const tokens2 = await exchangeMachineCredentials(
2065
2591
  configuration2,
2066
2592
  environment.clientId,
2067
- environment.clientSecret,
2593
+ // The broker key is not a client secret; the proxy supplies that.
2594
+ environment.secretInjection ? "" : environment.clientSecret,
2068
2595
  signal,
2069
- deps.fetch
2070
- );
2596
+ deps.fetch,
2597
+ { secretInjection: environment.secretInjection }
2598
+ ).catch((error) => {
2599
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2600
+ throw new MachineAuthError(
2601
+ "network_secret_mismatch",
2602
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2603
+ true
2604
+ );
2605
+ throw error;
2606
+ });
2071
2607
  const identity2 = await verifyMachineIdentity(
2072
2608
  apiUrl,
2073
2609
  tokens2.accessToken,
@@ -2084,17 +2620,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2084
2620
  ...identity,
2085
2621
  apiUrl,
2086
2622
  generation: environment.generation,
2087
- storage: "environment"
2623
+ storage: "environment",
2624
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
2088
2625
  };
2089
2626
  writeEnvironmentContext(cached, deps);
2090
2627
  return cached;
2091
2628
  } catch (error) {
2629
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2630
+ networkRejection = {
2631
+ generation: environment.generation,
2632
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2633
+ error
2634
+ };
2635
+ if (cached?.generation === environment.generation) cached = void 0;
2636
+ const contextPath = environmentContextPath(deps, environment.clientId);
2637
+ try {
2638
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2639
+ rmSync6(contextPath, { force: true });
2640
+ } catch {
2641
+ }
2642
+ throw error;
2643
+ }
2092
2644
  if (error instanceof MachineAuthError && error.terminal) {
2093
2645
  environmentTerminal = environment.generation;
2094
2646
  const contextPath = environmentContextPath(deps, environment.clientId);
2095
2647
  try {
2096
2648
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2097
- rmSync5(contextPath, { force: true });
2649
+ rmSync6(contextPath, { force: true });
2098
2650
  } catch {
2099
2651
  }
2100
2652
  }
@@ -2108,7 +2660,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2108
2660
  const expected = machineContext(deps);
2109
2661
  const directory = configurationDirectory(deps);
2110
2662
  return withFileLock(
2111
- join7(directory, "credentials.lock"),
2663
+ join9(directory, "credentials.lock"),
2112
2664
  async () => {
2113
2665
  const profile = readMachineProfile(deps);
2114
2666
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -2158,7 +2710,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2158
2710
  await persistRecord(record, deps, signal);
2159
2711
  } catch (error) {
2160
2712
  if (error instanceof MachineAuthError && error.terminal)
2161
- writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
2713
+ writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
2162
2714
  throw error;
2163
2715
  }
2164
2716
  }
@@ -2169,14 +2721,43 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2169
2721
  { signal }
2170
2722
  );
2171
2723
  }
2724
+ async function forwardMachineRequest(request2, signal, deps = {}) {
2725
+ const environment = environmentCredentials(deps);
2726
+ if (!environment?.tokenInjection)
2727
+ throw new MachineAuthError(
2728
+ "identity_changed",
2729
+ "Machine identity changed; restart the operation."
2730
+ );
2731
+ const directory = configurationDirectory(deps);
2732
+ ensureDirectory(directory);
2733
+ return forwardBrokerRequest({
2734
+ directory,
2735
+ apiUrl: apiUrlFor(deps),
2736
+ environment,
2737
+ env: deps.env ?? process.env,
2738
+ request: request2,
2739
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2740
+ });
2741
+ }
2742
+ async function verifyAcquiredMachineIdentity(machine, deps = {}) {
2743
+ if (!machine.tokenInjection)
2744
+ return verifyMachineIdentity(machine.apiUrl, machine.accessToken, machine.clientId);
2745
+ const response = await forwardMachineRequest(
2746
+ { method: "GET", path: "/api/cli/auth/status" },
2747
+ AbortSignal.timeout(1e4),
2748
+ deps
2749
+ );
2750
+ const value = response.ok ? await response.json().catch(() => void 0) : void 0;
2751
+ return parseInjectedMachineIdentity(response.status, value, machine.apiUrl, machine.clientId);
2752
+ }
2172
2753
  async function clearMachineCredentials(deps = {}) {
2173
2754
  const directory = configurationDirectory(deps);
2174
- if (!existsSync4(join7(directory, PROFILE_FILE))) return false;
2175
- return withFileLock(join7(directory, "credentials.lock"), async () => {
2755
+ if (!existsSync5(join9(directory, PROFILE_FILE))) return false;
2756
+ return withFileLock(join9(directory, "credentials.lock"), async () => {
2176
2757
  const profile = readMachineProfile(deps);
2177
2758
  if (!profile) return false;
2178
2759
  await cleanupRetired(deps, AbortSignal.timeout(1e4));
2179
- if (existsSync4(join7(directory, "machine_retired.json")))
2760
+ if (existsSync5(join9(directory, "machine_retired.json")))
2180
2761
  throw new MachineAuthError(
2181
2762
  "storage_unavailable",
2182
2763
  "Unlock the credential store to remove retired machine credentials."
@@ -2192,9 +2773,9 @@ async function clearMachineCredentials(deps = {}) {
2192
2773
  "Unlock the keychain to remove the saved machine credential."
2193
2774
  );
2194
2775
  }
2195
- } else rmSync5(recordPath(directory, profile.generation), { force: true });
2196
- rmSync5(join7(directory, PROFILE_FILE), { force: true });
2197
- rmSync5(join7(directory, "machine_terminal.json"), { force: true });
2776
+ } else rmSync6(recordPath(directory, profile.generation), { force: true });
2777
+ rmSync6(join9(directory, PROFILE_FILE), { force: true });
2778
+ rmSync6(join9(directory, "machine_terminal.json"), { force: true });
2198
2779
  cached = void 0;
2199
2780
  return true;
2200
2781
  });
@@ -2218,8 +2799,14 @@ function machineCaptureActor(deps = {}) {
2218
2799
  function machineJournalBucket(identity) {
2219
2800
  return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2220
2801
  }
2802
+ function identityPending(actor) {
2803
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
2804
+ }
2805
+ function machinePendingBucket(identity) {
2806
+ return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
2807
+ }
2221
2808
  function readRetiredProfiles(directory) {
2222
- const value = readPrivate(join7(directory, "machine_retired.json"));
2809
+ const value = readPrivate(join9(directory, "machine_retired.json"));
2223
2810
  if (value === void 0) return [];
2224
2811
  if (!Array.isArray(value))
2225
2812
  throw new MachineAuthError(
@@ -2230,20 +2817,20 @@ function readRetiredProfiles(directory) {
2230
2817
  }
2231
2818
  async function cleanupRetired(deps, signal) {
2232
2819
  const directory = configurationDirectory(deps);
2233
- const path = join7(directory, "machine_retired.json");
2820
+ const path = join9(directory, "machine_retired.json");
2234
2821
  const pending = [];
2235
2822
  for (const profile of readRetiredProfiles(directory)) {
2236
2823
  try {
2237
2824
  if (profile.storage === "keychain") {
2238
2825
  const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
2239
2826
  if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
2240
- } else rmSync5(recordPath(directory, profile.generation), { force: true });
2827
+ } else rmSync6(recordPath(directory, profile.generation), { force: true });
2241
2828
  } catch {
2242
2829
  pending.push(profile);
2243
2830
  }
2244
2831
  }
2245
2832
  if (pending.length) writePrivate(path, pending);
2246
- else rmSync5(path, { force: true });
2833
+ else rmSync6(path, { force: true });
2247
2834
  }
2248
2835
  function prepareMachineMetadataDirectory(directory) {
2249
2836
  ensureDirectory(directory);
@@ -2254,23 +2841,23 @@ function writeMachineMetadata(path, value) {
2254
2841
 
2255
2842
  // src/lib/credentials.ts
2256
2843
  import { createHash as createHash5 } from "crypto";
2257
- import { readFileSync as readFileSync7 } from "fs";
2258
- import { join as join8 } from "path";
2844
+ import { readFileSync as readFileSync9 } from "fs";
2845
+ import { join as join10 } from "path";
2259
2846
  var CONFIG_DIRECTORY = primConfigDirectory();
2260
- var TOKEN_FILE_PATH = join8(CONFIG_DIRECTORY, "token");
2261
- var REFRESH_TOKEN_PATH = join8(CONFIG_DIRECTORY, "refresh_token");
2262
- var TOKEN_EXPIRES_PATH = join8(CONFIG_DIRECTORY, "token_expires_at");
2263
- var TERMINAL_REFRESH_PATH = join8(CONFIG_DIRECTORY, "refresh_terminal");
2264
- var CREDENTIAL_METADATA_PATH = join8(CONFIG_DIRECTORY, "credential_metadata.json");
2265
- var CREDENTIAL_FAMILY_PATH = join8(CONFIG_DIRECTORY, "credential_family.json");
2266
- var CREDENTIAL_MIGRATION_PATH = join8(CONFIG_DIRECTORY, "credential_migration.json");
2267
- var CREDENTIAL_LOCK_PATH = join8(CONFIG_DIRECTORY, "credentials.lock");
2847
+ var TOKEN_FILE_PATH = join10(CONFIG_DIRECTORY, "token");
2848
+ var REFRESH_TOKEN_PATH = join10(CONFIG_DIRECTORY, "refresh_token");
2849
+ var TOKEN_EXPIRES_PATH = join10(CONFIG_DIRECTORY, "token_expires_at");
2850
+ var TERMINAL_REFRESH_PATH = join10(CONFIG_DIRECTORY, "refresh_terminal");
2851
+ var CREDENTIAL_METADATA_PATH = join10(CONFIG_DIRECTORY, "credential_metadata.json");
2852
+ var CREDENTIAL_FAMILY_PATH = join10(CONFIG_DIRECTORY, "credential_family.json");
2853
+ var CREDENTIAL_MIGRATION_PATH = join10(CONFIG_DIRECTORY, "credential_migration.json");
2854
+ var CREDENTIAL_LOCK_PATH = join10(CONFIG_DIRECTORY, "credentials.lock");
2268
2855
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
2269
2856
  var CREDENTIAL_MIGRATION_VERSION = 1;
2270
2857
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
2271
2858
  function readTrimmed(path) {
2272
2859
  try {
2273
- const value = readFileSync7(path, "utf8").trim();
2860
+ const value = readFileSync9(path, "utf8").trim();
2274
2861
  return value || void 0;
2275
2862
  } catch {
2276
2863
  return void 0;
@@ -2279,7 +2866,7 @@ function readTrimmed(path) {
2279
2866
  function resolveAuthCredential(options = {}) {
2280
2867
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
2281
2868
  const machine = cachedMachineCredential({ env: options.env });
2282
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
2869
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
2283
2870
  }
2284
2871
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
2285
2872
  if (envToken) return { token: envToken, source: "environment" };
@@ -2306,6 +2893,17 @@ function resolveAuthCredential(options = {}) {
2306
2893
  }
2307
2894
  return { token: stored, source: "token_file" };
2308
2895
  }
2896
+ function resolveStoredCredential(env = process.env) {
2897
+ const directory = primConfigDirectory({ env });
2898
+ return resolveAuthCredential({
2899
+ env,
2900
+ tokenFilePath: join10(directory, "token"),
2901
+ refreshTokenPath: join10(directory, "refresh_token"),
2902
+ metadataPath: join10(directory, "credential_metadata.json"),
2903
+ familyPath: join10(directory, "credential_family.json"),
2904
+ migrationPath: join10(directory, "credential_migration.json")
2905
+ });
2906
+ }
2309
2907
  function credentialFingerprint(value) {
2310
2908
  return createHash5("sha256").update(value).digest("hex");
2311
2909
  }
@@ -2327,7 +2925,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
2327
2925
  function readBoundedCredentialJson(path) {
2328
2926
  let raw;
2329
2927
  try {
2330
- raw = readFileSync7(path, "utf8");
2928
+ raw = readFileSync9(path, "utf8");
2331
2929
  } catch (error) {
2332
2930
  return error.code === "ENOENT" ? void 0 : null;
2333
2931
  }
@@ -2421,10 +3019,18 @@ export {
2421
3019
  pinnedHookCommand,
2422
3020
  PRIM_CONFIG_SHELL_RESOLVER,
2423
3021
  stableHookCommand,
3022
+ quietWithoutLauncher,
2424
3023
  detachedHookShimCommand,
2425
3024
  commandMatchesBin,
2426
3025
  hookCommandResolution,
2427
3026
  hookCommandResolutions,
3027
+ isClaudeCloudSession,
3028
+ insideClaudeCode,
3029
+ CLOUD_CREDENTIALS_REMEDY,
3030
+ CLOUD_REJECTED_CREDENTIALS_REMEDY,
3031
+ CLOUD_GITHUB_CONNECT_REMEDY,
3032
+ cloudSetupPointer,
3033
+ CLOUD_SETUP_POINTER,
2428
3034
  WORKOS_CONNECT_RESPONSE_MAX_BYTES,
2429
3035
  WorkosConnectProtocolError,
2430
3036
  readBoundedJson,
@@ -2437,11 +3043,16 @@ export {
2437
3043
  machineString,
2438
3044
  machineRecord,
2439
3045
  machineApiUrl,
3046
+ rejectedCredentialsMessage,
2440
3047
  discoverMachineConfiguration,
3048
+ exchangeMachineCredentials,
2441
3049
  parseMachineIdentity,
2442
3050
  verifyMachineIdentity,
2443
3051
  primConfigDirectory,
3052
+ clearMachineCooldowns,
3053
+ SERVER_WAIT_PREFIX,
2444
3054
  readMachineProfile,
3055
+ NETWORK_TOKEN_AUTH,
2445
3056
  environmentCredentials,
2446
3057
  hasMachineConfiguration,
2447
3058
  machineContext,
@@ -2449,9 +3060,13 @@ export {
2449
3060
  machineSessionEnded,
2450
3061
  configureMachine,
2451
3062
  acquireMachineCredential,
3063
+ forwardMachineRequest,
3064
+ verifyAcquiredMachineIdentity,
2452
3065
  clearMachineCredentials,
2453
3066
  machineCaptureActor,
2454
3067
  machineJournalBucket,
3068
+ identityPending,
3069
+ machinePendingBucket,
2455
3070
  prepareMachineMetadataDirectory,
2456
3071
  writeMachineMetadata,
2457
3072
  TOKEN_FILE_PATH,
@@ -2465,11 +3080,16 @@ export {
2465
3080
  CREDENTIAL_MIGRATION_VERSION,
2466
3081
  CREDENTIAL_MIGRATION_STATE,
2467
3082
  resolveAuthCredential,
3083
+ resolveStoredCredential,
2468
3084
  readCredentialMigrationState,
2469
3085
  readStoredCredentialMetadata,
2470
3086
  decodeJwtPayload,
2471
3087
  jwtExpiresAt,
2472
3088
  jwtOrganizationId,
3089
+ markCloudPrepared,
3090
+ preparedInSession,
3091
+ clearCloudPrepared,
3092
+ isPreparedCloudSession,
2473
3093
  readDemoPause,
2474
3094
  pauseCaptureForDemo,
2475
3095
  extendDemoPause,
@@ -2479,11 +3099,16 @@ export {
2479
3099
  gitToplevel,
2480
3100
  mainWorktreeRoot,
2481
3101
  currentBranch,
3102
+ parseGithubRepositoryName,
3103
+ originIdentifiesRepository,
3104
+ originGithubRepository,
3105
+ isGitIgnored,
2482
3106
  githubRepositoryFullName,
2483
3107
  canonicalGitRoot,
2484
3108
  relatedWorktreeTarget,
2485
3109
  resolveRepositoryContext,
2486
3110
  canonicalRepositoryPath,
3111
+ PRIM_ACTIVE_DECLARATION,
2487
3112
  repoActiveFlag,
2488
3113
  setRepoActive,
2489
3114
  isValidRepoSyncId,
@@ -2493,6 +3118,12 @@ export {
2493
3118
  setRepoSyncId,
2494
3119
  setRepositoryBindingState,
2495
3120
  repositoryBindingState,
3121
+ hasProjectPrimInstall,
3122
+ declaresInactive,
3123
+ markActivationImplicit,
3124
+ markActivationExplicit,
3125
+ explicitlyActive,
3126
+ withdrawImplicitActivation,
2496
3127
  isRepoActiveForCapture,
2497
3128
  decisionIngestionStatus
2498
3129
  };