@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
@@ -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,21 +194,45 @@ 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_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
207
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
208
+ function cloudSetupPointer(message, env = process.env) {
209
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
210
+ }
211
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
212
+
189
213
  // src/lib/git.ts
190
214
  import { execFileSync } from "child_process";
191
215
  import { createHash } from "crypto";
192
- import { lstatSync, realpathSync } from "fs";
193
- import { basename, dirname as dirname2, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
216
+ import { lstatSync, readFileSync as readFileSync2, realpathSync } from "fs";
217
+ import { basename, dirname as dirname2, isAbsolute as isAbsolute2, join as join2, relative, resolve, sep } from "path";
194
218
  var GIT_TIMEOUT_MS = 1e3;
219
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
195
220
  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;
221
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
222
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
223
+ function gitChildEnvironment(env = process.env) {
224
+ return Object.fromEntries(
225
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
226
+ );
227
+ }
197
228
  function gitToplevel(cwd) {
198
229
  try {
199
230
  return execFileSync("git", ["rev-parse", "--show-toplevel"], {
200
231
  cwd,
201
232
  encoding: "utf-8",
202
233
  stdio: ["ignore", "pipe", "ignore"],
203
- timeout: GIT_TIMEOUT_MS
234
+ timeout: GIT_TIMEOUT_MS,
235
+ env: gitChildEnvironment()
204
236
  }).trim();
205
237
  } catch {
206
238
  return null;
@@ -215,7 +247,8 @@ function mainWorktreeRoot(cwd) {
215
247
  cwd,
216
248
  encoding: "utf-8",
217
249
  stdio: ["ignore", "pipe", "ignore"],
218
- timeout: GIT_TIMEOUT_MS
250
+ timeout: GIT_TIMEOUT_MS,
251
+ env: gitChildEnvironment()
219
252
  }
220
253
  ).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
221
254
  if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
@@ -230,7 +263,8 @@ function gitValue(cwd, args) {
230
263
  cwd,
231
264
  encoding: "utf-8",
232
265
  stdio: ["ignore", "pipe", "ignore"],
233
- timeout: GIT_TIMEOUT_MS
266
+ timeout: GIT_TIMEOUT_MS,
267
+ env: gitChildEnvironment()
234
268
  }).trim();
235
269
  return value || void 0;
236
270
  } catch {
@@ -240,19 +274,78 @@ function gitValue(cwd, args) {
240
274
  function currentBranch(cwd) {
241
275
  return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
242
276
  }
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;
277
+ function parseGithubRepositoryName(path) {
278
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
279
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
280
+ return null;
281
+ }
282
+ return `${parts[0]}/${parts[1]}`;
283
+ }
284
+ function githubRepositoryFromRemote(remote) {
285
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
246
286
  const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
247
287
  remote
248
288
  );
249
289
  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] ?? "")) {
290
+ return path ? parseGithubRepositoryName(path) : null;
291
+ }
292
+ function originIdentifiesRepository(cwd) {
293
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
294
+ return remote !== void 0 && Boolean(githubRepositoryFromRemote(remote) || normalizeOriginRemote(remote));
295
+ }
296
+ function originGithubRepository(cwd) {
297
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
298
+ return remote ? githubRepositoryFromRemote(remote) : null;
299
+ }
300
+ function isGitIgnored(cwd, path) {
301
+ try {
302
+ execFileSync("git", ["check-ignore", "--quiet", "--", path], {
303
+ cwd,
304
+ stdio: ["ignore", "ignore", "ignore"],
305
+ timeout: GIT_TIMEOUT_MS,
306
+ env: gitChildEnvironment()
307
+ });
308
+ return true;
309
+ } catch {
310
+ return false;
311
+ }
312
+ }
313
+ function checkoutSettingsText(repoRoot) {
314
+ const path = join2(repoRoot, ".claude", "settings.json");
315
+ try {
316
+ if (!lstatSync(join2(repoRoot, ".claude")).isDirectory()) return null;
317
+ const stat = lstatSync(path);
318
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
319
+ return readFileSync2(path, "utf8");
320
+ } catch {
253
321
  return null;
254
322
  }
255
- return `${parts[0]}/${parts[1]}`;
323
+ }
324
+ function checkoutDeclaration(repoRoot, name) {
325
+ const text = checkoutSettingsText(repoRoot);
326
+ if (text === null) return null;
327
+ let parsed;
328
+ try {
329
+ parsed = JSON.parse(text);
330
+ } catch {
331
+ return null;
332
+ }
333
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
334
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
335
+ return typeof value === "string" ? value : null;
336
+ }
337
+ function declaredGithubRepository(repoRoot) {
338
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
339
+ return value === null ? null : parseGithubRepositoryName(value.trim());
340
+ }
341
+ function githubRepositoryFullName(cwd) {
342
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
343
+ if (remote) {
344
+ const fromOrigin = githubRepositoryFromRemote(remote);
345
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
346
+ }
347
+ const root = gitToplevel(cwd);
348
+ return root ? declaredGithubRepository(root) : null;
256
349
  }
257
350
  function canonicalGitRoot(cwd) {
258
351
  try {
@@ -331,6 +424,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
331
424
  repoFullName
332
425
  };
333
426
  }
427
+ if (repoFullName) {
428
+ return {
429
+ repoRoot,
430
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
431
+ identitySource: "declared",
432
+ repoFullName
433
+ };
434
+ }
334
435
  const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
