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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +140 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
  4. package/dist/{chunk-R6NDP7OF.js → chunk-A5VTE43F.js} +2 -2
  5. package/dist/{chunk-C5VBPHOS.js → chunk-C4QNBSWB.js} +20 -6
  6. package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
  7. package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
  8. package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
  9. package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
  10. package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
  11. package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
  12. package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
  13. package/dist/{chunk-KKUDAQQZ.js → chunk-MGKSZSTV.js} +3 -3
  14. package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
  15. package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
  16. package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
  17. package/dist/{chunk-5D2C6RCH.js → chunk-RV3JFSMX.js} +4 -4
  18. package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
  19. package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
  20. package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
  21. package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
  22. package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
  23. package/dist/daemon/server.js +805 -218
  24. package/dist/hook-runtime/daemon/server.js +805 -218
  25. package/dist/hook-runtime/hooks/post-commit.js +286 -59
  26. package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
  27. package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
  28. package/dist/hook-runtime/hooks/pre-commit.js +536 -88
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +608 -157
  30. package/dist/hook-runtime/hooks/prim-hook.js +642 -167
  31. package/dist/hook-runtime/hooks/session-end.js +263 -47
  32. package/dist/hook-runtime/hooks/session-start.js +1103 -476
  33. package/dist/hook-runtime/index.js +3645 -2120
  34. package/dist/hook-runtime/statusline-main.js +257 -29
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +15 -15
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +49 -18
  43. package/dist/index.js +1014 -271
  44. package/dist/statusline-main.js +257 -29
  45. package/package.json +1 -1
@@ -116,6 +116,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
116
116
  '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; ',
117
117
  "fi; fi; "
118
118
  ].join("");
119
+ var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
119
120
  function stableHookCommand(bin, args = "") {
120
121
  if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
121
122
  throw new Error("invalid stable hook command");
@@ -127,7 +128,7 @@ function stableHookCommand(bin, args = "") {
127
128
  `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
128
129
  PRIM_CONFIG_SHELL_RESOLVER,
129
130
  `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
130
- 'exec "$prim_launcher" "$@"'
131
+ LAUNCHER_EXEC
131
132
  ].join("");
132
133
  const suffix = args ? ` ${args}` : "";
133
134
  return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
@@ -27402,10 +27403,25 @@ function observeDemoInvocation(envelope, agent2, checkExclusion = true) {
27402
27403
 
27403
27404
  // src/lib/activation.ts
27404
27405
  import { execFileSync as execFileSync3 } from "child_process";
27405
- import { existsSync as existsSync8, readFileSync as readFileSync5 } from "fs";
27406
+ import { existsSync as existsSync9, readFileSync as readFileSync7 } from "fs";
27406
27407
  import { homedir as homedir2 } from "os";
27408
+ import { join as join10 } from "path";
27409
+
27410
+ // src/lib/cloud-prepared.ts
27411
+ import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync5, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
27407
27412
  import { join as join8 } from "path";
27408
27413
 
27414
+ // src/lib/cloud-env.ts
27415
+ function isClaudeCloudSession(env = process.env) {
27416
+ return env.CLAUDE_CODE_REMOTE === "true";
27417
+ }
27418
+ 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';
27419
+ 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';
27420
+ function cloudSetupPointer(message, env = process.env) {
27421
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
27422
+ }
27423
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
27424
+
27409
27425
  // src/lib/demo-pause.ts
27410
27426
  import { execFileSync } from "child_process";
27411
27427
  var DEMO_PAUSE_MS = 30 * 6e4;
@@ -27413,11 +27429,12 @@ var DEMO_PAUSE_MS = 30 * 6e4;
27413
27429
  // src/lib/git.ts
27414
27430
  import { execFileSync as execFileSync2 } from "child_process";
27415
27431
  import { createHash as createHash3 } from "crypto";
27416
- import { lstatSync as lstatSync3, realpathSync as realpathSync2 } from "fs";
27417
- import { basename, dirname as dirname6, isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "path";
27432
+ import { lstatSync as lstatSync3, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
27433
+ import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join9, relative, resolve as resolve3, sep } from "path";
27418
27434
  var GIT_TIMEOUT_MS = 1e3;
27435
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
27419
27436
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
27420
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
27437
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
27421
27438
  function gitToplevel(cwd) {
27422
27439
  try {
27423
27440
  return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
@@ -27446,19 +27463,57 @@ function gitValue(cwd, args) {
27446
27463
  function currentBranch(cwd) {
27447
27464
  return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
27448
27465
  }
27449
- function githubRepositoryFullName(cwd) {
27450
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
27451
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
27466
+ function parseGithubRepositoryName(path) {
27467
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
27468
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
27469
+ return null;
27470
+ }
27471
+ return `${parts[0]}/${parts[1]}`;
27472
+ }
27473
+ function githubRepositoryFromRemote(remote) {
27474
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
27452
27475
  const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
27453
27476
  remote
27454
27477
  );
27455
27478
  const path = match?.[1] ?? match?.[2];
27456
- if (!path) return null;
27457
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
27458
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
27479
+ return path ? parseGithubRepositoryName(path) : null;
27480
+ }
27481
+ function checkoutSettingsText(repoRoot) {
27482
+ const path = join9(repoRoot, ".claude", "settings.json");
27483
+ try {
27484
+ if (!lstatSync3(join9(repoRoot, ".claude")).isDirectory()) return null;
27485
+ const stat = lstatSync3(path);
27486
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
27487
+ return readFileSync6(path, "utf8");
27488
+ } catch {
27459
27489
  return null;
27460
27490
  }
27461
- return `${parts[0]}/${parts[1]}`;
27491
+ }
27492
+ function checkoutDeclaration(repoRoot, name2) {
27493
+ const text = checkoutSettingsText(repoRoot);
27494
+ if (text === null) return null;
27495
+ let parsed;
27496
+ try {
27497
+ parsed = JSON.parse(text);
27498
+ } catch {
27499
+ return null;
27500
+ }
27501
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
27502
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
27503
+ return typeof value === "string" ? value : null;
27504
+ }
27505
+ function declaredGithubRepository(repoRoot) {
27506
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
27507
+ return value === null ? null : parseGithubRepositoryName(value.trim());
27508
+ }
27509
+ function githubRepositoryFullName(cwd) {
27510
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
27511
+ if (remote) {
27512
+ const fromOrigin = githubRepositoryFromRemote(remote);
27513
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
27514
+ }
27515
+ const root = gitToplevel(cwd);
27516
+ return root ? declaredGithubRepository(root) : null;
27462
27517
  }
27463
27518
  function canonicalGitRoot(cwd) {
27464
27519
  try {
@@ -27512,6 +27567,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
27512
27567
  repoFullName
27513
27568
  };
27514
27569
  }
27570
+ if (repoFullName) {
27571
+ return {
27572
+ repoRoot,
27573
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
27574
+ identitySource: "declared",
27575
+ repoFullName
27576
+ };
27577
+ }
27515
27578
  const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
27516
27579
  if (roots && roots.length > 0) {
27517
27580
  return {
@@ -27724,30 +27787,69 @@ function publicDecisionResponse(value) {
27724
27787
 
27725
27788
  // src/client.ts
27726
27789
  import { createHash as createHash8 } from "crypto";
27727
- import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
27790
+ import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync13, rmSync as rmSync8 } from "fs";
27728
27791
  import { dirname as dirname8 } from "path";
27729
27792
 
27730
27793
  // src/lib/credentials.ts
27731
27794
  import { createHash as createHash7 } from "crypto";
27732
- import { readFileSync as readFileSync9 } from "fs";
27733
- import { join as join12 } from "path";
27795
+ import { readFileSync as readFileSync11 } from "fs";
27796
+ import { join as join14 } from "path";
27734
27797
 
27735
27798
  // src/lib/machine-credentials.ts
27736
27799
  import { execFileSync as execFileSync4 } from "child_process";
27737
- import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
27738
- import { chmodSync as chmodSync2, existsSync as existsSync9, lstatSync as lstatSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
27800
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID3 } from "crypto";
27801
+ import {
27802
+ chmodSync as chmodSync2,
27803
+ existsSync as existsSync10,
27804
+ linkSync,
27805
+ lstatSync as lstatSync6,
27806
+ mkdirSync as mkdirSync5,
27807
+ readFileSync as readFileSync10,
27808
+ rmSync as rmSync7,
27809
+ writeFileSync as writeFileSync5
27810
+ } from "fs";
27739
27811
  import { createRequire as createRequire2 } from "module";
27740
- import { dirname as dirname7, join as join11 } from "path";
27812
+ import { dirname as dirname7, join as join13 } from "path";
27741
27813
  import { fileURLToPath as fileURLToPath4 } from "url";
27742
27814
 
27743
27815
  // src/lib/machine-broker.ts
27744
27816
  import { spawn } from "child_process";
27745
27817
  import { createHash as createHash4, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
27746
- import { lstatSync as lstatSync4, readFileSync as readFileSync6, rmSync as rmSync4 } from "fs";
27818
+ import { lstatSync as lstatSync4, readFileSync as readFileSync8, rmSync as rmSync5 } from "fs";
27747
27819
  import { createServer } from "http";
27748
- import { basename as basename2, join as join9 } from "path";
27820
+ import { basename as basename2, join as join11 } from "path";
27749
27821
  import { fileURLToPath as fileURLToPath3 } from "url";
27750
27822
 
27823
+ // src/lib/loopback-fetch.ts
27824
+ import { request } from "http";
27825
+ import { Readable } from "stream";
27826
+ function loopbackFetch(url, init = {}) {
27827
+ const target = new URL(url);
27828
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
27829
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
27830
+ return new Promise((resolve7, reject) => {
27831
+ const outgoing = request(
27832
+ target,
27833
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
27834
+ (incoming) => {
27835
+ try {
27836
+ const headers = new Headers();
27837
+ for (const [name2, value] of Object.entries(incoming.headers))
27838
+ if (typeof value === "string") headers.set(name2, value);
27839
+ const status = incoming.statusCode ?? 502;
27840
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
27841
+ resolve7(new Response(body, { status, headers }));
27842
+ } catch (error) {
27843
+ incoming.destroy();
27844
+ reject(error);
27845
+ }
27846
+ }
27847
+ );
27848
+ outgoing.once("error", reject);
27849
+ outgoing.end(init.body);
27850
+ });
27851
+ }
27852
+
27751
27853
  // src/lib/workos-connect.ts
27752
27854
  var TOKEN_PATH = "/oauth2/token";
27753
27855
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -27943,9 +28045,19 @@ function parseMachineConfiguration(value) {
27943
28045
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
27944
28046
  };
27945
28047
  }
28048
+ function rejectedCredentialsMessage(message, env = process.env) {
28049
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
28050
+ }
27946
28051
  function machineSignal(signal) {
27947
28052
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
27948
28053
  }
28054
+ function hostOf(url) {
28055
+ try {
28056
+ return new URL(url).hostname;
28057
+ } catch {
28058
+ return "Primitive";
28059
+ }
28060
+ }
27949
28061
  async function fetchMachine(url, options, fetchImpl) {
27950
28062
  try {
27951
28063
  return await fetchImpl(url, options);
@@ -27953,7 +28065,9 @@ async function fetchMachine(url, options, fetchImpl) {
27953
28065
  options.signal?.throwIfAborted();
27954
28066
  throw new MachineAuthError(
27955
28067
  "authentication_unavailable",
27956
- "Machine authentication is temporarily unavailable. Check the connection and retry."
28068
+ // A cloud VM reaches only the hosts its environment allows, and both of
28069
+ // Primitive's are blocked by default: name the one that failed.
28070
+ 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."
27957
28071
  );
27958
28072
  }
27959
28073
  }
@@ -27980,8 +28094,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
27980
28094
  );
27981
28095
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
27982
28096
  }
27983
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
27984
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
28097
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
28098
+ const network = options.secretInjection === "network";
28099
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
27985
28100
  throw new MachineAuthError(
27986
28101
  "invalid_credentials",
27987
28102
  "A machine client ID and secret are required.",
@@ -27995,11 +28110,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
27995
28110
  redirect: "error",
27996
28111
  signal: machineSignal(signal),
27997
28112
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
27998
- body: new URLSearchParams({
27999
- grant_type: "client_credentials",
28000
- client_id: clientId,
28001
- client_secret: clientSecret
28002
- })
28113
+ // With a network secret the agent proxy authenticates the client with
28114
+ // HTTP Basic (client_secret_basic); the body carries no credential.
28115
+ body: new URLSearchParams(
28116
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
28117
+ )
28003
28118
  },
28004
28119
  fetchImpl
28005
28120
  );
@@ -28007,7 +28122,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
28007
28122
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
28008
28123
  throw new MachineAuthError(
28009
28124
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
28010
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
28125
+ 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(
28126
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
28127
+ ) : "The machine token service is temporarily unavailable.",
28011
28128
  terminal,
28012
28129
  terminal ? void 0 : machineRetryAt(response)
28013
28130
  );
@@ -28027,6 +28144,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
28027
28144
  } catch {
28028
28145
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
28029
28146
  }
28147
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
28148
+ throw new MachineAuthError(
28149
+ "token_client_mismatch",
28150
+ "The token service issued a token for another machine client."
28151
+ );
28030
28152
  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()) {
28031
28153
  throw new MachineAuthError(
28032
28154
  "token_identity_mismatch",
@@ -28072,32 +28194,76 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
28072
28194
  const terminal = response.status === 401 || response.status === 403;
28073
28195
  throw new MachineAuthError(
28074
28196
  terminal ? "machine_access_rejected" : "verification_unavailable",
28075
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
28197
+ terminal ? rejectedCredentialsMessage(
28198
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
28199
+ ) : "Machine verification is temporarily unavailable.",
28076
28200
  terminal
28077
28201
  );
28078
28202
  }
28079
28203
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
28080
28204
  }
28205
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
28206
+ const rejected = () => new MachineAuthError(
28207
+ "network_token_rejected",
28208
+ `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.`,
28209
+ true
28210
+ );
28211
+ if (status === 401 || status === 403) throw rejected();
28212
+ if (status < 200 || status > 299)
28213
+ throw new MachineAuthError(
28214
+ "verification_unavailable",
28215
+ "Machine verification is temporarily unavailable."
28216
+ );
28217
+ let data;
28218
+ try {
28219
+ data = machineRecord(value);
28220
+ } catch {
28221
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
28222
+ }
28223
+ if (data.authenticated !== true) throw rejected();
28224
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
28225
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
28226
+ throw new MachineAuthError(
28227
+ "network_secret_mismatch",
28228
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
28229
+ true
28230
+ );
28231
+ return parseMachineIdentity(data, clientId);
28232
+ }
28233
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
28234
+ const response = await fetchMachine(
28235
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
28236
+ { redirect: "error", signal: machineSignal(signal) },
28237
+ fetchImpl
28238
+ );
28239
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
28240
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
28241
+ }
28081
28242
 
28082
28243
  // src/lib/machine-broker.ts
28083
28244
  var MAX_RESPONSE_BYTES = 96 * 1024;
28245
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
28246
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
28247
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
28248
+ var FORWARD_REQUEST_PROOF = "forward-request";
28249
+ var FORWARD_ANSWER_PROOF = "forward-answer";
28084
28250
  var IDLE_MS = 5 * 6e4;
28085
28251
  function descriptorPath(directory, generation) {
28086
- return join9(directory, `machine_broker_${generation}.json`);
28252
+ return join11(directory, `machine_broker_${generation}.json`);
28087
28253
  }
28088
28254
  function readDescriptor(path) {
28089
28255
  try {
28090
28256
  const stat = lstatSync4(path);
28091
28257
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
28092
28258
  return void 0;
28093
- const data = JSON.parse(readFileSync6(path, "utf8"));
28259
+ const data = JSON.parse(readFileSync8(path, "utf8"));
28094
28260
  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;
28095
28261
  } catch {
28096
28262
  return void 0;
28097
28263
  }
28098
28264
  }
28099
- function signature(secret, nonce, body) {
28100
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
28265
+ function signature(secret, nonce, body, purpose) {
28266
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
28101
28267
  }
28102
28268
  function matches(left, right) {
28103
28269
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
@@ -28112,10 +28278,9 @@ async function brokerRequest(descriptor, environment, options) {
28112
28278
  observedTokenHash: tokenHash(options.observedToken),
28113
28279
  timestamp: Date.now()
28114
28280
  });
28115
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
28281
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
28116
28282
  method: "POST",
28117
28283
  body,
28118
- redirect: "error",
28119
28284
  signal: options.signal,
28120
28285
  headers: {
28121
28286
  "Content-Type": "application/json",
@@ -28146,6 +28311,15 @@ async function brokerRequest(descriptor, environment, options) {
28146
28311
  );
28147
28312
  return credential;
28148
28313
  }
28314
+ function brokerEnvironment(options) {
28315
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
28316
+ return {
28317
+ ...options.env,
28318
+ PRIM_API_URL: options.apiUrl,
28319
+ PRIM_CONFIG_DIR: options.directory,
28320
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
28321
+ };
28322
+ }
28149
28323
  async function acquireBrokerCredential(options) {
28150
28324
  const path = descriptorPath(options.directory, options.environment.generation);
28151
28325
  const existing = readDescriptor(path);
@@ -28157,15 +28331,28 @@ async function acquireBrokerCredential(options) {
28157
28331
  if (error instanceof MachineAuthError) throw error;
28158
28332
  }
28159
28333
  }
28160
- const descriptor = await withFileLock(
28161
- join9(options.directory, "machine-broker.lock"),
28334
+ const descriptor = await ensureBroker(options);
28335
+ try {
28336
+ return await brokerRequest(descriptor, options.environment, options);
28337
+ } catch (error) {
28338
+ options.signal.throwIfAborted();
28339
+ if (error instanceof MachineAuthError) throw error;
28340
+ throw new MachineAuthError(
28341
+ "broker_unavailable",
28342
+ "Machine credential broker is unavailable. Retry the command."
28343
+ );
28344
+ }
28345
+ }
28346
+ async function ensureBroker(options) {
28347
+ const path = descriptorPath(options.directory, options.environment.generation);
28348
+ return withFileLock(
28349
+ join11(options.directory, "machine-broker.lock"),
28162
28350
  async () => {
28163
28351
  const current = readDescriptor(path);
28164
28352
  if (current) {
28165
28353
  try {
28166
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
28167
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
28168
- redirect: "error"
28354
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
28355
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
28169
28356
  });
28170
28357
  if (response.ok && await response.text() === current.nonce) return current;
28171
28358
  } catch {
@@ -28184,7 +28371,7 @@ async function acquireBrokerCredential(options) {
28184
28371
  detached: true,
28185
28372
  stdio: ["ignore", "ignore", "ignore", "ipc"],
28186
28373
  windowsHide: true,
28187
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
28374
+ env: brokerEnvironment(options)
28188
28375
  });
28189
28376
  let settled = false;
28190
28377
  const finish = (error) => {
@@ -28236,31 +28423,97 @@ async function acquireBrokerCredential(options) {
28236
28423
  },
28237
28424
  { signal: options.signal }
28238
28425
  );
28426
+ }
28427
+ async function forwardOnce(descriptor, environment, request3, signal) {
28428
+ const body = JSON.stringify({
28429
+ generation: environment.generation,
28430
+ timestamp: Date.now(),
28431
+ method: request3.method,
28432
+ path: request3.path,
28433
+ headers: request3.headers ?? {},
28434
+ ...request3.body === void 0 ? {} : { body: request3.body }
28435
+ });
28436
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
28437
+ method: "POST",
28438
+ body,
28439
+ signal,
28440
+ headers: {
28441
+ "Content-Type": "application/json",
28442
+ "X-Prim-Proof": signature(
28443
+ environment.clientSecret,
28444
+ descriptor.nonce,
28445
+ body,
28446
+ FORWARD_REQUEST_PROOF
28447
+ )
28448
+ }
28449
+ });
28450
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
28451
+ if (typeof envelope.body !== "string" || !matches(
28452
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
28453
+ envelope.proof
28454
+ ))
28455
+ throw new MachineAuthError(
28456
+ "broker_unavailable",
28457
+ "Machine credential broker could not be authenticated. Retry the command."
28458
+ );
28459
+ const data = machineRecord(JSON.parse(envelope.body));
28460
+ if (data.error) {
28461
+ const error = machineRecord(data.error);
28462
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
28463
+ }
28464
+ const status = data.status;
28465
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
28466
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
28467
+ const headers = new Headers();
28468
+ for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
28469
+ if (typeof value === "string") headers.set(name2, value);
28470
+ const text = typeof data.body === "string" ? data.body : "";
28471
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
28472
+ }
28473
+ async function forwardBrokerRequest(options) {
28474
+ const path = descriptorPath(options.directory, options.environment.generation);
28475
+ const unavailable = () => new MachineAuthError(
28476
+ "broker_unavailable",
28477
+ "Machine credential broker is unavailable. Retry the command."
28478
+ );
28479
+ const existing = readDescriptor(path);
28480
+ if (existing) {
28481
+ try {
28482
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
28483
+ } catch (error) {
28484
+ options.signal.throwIfAborted();
28485
+ if (error instanceof MachineAuthError) throw error;
28486
+ if (error.code !== "ECONNREFUSED") throw unavailable();
28487
+ }
28488
+ }
28489
+ const descriptor = await ensureBroker(options);
28239
28490
  try {
28240
- return await brokerRequest(descriptor, options.environment, options);
28491
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
28241
28492
  } catch (error) {
28242
28493
  options.signal.throwIfAborted();
28243
28494
  if (error instanceof MachineAuthError) throw error;
28244
- throw new MachineAuthError(
28245
- "broker_unavailable",
28246
- "Machine credential broker is unavailable. Retry the command."
28247
- );
28495
+ throw unavailable();
28248
28496
  }
28249
28497
  }
28250
28498
 
28251
28499
  // src/lib/machine-retry.ts
28252
28500
  import { createHash as createHash5 } from "crypto";
28253
- import { lstatSync as lstatSync5, readFileSync as readFileSync7, rmSync as rmSync5 } from "fs";
28254
- import { join as join10 } from "path";
28255
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
28501
+ import { lstatSync as lstatSync5, readFileSync as readFileSync9, readdirSync as readdirSync3, rmSync as rmSync6 } from "fs";
28502
+ import { join as join12 } from "path";
28503
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
28504
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
28505
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
28256
28506
  signal?.throwIfAborted();
28257
28507
  const key = createHash5("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
28258
- const path = join10(directory, `machine_retry_${key}.json`);
28259
- let state = { failures: 0, retryAt: 0 };
28508
+ const path = join12(directory, `machine_retry_${key}.json`);
28509
+ let state = {
28510
+ failures: 0,
28511
+ retryAt: 0
28512
+ };
28260
28513
  try {
28261
28514
  const stat = lstatSync5(path);
28262
28515
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
28263
- const data = JSON.parse(readFileSync7(path, "utf8"));
28516
+ const data = JSON.parse(readFileSync9(path, "utf8"));
28264
28517
  if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
28265
28518
  throw new Error("Invalid retry state");
28266
28519
  state = data;
@@ -28271,13 +28524,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
28271
28524
  if (state.retryAt > Date.now())
28272
28525
  throw new MachineAuthError(
28273
28526
  "token_service_unavailable",
28274
- "Machine authentication is cooling down after a temporary failure. Retry later.",
28527
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
28528
+ // Cloud setup keeps this wait too, so pointing at it would loop.
28529
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
28530
+ ) : (
28531
+ // The cooldown hides the failure that started it; cloud setup
28532
+ // retries at once and names the cause.
28533
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
28534
+ ),
28275
28535
  false,
28276
28536
  state.retryAt
28277
28537
  );
28278
28538
  try {
28279
- const result = await request2();
28280
- rmSync5(path, { force: true });
28539
+ const result = await request3();
28540
+ rmSync6(path, { force: true });
28281
28541
  return result;
28282
28542
  } catch (error) {
28283
28543
  if (!signal?.aborted && error instanceof MachineAuthError && [
@@ -28288,8 +28548,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
28288
28548
  ].includes(error.code)) {
28289
28549
  const failures = Math.min(16, state.failures + 1);
28290
28550
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
28291
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
28292
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
28551
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
28552
+ atomicWriteFile(
28553
+ path,
28554
+ JSON.stringify({
28555
+ failures,
28556
+ retryAt,
28557
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
28558
+ }),
28559
+ { mode: 384 }
28560
+ );
28293
28561
  throw new MachineAuthError(error.code, error.message, false, retryAt);
28294
28562
  }
28295
28563
  throw error;
@@ -28313,13 +28581,13 @@ function hash(value) {
28313
28581
  return createHash6("sha256").update(value).digest("hex");
28314
28582
  }
28315
28583
  function recordPath(directory, generation) {
28316
- return join11(directory, `machine_${generation}.json`);
28584
+ return join13(directory, `machine_${generation}.json`);
28317
28585
  }
28318
28586
  function storageKey(directory, generation) {
28319
28587
  return `${hash(directory)}:${generation}`;
28320
28588
  }
28321
28589
  function environmentContextPath(deps, clientId) {
28322
- return join11(
28590
+ return join13(
28323
28591
  configurationDirectory(deps),
28324
28592
  `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
28325
28593
  );
@@ -28382,8 +28650,8 @@ function readEnvironmentContext(environment, deps) {
28382
28650
  function keyringEntry(key) {
28383
28651
  let directory = dirname7(fileURLToPath4(import.meta.url));
28384
28652
  for (let depth = 0; depth < 5; depth++) {
28385
- const loader = join11(directory, "native", "keyring.cjs");
28386
- if (existsSync9(loader)) {
28653
+ const loader = join13(directory, "native", "keyring.cjs");
28654
+ if (existsSync10(loader)) {
28387
28655
  const module2 = require3(loader);
28388
28656
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
28389
28657
  }
@@ -28411,7 +28679,7 @@ function protectPath(path, directory) {
28411
28679
  );
28412
28680
  }
28413
28681
  function ensureDirectory(directory) {
28414
- mkdirSync4(directory, { recursive: true, mode: 448 });
28682
+ mkdirSync5(directory, { recursive: true, mode: 448 });
28415
28683
  if (lstatSync6(directory).isSymbolicLink())
28416
28684
  throw new MachineAuthError(
28417
28685
  "unsafe_storage",
@@ -28434,7 +28702,7 @@ function readPrivate(path) {
28434
28702
  "Machine credential files must be owner-only regular files."
28435
28703
  );
28436
28704
  }
28437
- raw = readFileSync8(path, "utf8");
28705
+ raw = readFileSync10(path, "utf8");
28438
28706
  } catch (error) {
28439
28707
  if (error.code === "ENOENT") return void 0;
28440
28708
  throw error;
@@ -28479,13 +28747,101 @@ function parseProfile(value) {
28479
28747
  };
28480
28748
  }
28481
28749
  function readMachineProfile(deps = {}) {
28482
- const value = readPrivate(join11(configurationDirectory(deps), PROFILE_FILE));
28750
+ const value = readPrivate(join13(configurationDirectory(deps), PROFILE_FILE));
28483
28751
  return value === void 0 ? void 0 : parseProfile(value);
28484
28752
  }
28753
+ var NETWORK_SECRET_AUTH = "network-secret";
28754
+ var NETWORK_TOKEN_AUTH = "network-token";
28755
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
28756
+ var brokerKeys = /* @__PURE__ */ new Map();
28757
+ function networkSecretBrokerKey(deps, clientId) {
28758
+ const directory = configurationDirectory(deps);
28759
+ const path = join13(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
28760
+ const known = brokerKeys.get(path);
28761
+ if (known) return known;
28762
+ ensureDirectory(directory);
28763
+ const read = () => {
28764
+ try {
28765
+ const stat = lstatSync6(path);
28766
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
28767
+ throw new MachineAuthError(
28768
+ "unsafe_storage",
28769
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
28770
+ true
28771
+ );
28772
+ const value = readFileSync10(path, "utf8").trim();
28773
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
28774
+ } catch (error) {
28775
+ if (error.code === "ENOENT") return void 0;
28776
+ throw error;
28777
+ }
28778
+ };
28779
+ for (let attempt = 0; attempt < 2; attempt += 1) {
28780
+ const existing = read();
28781
+ if (existing?.key) {
28782
+ brokerKeys.set(path, existing.key);
28783
+ return existing.key;
28784
+ }
28785
+ if (existing)
28786
+ throw new MachineAuthError(
28787
+ "unsafe_storage",
28788
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
28789
+ true
28790
+ );
28791
+ const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
28792
+ try {
28793
+ writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
28794
+ `, { mode: 384, flag: "wx" });
28795
+ protectPath(staged, false);
28796
+ linkSync(staged, path);
28797
+ } catch (error) {
28798
+ if (error.code !== "EEXIST") throw error;
28799
+ } finally {
28800
+ rmSync7(staged, { force: true });
28801
+ }
28802
+ }
28803
+ const key = read()?.key;
28804
+ if (!key)
28805
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
28806
+ brokerKeys.set(path, key);
28807
+ return key;
28808
+ }
28485
28809
  function environmentCredentials(deps) {
28486
28810
  const env = deps.env ?? process.env;
28487
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
28488
- if (clientId === void 0 && clientSecret === void 0) return void 0;
28811
+ const {
28812
+ PRIM_M2M_CLIENT_ID: clientId,
28813
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
28814
+ PRIM_M2M_CLIENT_AUTH: auth
28815
+ } = env;
28816
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
28817
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
28818
+ throw new MachineAuthError(
28819
+ "incomplete_machine_credentials",
28820
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
28821
+ );
28822
+ if (auth !== void 0) {
28823
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
28824
+ throw new MachineAuthError(
28825
+ "incomplete_machine_credentials",
28826
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
28827
+ );
28828
+ if (clientSecret !== void 0)
28829
+ throw new MachineAuthError(
28830
+ "conflicting_credentials",
28831
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
28832
+ );
28833
+ const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
28834
+ const credentials = {
28835
+ clientId,
28836
+ generation,
28837
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
28838
+ };
28839
+ Object.defineProperty(credentials, "clientSecret", {
28840
+ enumerable: true,
28841
+ get: () => networkSecretBrokerKey(deps, clientId)
28842
+ });
28843
+ return credentials;
28844
+ }
28489
28845
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
28490
28846
  throw new MachineAuthError(
28491
28847
  "incomplete_machine_credentials",
@@ -28500,7 +28856,7 @@ function environmentCredentials(deps) {
28500
28856
  }
28501
28857
  function hasMachineConfiguration(deps = {}) {
28502
28858
  const env = deps.env ?? process.env;
28503
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync9(join11(configurationDirectory(deps), PROFILE_FILE));
28859
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync10(join13(configurationDirectory(deps), PROFILE_FILE));
28504
28860
  if (configured && env.PRIM_TOKEN?.trim()) {
28505
28861
  throw new MachineAuthError(
28506
28862
  "conflicting_credentials",
@@ -28534,9 +28890,11 @@ function machineSessionEnded(deps = {}) {
28534
28890
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
28535
28891
  if (!generation) return false;
28536
28892
  if (environmentCredentials(deps)) return environmentTerminal === generation;
28537
- return readPrivate(join11(configurationDirectory(deps), "machine_terminal.json")) === generation;
28893
+ return readPrivate(join13(configurationDirectory(deps), "machine_terminal.json")) === generation;
28538
28894
  }
28539
28895
  var environmentTerminal;
28896
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
28897
+ var networkRejection;
28540
28898
  async function loadRecord(profile, deps, signal) {
28541
28899
  const directory = configurationDirectory(deps);
28542
28900
  let value;
@@ -28600,6 +28958,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28600
28958
  const apiUrl = apiUrlFor(deps);
28601
28959
  const environment = environmentCredentials(deps);
28602
28960
  if (environment) {
28961
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
28603
28962
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
28604
28963
  const directory2 = configurationDirectory(deps);
28605
28964
  ensureDirectory(directory2);
@@ -28617,22 +28976,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28617
28976
  writeEnvironmentContext(cached, deps);
28618
28977
  return cached;
28619
28978
  } catch (error) {
28620
- if (error instanceof MachineAuthError && error.terminal)
28979
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
28621
28980
  environmentTerminal = environment.generation;
28622
28981
  throw error;
28623
28982
  }
28624
28983
  }
28625
28984
  return withFileLock(
28626
- join11(directory2, "credentials.lock"),
28985
+ join13(directory2, "credentials.lock"),
28627
28986
  async () => {
28628
28987
  if (machineSessionEnded(deps))
28629
28988
  throw new MachineAuthError(
28630
28989
  "machine_credentials_rejected",
28631
- "Rotate the injected machine credentials.",
28990
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
28632
28991
  true
28633
28992
  );
28634
28993
  if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
28635
28994
  return cached;
28995
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
28996
+ throw networkRejection.error;
28636
28997
  try {
28637
28998
  const { configuration, tokens, identity } = await withMachineCooldown(
28638
28999
  directory2,
@@ -28641,13 +29002,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28641
29002
  signal,
28642
29003
  async () => {
28643
29004
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
29005
+ if (environment.tokenInjection) {
29006
+ const identity3 = await verifyInjectedMachineIdentity(
29007
+ apiUrl,
29008
+ environment.clientId,
29009
+ signal,
29010
+ deps.fetch
29011
+ );
29012
+ const tokens3 = {
29013
+ accessToken: "",
29014
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
29015
+ };
29016
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
29017
+ }
28644
29018
  const tokens2 = await exchangeMachineCredentials(
28645
29019
  configuration2,
28646
29020
  environment.clientId,
28647
- environment.clientSecret,
29021
+ // The broker key is not a client secret; the proxy supplies that.
29022
+ environment.secretInjection ? "" : environment.clientSecret,
28648
29023
  signal,
28649
- deps.fetch
28650
- );
29024
+ deps.fetch,
29025
+ { secretInjection: environment.secretInjection }
29026
+ ).catch((error) => {
29027
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
29028
+ throw new MachineAuthError(
29029
+ "network_secret_mismatch",
29030
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
29031
+ true
29032
+ );
29033
+ throw error;
29034
+ });
28651
29035
  const identity2 = await verifyMachineIdentity(
28652
29036
  apiUrl,
28653
29037
  tokens2.accessToken,
@@ -28664,17 +29048,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28664
29048
  ...identity,
28665
29049
  apiUrl,
28666
29050
  generation: environment.generation,
28667
- storage: "environment"
29051
+ storage: "environment",
29052
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
28668
29053
  };
28669
29054
  writeEnvironmentContext(cached, deps);
28670
29055
  return cached;
28671
29056
  } catch (error) {
29057
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
29058
+ networkRejection = {
29059
+ generation: environment.generation,
29060
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
29061
+ error
29062
+ };
29063
+ if (cached?.generation === environment.generation) cached = void 0;
29064
+ const contextPath = environmentContextPath(deps, environment.clientId);
29065
+ try {
29066
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
29067
+ rmSync7(contextPath, { force: true });
29068
+ } catch {
29069
+ }
29070
+ throw error;
29071
+ }
28672
29072
  if (error instanceof MachineAuthError && error.terminal) {
28673
29073
  environmentTerminal = environment.generation;
28674
29074
  const contextPath = environmentContextPath(deps, environment.clientId);
28675
29075
  try {
28676
29076
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
28677
- rmSync6(contextPath, { force: true });
29077
+ rmSync7(contextPath, { force: true });
28678
29078
  } catch {
28679
29079
  }
28680
29080
  }
@@ -28688,7 +29088,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28688
29088
  const expected = machineContext(deps);
28689
29089
  const directory = configurationDirectory(deps);
28690
29090
  return withFileLock(
28691
- join11(directory, "credentials.lock"),
29091
+ join13(directory, "credentials.lock"),
28692
29092
  async () => {
28693
29093
  const profile = readMachineProfile(deps);
28694
29094
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -28738,7 +29138,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28738
29138
  await persistRecord(record, deps, signal);
28739
29139
  } catch (error) {
28740
29140
  if (error instanceof MachineAuthError && error.terminal)
28741
- writePrivate(join11(directory, "machine_terminal.json"), profile.generation);
29141
+ writePrivate(join13(directory, "machine_terminal.json"), profile.generation);
28742
29142
  throw error;
28743
29143
  }
28744
29144
  }
@@ -28749,23 +29149,41 @@ async function acquireMachineCredential(options = {}, deps = {}) {
28749
29149
  { signal }
28750
29150
  );
28751
29151
  }
29152
+ async function forwardMachineRequest(request3, signal, deps = {}) {
29153
+ const environment = environmentCredentials(deps);
29154
+ if (!environment?.tokenInjection)
29155
+ throw new MachineAuthError(
29156
+ "identity_changed",
29157
+ "Machine identity changed; restart the operation."
29158
+ );
29159
+ const directory = configurationDirectory(deps);
29160
+ ensureDirectory(directory);
29161
+ return forwardBrokerRequest({
29162
+ directory,
29163
+ apiUrl: apiUrlFor(deps),
29164
+ environment,
29165
+ env: deps.env ?? process.env,
29166
+ request: request3,
29167
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
29168
+ });
29169
+ }
28752
29170
 
28753
29171
  // src/lib/credentials.ts
28754
29172
  var CONFIG_DIRECTORY = primConfigDirectory();
28755
- var TOKEN_FILE_PATH = join12(CONFIG_DIRECTORY, "token");
28756
- var REFRESH_TOKEN_PATH = join12(CONFIG_DIRECTORY, "refresh_token");
28757
- var TOKEN_EXPIRES_PATH = join12(CONFIG_DIRECTORY, "token_expires_at");
28758
- var TERMINAL_REFRESH_PATH = join12(CONFIG_DIRECTORY, "refresh_terminal");
28759
- var CREDENTIAL_METADATA_PATH = join12(CONFIG_DIRECTORY, "credential_metadata.json");
28760
- var CREDENTIAL_FAMILY_PATH = join12(CONFIG_DIRECTORY, "credential_family.json");
28761
- var CREDENTIAL_MIGRATION_PATH = join12(CONFIG_DIRECTORY, "credential_migration.json");
28762
- var CREDENTIAL_LOCK_PATH = join12(CONFIG_DIRECTORY, "credentials.lock");
29173
+ var TOKEN_FILE_PATH = join14(CONFIG_DIRECTORY, "token");
29174
+ var REFRESH_TOKEN_PATH = join14(CONFIG_DIRECTORY, "refresh_token");
29175
+ var TOKEN_EXPIRES_PATH = join14(CONFIG_DIRECTORY, "token_expires_at");
29176
+ var TERMINAL_REFRESH_PATH = join14(CONFIG_DIRECTORY, "refresh_terminal");
29177
+ var CREDENTIAL_METADATA_PATH = join14(CONFIG_DIRECTORY, "credential_metadata.json");
29178
+ var CREDENTIAL_FAMILY_PATH = join14(CONFIG_DIRECTORY, "credential_family.json");
29179
+ var CREDENTIAL_MIGRATION_PATH = join14(CONFIG_DIRECTORY, "credential_migration.json");
29180
+ var CREDENTIAL_LOCK_PATH = join14(CONFIG_DIRECTORY, "credentials.lock");
28763
29181
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
28764
29182
  var CREDENTIAL_MIGRATION_VERSION = 1;
28765
29183
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
28766
29184
  function readTrimmed(path) {
28767
29185
  try {
28768
- const value = readFileSync9(path, "utf8").trim();
29186
+ const value = readFileSync11(path, "utf8").trim();
28769
29187
  return value || void 0;
28770
29188
  } catch {
28771
29189
  return void 0;
@@ -28774,7 +29192,7 @@ function readTrimmed(path) {
28774
29192
  function resolveAuthCredential(options = {}) {
28775
29193
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
28776
29194
  const machine = cachedMachineCredential({ env: options.env });
28777
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
29195
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
28778
29196
  }
28779
29197
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
28780
29198
  if (envToken) return { token: envToken, source: "environment" };
@@ -28822,7 +29240,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
28822
29240
  function readBoundedCredentialJson(path) {
28823
29241
  let raw;
28824
29242
  try {
28825
- raw = readFileSync9(path, "utf8");
29243
+ raw = readFileSync11(path, "utf8");
28826
29244
  } catch (error) {
28827
29245
  return error.code === "ENOENT" ? void 0 : null;
28828
29246
  }
@@ -28894,9 +29312,9 @@ function jwtExpiresAt(token) {
28894
29312
  }
28895
29313
 
28896
29314
  // src/daemon/client-instance-id.ts
28897
- import { randomBytes as randomBytes4 } from "crypto";
28898
- import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync10 } from "fs";
28899
- import { join as join13 } from "path";
29315
+ import { randomBytes as randomBytes5 } from "crypto";
29316
+ import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync12 } from "fs";
29317
+ import { join as join15 } from "path";
28900
29318
  var CONFIG_DIRECTORY_MODE = 448;
28901
29319
  var INSTANCE_FILE_MODE = 384;
28902
29320
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -28933,7 +29351,7 @@ function readExisting(path) {
28933
29351
  if (metadata.size > MAX_STORED_BYTES) {
28934
29352
  throw new Error("stored client instance identity is invalid");
28935
29353
  }
28936
- const raw = readFileSync10(path, "utf8");
29354
+ const raw = readFileSync12(path, "utf8");
28937
29355
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
28938
29356
  if (raw !== value && raw !== `${value}
28939
29357
  ` || !isClientInstanceId(value)) {
@@ -28947,8 +29365,8 @@ function atomicWrite(path, value) {
28947
29365
  }
28948
29366
  async function getOrCreateClientInstanceId(options) {
28949
29367
  const configDir = options.configDir;
28950
- const path = join13(configDir, "client_instance_id");
28951
- const lockPath = join13(configDir, "client-instance.lock");
29368
+ const path = join15(configDir, "client_instance_id");
29369
+ const lockPath = join15(configDir, "client-instance.lock");
28952
29370
  ensurePrivateConfigDirectory(configDir);
28953
29371
  return withFileLock(
28954
29372
  lockPath,
@@ -28957,7 +29375,7 @@ async function getOrCreateClientInstanceId(options) {
28957
29375
  if (existing !== void 0) {
28958
29376
  return existing;
28959
29377
  }
28960
- const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
29378
+ const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
28961
29379
  "base64url"
28962
29380
  )}`;
28963
29381
  if (!isClientInstanceId(generated)) {
@@ -29039,9 +29457,12 @@ var CREDENTIAL_FILE_MODE = 384;
29039
29457
  var REFRESH_THRESHOLD_MS = 6e4;
29040
29458
  var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
29041
29459
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
29460
+ function authExpiredMessage() {
29461
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
29462
+ }
29042
29463
  function readTrimmed2(path) {
29043
29464
  try {
29044
- const value = readFileSync11(path, "utf8").trim();
29465
+ const value = readFileSync13(path, "utf8").trim();
29045
29466
  return value || void 0;
29046
29467
  } catch {
29047
29468
  return void 0;
@@ -29058,7 +29479,7 @@ function expiresAtFor(token, expiresIn) {
29058
29479
  }
29059
29480
  function ensureConfigDirectory() {
29060
29481
  const directory = dirname8(TOKEN_FILE_PATH);
29061
- mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
29482
+ mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
29062
29483
  chmodSync4(directory, CONFIG_DIR_MODE);
29063
29484
  }
29064
29485
  function atomicWrite2(path, content2) {
@@ -29066,8 +29487,8 @@ function atomicWrite2(path, content2) {
29066
29487
  atomicWriteFile(path, content2, { mode: CREDENTIAL_FILE_MODE });
29067
29488
  }
29068
29489
  function removeCredentialFile(path) {
29069
- if (!existsSync10(path)) return false;
29070
- rmSync7(path, { force: true });
29490
+ if (!existsSync11(path)) return false;
29491
+ rmSync8(path, { force: true });
29071
29492
  return true;
29072
29493
  }
29073
29494
  function getTokenExpiresAt() {
@@ -29420,7 +29841,7 @@ var CliManagementResponseError = class extends Error {
29420
29841
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
29421
29842
  async function managementResponseValue(response) {
29422
29843
  if (response.status === 401) {
29423
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
29844
+ throw new HttpError(401, authExpiredMessage());
29424
29845
  }
29425
29846
  let value;
29426
29847
  try {
@@ -29442,23 +29863,50 @@ function selectedCredential() {
29442
29863
  }
29443
29864
  return _cachedCredential;
29444
29865
  }
29866
+ async function requestHeaders(method, path) {
29867
+ return {
29868
+ "Content-Type": "application/json",
29869
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
29870
+ };
29871
+ }
29445
29872
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
29446
29873
  return fetch(`${siteUrl}${path}`, {
29447
29874
  method,
29448
- headers: {
29449
- Authorization: `Bearer ${token}`,
29450
- "Content-Type": "application/json",
29451
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
29452
- },
29875
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
29453
29876
  body: body === void 0 ? void 0 : JSON.stringify(body),
29454
29877
  signal: options?.signal,
29455
29878
  redirect: options?.redirect
29456
29879
  });
29457
29880
  }
29881
+ async function fetchAsMachine(credential, method, path, body, options) {
29882
+ if (!credential.tokenInjection)
29883
+ return fetchWithToken(
29884
+ method,
29885
+ path,
29886
+ body,
29887
+ { ...options, redirect: "error" },
29888
+ credential.accessToken,
29889
+ credential.apiUrl
29890
+ );
29891
+ try {
29892
+ return await forwardMachineRequest(
29893
+ {
29894
+ method,
29895
+ path,
29896
+ headers: await requestHeaders(method, path),
29897
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
29898
+ },
29899
+ options.signal
29900
+ );
29901
+ } catch (error) {
29902
+ if (!(error instanceof MachineAuthError)) throw error;
29903
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
29904
+ }
29905
+ }
29458
29906
  async function responseValue(response) {
29459
29907
  if (!response.ok) {
29460
29908
  if (response.status === 401) {
29461
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
29909
+ throw new HttpError(401, authExpiredMessage());
29462
29910
  }
29463
29911
  const errorBody = await response.json().catch(() => null);
29464
29912
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -29485,14 +29933,7 @@ async function machineClient(options = {}, management = false) {
29485
29933
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
29486
29934
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
29487
29935
  throw new HttpError(409, "Machine identity changed; restart the operation.");
29488
- let response = await fetchWithToken(
29489
- method,
29490
- path,
29491
- body,
29492
- { ...requestOptions, redirect: "error" },
29493
- current.accessToken,
29494
- selected.apiUrl
29495
- );
29936
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
29496
29937
  if (response.status === 401) {
29497
29938
  const renewed = await acquireMachineCredential({
29498
29939
  force: true,
@@ -29501,19 +29942,14 @@ async function machineClient(options = {}, management = false) {
29501
29942
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
29502
29943
  throw new HttpError(409, "Machine identity changed; restart the operation.");
29503
29944
  }
29504
- response = await fetchWithToken(
29505
- method,
29506
- path,
29507
- body,
29508
- { ...requestOptions, redirect: "error" },
29509
- renewed.accessToken,
29510
- renewed.apiUrl
29511
- );
29945
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
29512
29946
  }
29513
29947
  if (response.status === 401)
29514
29948
  throw new HttpError(
29515
29949
  401,
29516
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
29950
+ selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
29951
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
29952
+ )
29517
29953
  );
29518
29954
  return parse2(response);
29519
29955
  };
@@ -29523,7 +29959,7 @@ async function machineClient(options = {}, management = false) {
29523
29959
  delete: (path, body, opts) => send("DELETE", path, body, opts)
29524
29960
  };
29525
29961
  }
29526
- async function request(method, path, body, options) {
29962
+ async function request2(method, path, body, options) {
29527
29963
  const machine = await machineClient(options);
29528
29964
  if (machine)
29529
29965
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -29539,10 +29975,10 @@ async function request(method, path, body, options) {
29539
29975
  if (token) credential = { token, source: "token_file" };
29540
29976
  }
29541
29977
  if (!credential) {
29542
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
29978
+ throw new HttpError(401, authExpiredMessage());
29543
29979
  }
29544
29980
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
29545
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
29981
+ throw new HttpError(401, authExpiredMessage());
29546
29982
  }
29547
29983
  const tokenUsed = credential.token;
29548
29984
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -29565,8 +30001,8 @@ async function request(method, path, body, options) {
29565
30001
  }
29566
30002
  function getClient() {
29567
30003
  return {
29568
- get: (path, options) => request("GET", path, void 0, options),
29569
- post: (path, body, options) => request("POST", path, body, options)
30004
+ get: (path, options) => request2("GET", path, void 0, options),
30005
+ post: (path, body, options) => request2("POST", path, body, options)
29570
30006
  };
29571
30007
  }
29572
30008
 
@@ -29868,8 +30304,8 @@ function parseAgent(argv) {
29868
30304
  }
29869
30305
 
29870
30306
  // src/hooks/redact.ts
29871
- import { existsSync as existsSync11, readFileSync as readFileSync12, statSync as statSync3 } from "fs";
29872
- import { join as join15 } from "path";
30307
+ import { existsSync as existsSync12, readFileSync as readFileSync14, statSync as statSync3 } from "fs";
30308
+ import { join as join17 } from "path";
29873
30309
  import { Worker } from "worker_threads";
29874
30310
 
29875
30311
  // src/lib/ansi.ts
@@ -29924,6 +30360,11 @@ var DEFAULT_RULES = [
29924
30360
  pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
29925
30361
  reason: "aws-secret"
29926
30362
  },
30363
+ {
30364
+ // `prim auth enroll --print-env` output an agent may write into a file.
30365
+ pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
30366
+ reason: "prim-m2m-secret"
30367
+ },
29927
30368
  { pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
29928
30369
  {
29929
30370
  pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
@@ -30048,9 +30489,14 @@ function decisionLabel(conflict) {
30048
30489
  const title = typeof conflict.title === "string" ? displayText(conflict.title, MAX_TITLE_CHARS) : "";
30049
30490
  return title ? `Decision ${id2}: \u201C${title}\u201D.` : `Decision ${id2}: details unavailable; inspect it before approving.`;
30050
30491
  }
30492
+ function isEmptyCheck(check) {
30493
+ const coverage = check.evaluationCoverage;
30494
+ return coverage?.status === "not_run" && coverage.candidateCount === 0 && (check.verdict === "allow" || check.verdict === "warn") && check.conflicts.length === 0;
30495
+ }
30051
30496
  function incomplete(evidence) {
30052
30497
  const coverage = evidence.evaluationCoverage;
30053
- return Array.isArray(coverage?.selectionOmissions) && coverage.selectionOmissions.length > 0 || Array.isArray(coverage?.evidenceOmissions) && coverage.evidenceOmissions.length > 0 || coverage?.status !== void 0 && coverage.status !== "completed" || ["candidate_set_truncated", "evidence_incomplete", "coverage_unverified"].includes(
30498
+ const settled = coverage?.status === void 0 || coverage.status === "completed" || isEmptyCheck(evidence);
30499
+ return Array.isArray(coverage?.selectionOmissions) && coverage.selectionOmissions.length > 0 || Array.isArray(coverage?.evidenceOmissions) && coverage.evidenceOmissions.length > 0 || !settled || ["candidate_set_truncated", "evidence_incomplete", "coverage_unverified"].includes(
30054
30500
  evidence.reasonCode
30055
30501
  );
30056
30502
  }
@@ -30073,17 +30519,17 @@ function approvalSummary(evidence, preview) {
30073
30519
  }
30074
30520
 
30075
30521
  // src/commands/cursor-install.ts
30076
- import { existsSync as existsSync13, readFileSync as readFileSync14 } from "fs";
30522
+ import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
30077
30523
  import { homedir as homedir4 } from "os";
30078
- import { isAbsolute as isAbsolute5, join as join17 } from "path";
30524
+ import { isAbsolute as isAbsolute5, join as join19 } from "path";
30079
30525
 
30080
30526
  // src/lib/preflight-host.ts
30081
30527
  import { execFileSync as execFileSync5 } from "child_process";
30082
30528
 
30083
30529
  // src/commands/claude-install.ts
30084
- import { existsSync as existsSync12, readFileSync as readFileSync13 } from "fs";
30530
+ import { existsSync as existsSync13, lstatSync as lstatSync8, readFileSync as readFileSync15 } from "fs";
30085
30531
  import { homedir as homedir3 } from "os";
30086
- import { join as join16 } from "path";
30532
+ import { join as join18 } from "path";
30087
30533
  var CAPTURE_BIN = "prim-hook";
30088
30534
  var GATE_BIN = "prim-pre-tool-use";
30089
30535
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -30092,7 +30538,7 @@ var SESSION_END_BIN = "prim-session-end";
30092
30538
  var STATUSLINE_BIN = "prim-statusline";
30093
30539
  var STATUSLINE_ARGS = "";
30094
30540
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
30095
- var USER_SCOPE_PATH = join16(homedir3(), ".claude", "settings.json");
30541
+ var USER_SCOPE_PATH = join18(homedir3(), ".claude", "settings.json");
30096
30542
  function projectRoot() {
30097
30543
  return gitToplevel() ?? process.cwd();
30098
30544
  }
@@ -30172,20 +30618,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
30172
30618
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
30173
30619
  if (explicit && isAbsolute5(explicit)) return explicit;
30174
30620
  const xdg = env.XDG_CONFIG_HOME?.trim();
30175
- if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join17(xdg, "cursor");
30176
- return join17(home, ".cursor");
30621
+ if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join19(xdg, "cursor");
30622
+ return join19(home, ".cursor");
30177
30623
  }
30178
30624
  function cursorHooksPath(scope, root = projectRoot()) {
30179
- return scope === "user" ? join17(cursorConfigDirectory(), "hooks.json") : join17(root, ".cursor", "hooks.json");
30625
+ return scope === "user" ? join19(cursorConfigDirectory(), "hooks.json") : join19(root, ".cursor", "hooks.json");
30180
30626
  }
30181
30627
  function plainObject(value) {
30182
30628
  return typeof value === "object" && value !== null && !Array.isArray(value);
30183
30629
  }
30184
30630
  function readCursorHooks(path) {
30185
- if (!existsSync13(path)) return {};
30631
+ if (!existsSync14(path)) return {};
30186
30632
  let parsed;
30187
30633
  try {
30188
- parsed = JSON.parse(readFileSync14(path, "utf8"));
30634
+ parsed = JSON.parse(readFileSync16(path, "utf8"));
30189
30635
  } catch {
30190
30636
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
30191
30637
  }
@@ -40105,8 +40551,8 @@ function parsePreflightResponse(value) {
40105
40551
  function decisionDisclosureContext(response) {
40106
40552
  return response.decisionDisclosures?.map(({ decisionId }) => `[primitive] hidden Decision: prim decisions show ${decisionId}`).join("\n") ?? "";
40107
40553
  }
40108
- async function requestPreflight(request2, signal = AbortSignal.timeout(PREFLIGHT_TIMEOUT_MS)) {
40109
- const response = await getClient().post("/api/cli/decisions/conflict-check", request2, {
40554
+ async function requestPreflight(request3, signal = AbortSignal.timeout(PREFLIGHT_TIMEOUT_MS)) {
40555
+ const response = await getClient().post("/api/cli/decisions/conflict-check", request3, {
40110
40556
  signal,
40111
40557
  quietRefresh: true
40112
40558
  });
@@ -40124,6 +40570,13 @@ function proposedChangeExcerpt(proposal) {
40124
40570
  }
40125
40571
  return boundedHealthError(proposal);
40126
40572
  }
40573
+ var COVERAGE_NOTE = "[primitive] Decision coverage is incomplete; some candidates or evidence were not evaluated.";
40574
+ function coverageNote(response) {
40575
+ const coverage = response.evaluationCoverage;
40576
+ if (!coverage) return "";
40577
+ const settled = coverage.status === "completed" || isEmptyCheck(response);
40578
+ return !settled || coverage.selectionOmissions?.length || coverage.evidenceOmissions?.length ? COVERAGE_NOTE : "";
40579
+ }
40127
40580
  function resultForPreflight(response, preview = "Review the requested change.", invocation, proposalTruncated = false) {
40128
40581
  const verdict = response.verdict === "block" ? "deny" : response.verdict;
40129
40582
  const silentCoverageOutcome = response.reasonCode === "coverage_unverified" || response.reasonCode === "candidate_set_truncated";
@@ -40159,6 +40612,7 @@ function resultForPreflight(response, preview = "Review the requested change.",
40159
40612
  conflicts: response.conflicts,
40160
40613
  message,
40161
40614
  reasonCode: response.reasonCode,
40615
+ verdict: response.verdict,
40162
40616
  evaluationCoverage: response.evaluationCoverage
40163
40617
  },
40164
40618
  preview
@@ -40525,7 +40979,7 @@ async function main() {
40525
40979
  const callId = invocationId(envelope);
40526
40980
  if (!binding || typeof sessionId !== "string" || !sessionId || !callId) {
40527
40981
  await unverified(
40528
- !binding ? "GitHub repo connection is required" : "Session or tool identity is missing"
40982
+ !binding ? cloudSetupPointer("GitHub repo connection is required") : "Session or tool identity is missing"
40529
40983
  );
40530
40984
  return;
40531
40985
  }
@@ -40556,12 +41010,12 @@ async function main() {
40556
41010
  proposal: collectScopeAdmits2 ? proposalFor(proposalInput) : ""
40557
41011
  };
40558
41012
  if (agent === "claude_code") {
40559
- const request3 = { ...common, protocolVersion: 3 };
41013
+ const request4 = { ...common, protocolVersion: 3 };
40560
41014
  let result2;
40561
41015
  try {
40562
41016
  const remaining = Math.floor(Math.min(PREFLIGHT_TIMEOUT_MS, deadline - performance.now()));
40563
41017
  if (remaining <= 0) throw new Error("Deadline exceeded");
40564
- const response = await requestPreflight(request3, AbortSignal.timeout(remaining));
41018
+ const response = await requestPreflight(request4, AbortSignal.timeout(remaining));
40565
41019
  if (!response) {
40566
41020
  await unverified("Decision check returned an invalid response");
40567
41021
  return;
@@ -40569,21 +41023,18 @@ async function main() {
40569
41023
  result2 = resultForPreflight(
40570
41024
  response,
40571
41025
  editPreview(toolName, envelope.tool_input, targets.paths),
40572
- request3,
41026
+ request4,
40573
41027
  collectScopeAdmits2 && protectedShell && proposalIsTruncated(proposalInput)
40574
41028
  );
40575
41029
  if (result2.verdict === "unavailable") {
40576
41030
  result2.unavailable = `${result2.unavailable || "Decision check is unavailable"}; change was not verified.`;
40577
41031
  }
40578
- const coverage = response.evaluationCoverage;
40579
41032
  const notes = [
40580
41033
  ...targets.coverage === "unverified" ? [
40581
41034
  "[primitive] Some mutation targets could not be resolved; the complete change was not verified."
40582
41035
  ] : [],
40583
- ...coverage && (coverage.status !== "completed" || coverage.selectionOmissions?.length || coverage.evidenceOmissions?.length) ? [
40584
- "[primitive] Decision coverage is incomplete; some candidates or evidence were not evaluated."
40585
- ] : []
40586
- ];
41036
+ coverageNote(response)
41037
+ ].filter(Boolean);
40587
41038
  if (notes.length > 0) {
40588
41039
  const note = notes.join("\n");
40589
41040
  result2.reason = [result2.reason, note].filter(Boolean).join("\n");
@@ -40602,7 +41053,7 @@ async function main() {
40602
41053
  );
40603
41054
  return;
40604
41055
  }
40605
- const request2 = {
41056
+ const request3 = {
40606
41057
  ...common,
40607
41058
  protocolVersion: PREFLIGHT_PROTOCOL_VERSION2,
40608
41059
  operation: "start",
@@ -40615,7 +41066,7 @@ async function main() {
40615
41066
  };
40616
41067
  let result;
40617
41068
  try {
40618
- const response = await waitForPreflight(request2, {
41069
+ const response = await waitForPreflight(request3, {
40619
41070
  deadline,
40620
41071
  stopOnConflict: true
40621
41072
  });
@@ -40626,7 +41077,7 @@ async function main() {
40626
41077
  result = resultForPreflight2(
40627
41078
  response,
40628
41079
  editPreview(toolName, envelope.tool_input, targets.paths),
40629
- request2,
41080
+ request3,
40630
41081
  collectScopeAdmits2 && (toolName === "Bash" || toolName === "Shell") && proposalIsTruncated(proposalInput)
40631
41082
  );
40632
41083
  } catch {