335
436
  if (roots && roots.length > 0) {
336
437
  return {
@@ -419,9 +520,77 @@ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
419
520
 
420
521
  // src/lib/activation.ts
421
522
  import { execFileSync as execFileSync3 } from "child_process";
422
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
523
+ import { existsSync as existsSync3, readFileSync as readFileSync4 } from "fs";
524
+ import { homedir as homedir2 } from "os";
525
+ import { join as join5 } from "path";
526
+
527
+ // src/lib/cloud-prepared.ts
528
+ import { existsSync as existsSync2, mkdirSync, readFileSync as readFileSync3, rmSync, writeFileSync } from "fs";
529
+ import { join as join4 } from "path";
530
+
531
+ // src/lib/paths.ts
423
532
  import { homedir } from "os";
424
- import { join as join2 } from "path";
533
+ import { isAbsolute as isAbsolute3, join as join3, normalize } from "path";
534
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
535
+ function absolutePath(value, variable) {
536
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
537
+ throw new Error(`${variable} contains unsafe characters`);
538
+ }
539
+ if (!value || value.trim() !== value || !isAbsolute3(value)) return;
540
+ const normalized = normalize(value);
541
+ return normalized === value ? value : void 0;
542
+ }
543
+ function resolvePrimConfigDirectory(options = {}) {
544
+ const env = options.env ?? process.env;
545
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
546
+ if (explicit) return { path: explicit, source: "explicit" };
547
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
548
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
549
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
550
+ if (!home) {
551
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
552
+ }
553
+ return { path: join3(home, ".config", "prim"), source: "default" };
554
+ }
555
+ function primConfigDirectory(options = {}) {
556
+ return resolvePrimConfigDirectory(options).path;
557
+ }
558
+
559
+ // src/lib/cloud-prepared.ts
560
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
561
+ var CLOUD_PREPARED_VERSION = "1";
562
+ var SESSION_ORIGIN = "session";
563
+ function cloudPreparedPath(env = process.env) {
564
+ return join4(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
565
+ }
566
+ function markCloudPrepared(env = process.env, origin = "image") {
567
+ const directory = primConfigDirectory({ env });
568
+ mkdirSync(directory, { recursive: true, mode: 448 });
569
+ writeFileSync(
570
+ cloudPreparedPath(env),
571
+ `${CLOUD_PREPARED_VERSION}${origin === "session" ? ` ${SESSION_ORIGIN}` : ""}
572
+ `,
573
+ { mode: 384 }
574
+ );
575
+ }
576
+ function preparedInSession(env = process.env) {
577
+ try {
578
+ return readFileSync3(cloudPreparedPath(env), "utf8").trim().split(/\s+/u)[1] === SESSION_ORIGIN;
579
+ } catch {
580
+ return false;
581
+ }
582
+ }
583
+ function clearCloudPrepared(env = process.env) {
584
+ rmSync(cloudPreparedPath(env), { force: true });
585
+ }
586
+ function isPreparedCloudSession(env = process.env) {
587
+ if (!isClaudeCloudSession(env)) return false;
588
+ try {
589
+ return existsSync2(cloudPreparedPath(env));
590
+ } catch {
591
+ return false;
592
+ }
593
+ }
425
594
 
426
595
  // src/lib/demo-pause.ts
427
596
  import { execFileSync as execFileSync2 } from "child_process";
@@ -515,6 +684,8 @@ function healDemoPause(cwd, pause, options = {}) {
515
684
 
516
685
  // src/lib/activation.ts
517
686
  var PRIM_ACTIVE_KEY = "prim.active";
687
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
688
+ var PRIM_ACTIVE_IMPLICIT_KEY = "prim.activeImplicit";
518
689
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
519
690
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
520
691
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
@@ -610,14 +781,30 @@ function repositoryBindingState(cwd) {
610
781
  if (marker !== void 0) return "invalid";
611
782
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
612
783
  }
784
+ function unsetLocalGitConfigValue(cwd, key) {
785
+ try {
786
+ execFileSync3("git", ["config", "--local", "--unset-all", key], {
787
+ cwd,
788
+ stdio: ["ignore", "ignore", "pipe"],
789
+ timeout: GIT_TIMEOUT_MS3
790
+ });
791
+ } catch (error) {
792
+ if (typeof error === "object" && error !== null && "status" in error && error.status === 5) {
793
+ return;
794
+ }
795
+ throw error;
796
+ }
797
+ }
613
798
  function hasProjectPrimInstall(cwd) {
614
- const root = gitToplevel(cwd);
615
- if (root === null || root === homedir()) return false;
799
+ return projectPrimInstallAt(gitToplevel(cwd));
800
+ }
801
+ function projectPrimInstallAt(root) {
802
+ if (root === null || root === homedir2()) return false;
616
803
  for (const rel of PROJECT_INSTALL_FILES) {
617
- const path = join2(root, rel);
618
- if (existsSync2(path)) {
804
+ const path = join5(root, rel);
805
+ if (existsSync3(path)) {
619
806
  try {
620
- const content = readFileSync2(path, "utf-8");
807
+ const content = readFileSync4(path, "utf-8");
621
808
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
622
809
  } catch {
623
810
  }
@@ -625,12 +812,56 @@ function hasProjectPrimInstall(cwd) {
625
812
  }
626
813
  return false;
627
814
  }
815
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
816
+ function declaresInactive(cwd) {
817
+ return declaresInactiveAt(gitToplevel(cwd));
818
+ }
819
+ function declaresInactiveAt(root) {
820
+ if (root === null || root === homedir2()) return false;
821
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
822
+ const text = checkoutSettingsText(root);
823
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
824
+ try {
825
+ JSON.parse(text);
826
+ return false;
827
+ } catch {
828
+ return true;
829
+ }
830
+ }
831
+ function markActivationImplicit(cwd) {
832
+ try {
833
+ setLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY, "true");
834
+ } catch {
835
+ }
836
+ }
837
+ function markActivationExplicit(cwd) {
838
+ unsetLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY);
839
+ }
840
+ function explicitlyActive(cwd) {
841
+ return repoActiveFlag(cwd) === "true" && !(localGitConfigValue(cwd, PRIM_ACTIVE_KEY) === "true" && localGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY) === "true");
842
+ }
843
+ function withdrawImplicitActivation(cwd) {
844
+ try {
845
+ const root = gitToplevel(cwd);
846
+ if (root === null) return false;
847
+ if (localGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY) !== "true") return false;
848
+ if (localGitConfigValue(root, PRIM_ACTIVE_KEY) !== "true" || !declaresInactiveAt(root))
849
+ return false;
850
+ unsetLocalGitConfigValue(root, PRIM_ACTIVE_KEY);
851
+ unsetLocalGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY);
852
+ return true;
853
+ } catch {
854
+ return false;
855
+ }
856
+ }
628
857
  function isRepoActiveForCapture(cwd, options = {}) {
629
858
  let { active: flag, pause } = readCaptureConfig(cwd);
630
859
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
631
860
  if (flag === "true") return true;
632
861
  if (flag === "false") return false;
633
- return hasProjectPrimInstall(cwd);
862
+ const root = gitToplevel(cwd);
863
+ if (declaresInactiveAt(root)) return false;
864
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
634
865
  }
635
866
  function decisionIngestionStatus(cwd) {
636
867
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -643,11 +874,11 @@ import {
643
874
  closeSync,
644
875
  fchmodSync,
645
876
  fsyncSync,
646
- mkdirSync,
877
+ mkdirSync as mkdirSync2,
647
878
  openSync,
648
879
  renameSync,
649
- rmSync,
650
- writeFileSync
880
+ rmSync as rmSync2,
881
+ writeFileSync as writeFileSync2
651
882
  } from "fs";
652
883
  import { dirname as dirname3 } from "path";
653
884
  var DEFAULT_FILE_MODE = 438;
@@ -686,7 +917,7 @@ function syncCreatedParentChain(firstCreatedParent, parent) {
686
917
  }
687
918
  }
688
919
  function ensureDurableDirectory(path, mode) {
689
- const firstCreatedParent = mkdirSync(path, { recursive: true, mode });
920
+ const firstCreatedParent = mkdirSync2(path, { recursive: true, mode });
690
921
  if (firstCreatedParent) {
691
922
  syncCreatedParentChain(firstCreatedParent, path);
692
923
  }
@@ -704,7 +935,7 @@ function atomicWriteFile(target, content, options = {}) {
704
935
  temporaryCreated = true;
705
936
  try {
706
937
  if (options.mode !== void 0) fchmodSync(fd, options.mode);
707
- writeFileSync(fd, content);
938
+ writeFileSync2(fd, content);
708
939
  fsyncSync(fd);
709
940
  } finally {
710
941
  closeSync(fd);
@@ -715,7 +946,7 @@ function atomicWriteFile(target, content, options = {}) {
715
946
  } catch (error) {
716
947
  if (temporaryCreated) {
717
948
  try {
718
- rmSync(temporaryPath, { force: true });
949
+ rmSync2(temporaryPath, { force: true });
719
950
  } catch {
720
951
  }
721
952
  }
@@ -736,19 +967,19 @@ function processIsAlive(pid, probe = process.kill) {
736
967
 
737
968
  // src/lib/file-lock.ts
738
969
  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";
970
+ import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync3, statSync, writeFileSync as writeFileSync3 } from "fs";
971
+ import { dirname as dirname4, join as join6 } from "path";
741
972
  var DEFAULT_TIMEOUT_MS = 3e4;
742
973
  var DEFAULT_POLL_MS = 50;
743
974
  var DEFAULT_INIT_GRACE_MS = 2e3;
744
975
  var DIRECTORY_MODE = 448;
745
976
  var FILE_MODE = 384;
746
977
  function ownerPath(lockDir) {
747
- return join3(lockDir, "owner.json");
978
+ return join6(lockDir, "owner.json");
748
979
  }
749
980
  function readOwner(lockDir) {
750
981
  try {
751
- const owner = JSON.parse(readFileSync3(ownerPath(lockDir), "utf8"));
982
+ const owner = JSON.parse(readFileSync5(ownerPath(lockDir), "utf8"));
752
983
  if (!Number.isInteger(owner.pid) || owner.pid <= 0 || typeof owner.nonce !== "string" || typeof owner.createdAt !== "number") {
753
984
  return null;
754
985
  }
@@ -762,7 +993,7 @@ function sameOwner(a, b) {
762
993
  }
763
994
  function tryTakeLock(lockDir, now) {
764
995
  try {
765
- mkdirSync2(lockDir, { mode: DIRECTORY_MODE });
996
+ mkdirSync3(lockDir, { mode: DIRECTORY_MODE });
766
997
  } catch (error) {
767
998
  if (error.code === "EEXIST") return null;
768
999
  throw error;
@@ -773,7 +1004,7 @@ function tryTakeLock(lockDir, now) {
773
1004
  createdAt: now
774
1005
  };
775
1006
  try {
776
- writeFileSync2(ownerPath(lockDir), `${JSON.stringify(owner)}
1007
+ writeFileSync3(ownerPath(lockDir), `${JSON.stringify(owner)}
777
1008
  `, {
778
1009
  encoding: "utf8",
779
1010
  mode: FILE_MODE,
@@ -781,7 +1012,7 @@ function tryTakeLock(lockDir, now) {
781
1012
  });
782
1013
  return owner;
783
1014
  } catch (error) {
784
- rmSync2(lockDir, { recursive: true, force: true });
1015
+ rmSync3(lockDir, { recursive: true, force: true });
785
1016
  throw error;
786
1017
  }
787
1018
  }
@@ -790,7 +1021,7 @@ function recoverStaleLock(lockDir, now, alive, initGraceMs) {
790
1021
  if (owner) {
791
1022
  if (alive(owner.pid)) return false;
792
1023
  if (!sameOwner(readOwner(lockDir), owner)) return false;
793
- rmSync2(lockDir, { recursive: true, force: true });
1024
+ rmSync3(lockDir, { recursive: true, force: true });
794
1025
  return true;
795
1026
  }
796
1027
  try {
@@ -798,7 +1029,7 @@ function recoverStaleLock(lockDir, now, alive, initGraceMs) {
798
1029
  if (now - before < initGraceMs) return false;
799
1030
  if (readOwner(lockDir)) return false;
800
1031
  if (statSync(lockDir).mtimeMs !== before) return false;
801
- rmSync2(lockDir, { recursive: true, force: true });
1032
+ rmSync3(lockDir, { recursive: true, force: true });
802
1033
  return true;
803
1034
  } catch {
804
1035
  return true;
@@ -836,7 +1067,7 @@ function defaultSleepSync(ms) {
836
1067
  Atomics.wait(syncSleeper, 0, 0, ms);
837
1068
  }
838
1069
  function withFileLockSync(lockDir, operation, options = {}) {
839
- mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1070
+ mkdirSync3(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
840
1071
  const nowMs = options.nowMs ?? Date.now;
841
1072
  const alive = options.processAlive ?? processIsAlive;
842
1073
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -855,12 +1086,12 @@ function withFileLockSync(lockDir, operation, options = {}) {
855
1086
  return operation();
856
1087
  } finally {
857
1088
  if (sameOwner(readOwner(lockDir), owner)) {
858
- rmSync2(lockDir, { recursive: true, force: true });
1089
+ rmSync3(lockDir, { recursive: true, force: true });
859
1090
  }
860
1091
  }
861
1092
  }
862
1093
  async function withFileLock(lockDir, operation, options = {}) {
863
- mkdirSync2(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
1094
+ mkdirSync3(dirname4(lockDir), { recursive: true, mode: DIRECTORY_MODE });
864
1095
  const nowMs = options.nowMs ?? Date.now;
865
1096
  const alive = options.processAlive ?? processIsAlive;
866
1097
  const deadline = nowMs() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
@@ -886,7 +1117,7 @@ async function withFileLock(lockDir, operation, options = {}) {
886
1117
  return await operation();
887
1118
  } finally {
888
1119
  if (sameOwner(readOwner(lockDir), owner)) {
889
- rmSync2(lockDir, { recursive: true, force: true });
1120
+ rmSync3(lockDir, { recursive: true, force: true });
890
1121
  }
891
1122
  }
892
1123
  }
@@ -1119,10 +1350,10 @@ function parseWorkosConnectTokens(value, options = {}) {
1119
1350
  "access_token",
1120
1351
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
1121
1352
  );
1122
- const refreshToken = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
1353
+ const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
1123
1354
  return {
1124
1355
  accessToken,
1125
- refreshToken,
1356
+ refreshToken: refreshToken2,
1126
1357
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
1127
1358
  };
1128
1359
  }
@@ -1242,9 +1473,19 @@ function parseMachineConfiguration(value) {
1242
1473
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
1243
1474
  };
1244
1475
  }
1476
+ function rejectedCredentialsMessage(message, env = process.env) {
1477
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
1478
+ }
1245
1479
  function machineSignal(signal) {
1246
1480
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1247
1481
  }
1482
+ function hostOf(url) {
1483
+ try {
1484
+ return new URL(url).hostname;
1485
+ } catch {
1486
+ return "Primitive";
1487
+ }
1488
+ }
1248
1489
  async function fetchMachine(url, options, fetchImpl) {
1249
1490
  try {
1250
1491
  return await fetchImpl(url, options);
@@ -1252,7 +1493,9 @@ async function fetchMachine(url, options, fetchImpl) {
1252
1493
  options.signal?.throwIfAborted();
1253
1494
  throw new MachineAuthError(
1254
1495
  "authentication_unavailable",
1255
- "Machine authentication is temporarily unavailable. Check the connection and retry."
1496
+ // A cloud VM reaches only the hosts its environment allows, and both of
1497
+ // Primitive's are blocked by default: name the one that failed.
1498
+ 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
1499
  );
1257
1500
  }
1258
1501
  }
@@ -1279,8 +1522,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
1279
1522
  );
1280
1523
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
1281
1524
  }
1282
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
1283
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1525
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
1526
+ const network = options.secretInjection === "network";
1527
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
1284
1528
  throw new MachineAuthError(
1285
1529
  "invalid_credentials",
1286
1530
  "A machine client ID and secret are required.",
@@ -1294,11 +1538,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1294
1538
  redirect: "error",
1295
1539
  signal: machineSignal(signal),
1296
1540
  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
- })
1541
+ // With a network secret the agent proxy authenticates the client with
1542
+ // HTTP Basic (client_secret_basic); the body carries no credential.
1543
+ body: new URLSearchParams(
1544
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
1545
+ )
1302
1546
  },
1303
1547
  fetchImpl
1304
1548
  );
@@ -1306,7 +1550,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1306
1550
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
1307
1551
  throw new MachineAuthError(
1308
1552
  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.",
1553
+ 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(
1554
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
1555
+ ) : "The machine token service is temporarily unavailable.",
1310
1556
  terminal,
1311
1557
  terminal ? void 0 : machineRetryAt(response)
1312
1558
  );
@@ -1326,6 +1572,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
1326
1572
  } catch {
1327
1573
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
1328
1574
  }
1575
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
1576
+ throw new MachineAuthError(
1577
+ "token_client_mismatch",
1578
+ "The token service issued a token for another machine client."
1579
+ );
1329
1580
  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
1581
  throw new MachineAuthError(
1331
1582
  "token_identity_mismatch",
@@ -1371,74 +1622,183 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
1371
1622
  const terminal = response.status === 401 || response.status === 403;
1372
1623
  throw new MachineAuthError(
1373
1624
  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.",
1625
+ terminal ? rejectedCredentialsMessage(
1626
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
1627
+ ) : "Machine verification is temporarily unavailable.",
1375
1628
  terminal
1376
1629
  );
1377
1630
  }
1378
1631
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
1379
1632
  }
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");
1633
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
1634
+ const rejected = () => new MachineAuthError(
1635
+ "network_token_rejected",
1636
+ `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.`,
1637
+ true
1638
+ );
1639
+ if (status === 401 || status === 403) throw rejected();
1640
+ if (status < 200 || status > 299)
1641
+ throw new MachineAuthError(
1642
+ "verification_unavailable",
1643
+ "Machine verification is temporarily unavailable."
1644
+ );
1645
+ let data;
1646
+ try {
1647
+ data = machineRecord(value);
1648
+ } catch {
1649
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
1402
1650
  }
1403
- return { path: join4(home, ".config", "prim"), source: "default" };
1651
+ if (data.authenticated !== true) throw rejected();
1652
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
1653
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
1654
+ throw new MachineAuthError(
1655
+ "network_secret_mismatch",
1656
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
1657
+ true
1658
+ );
1659
+ return parseMachineIdentity(data, clientId);
1404
1660
  }
1405
- function primConfigDirectory(options = {}) {
1406
- return resolvePrimConfigDirectory(options).path;
1661
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
1662
+ const response = await fetchMachine(
1663
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
1664
+ { redirect: "error", signal: machineSignal(signal) },
1665
+ fetchImpl
1666
+ );
1667
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
1668
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
1407
1669
  }
1408
1670
 
1671
+ // src/lib/terminal-safe.ts
1672
+ function replaceIsolatedSurrogates(value) {
1673
+ let out = "";
1674
+ for (let index = 0; index < value.length; index += 1) {
1675
+ const unit = value.charCodeAt(index);
1676
+ if (unit >= 55296 && unit <= 56319) {
1677
+ const next = value.charCodeAt(index + 1);
1678
+ if (next >= 56320 && next <= 57343) {
1679
+ out += value[index] + value[index + 1];
1680
+ index += 1;
1681
+ } else {
1682
+ out += "\uFFFD";
1683
+ }
1684
+ } else if (unit >= 56320 && unit <= 57343) {
1685
+ out += "\uFFFD";
1686
+ } else {
1687
+ out += value[index];
1688
+ }
1689
+ }
1690
+ return out;
1691
+ }
1692
+ function isUnsafeTerminalCodePoint(point) {
1693
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1694
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1695
+ point === 1564 || // Arabic letter mark
1696
+ point === 6158 || // Mongolian vowel separator
1697
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1698
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1699
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1700
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1701
+ point === 65279 || // zero-width no-break space / BOM
1702
+ point >= 917504 && point <= 917631;
1703
+ return c0OrC1 || bidiOrZeroWidth;
1704
+ }
1705
+ function terminalSafeText(value) {
1706
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1707
+ }
1708
+ function terminalSafeLine(value) {
1709
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1710
+ }
1711
+ function isTerminalSafeText(value) {
1712
+ return terminalSafeText(value) === value;
1713
+ }
1714
+ var stripControlChars = terminalSafeText;
1715
+
1716
+ // src/lib/session-identity.ts
1717
+ import { execFile } from "child_process";
1718
+ import { createHash as createHash5 } from "crypto";
1719
+ import { rmSync as rmSync7 } from "fs";
1720
+ import { join as join10 } from "path";
1721
+ import { promisify } from "util";
1722
+
1409
1723
  // src/lib/machine-credentials.ts
1410
1724
  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";
1725
+ import { createHash as createHash4, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
1726
+ import {
1727
+ chmodSync,
1728
+ existsSync as existsSync5,
1729
+ linkSync,
1730
+ lstatSync as lstatSync4,
1731
+ mkdirSync as mkdirSync4,
1732
+ readFileSync as readFileSync8,
1733
+ rmSync as rmSync6,
1734
+ writeFileSync as writeFileSync4
1735
+ } from "fs";
1413
1736
  import { createRequire } from "module";
1414
- import { dirname as dirname5, join as join7 } from "path";
1737
+ import { dirname as dirname5, join as join9 } from "path";
1415
1738
  import { fileURLToPath as fileURLToPath3 } from "url";
1416
1739
 
1417
1740
  // src/lib/machine-broker.ts
1418
1741
  import { spawn } from "child_process";
1419
1742
  import { createHash as createHash2, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
1420
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync3 } from "fs";
1743
+ import { lstatSync as lstatSync2, readFileSync as readFileSync6, rmSync as rmSync4 } from "fs";
1421
1744
  import { createServer } from "http";
1422
- import { basename as basename2, join as join5 } from "path";
1745
+ import { basename as basename2, join as join7 } from "path";
1423
1746
  import { fileURLToPath as fileURLToPath2 } from "url";
1747
+
1748
+ // src/lib/loopback-fetch.ts
1749
+ import { request } from "http";
1750
+ import { Readable } from "stream";
1751
+ function loopbackFetch(url, init = {}) {
1752
+ const target = new URL(url);
1753
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
1754
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
1755
+ return new Promise((resolve2, reject) => {
1756
+ const outgoing = request(
1757
+ target,
1758
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
1759
+ (incoming) => {
1760
+ try {
1761
+ const headers = new Headers();
1762
+ for (const [name, value] of Object.entries(incoming.headers))
1763
+ if (typeof value === "string") headers.set(name, value);
1764
+ const status = incoming.statusCode ?? 502;
1765
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
1766
+ resolve2(new Response(body, { status, headers }));
1767
+ } catch (error) {
1768
+ incoming.destroy();
1769
+ reject(error);
1770
+ }
1771
+ }
1772
+ );
1773
+ outgoing.once("error", reject);
1774
+ outgoing.end(init.body);
1775
+ });
1776
+ }
1777
+
1778
+ // src/lib/machine-broker.ts
1424
1779
  var MAX_RESPONSE_BYTES = 96 * 1024;
1780
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
1781
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
1782
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
1783
+ var FORWARD_REQUEST_PROOF = "forward-request";
1784
+ var FORWARD_ANSWER_PROOF = "forward-answer";
1425
1785
  var IDLE_MS = 5 * 6e4;
1426
1786
  function descriptorPath(directory, generation) {
1427
- return join5(directory, `machine_broker_${generation}.json`);
1787
+ return join7(directory, `machine_broker_${generation}.json`);
1428
1788
  }
1429
1789
  function readDescriptor(path) {
1430
1790
  try {
1431
1791
  const stat = lstatSync2(path);
1432
1792
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1433
1793
  return void 0;
1434
- const data = JSON.parse(readFileSync4(path, "utf8"));
1794
+ const data = JSON.parse(readFileSync6(path, "utf8"));
1435
1795
  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
1796
  } catch {
1437
1797
  return void 0;
1438
1798
  }
1439
1799
  }
1440
- function signature(secret, nonce, body) {
1441
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
1800
+ function signature(secret, nonce, body, purpose) {
1801
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
1442
1802
  }
1443
1803
  function matches(left, right) {
1444
1804
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -1453,10 +1813,9 @@ async function brokerRequest(descriptor, environment, options) {
1453
1813
  observedTokenHash: tokenHash(options.observedToken),
1454
1814
  timestamp: Date.now()
1455
1815
  });
1456
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1816
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1457
1817
  method: "POST",
1458
1818
  body,
1459
- redirect: "error",
1460
1819
  signal: options.signal,
1461
1820
  headers: {
1462
1821
  "Content-Type": "application/json",
@@ -1487,6 +1846,15 @@ async function brokerRequest(descriptor, environment, options) {
1487
1846
  );
1488
1847
  return credential;
1489
1848
  }
1849
+ function brokerEnvironment(options) {
1850
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
1851
+ return {
1852
+ ...options.env,
1853
+ PRIM_API_URL: options.apiUrl,
1854
+ PRIM_CONFIG_DIR: options.directory,
1855
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
1856
+ };
1857
+ }
1490
1858
  async function acquireBrokerCredential(options) {
1491
1859
  const path = descriptorPath(options.directory, options.environment.generation);
1492
1860
  const existing = readDescriptor(path);
@@ -1498,15 +1866,28 @@ async function acquireBrokerCredential(options) {
1498
1866
  if (error instanceof MachineAuthError) throw error;
1499
1867
  }
1500
1868
  }
1501
- const descriptor = await withFileLock(
1502
- join5(options.directory, "machine-broker.lock"),
1869
+ const descriptor = await ensureBroker(options);
1870
+ try {
1871
+ return await brokerRequest(descriptor, options.environment, options);
1872
+ } catch (error) {
1873
+ options.signal.throwIfAborted();
1874
+ if (error instanceof MachineAuthError) throw error;
1875
+ throw new MachineAuthError(
1876
+ "broker_unavailable",
1877
+ "Machine credential broker is unavailable. Retry the command."
1878
+ );
1879
+ }
1880
+ }
1881
+ async function ensureBroker(options) {
1882
+ const path = descriptorPath(options.directory, options.environment.generation);
1883
+ return withFileLock(
1884
+ join7(options.directory, "machine-broker.lock"),
1503
1885
  async () => {
1504
1886
  const current = readDescriptor(path);
1505
1887
  if (current) {
1506
1888
  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"
1889
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
1890
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
1510
1891
  });
1511
1892
  if (response.ok && await response.text() === current.nonce) return current;
1512
1893
  } catch {
@@ -1525,7 +1906,7 @@ async function acquireBrokerCredential(options) {
1525
1906
  detached: true,
1526
1907
  stdio: ["ignore", "ignore", "ignore", "ipc"],
1527
1908
  windowsHide: true,
1528
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
1909
+ env: brokerEnvironment(options)
1529
1910
  });
1530
1911
  let settled = false;
1531
1912
  const finish = (error) => {
@@ -1577,31 +1958,118 @@ async function acquireBrokerCredential(options) {
1577
1958
  },
1578
1959
  { signal: options.signal }
1579
1960
  );
1961
+ }
1962
+ async function forwardOnce(descriptor, environment, request2, signal) {
1963
+ const body = JSON.stringify({
1964
+ generation: environment.generation,
1965
+ timestamp: Date.now(),
1966
+ method: request2.method,
1967
+ path: request2.path,
1968
+ headers: request2.headers ?? {},
1969
+ ...request2.body === void 0 ? {} : { body: request2.body }
1970
+ });
1971
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
1972
+ method: "POST",
1973
+ body,
1974
+ signal,
1975
+ headers: {
1976
+ "Content-Type": "application/json",
1977
+ "X-Prim-Proof": signature(
1978
+ environment.clientSecret,
1979
+ descriptor.nonce,
1980
+ body,
1981
+ FORWARD_REQUEST_PROOF
1982
+ )
1983
+ }
1984
+ });
1985
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
1986
+ if (typeof envelope.body !== "string" || !matches(
1987
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
1988
+ envelope.proof
1989
+ ))
1990
+ throw new MachineAuthError(
1991
+ "broker_unavailable",
1992
+ "Machine credential broker could not be authenticated. Retry the command."
1993
+ );
1994
+ const data = machineRecord(JSON.parse(envelope.body));
1995
+ if (data.error) {
1996
+ const error = machineRecord(data.error);
1997
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
1998
+ }
1999
+ const status = data.status;
2000
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
2001
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
2002
+ const headers = new Headers();
2003
+ for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
2004
+ if (typeof value === "string") headers.set(name, value);
2005
+ const text = typeof data.body === "string" ? data.body : "";
2006
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
2007
+ }
2008
+ async function forwardBrokerRequest(options) {
2009
+ const path = descriptorPath(options.directory, options.environment.generation);
2010
+ const unavailable = () => new MachineAuthError(
2011
+ "broker_unavailable",
2012
+ "Machine credential broker is unavailable. Retry the command."
2013
+ );
2014
+ const existing = readDescriptor(path);
2015
+ if (existing) {
2016
+ try {
2017
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
2018
+ } catch (error) {
2019
+ options.signal.throwIfAborted();
2020
+ if (error instanceof MachineAuthError) throw error;
2021
+ if (error.code !== "ECONNREFUSED") throw unavailable();
2022
+ }
2023
+ }
2024
+ const descriptor = await ensureBroker(options);
1580
2025
  try {
1581
- return await brokerRequest(descriptor, options.environment, options);
2026
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
1582
2027
  } catch (error) {
1583
2028
  options.signal.throwIfAborted();
1584
2029
  if (error instanceof MachineAuthError) throw error;
1585
- throw new MachineAuthError(
1586
- "broker_unavailable",
1587
- "Machine credential broker is unavailable. Retry the command."
1588
- );
2030
+ throw unavailable();
1589
2031
  }
1590
2032
  }
1591
2033
 
1592
2034
  // src/lib/machine-retry.ts
1593
2035
  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) {
2036
+ import { lstatSync as lstatSync3, readFileSync as readFileSync7, readdirSync, rmSync as rmSync5 } from "fs";
2037
+ import { join as join8 } from "path";
2038
+ function clearMachineCooldowns(directory) {
2039
+ let names;
2040
+ try {
2041
+ names = readdirSync(directory);
2042
+ } catch {
2043
+ return;
2044
+ }
2045
+ for (const name of names) {
2046
+ if (!/^machine_retry_[0-9a-f]{64}\.json$/u.test(name)) continue;
2047
+ const path = join8(directory, name);
2048
+ try {
2049
+ const state = JSON.parse(readFileSync7(path, "utf8"));
2050
+ if (state.serverRetryAfter === true) continue;
2051
+ } catch {
2052
+ }
2053
+ try {
2054
+ rmSync5(path, { force: true });
2055
+ } catch {
2056
+ }
2057
+ }
2058
+ }
2059
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
2060
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
2061
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
1597
2062
  signal?.throwIfAborted();
1598
2063
  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 };
2064
+ const path = join8(directory, `machine_retry_${key}.json`);
2065
+ let state = {
2066
+ failures: 0,
2067
+ retryAt: 0
2068
+ };
1601
2069
  try {
1602
2070
  const stat = lstatSync3(path);
1603
2071
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
1604
- const data = JSON.parse(readFileSync5(path, "utf8"));
2072
+ const data = JSON.parse(readFileSync7(path, "utf8"));
1605
2073
  if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
1606
2074
  throw new Error("Invalid retry state");
1607
2075
  state = data;
@@ -1612,13 +2080,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request)
1612
2080
  if (state.retryAt > Date.now())
1613
2081
  throw new MachineAuthError(
1614
2082
  "token_service_unavailable",
1615
- "Machine authentication is cooling down after a temporary failure. Retry later.",
2083
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
2084
+ // Cloud setup keeps this wait too, so pointing at it would loop.
2085
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
2086
+ ) : (
2087
+ // The cooldown hides the failure that started it; cloud setup
2088
+ // retries at once and names the cause.
2089
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
2090
+ ),
1616
2091
  false,
1617
2092
  state.retryAt
1618
2093
  );
1619
2094
  try {
1620
- const result = await request();
1621
- rmSync4(path, { force: true });
2095
+ const result = await request2();
2096
+ rmSync5(path, { force: true });
1622
2097
  return result;
1623
2098
  } catch (error) {
1624
2099
  if (!signal?.aborted && error instanceof MachineAuthError && [
@@ -1629,8 +2104,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request)
1629
2104
  ].includes(error.code)) {
1630
2105
  const failures = Math.min(16, state.failures + 1);
1631
2106
  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 });
2107
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
2108
+ atomicWriteFile(
2109
+ path,
2110
+ JSON.stringify({
2111
+ failures,
2112
+ retryAt,
2113
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
2114
+ }),
2115
+ { mode: 384 }
2116
+ );
1634
2117
  throw new MachineAuthError(error.code, error.message, false, retryAt);
1635
2118
  }
1636
2119
  throw error;
@@ -1638,6 +2121,9 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request)
1638
2121
  }
1639
2122
 
1640
2123
  // src/lib/machine-credentials.ts
2124
+ function sessionScoped(deps) {
2125
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2126
+ }
1641
2127
  var require2 = createRequire(import.meta.url);
1642
2128
  var SERVICE = "ai.primitive.prim.machine";
1643
2129
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
@@ -1654,13 +2140,13 @@ function hash(value) {
1654
2140
  return createHash4("sha256").update(value).digest("hex");
1655
2141
  }
1656
2142
  function recordPath(directory, generation) {
1657
- return join7(directory, `machine_${generation}.json`);
2143
+ return join9(directory, `machine_${generation}.json`);
1658
2144
  }
1659
2145
  function storageKey(directory, generation) {
1660
2146
  return `${hash(directory)}:${generation}`;
1661
2147
  }
1662
2148
  function environmentContextPath(deps, clientId) {
1663
- return join7(
2149
+ return join9(
1664
2150
  configurationDirectory(deps),
1665
2151
  `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1666
2152
  );
@@ -1723,8 +2209,8 @@ function readEnvironmentContext(environment, deps) {
1723
2209
  function keyringEntry(key) {
1724
2210
  let directory = dirname5(fileURLToPath3(import.meta.url));
1725
2211
  for (let depth = 0; depth < 5; depth++) {
1726
- const loader = join7(directory, "native", "keyring.cjs");
1727
- if (existsSync4(loader)) {
2212
+ const loader = join9(directory, "native", "keyring.cjs");
2213
+ if (existsSync5(loader)) {
1728
2214
  const module2 = require2(loader);
1729
2215
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1730
2216
  }
@@ -1752,7 +2238,7 @@ function protectPath(path, directory) {
1752
2238
  );
1753
2239
  }
1754
2240
  function ensureDirectory(directory) {
1755
- mkdirSync3(directory, { recursive: true, mode: 448 });
2241
+ mkdirSync4(directory, { recursive: true, mode: 448 });
1756
2242
  if (lstatSync4(directory).isSymbolicLink())
1757
2243
  throw new MachineAuthError(
1758
2244
  "unsafe_storage",
@@ -1765,6 +2251,9 @@ function writePrivate(path, value) {
1765
2251
  `, { mode: 384 });
1766
2252
  protectPath(path, false);
1767
2253
  }
2254
+ function readMachineMetadata(path) {
2255
+ return readPrivate(path);
2256
+ }
1768
2257
  function readPrivate(path) {
1769
2258
  let raw;
1770
2259
  try {
@@ -1775,7 +2264,7 @@ function readPrivate(path) {
1775
2264
  "Machine credential files must be owner-only regular files."
1776
2265
  );
1777
2266
  }
1778
- raw = readFileSync6(path, "utf8");
2267
+ raw = readFileSync8(path, "utf8");
1779
2268
  } catch (error) {
1780
2269
  if (error.code === "ENOENT") return void 0;
1781
2270
  throw error;
@@ -1820,17 +2309,105 @@ function parseProfile(value) {
1820
2309
  };
1821
2310
  }
1822
2311
  function readMachineProfile(deps = {}) {
1823
- const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
2312
+ const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
1824
2313
  return value === void 0 ? void 0 : parseProfile(value);
1825
2314
  }
1826
- function environmentCredentials(deps) {
1827
- 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;
1830
- if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
1831
- throw new MachineAuthError(
1832
- "incomplete_machine_credentials",
1833
- "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
2315
+ var NETWORK_SECRET_AUTH = "network-secret";
2316
+ var NETWORK_TOKEN_AUTH = "network-token";
2317
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2318
+ var brokerKeys = /* @__PURE__ */ new Map();
2319
+ function networkSecretBrokerKey(deps, clientId) {
2320
+ const directory = configurationDirectory(deps);
2321
+ const path = join9(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2322
+ const known = brokerKeys.get(path);
2323
+ if (known) return known;
2324
+ ensureDirectory(directory);
2325
+ const read = () => {
2326
+ try {
2327
+ const stat = lstatSync4(path);
2328
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2329
+ throw new MachineAuthError(
2330
+ "unsafe_storage",
2331
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2332
+ true
2333
+ );
2334
+ const value = readFileSync8(path, "utf8").trim();
2335
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2336
+ } catch (error) {
2337
+ if (error.code === "ENOENT") return void 0;
2338
+ throw error;
2339
+ }
2340
+ };
2341
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2342
+ const existing = read();
2343
+ if (existing?.key) {
2344
+ brokerKeys.set(path, existing.key);
2345
+ return existing.key;
2346
+ }
2347
+ if (existing)
2348
+ throw new MachineAuthError(
2349
+ "unsafe_storage",
2350
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2351
+ true
2352
+ );
2353
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
2354
+ try {
2355
+ writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
2356
+ `, { mode: 384, flag: "wx" });
2357
+ protectPath(staged, false);
2358
+ linkSync(staged, path);
2359
+ } catch (error) {
2360
+ if (error.code !== "EEXIST") throw error;
2361
+ } finally {
2362
+ rmSync6(staged, { force: true });
2363
+ }
2364
+ }
2365
+ const key = read()?.key;
2366
+ if (!key)
2367
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2368
+ brokerKeys.set(path, key);
2369
+ return key;
2370
+ }
2371
+ function environmentCredentials(deps) {
2372
+ const env = deps.env ?? process.env;
2373
+ const {
2374
+ PRIM_M2M_CLIENT_ID: clientId,
2375
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2376
+ PRIM_M2M_CLIENT_AUTH: auth
2377
+ } = env;
2378
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2379
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2380
+ throw new MachineAuthError(
2381
+ "incomplete_machine_credentials",
2382
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2383
+ );
2384
+ if (auth !== void 0) {
2385
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2386
+ throw new MachineAuthError(
2387
+ "incomplete_machine_credentials",
2388
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2389
+ );
2390
+ if (clientSecret !== void 0)
2391
+ throw new MachineAuthError(
2392
+ "conflicting_credentials",
2393
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2394
+ );
2395
+ const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2396
+ const credentials = {
2397
+ clientId,
2398
+ generation,
2399
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2400
+ };
2401
+ Object.defineProperty(credentials, "clientSecret", {
2402
+ enumerable: true,
2403
+ get: () => networkSecretBrokerKey(deps, clientId)
2404
+ });
2405
+ return credentials;
2406
+ }
2407
+ if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
2408
+ throw new MachineAuthError(
2409
+ "incomplete_machine_credentials",
2410
+ "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
1834
2411
  );
1835
2412
  }
1836
2413
  return {
@@ -1841,7 +2418,7 @@ function environmentCredentials(deps) {
1841
2418
  }
1842
2419
  function hasMachineConfiguration(deps = {}) {
1843
2420
  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));
2421
+ 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
2422
  if (configured && env.PRIM_TOKEN?.trim()) {
1846
2423
  throw new MachineAuthError(
1847
2424
  "conflicting_credentials",
@@ -1853,6 +2430,7 @@ function hasMachineConfiguration(deps = {}) {
1853
2430
  }
1854
2431
  function machineContext(deps = {}) {
1855
2432
  if (!hasMachineConfiguration(deps)) return void 0;
2433
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1856
2434
  const environment = environmentCredentials(deps);
1857
2435
  if (environment) {
1858
2436
  if (environmentTerminal === environment.generation) return void 0;
@@ -1867,6 +2445,7 @@ function machineContext(deps = {}) {
1867
2445
  return profile;
1868
2446
  }
1869
2447
  function cachedMachineCredential(deps = {}) {
2448
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1870
2449
  const context = machineContext(deps);
1871
2450
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1872
2451
  }
@@ -1875,9 +2454,11 @@ function machineSessionEnded(deps = {}) {
1875
2454
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1876
2455
  if (!generation) return false;
1877
2456
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1878
- return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
2457
+ return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
1879
2458
  }
1880
2459
  var environmentTerminal;
2460
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2461
+ var networkRejection;
1881
2462
  async function loadRecord(profile, deps, signal) {
1882
2463
  const directory = configurationDirectory(deps);
1883
2464
  let value;
@@ -1946,7 +2527,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
1946
2527
  const directory = configurationDirectory(deps);
1947
2528
  ensureDirectory(directory);
1948
2529
  return withFileLock(
1949
- join7(directory, "credentials.lock"),
2530
+ join9(directory, "credentials.lock"),
1950
2531
  async () => {
1951
2532
  const { configuration, tokens, identity } = await withMachineCooldown(
1952
2533
  directory,
@@ -2002,11 +2583,11 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
2002
2583
  profile = { ...profile, storage: "file" };
2003
2584
  await persistRecord({ ...profile, ...tokens, clientSecret }, deps, signal);
2004
2585
  }
2005
- writePrivate(join7(directory, PROFILE_FILE), profile);
2006
- rmSync5(join7(directory, "machine_terminal.json"), { force: true });
2586
+ writePrivate(join9(directory, PROFILE_FILE), profile);
2587
+ rmSync6(join9(directory, "machine_terminal.json"), { force: true });
2007
2588
  cached = { ...profile, ...tokens };
2008
2589
  if (previous) {
2009
- writePrivate(join7(directory, "machine_retired.json"), [...retired, previous]);
2590
+ writePrivate(join9(directory, "machine_retired.json"), [...retired, previous]);
2010
2591
  }
2011
2592
  await cleanupRetired(deps, signal);
2012
2593
  return profile;
@@ -2016,10 +2597,12 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
2016
2597
  }
2017
2598
  async function acquireMachineCredential(options = {}, deps = {}) {
2018
2599
  if (!hasMachineConfiguration(deps)) return void 0;
2600
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
2019
2601
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2020
2602
  const apiUrl = apiUrlFor(deps);
2021
2603
  const environment = environmentCredentials(deps);
2022
2604
  if (environment) {
2605
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
2023
2606
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
2024
2607
  const directory2 = configurationDirectory(deps);
2025
2608
  ensureDirectory(directory2);
@@ -2037,22 +2620,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2037
2620
  writeEnvironmentContext(cached, deps);
2038
2621
  return cached;
2039
2622
  } catch (error) {
2040
- if (error instanceof MachineAuthError && error.terminal)
2623
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
2041
2624
  environmentTerminal = environment.generation;
2042
2625
  throw error;
2043
2626
  }
2044
2627
  }
2045
2628
  return withFileLock(
2046
- join7(directory2, "credentials.lock"),
2629
+ join9(directory2, "credentials.lock"),
2047
2630
  async () => {
2048
2631
  if (machineSessionEnded(deps))
2049
2632
  throw new MachineAuthError(
2050
2633
  "machine_credentials_rejected",
2051
- "Rotate the injected machine credentials.",
2634
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
2052
2635
  true
2053
2636
  );
2054
2637
  if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2055
2638
  return cached;
2639
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2640
+ throw networkRejection.error;
2056
2641
  try {
2057
2642
  const { configuration, tokens, identity } = await withMachineCooldown(
2058
2643
  directory2,
@@ -2061,13 +2646,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2061
2646
  signal,
2062
2647
  async () => {
2063
2648
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2649
+ if (environment.tokenInjection) {
2650
+ const identity3 = await verifyInjectedMachineIdentity(
2651
+ apiUrl,
2652
+ environment.clientId,
2653
+ signal,
2654
+ deps.fetch
2655
+ );
2656
+ const tokens3 = {
2657
+ accessToken: "",
2658
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2659
+ };
2660
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2661
+ }
2064
2662
  const tokens2 = await exchangeMachineCredentials(
2065
2663
  configuration2,
2066
2664
  environment.clientId,
2067
- environment.clientSecret,
2665
+ // The broker key is not a client secret; the proxy supplies that.
2666
+ environment.secretInjection ? "" : environment.clientSecret,
2068
2667
  signal,
2069
- deps.fetch
2070
- );
2668
+ deps.fetch,
2669
+ { secretInjection: environment.secretInjection }
2670
+ ).catch((error) => {
2671
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2672
+ throw new MachineAuthError(
2673
+ "network_secret_mismatch",
2674
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2675
+ true
2676
+ );
2677
+ throw error;
2678
+ });
2071
2679
  const identity2 = await verifyMachineIdentity(
2072
2680
  apiUrl,
2073
2681
  tokens2.accessToken,
@@ -2084,17 +2692,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2084
2692
  ...identity,
2085
2693
  apiUrl,
2086
2694
  generation: environment.generation,
2087
- storage: "environment"
2695
+ storage: "environment",
2696
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
2088
2697
  };
2089
2698
  writeEnvironmentContext(cached, deps);
2090
2699
  return cached;
2091
2700
  } catch (error) {
2701
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2702
+ networkRejection = {
2703
+ generation: environment.generation,
2704
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2705
+ error
2706
+ };
2707
+ if (cached?.generation === environment.generation) cached = void 0;
2708
+ const contextPath = environmentContextPath(deps, environment.clientId);
2709
+ try {
2710
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2711
+ rmSync6(contextPath, { force: true });
2712
+ } catch {
2713
+ }
2714
+ throw error;
2715
+ }
2092
2716
  if (error instanceof MachineAuthError && error.terminal) {
2093
2717
  environmentTerminal = environment.generation;
2094
2718
  const contextPath = environmentContextPath(deps, environment.clientId);
2095
2719
  try {
2096
2720
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2097
- rmSync5(contextPath, { force: true });
2721
+ rmSync6(contextPath, { force: true });
2098
2722
  } catch {
2099
2723
  }
2100
2724
  }
@@ -2108,7 +2732,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2108
2732
  const expected = machineContext(deps);
2109
2733
  const directory = configurationDirectory(deps);
2110
2734
  return withFileLock(
2111
- join7(directory, "credentials.lock"),
2735
+ join9(directory, "credentials.lock"),
2112
2736
  async () => {
2113
2737
  const profile = readMachineProfile(deps);
2114
2738
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -2158,7 +2782,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2158
2782
  await persistRecord(record, deps, signal);
2159
2783
  } catch (error) {
2160
2784
  if (error instanceof MachineAuthError && error.terminal)
2161
- writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
2785
+ writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
2162
2786
  throw error;
2163
2787
  }
2164
2788
  }
@@ -2169,14 +2793,43 @@ async function acquireMachineCredential(options = {}, deps = {}) {
2169
2793
  { signal }
2170
2794
  );
2171
2795
  }
2796
+ async function forwardMachineRequest(request2, signal, deps = {}) {
2797
+ const environment = environmentCredentials(deps);
2798
+ if (!environment?.tokenInjection)
2799
+ throw new MachineAuthError(
2800
+ "identity_changed",
2801
+ "Machine identity changed; restart the operation."
2802
+ );
2803
+ const directory = configurationDirectory(deps);
2804
+ ensureDirectory(directory);
2805
+ return forwardBrokerRequest({
2806
+ directory,
2807
+ apiUrl: apiUrlFor(deps),
2808
+ environment,
2809
+ env: deps.env ?? process.env,
2810
+ request: request2,
2811
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2812
+ });
2813
+ }
2814
+ async function verifyAcquiredMachineIdentity(machine, deps = {}) {
2815
+ if (!machine.tokenInjection)
2816
+ return verifyMachineIdentity(machine.apiUrl, machine.accessToken, machine.clientId);
2817
+ const response = await forwardMachineRequest(
2818
+ { method: "GET", path: "/api/cli/auth/status" },
2819
+ AbortSignal.timeout(1e4),
2820
+ deps
2821
+ );
2822
+ const value = response.ok ? await response.json().catch(() => void 0) : void 0;
2823
+ return parseInjectedMachineIdentity(response.status, value, machine.apiUrl, machine.clientId);
2824
+ }
2172
2825
  async function clearMachineCredentials(deps = {}) {
2173
2826
  const directory = configurationDirectory(deps);
2174
- if (!existsSync4(join7(directory, PROFILE_FILE))) return false;
2175
- return withFileLock(join7(directory, "credentials.lock"), async () => {
2827
+ if (!existsSync5(join9(directory, PROFILE_FILE))) return false;
2828
+ return withFileLock(join9(directory, "credentials.lock"), async () => {
2176
2829
  const profile = readMachineProfile(deps);
2177
2830
  if (!profile) return false;
2178
2831
  await cleanupRetired(deps, AbortSignal.timeout(1e4));
2179
- if (existsSync4(join7(directory, "machine_retired.json")))
2832
+ if (existsSync5(join9(directory, "machine_retired.json")))
2180
2833
  throw new MachineAuthError(
2181
2834
  "storage_unavailable",
2182
2835
  "Unlock the credential store to remove retired machine credentials."
@@ -2192,9 +2845,9 @@ async function clearMachineCredentials(deps = {}) {
2192
2845
  "Unlock the keychain to remove the saved machine credential."
2193
2846
  );
2194
2847
  }
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 });
2848
+ } else rmSync6(recordPath(directory, profile.generation), { force: true });
2849
+ rmSync6(join9(directory, PROFILE_FILE), { force: true });
2850
+ rmSync6(join9(directory, "machine_terminal.json"), { force: true });
2198
2851
  cached = void 0;
2199
2852
  return true;
2200
2853
  });
@@ -2218,8 +2871,14 @@ function machineCaptureActor(deps = {}) {
2218
2871
  function machineJournalBucket(identity) {
2219
2872
  return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2220
2873
  }
2874
+ function identityPending(actor) {
2875
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
2876
+ }
2877
+ function machinePendingBucket(identity) {
2878
+ return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
2879
+ }
2221
2880
  function readRetiredProfiles(directory) {
2222
- const value = readPrivate(join7(directory, "machine_retired.json"));
2881
+ const value = readPrivate(join9(directory, "machine_retired.json"));
2223
2882
  if (value === void 0) return [];
2224
2883
  if (!Array.isArray(value))
2225
2884
  throw new MachineAuthError(
@@ -2230,20 +2889,20 @@ function readRetiredProfiles(directory) {
2230
2889
  }
2231
2890
  async function cleanupRetired(deps, signal) {
2232
2891
  const directory = configurationDirectory(deps);
2233
- const path = join7(directory, "machine_retired.json");
2892
+ const path = join9(directory, "machine_retired.json");
2234
2893
  const pending = [];
2235
2894
  for (const profile of readRetiredProfiles(directory)) {
2236
2895
  try {
2237
2896
  if (profile.storage === "keychain") {
2238
2897
  const entry = (deps.entry ?? keyringEntry)(storageKey(directory, profile.generation));
2239
2898
  if (await entry.getPassword(signal) !== null) await entry.deletePassword(signal);
2240
- } else rmSync5(recordPath(directory, profile.generation), { force: true });
2899
+ } else rmSync6(recordPath(directory, profile.generation), { force: true });
2241
2900
  } catch {
2242
2901
  pending.push(profile);
2243
2902
  }
2244
2903
  }
2245
2904
  if (pending.length) writePrivate(path, pending);
2246
- else rmSync5(path, { force: true });
2905
+ else rmSync6(path, { force: true });
2247
2906
  }
2248
2907
  function prepareMachineMetadataDirectory(directory) {
2249
2908
  ensureDirectory(directory);
@@ -2252,25 +2911,1032 @@ function writeMachineMetadata(path, value) {
2252
2911
  writePrivate(path, value);
2253
2912
  }
2254
2913
 
2914
+ // src/lib/session-identity.ts
2915
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
2916
+ var SESSION_IDENTITY_VALUE = "session";
2917
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
2918
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
2919
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
2920
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
2921
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
2922
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
2923
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
2924
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
2925
+ var SESSION_IDENTITY_ROUTES = {
2926
+ challenge: "/api/cli/session-identity/challenge",
2927
+ token: "/api/cli/session-identity/token",
2928
+ refresh: "/api/cli/session-identity/token/refresh",
2929
+ link: "/api/cli/session-identity/link"
2930
+ };
2931
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
2932
+ var RENEW_BEFORE_MS2 = 6e4;
2933
+ var GIT_TIMEOUT_MS4 = 1e4;
2934
+ var POLL_BUDGET_MS = 15e3;
2935
+ var POLL_FIRST_DELAY_MS = 500;
2936
+ var POLL_MAX_DELAY_MS = 3e3;
2937
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
2938
+ var LOCK_TIMEOUT_MS = 6e4;
2939
+ var RESPONSE_MAX_BYTES = 64 * 1024;
2940
+ function sessionIdentityRequested(env = process.env) {
2941
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
2942
+ }
2943
+ function sessionIdentityMode(deps = {}) {
2944
+ const env = deps.env ?? process.env;
2945
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
2946
+ }
2947
+ function failure(code, cause, remedy) {
2948
+ return { status: "failed", code, cause, remedy };
2949
+ }
2950
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
2951
+ var NEW_SESSION_REMEDY = "start a new cloud session";
2952
+ var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
2953
+ var SESSION_REVOKED = failure(
2954
+ "session_revoked",
2955
+ "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",
2956
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
2957
+ );
2958
+ var CHALLENGE_WINDOW_PASSED = failure(
2959
+ "challenge_expired",
2960
+ "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)",
2961
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
2962
+ );
2963
+ var CHALLENGE_GONE = failure(
2964
+ "challenge_not_found",
2965
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
2966
+ NEW_SESSION_REMEDY
2967
+ );
2968
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
2969
+ function rejectionFailure(reason, repository) {
2970
+ switch (reason) {
2971
+ case "identity_mismatch":
2972
+ return failure(
2973
+ "identity_mismatch",
2974
+ "the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
2975
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
2976
+ );
2977
+ case "push_after_expiry":
2978
+ return failure(
2979
+ "push_after_expiry",
2980
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
2981
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
2982
+ );
2983
+ case "repository_mismatch":
2984
+ return failure(
2985
+ "repository_mismatch",
2986
+ `Primitive received the identity push from a different repository than ${repository}`,
2987
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
2988
+ );
2989
+ case "conflicting_push":
2990
+ return failure(
2991
+ "conflicting_push",
2992
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
2993
+ NEW_SESSION_REMEDY
2994
+ );
2995
+ case "unsupported_sender":
2996
+ return failure(
2997
+ "unsupported_sender",
2998
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
2999
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
3000
+ );
3001
+ default:
3002
+ return failure(
3003
+ "challenge_rejected",
3004
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
3005
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
3006
+ );
3007
+ }
3008
+ }
3009
+ function sessionIdentityMessage(outcome) {
3010
+ if (outcome.status === "link_required")
3011
+ return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
3012
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
3013
+ }
3014
+ function hash2(value) {
3015
+ return createHash5("sha256").update(value).digest("hex");
3016
+ }
3017
+ function sessionContext(deps) {
3018
+ const env = deps.env ?? process.env;
3019
+ const environment = environmentCredentials(deps);
3020
+ if (!environment)
3021
+ return failure(
3022
+ "environment_credential_missing",
3023
+ "the cloud environment has no environment credential",
3024
+ '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'
3025
+ );
3026
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
3027
+ if (!sessionId || !SESSION_ID.test(sessionId))
3028
+ return failure(
3029
+ "session_id_missing",
3030
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
3031
+ NEW_SESSION_REMEDY
3032
+ );
3033
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL2);
3034
+ const directory = deps.directory ?? primConfigDirectory({ env });
3035
+ const key = hash2(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
3036
+ return {
3037
+ directory,
3038
+ apiUrl,
3039
+ clientId: environment.clientId,
3040
+ generation: environment.generation,
3041
+ sessionId,
3042
+ tokenPath: join10(directory, `session_identity_${key}.json`),
3043
+ statePath: join10(directory, `session_identity_${key}.state.json`),
3044
+ lockPath: join10(directory, "session-identity.lock")
3045
+ };
3046
+ }
3047
+ function readRecord(path) {
3048
+ try {
3049
+ const value = readMachineMetadata(path);
3050
+ return value === void 0 ? void 0 : machineRecord(value);
3051
+ } catch {
3052
+ return void 0;
3053
+ }
3054
+ }
3055
+ function finiteNumber(value) {
3056
+ return typeof value === "number" && Number.isFinite(value);
3057
+ }
3058
+ function readToken(context) {
3059
+ const data = readRecord(context.tokenPath);
3060
+ 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))
3061
+ return void 0;
3062
+ const identity = data.identity;
3063
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
3064
+ return void 0;
3065
+ return data;
3066
+ }
3067
+ function readState(context) {
3068
+ const data = readRecord(context.statePath);
3069
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
3070
+ return void 0;
3071
+ return data;
3072
+ }
3073
+ function writeToken(context, record) {
3074
+ prepareMachineMetadataDirectory(context.directory);
3075
+ writeMachineMetadata(context.tokenPath, record);
3076
+ rmSync7(context.statePath, { force: true });
3077
+ }
3078
+ function writeState(context, state) {
3079
+ try {
3080
+ prepareMachineMetadataDirectory(context.directory);
3081
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
3082
+ } catch {
3083
+ }
3084
+ }
3085
+ function tokenValid(record, now = Date.now()) {
3086
+ return now < record.expiresAt - RENEW_BEFORE_MS2;
3087
+ }
3088
+ function tokenFresh(record, now = Date.now()) {
3089
+ return tokenValid(record, now) && now < record.refreshAfter;
3090
+ }
3091
+ function toCredential(record) {
3092
+ return {
3093
+ issuer: record.issuer,
3094
+ audience: record.audience,
3095
+ ...record.identity,
3096
+ accessToken: record.accessToken,
3097
+ expiresAt: record.expiresAt,
3098
+ apiUrl: record.apiUrl,
3099
+ generation: record.generation,
3100
+ storage: "environment",
3101
+ session: {
3102
+ userId: record.userId,
3103
+ displayName: record.displayName,
3104
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
3105
+ refreshAfter: record.refreshAfter
3106
+ }
3107
+ };
3108
+ }
3109
+ function identified(record, reused) {
3110
+ return {
3111
+ status: "ok",
3112
+ credential: toCredential(record),
3113
+ displayName: record.displayName,
3114
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
3115
+ reused
3116
+ };
3117
+ }
3118
+ function cachedSessionCredential(deps = {}) {
3119
+ if (!sessionIdentityMode(deps)) return void 0;
3120
+ let context;
3121
+ try {
3122
+ context = sessionContext(deps);
3123
+ } catch {
3124
+ return void 0;
3125
+ }
3126
+ if ("status" in context) return void 0;
3127
+ const record = readToken(context);
3128
+ return record && tokenValid(record) ? toCredential(record) : void 0;
3129
+ }
3130
+ function outcomeFromState(state) {
3131
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
3132
+ return {
3133
+ status: "link_required",
3134
+ githubLogin: state.githubLogin,
3135
+ challengeId: state.challengeId,
3136
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
3137
+ };
3138
+ return failure(
3139
+ state.code,
3140
+ state.cause ?? "the last identity check failed",
3141
+ state.remedy ?? RETRY_REMEDY
3142
+ );
3143
+ }
3144
+ function parseInstant(value) {
3145
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
3146
+ if (typeof value === "string" && value.length <= 64) {
3147
+ const parsed = Date.parse(value);
3148
+ return Number.isFinite(parsed) ? parsed : void 0;
3149
+ }
3150
+ return void 0;
3151
+ }
3152
+ async function sendJson(url, init, fetchImpl) {
3153
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
3154
+ let value;
3155
+ try {
3156
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
3157
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
3158
+ } catch {
3159
+ value = void 0;
3160
+ }
3161
+ return { status: response.status, value };
3162
+ }
3163
+ function environmentOnly(deps) {
3164
+ return { ...deps, environmentOnly: true };
3165
+ }
3166
+ async function environmentRequest(method, path, body, deps, signal) {
3167
+ const send = async (credential2) => {
3168
+ const headers = { "Content-Type": "application/json" };
3169
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
3170
+ if (credential2.tokenInjection) {
3171
+ const response = await forwardMachineRequest(
3172
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
3173
+ signal,
3174
+ environmentOnly(deps)
3175
+ );
3176
+ const parsed = await response.json().catch(() => void 0);
3177
+ return {
3178
+ status: response.status,
3179
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
3180
+ };
3181
+ }
3182
+ return sendJson(
3183
+ `${credential2.apiUrl}${path}`,
3184
+ {
3185
+ method,
3186
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
3187
+ ...text === void 0 ? {} : { body: text },
3188
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS4)
3189
+ },
3190
+ deps.fetch ?? fetch
3191
+ );
3192
+ };
3193
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
3194
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
3195
+ let answer = await send(credential);
3196
+ if (answer.status === 401) {
3197
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
3198
+ if (!credential)
3199
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
3200
+ answer = await send(credential);
3201
+ }
3202
+ return answer;
3203
+ }
3204
+ function environmentFailure(error, apiUrl) {
3205
+ if (error instanceof MachineAuthError && error.terminal)
3206
+ return failure(
3207
+ "environment_credential_rejected",
3208
+ "Primitive rejected the cloud environment's credential",
3209
+ ENVIRONMENT_CREDENTIAL_REMEDY
3210
+ );
3211
+ const host = (() => {
3212
+ try {
3213
+ return new URL(apiUrl).hostname;
3214
+ } catch {
3215
+ return "Primitive";
3216
+ }
3217
+ })();
3218
+ return failure(
3219
+ "identity_unavailable",
3220
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
3221
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
3222
+ );
3223
+ }
3224
+ function answerError(answer) {
3225
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
3226
+ }
3227
+ async function git2(root, args, signal) {
3228
+ try {
3229
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
3230
+ cwd: root,
3231
+ encoding: "utf8",
3232
+ timeout: GIT_TIMEOUT_MS4,
3233
+ signal,
3234
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
3235
+ maxBuffer: 1024 * 1024
3236
+ });
3237
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
3238
+ } catch (error) {
3239
+ const failed = error;
3240
+ return {
3241
+ ok: false,
3242
+ code: typeof failed.code === "number" ? failed.code : void 0,
3243
+ stdout: failed.stdout ?? "",
3244
+ stderr: failed.stderr ?? "",
3245
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
3246
+ };
3247
+ }
3248
+ }
3249
+ function gitDetail(stderr) {
3250
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
3251
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
3252
+ }
3253
+ async function defaultSleep3(milliseconds, signal) {
3254
+ await new Promise((resolve2, reject) => {
3255
+ const timer = setTimeout(resolve2, milliseconds);
3256
+ signal?.addEventListener(
3257
+ "abort",
3258
+ () => {
3259
+ clearTimeout(timer);
3260
+ reject(signal.reason);
3261
+ },
3262
+ { once: true }
3263
+ );
3264
+ });
3265
+ }
3266
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
3267
+ const sleep = deps.sleep ?? defaultSleep3;
3268
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
3269
+ let delay = POLL_FIRST_DELAY_MS;
3270
+ let unreachable;
3271
+ for (; ; ) {
3272
+ const remaining = deadline - Date.now();
3273
+ if (remaining <= 0) break;
3274
+ await sleep(Math.min(delay, remaining), signal);
3275
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
3276
+ let answer;
3277
+ try {
3278
+ answer = await environmentRequest(
3279
+ "GET",
3280
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
3281
+ void 0,
3282
+ deps,
3283
+ signal
3284
+ );
3285
+ } catch (error) {
3286
+ signal?.throwIfAborted();
3287
+ unreachable = error;
3288
+ continue;
3289
+ }
3290
+ if (answer.status === 404) return CHALLENGE_GONE;
3291
+ if (answer.status === 401 || answer.status === 403)
3292
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
3293
+ if (answer.status < 200 || answer.status > 299) {
3294
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
3295
+ continue;
3296
+ }
3297
+ unreachable = void 0;
3298
+ const status = answer.value;
3299
+ if (status?.status === "verified")
3300
+ return {
3301
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
3302
+ };
3303
+ if (status?.status === "expired")
3304
+ return failure(
3305
+ "challenge_expired",
3306
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
3307
+ NEW_SESSION_REMEDY
3308
+ );
3309
+ if (status?.status === "rejected")
3310
+ return rejectionFailure(status.reason, repository);
3311
+ }
3312
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
3313
+ return failure(
3314
+ "webhook_timeout",
3315
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
3316
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
3317
+ );
3318
+ }
3319
+ function parseTokenAnswer(value) {
3320
+ if (!value) return void 0;
3321
+ const user = value.user;
3322
+ const expiresAt = parseInstant(value.expiresAt);
3323
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
3324
+ if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
3325
+ return void 0;
3326
+ return {
3327
+ accessToken: value.accessToken,
3328
+ expiresAt,
3329
+ refreshAfter: Math.min(refreshAfter, expiresAt),
3330
+ userId: user.id,
3331
+ displayName: user.displayName,
3332
+ organizationId: value.organizationId
3333
+ };
3334
+ }
3335
+ var SERVER_CONTRACT_FAILURE = failure(
3336
+ "server_contract",
3337
+ "Primitive's answer did not identify the linked member",
3338
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
3339
+ );
3340
+ async function recordFor(context, answer, extra, deps, signal) {
3341
+ let identity;
3342
+ let environment;
3343
+ try {
3344
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
3345
+ identity = await verifyMachineIdentity(
3346
+ context.apiUrl,
3347
+ answer.accessToken,
3348
+ context.clientId,
3349
+ signal,
3350
+ deps.fetch
3351
+ );
3352
+ } catch (error) {
3353
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
3354
+ return SERVER_CONTRACT_FAILURE;
3355
+ return environmentFailure(error, context.apiUrl);
3356
+ }
3357
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
3358
+ return SERVER_CONTRACT_FAILURE;
3359
+ return {
3360
+ version: 1,
3361
+ apiUrl: context.apiUrl,
3362
+ clientId: context.clientId,
3363
+ generation: context.generation,
3364
+ sessionId: context.sessionId,
3365
+ issuer: environment.issuer,
3366
+ audience: environment.audience,
3367
+ accessToken: answer.accessToken,
3368
+ expiresAt: answer.expiresAt,
3369
+ refreshAfter: answer.refreshAfter,
3370
+ userId: answer.userId,
3371
+ displayName: answer.displayName,
3372
+ organizationId: answer.organizationId,
3373
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
3374
+ identity,
3375
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
3376
+ };
3377
+ }
3378
+ async function refreshToken(context, record, deps, signal) {
3379
+ let answer;
3380
+ try {
3381
+ answer = await environmentRequest(
3382
+ "POST",
3383
+ SESSION_IDENTITY_ROUTES.refresh,
3384
+ { accessToken: record.accessToken },
3385
+ deps,
3386
+ signal
3387
+ );
3388
+ } catch (error) {
3389
+ signal?.throwIfAborted();
3390
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
3391
+ }
3392
+ const code = answerError(answer);
3393
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
3394
+ return { status: "refused", failure: SESSION_REVOKED };
3395
+ if (answer.status === 401 || answer.status === 403)
3396
+ return {
3397
+ status: "refused",
3398
+ failure: environmentFailure(
3399
+ new MachineAuthError("rejected", "rejected", true),
3400
+ context.apiUrl
3401
+ )
3402
+ };
3403
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
3404
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
3405
+ return { status: "unavailable" };
3406
+ return {
3407
+ status: "ok",
3408
+ record: {
3409
+ ...record,
3410
+ accessToken: token.accessToken,
3411
+ expiresAt: token.expiresAt,
3412
+ refreshAfter: token.refreshAfter,
3413
+ displayName: token.displayName
3414
+ }
3415
+ };
3416
+ }
3417
+ function exchangeRefusal(answer, repository) {
3418
+ if (answer.status === 404) return CHALLENGE_GONE;
3419
+ if (answer.status !== 409) return void 0;
3420
+ switch (answerError(answer)) {
3421
+ case "identity_mismatch":
3422
+ return rejectionFailure("identity_mismatch", repository);
3423
+ case "challenge_rejected":
3424
+ return rejectionFailure(answer.value?.reason, repository);
3425
+ case "challenge_expired":
3426
+ return CHALLENGE_WINDOW_PASSED;
3427
+ case "challenge_already_exchanged":
3428
+ return failure(
3429
+ "challenge_already_exchanged",
3430
+ "this session's identity check was already exchanged for a token this VM does not hold",
3431
+ NEW_SESSION_REMEDY
3432
+ );
3433
+ case "challenge_pending":
3434
+ return failure(
3435
+ "webhook_timeout",
3436
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
3437
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
3438
+ );
3439
+ default:
3440
+ return void 0;
3441
+ }
3442
+ }
3443
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
3444
+ let answer;
3445
+ try {
3446
+ answer = await environmentRequest(
3447
+ "POST",
3448
+ SESSION_IDENTITY_ROUTES.token,
3449
+ { challengeId: challenge.challengeId },
3450
+ deps,
3451
+ signal
3452
+ );
3453
+ } catch (error) {
3454
+ signal?.throwIfAborted();
3455
+ return environmentFailure(error, context.apiUrl);
3456
+ }
3457
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
3458
+ const login = answer.value?.githubLogin;
3459
+ return {
3460
+ status: "link_required",
3461
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
3462
+ challengeId: challenge.challengeId,
3463
+ challengeExpiresAt: challenge.challengeExpiresAt
3464
+ };
3465
+ }
3466
+ const refused = exchangeRefusal(
3467
+ answer,
3468
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
3469
+ );
3470
+ if (refused) return refused;
3471
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
3472
+ if (!token) {
3473
+ if (answer.status === 401 || answer.status === 403)
3474
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
3475
+ return answer.status >= 500 ? environmentFailure(
3476
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
3477
+ context.apiUrl
3478
+ ) : SERVER_CONTRACT_FAILURE;
3479
+ }
3480
+ return recordFor(
3481
+ context,
3482
+ token,
3483
+ { githubLogin: challenge.githubLogin, repositoryRoot },
3484
+ deps,
3485
+ signal
3486
+ );
3487
+ }
3488
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
3489
+ const env = deps.env ?? process.env;
3490
+ const repository = githubRepositoryFullName(root);
3491
+ if (!repository)
3492
+ return failure(
3493
+ "repository_unidentified",
3494
+ "this checkout does not name its GitHub repository",
3495
+ "run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
3496
+ );
3497
+ const branch = currentBranch(root);
3498
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
3499
+ return failure(
3500
+ "not_session_branch",
3501
+ `this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
3502
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
3503
+ );
3504
+ attempt.branch = branch;
3505
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
3506
+ if (!baseSha) {
3507
+ const head = await git2(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
3508
+ baseSha = head.stdout.trim();
3509
+ if (!head.ok || !SHA.test(baseSha))
3510
+ return failure(
3511
+ "no_commit",
3512
+ "this checkout has no commit to create the session branch at",
3513
+ NEW_SESSION_REMEDY
3514
+ );
3515
+ }
3516
+ const published = await git2(
3517
+ root,
3518
+ [
3519
+ "for-each-ref",
3520
+ "--count=1",
3521
+ "--format=%(refname)",
3522
+ "--contains",
3523
+ baseSha,
3524
+ "refs/remotes/origin/"
3525
+ ],
3526
+ signal
3527
+ );
3528
+ if (!published.ok || published.stdout.trim() === "")
3529
+ return failure(
3530
+ "unpublished_commits",
3531
+ `this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
3532
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
3533
+ );
3534
+ attempt.baseSha = baseSha;
3535
+ const remote = await git2(
3536
+ root,
3537
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
3538
+ signal
3539
+ );
3540
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
3541
+ if (remote.ok && recorded) {
3542
+ Object.assign(attempt, recorded);
3543
+ return { ...recorded, repository };
3544
+ }
3545
+ if (remote.ok)
3546
+ return failure(
3547
+ "branch_exists",
3548
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
3549
+ NEW_SESSION_REMEDY
3550
+ );
3551
+ if (remote.code !== 2)
3552
+ return failure(
3553
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
3554
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
3555
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
3556
+ );
3557
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
3558
+ Object.assign(attempt, recorded);
3559
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
3560
+ }
3561
+ let answer;
3562
+ try {
3563
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
3564
+ answer = await environmentRequest(
3565
+ "POST",
3566
+ SESSION_IDENTITY_ROUTES.challenge,
3567
+ {
3568
+ repositoryFullName: repository,
3569
+ claudeSessionId: context.sessionId,
3570
+ branch,
3571
+ baseSha,
3572
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
3573
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
3574
+ },
3575
+ deps,
3576
+ signal
3577
+ );
3578
+ } catch (error) {
3579
+ signal?.throwIfAborted();
3580
+ return environmentFailure(error, context.apiUrl);
3581
+ }
3582
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
3583
+ return failure(
3584
+ "repository_not_connected",
3585
+ `${repository} is not connected to Primitive`,
3586
+ CLOUD_GITHUB_CONNECT_REMEDY
3587
+ );
3588
+ if (answer.status === 401 || answer.status === 403)
3589
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
3590
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
3591
+ return failure(
3592
+ "challenge_open",
3593
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
3594
+ `wait five minutes, then ${RETRY_REMEDY}`
3595
+ );
3596
+ if (answer.status === 429)
3597
+ return failure(
3598
+ "too_many_challenges",
3599
+ "too many sessions of this cloud environment are being identified at once",
3600
+ `wait a few minutes, then ${RETRY_REMEDY}`
3601
+ );
3602
+ const challengeId = answer.value?.challengeId;
3603
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
3604
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
3605
+ return answer.status >= 500 ? environmentFailure(
3606
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
3607
+ context.apiUrl
3608
+ ) : SERVER_CONTRACT_FAILURE;
3609
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
3610
+ attempt.challengeId = challengeId;
3611
+ attempt.challengeExpiresAt = challengeExpiresAt;
3612
+ return pushSessionBranch(
3613
+ root,
3614
+ repository,
3615
+ branch,
3616
+ baseSha,
3617
+ { challengeId, challengeExpiresAt },
3618
+ signal
3619
+ );
3620
+ }
3621
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
3622
+ const push = await git2(
3623
+ root,
3624
+ [
3625
+ "-c",
3626
+ "core.hooksPath=/dev/null",
3627
+ "-c",
3628
+ "push.followTags=false",
3629
+ "-c",
3630
+ "push.recurseSubmodules=no",
3631
+ "-c",
3632
+ "push.gpgSign=false",
3633
+ "-c",
3634
+ "push.pushOption=",
3635
+ "push",
3636
+ "--no-verify",
3637
+ "--no-follow-tags",
3638
+ "--no-recurse-submodules",
3639
+ "--no-signed",
3640
+ "--quiet",
3641
+ "origin",
3642
+ `${baseSha}:refs/heads/${branch}`
3643
+ ],
3644
+ signal
3645
+ );
3646
+ if (!push.ok)
3647
+ return push.timedOut ? failure(
3648
+ "push_timeout",
3649
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS4 / 1e3} s`,
3650
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
3651
+ ) : failure(
3652
+ "push_refused",
3653
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
3654
+ `check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
3655
+ );
3656
+ return { ...challenge, repository };
3657
+ }
3658
+ async function ensureSessionIdentity(options = {}, deps = {}) {
3659
+ let context;
3660
+ try {
3661
+ context = sessionContext(deps);
3662
+ } catch (error) {
3663
+ return failure(
3664
+ "environment_credential_invalid",
3665
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
3666
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
3667
+ );
3668
+ }
3669
+ if ("status" in context) return context;
3670
+ const ctx = context;
3671
+ const startedAt = Date.now();
3672
+ prepareMachineMetadataDirectory(ctx.directory);
3673
+ return withFileLock(
3674
+ ctx.lockPath,
3675
+ async () => {
3676
+ const record = readToken(ctx);
3677
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
3678
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
3679
+ if (record) {
3680
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
3681
+ if (refreshed.status === "ok") {
3682
+ writeToken(ctx, refreshed.record);
3683
+ return identified(refreshed.record, true);
3684
+ }
3685
+ if (refreshed.status === "refused") {
3686
+ rmSync7(ctx.tokenPath, { force: true });
3687
+ writeState(ctx, {
3688
+ sessionId: ctx.sessionId,
3689
+ status: "failed",
3690
+ code: refreshed.failure.code,
3691
+ cause: refreshed.failure.cause,
3692
+ remedy: refreshed.failure.remedy,
3693
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
3694
+ at: Date.now()
3695
+ });
3696
+ return refreshed.failure;
3697
+ }
3698
+ if (!forced && tokenValid(record)) return identified(record, true);
3699
+ }
3700
+ const state = readState(ctx);
3701
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
3702
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
3703
+ if (!options.explicit) {
3704
+ if (!root || !(record || state))
3705
+ return failure(
3706
+ "not_identified",
3707
+ "this session has not identified who started it yet",
3708
+ RETRY_REMEDY
3709
+ );
3710
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
3711
+ } else if (state && state.at >= startedAt) {
3712
+ return outcomeFromState(state);
3713
+ }
3714
+ if (!root)
3715
+ return failure(
3716
+ "repository_missing",
3717
+ "this is not a git repository",
3718
+ "run it in the repository the session cloned"
3719
+ );
3720
+ const attempt = { root };
3721
+ const remember = (outcome) => {
3722
+ writeState(ctx, {
3723
+ sessionId: ctx.sessionId,
3724
+ status: outcome.status,
3725
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
3726
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
3727
+ githubLogin: outcome.githubLogin
3728
+ },
3729
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
3730
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
3731
+ repositoryRoot: root,
3732
+ branch: attempt.branch ?? state?.branch,
3733
+ baseSha: attempt.baseSha ?? state?.baseSha,
3734
+ at: Date.now()
3735
+ });
3736
+ return outcome;
3737
+ };
3738
+ let challenge;
3739
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
3740
+ attempt.challengeId = state.challengeId;
3741
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
3742
+ attempt.branch = state.branch;
3743
+ attempt.baseSha = state.baseSha;
3744
+ challenge = {
3745
+ challengeId: state.challengeId,
3746
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
3747
+ repository: githubRepositoryFullName(root) ?? "the repository"
3748
+ };
3749
+ } else if (state?.status === "link_required" && state.challengeId) {
3750
+ attempt.challengeId = state.challengeId;
3751
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
3752
+ const exchanged2 = await exchangeChallenge(
3753
+ ctx,
3754
+ {
3755
+ challengeId: state.challengeId,
3756
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
3757
+ githubLogin: state.githubLogin
3758
+ },
3759
+ root,
3760
+ deps,
3761
+ options.signal
3762
+ );
3763
+ if ("status" in exchanged2) return remember(exchanged2);
3764
+ writeToken(ctx, exchanged2);
3765
+ return identified(exchanged2, false);
3766
+ } else if (!options.explicit) {
3767
+ return state ? outcomeFromState(state) : failure(
3768
+ "not_identified",
3769
+ "this session has not identified who started it yet",
3770
+ RETRY_REMEDY
3771
+ );
3772
+ } else {
3773
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
3774
+ if ("status" in pushed) return remember(pushed);
3775
+ challenge = pushed;
3776
+ }
3777
+ const verified = await pollChallenge(
3778
+ ctx.apiUrl,
3779
+ challenge.challengeId,
3780
+ challenge.repository,
3781
+ // A hook process waits only briefly for a late notice.
3782
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
3783
+ options.signal
3784
+ );
3785
+ if ("status" in verified) return remember(verified);
3786
+ const exchanged = await exchangeChallenge(
3787
+ ctx,
3788
+ { ...challenge, githubLogin: verified.githubLogin },
3789
+ root,
3790
+ deps,
3791
+ options.signal
3792
+ );
3793
+ if ("status" in exchanged) return remember(exchanged);
3794
+ writeToken(ctx, exchanged);
3795
+ return identified(exchanged, false);
3796
+ },
3797
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
3798
+ );
3799
+ }
3800
+ async function acquireSessionCredential(options = {}, deps = {}) {
3801
+ const cached2 = cachedSessionCredential(deps);
3802
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
3803
+ if (cached2 && fresh && !options.force) return cached2;
3804
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
3805
+ let outcome;
3806
+ try {
3807
+ outcome = await ensureSessionIdentity(
3808
+ { force: options.force, observedToken: cached2?.accessToken, signal },
3809
+ deps
3810
+ );
3811
+ } catch (error) {
3812
+ options.signal?.throwIfAborted();
3813
+ if (error instanceof MachineAuthError) throw error;
3814
+ throw new MachineAuthError(
3815
+ "identity_unavailable",
3816
+ "Identifying who started this cloud session is still in progress; retry shortly."
3817
+ );
3818
+ }
3819
+ if (outcome.status === "ok") return outcome.credential;
3820
+ throw new MachineAuthError(
3821
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
3822
+ sessionIdentityMessage(outcome)
3823
+ );
3824
+ }
3825
+ function linkRefusal(answer, githubLogin) {
3826
+ const login = (value) => machineString(value, 64) ? terminalSafeLine(value) : void 0;
3827
+ switch (answerError(answer)) {
3828
+ case "member_already_linked": {
3829
+ const current = login(answer.value?.linkedGithubLogin) ?? login(answer.value?.currentGithubLogin) ?? login(answer.value?.githubLogin);
3830
+ return failure(
3831
+ "member_already_linked",
3832
+ `your Primitive account is already linked to ${current ? `GitHub account @${current}` : "another GitHub account"}, and Primitive links one GitHub account per member`,
3833
+ `remove that link in Primitive's settings first, then run \`prim auth link\` again (in a new cloud session if this one has passed its 30 minutes)`
3834
+ );
3835
+ }
3836
+ case "github_account_linked_to_another_member":
3837
+ return failure(
3838
+ "github_account_linked_to_another_member",
3839
+ `GitHub account @${githubLogin} is already linked to another member of this organization`,
3840
+ `sign in as the member it is linked to; if that link is wrong, ask an organization admin to remove it in Primitive's settings, then ${NEW_SESSION_REMEDY}`
3841
+ );
3842
+ case "identity_mismatch":
3843
+ return failure(
3844
+ "identity_mismatch",
3845
+ "the person who signed in is a different Primitive member than the one signed in to Claude for this session, so Primitive refused the link and attributes this session to no one",
3846
+ `${NEW_SESSION_REMEDY}, and when \`prim auth link\` asks, sign in as yourself`
3847
+ );
3848
+ case "challenge_expired":
3849
+ return CHALLENGE_WINDOW_PASSED;
3850
+ case "challenge_not_found":
3851
+ case "challenge_not_verified":
3852
+ return failure(
3853
+ "link_failed",
3854
+ "this session's identity check can no longer be linked",
3855
+ `${NEW_SESSION_REMEDY} and run \`prim auth link\` there as soon as it asks`
3856
+ );
3857
+ default:
3858
+ return void 0;
3859
+ }
3860
+ }
3861
+ async function linkSessionIdentity(challenge, humanAccessToken, options = {}, deps = {}) {
3862
+ const context = sessionContext(deps);
3863
+ if ("status" in context) return context;
3864
+ let answer;
3865
+ try {
3866
+ answer = await sendJson(
3867
+ `${context.apiUrl}${SESSION_IDENTITY_ROUTES.link}`,
3868
+ {
3869
+ method: "POST",
3870
+ headers: {
3871
+ Authorization: `Bearer ${humanAccessToken}`,
3872
+ "Content-Type": "application/json"
3873
+ },
3874
+ body: JSON.stringify({ challengeId: challenge.challengeId }),
3875
+ signal: options.signal ?? AbortSignal.timeout(3e4)
3876
+ },
3877
+ deps.fetch ?? fetch
3878
+ );
3879
+ } catch (error) {
3880
+ options.signal?.throwIfAborted();
3881
+ return environmentFailure(error, context.apiUrl);
3882
+ }
3883
+ if (answer.status !== 200 || answer.value?.linked !== true) {
3884
+ const code = answerError(answer);
3885
+ const refused = linkRefusal(answer, challenge.githubLogin);
3886
+ if (refused) return refused;
3887
+ return failure(
3888
+ "link_failed",
3889
+ `Primitive did not link GitHub account @${challenge.githubLogin}${code ? ` (${terminalSafeLine(code).slice(0, 120)})` : ` (HTTP ${answer.status})`}`,
3890
+ answer.status === 401 || answer.status === 403 ? "sign in as a member of the organization that owns this environment and run `prim auth link` again" : `${NEW_SESSION_REMEDY} and run \`prim auth link\` there as soon as it asks`
3891
+ );
3892
+ }
3893
+ const linkedLogin = machineString(answer.value.githubLogin, 64) ? answer.value.githubLogin : challenge.githubLogin;
3894
+ const root = options.cwd ? gitToplevel(options.cwd) ?? void 0 : void 0;
3895
+ return withFileLock(
3896
+ context.lockPath,
3897
+ async () => {
3898
+ const exchanged = await exchangeChallenge(
3899
+ context,
3900
+ { ...challenge, githubLogin: linkedLogin },
3901
+ root ?? readState(context)?.repositoryRoot,
3902
+ deps,
3903
+ options.signal
3904
+ );
3905
+ if ("status" in exchanged) {
3906
+ if (exchanged.status === "link_required")
3907
+ return failure(
3908
+ "link_failed",
3909
+ `Primitive linked GitHub account @${linkedLogin} but still refused this session's token`,
3910
+ `${NEW_SESSION_REMEDY}; it should identify you automatically`
3911
+ );
3912
+ return exchanged;
3913
+ }
3914
+ writeToken(context, exchanged);
3915
+ return identified(exchanged, false);
3916
+ },
3917
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
3918
+ );
3919
+ }
3920
+
2255
3921
  // src/lib/credentials.ts
2256
- import { createHash as createHash5 } from "crypto";
2257
- import { readFileSync as readFileSync7 } from "fs";
2258
- import { join as join8 } from "path";
3922
+ import { createHash as createHash6 } from "crypto";
3923
+ import { readFileSync as readFileSync9 } from "fs";
3924
+ import { join as join11 } from "path";
2259
3925
  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");
3926
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
3927
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
3928
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
3929
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
3930
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
3931
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
3932
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
3933
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
2268
3934
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
2269
3935
  var CREDENTIAL_MIGRATION_VERSION = 1;
2270
3936
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
2271
3937
  function readTrimmed(path) {
2272
3938
  try {
2273
- const value = readFileSync7(path, "utf8").trim();
3939
+ const value = readFileSync9(path, "utf8").trim();
2274
3940
  return value || void 0;
2275
3941
  } catch {
2276
3942
  return void 0;
@@ -2279,7 +3945,7 @@ function readTrimmed(path) {
2279
3945
  function resolveAuthCredential(options = {}) {
2280
3946
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
2281
3947
  const machine = cachedMachineCredential({ env: options.env });
2282
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
3948
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
2283
3949
  }
2284
3950
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
2285
3951
  if (envToken) return { token: envToken, source: "environment" };
@@ -2292,22 +3958,33 @@ function resolveAuthCredential(options = {}) {
2292
3958
  );
2293
3959
  if (metadata.state === "legacy_broker") {
2294
3960
  if (metadata.metadata) {
2295
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2296
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3961
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3962
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
2297
3963
  return void 0;
2298
3964
  }
2299
3965
  }
2300
3966
  return { token: stored, source: "token_file" };
2301
3967
  }
2302
3968
  if (metadata.state === "invalid") return void 0;
2303
- const refreshToken = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2304
- if (!refreshToken || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken)) {
3969
+ const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3970
+ if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
2305
3971
  return void 0;
2306
3972
  }
2307
3973
  return { token: stored, source: "token_file" };
2308
3974
  }
3975
+ function resolveStoredCredential(env = process.env) {
3976
+ const directory = primConfigDirectory({ env });
3977
+ return resolveAuthCredential({
3978
+ env,
3979
+ tokenFilePath: join11(directory, "token"),
3980
+ refreshTokenPath: join11(directory, "refresh_token"),
3981
+ metadataPath: join11(directory, "credential_metadata.json"),
3982
+ familyPath: join11(directory, "credential_family.json"),
3983
+ migrationPath: join11(directory, "credential_migration.json")
3984
+ });
3985
+ }
2309
3986
  function credentialFingerprint(value) {
2310
- return createHash5("sha256").update(value).digest("hex");
3987
+ return createHash6("sha256").update(value).digest("hex");
2311
3988
  }
2312
3989
  function parseLegacyBrokerCredentialMetadata(value) {
2313
3990
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -2327,7 +4004,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
2327
4004
  function readBoundedCredentialJson(path) {
2328
4005
  let raw;
2329
4006
  try {
2330
- raw = readFileSync7(path, "utf8");
4007
+ raw = readFileSync9(path, "utf8");
2331
4008
  } catch (error) {
2332
4009
  return error.code === "ENOENT" ? void 0 : null;
2333
4010
  }
@@ -2421,10 +4098,18 @@ export {
2421
4098
  pinnedHookCommand,
2422
4099
  PRIM_CONFIG_SHELL_RESOLVER,
2423
4100
  stableHookCommand,
4101
+ quietWithoutLauncher,
2424
4102
  detachedHookShimCommand,
2425
4103
  commandMatchesBin,
2426
4104
  hookCommandResolution,
2427
4105
  hookCommandResolutions,
4106
+ isClaudeCloudSession,
4107
+ insideClaudeCode,
4108
+ CLOUD_CREDENTIALS_REMEDY,
4109
+ CLOUD_REJECTED_CREDENTIALS_NOTICE,
4110
+ CLOUD_GITHUB_CONNECT_REMEDY,
4111
+ cloudSetupPointer,
4112
+ CLOUD_SETUP_POINTER,
2428
4113
  WORKOS_CONNECT_RESPONSE_MAX_BYTES,
2429
4114
  WorkosConnectProtocolError,
2430
4115
  readBoundedJson,
@@ -2437,11 +4122,39 @@ export {
2437
4122
  machineString,
2438
4123
  machineRecord,
2439
4124
  machineApiUrl,
4125
+ rejectedCredentialsMessage,
2440
4126
  discoverMachineConfiguration,
4127
+ exchangeMachineCredentials,
2441
4128
  parseMachineIdentity,
2442
4129
  verifyMachineIdentity,
2443
4130
  primConfigDirectory,
4131
+ clearMachineCooldowns,
4132
+ SERVER_WAIT_PREFIX,
4133
+ gitToplevel,
4134
+ mainWorktreeRoot,
4135
+ currentBranch,
4136
+ parseGithubRepositoryName,
4137
+ originIdentifiesRepository,
4138
+ originGithubRepository,
4139
+ isGitIgnored,
4140
+ githubRepositoryFullName,
4141
+ canonicalGitRoot,
4142
+ relatedWorktreeTarget,
4143
+ resolveRepositoryContext,
4144
+ canonicalRepositoryPath,
4145
+ terminalSafeText,
4146
+ terminalSafeLine,
4147
+ isTerminalSafeText,
4148
+ stripControlChars,
4149
+ SESSION_IDENTITY_VARIABLE,
4150
+ SESSION_IDENTITY_VALUE,
4151
+ sessionIdentityMode,
4152
+ ENVIRONMENT_CREDENTIAL_REMEDY,
4153
+ sessionIdentityMessage,
4154
+ ensureSessionIdentity,
4155
+ linkSessionIdentity,
2444
4156
  readMachineProfile,
4157
+ NETWORK_TOKEN_AUTH,
2445
4158
  environmentCredentials,
2446
4159
  hasMachineConfiguration,
2447
4160
  machineContext,
@@ -2449,9 +4162,13 @@ export {
2449
4162
  machineSessionEnded,
2450
4163
  configureMachine,
2451
4164
  acquireMachineCredential,
4165
+ forwardMachineRequest,
4166
+ verifyAcquiredMachineIdentity,
2452
4167
  clearMachineCredentials,
2453
4168
  machineCaptureActor,
2454
4169
  machineJournalBucket,
4170
+ identityPending,
4171
+ machinePendingBucket,
2455
4172
  prepareMachineMetadataDirectory,
2456
4173
  writeMachineMetadata,
2457
4174
  TOKEN_FILE_PATH,
@@ -2465,25 +4182,23 @@ export {
2465
4182
  CREDENTIAL_MIGRATION_VERSION,
2466
4183
  CREDENTIAL_MIGRATION_STATE,
2467
4184
  resolveAuthCredential,
4185
+ resolveStoredCredential,
2468
4186
  readCredentialMigrationState,
2469
4187
  readStoredCredentialMetadata,
2470
4188
  decodeJwtPayload,
2471
4189
  jwtExpiresAt,
2472
4190
  jwtOrganizationId,
4191
+ markCloudPrepared,
4192
+ preparedInSession,
4193
+ clearCloudPrepared,
4194
+ isPreparedCloudSession,
2473
4195
  readDemoPause,
2474
4196
  pauseCaptureForDemo,
2475
4197
  extendDemoPause,
2476
4198
  endDemoPause,
2477
4199
  clearDemoPause,
2478
4200
  healDemoPause,
2479
- gitToplevel,
2480
- mainWorktreeRoot,
2481
- currentBranch,
2482
- githubRepositoryFullName,
2483
- canonicalGitRoot,
2484
- relatedWorktreeTarget,
2485
- resolveRepositoryContext,
2486
- canonicalRepositoryPath,
4201
+ PRIM_ACTIVE_DECLARATION,
2487
4202
  repoActiveFlag,
2488
4203
  setRepoActive,
2489
4204
  isValidRepoSyncId,
@@ -2493,6 +4208,12 @@ export {
2493
4208
  setRepoSyncId,
2494
4209
  setRepositoryBindingState,
2495
4210
  repositoryBindingState,
4211
+ hasProjectPrimInstall,
4212
+ declaresInactive,
4213
+ markActivationImplicit,
4214
+ markActivationExplicit,
4215
+ explicitlyActive,
4216
+ withdrawImplicitActivation,
2496
4217
  isRepoActiveForCapture,
2497
4218
  decisionIngestionStatus
2498
4219
  };