@primitive.ai/prim 0.1.0-alpha.127 → 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 (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
  3. package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
  4. package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
  5. package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
  6. package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
  7. package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
  8. package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
  9. package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
  10. package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
  11. package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
  12. package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
  13. package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
  14. package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
  15. package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
  16. package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
  17. package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
  19. package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
  20. package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
  21. package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
  22. package/dist/daemon/server.js +1311 -364
  23. package/dist/hook-runtime/daemon/server.js +1311 -364
  24. package/dist/hook-runtime/hooks/post-commit.js +395 -242
  25. package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
  27. package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
  29. package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
  30. package/dist/hook-runtime/hooks/session-end.js +369 -216
  31. package/dist/hook-runtime/hooks/session-start.js +1209 -219
  32. package/dist/hook-runtime/index.js +2406 -1036
  33. package/dist/hook-runtime/statusline-main.js +360 -207
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +18 -18
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +63 -20
  42. package/dist/index.js +387 -43
  43. package/dist/statusline-main.js +360 -207
  44. package/package.json +1 -1
@@ -203,6 +203,7 @@ function insideClaudeCode(env = process.env) {
203
203
  }
204
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
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}.`;
206
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";
207
208
  function cloudSetupPointer(message, env = process.env) {
208
209
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
@@ -218,13 +219,20 @@ var GIT_TIMEOUT_MS = 1e3;
218
219
  var MAX_SETTINGS_BYTES = 1024 * 1024;
219
220
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
220
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
+ }
221
228
  function gitToplevel(cwd) {
222
229
  try {
223
230
  return execFileSync("git", ["rev-parse", "--show-toplevel"], {
224
231
  cwd,
225
232
  encoding: "utf-8",
226
233
  stdio: ["ignore", "pipe", "ignore"],
227
- timeout: GIT_TIMEOUT_MS
234
+ timeout: GIT_TIMEOUT_MS,
235
+ env: gitChildEnvironment()
228
236
  }).trim();
229
237
  } catch {
230
238
  return null;
@@ -239,7 +247,8 @@ function mainWorktreeRoot(cwd) {
239
247
  cwd,
240
248
  encoding: "utf-8",
241
249
  stdio: ["ignore", "pipe", "ignore"],
242
- timeout: GIT_TIMEOUT_MS
250
+ timeout: GIT_TIMEOUT_MS,
251
+ env: gitChildEnvironment()
243
252
  }
244
253
  ).trim().split("\n").map((value) => resolve(cwd ?? process.cwd(), value));
245
254
  if (gitDir === void 0 || commonDir === void 0 || gitDir === commonDir) return null;
@@ -254,7 +263,8 @@ function gitValue(cwd, args) {
254
263
  cwd,
255
264
  encoding: "utf-8",
256
265
  stdio: ["ignore", "pipe", "ignore"],
257
- timeout: GIT_TIMEOUT_MS
266
+ timeout: GIT_TIMEOUT_MS,
267
+ env: gitChildEnvironment()
258
268
  }).trim();
259
269
  return value || void 0;
260
270
  } catch {
@@ -292,7 +302,8 @@ function isGitIgnored(cwd, path) {
292
302
  execFileSync("git", ["check-ignore", "--quiet", "--", path], {
293
303
  cwd,
294
304
  stdio: ["ignore", "ignore", "ignore"],
295
- timeout: GIT_TIMEOUT_MS
305
+ timeout: GIT_TIMEOUT_MS,
306
+ env: gitChildEnvironment()
296
307
  });
297
308
  return true;
298
309
  } catch {
@@ -1339,10 +1350,10 @@ function parseWorkosConnectTokens(value, options = {}) {
1339
1350
  "access_token",
1340
1351
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
1341
1352
  );
1342
- 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);
1343
1354
  return {
1344
1355
  accessToken,
1345
- refreshToken,
1356
+ refreshToken: refreshToken2,
1346
1357
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
1347
1358
  };
1348
1359
  }
@@ -1657,6 +1668,58 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
1657
1668
  return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
1658
1669
  }
1659
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
+
1660
1723
  // src/lib/machine-credentials.ts
1661
1724
  import { execFileSync as execFileSync4 } from "child_process";
1662
1725
  import { createHash as createHash4, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
@@ -2058,6 +2121,9 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
2058
2121
  }
2059
2122
 
2060
2123
  // src/lib/machine-credentials.ts
2124
+ function sessionScoped(deps) {
2125
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2126
+ }
2061
2127
  var require2 = createRequire(import.meta.url);
2062
2128
  var SERVICE = "ai.primitive.prim.machine";
2063
2129
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
@@ -2185,6 +2251,9 @@ function writePrivate(path, value) {
2185
2251
  `, { mode: 384 });
2186
2252
  protectPath(path, false);
2187
2253
  }
2254
+ function readMachineMetadata(path) {
2255
+ return readPrivate(path);
2256
+ }
2188
2257
  function readPrivate(path) {
2189
2258
  let raw;
2190
2259
  try {
@@ -2361,6 +2430,7 @@ function hasMachineConfiguration(deps = {}) {
2361
2430
  }
2362
2431
  function machineContext(deps = {}) {
2363
2432
  if (!hasMachineConfiguration(deps)) return void 0;
2433
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
2364
2434
  const environment = environmentCredentials(deps);
2365
2435
  if (environment) {
2366
2436
  if (environmentTerminal === environment.generation) return void 0;
@@ -2375,6 +2445,7 @@ function machineContext(deps = {}) {
2375
2445
  return profile;
2376
2446
  }
2377
2447
  function cachedMachineCredential(deps = {}) {
2448
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
2378
2449
  const context = machineContext(deps);
2379
2450
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
2380
2451
  }
@@ -2526,6 +2597,7 @@ async function configureMachine(clientId, clientSecret, deps = {}, signal) {
2526
2597
  }
2527
2598
  async function acquireMachineCredential(options = {}, deps = {}) {
2528
2599
  if (!hasMachineConfiguration(deps)) return void 0;
2600
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
2529
2601
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2530
2602
  const apiUrl = apiUrlFor(deps);
2531
2603
  const environment = environmentCredentials(deps);
@@ -2839,19 +2911,1026 @@ function writeMachineMetadata(path, value) {
2839
2911
  writePrivate(path, value);
2840
2912
  }
2841
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
+
2842
3921
  // src/lib/credentials.ts
2843
- import { createHash as createHash5 } from "crypto";
3922
+ import { createHash as createHash6 } from "crypto";
2844
3923
  import { readFileSync as readFileSync9 } from "fs";
2845
- import { join as join10 } from "path";
3924
+ import { join as join11 } from "path";
2846
3925
  var CONFIG_DIRECTORY = primConfigDirectory();
2847
- var TOKEN_FILE_PATH = join10(CONFIG_DIRECTORY, "token");
2848
- var REFRESH_TOKEN_PATH = join10(CONFIG_DIRECTORY, "refresh_token");
2849
- var TOKEN_EXPIRES_PATH = join10(CONFIG_DIRECTORY, "token_expires_at");
2850
- var TERMINAL_REFRESH_PATH = join10(CONFIG_DIRECTORY, "refresh_terminal");
2851
- var CREDENTIAL_METADATA_PATH = join10(CONFIG_DIRECTORY, "credential_metadata.json");
2852
- var CREDENTIAL_FAMILY_PATH = join10(CONFIG_DIRECTORY, "credential_family.json");
2853
- var CREDENTIAL_MIGRATION_PATH = join10(CONFIG_DIRECTORY, "credential_migration.json");
2854
- var CREDENTIAL_LOCK_PATH = join10(CONFIG_DIRECTORY, "credentials.lock");
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");
2855
3934
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
2856
3935
  var CREDENTIAL_MIGRATION_VERSION = 1;
2857
3936
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
@@ -2879,16 +3958,16 @@ function resolveAuthCredential(options = {}) {
2879
3958
  );
2880
3959
  if (metadata.state === "legacy_broker") {
2881
3960
  if (metadata.metadata) {
2882
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2883
- 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)) {
2884
3963
  return void 0;
2885
3964
  }
2886
3965
  }
2887
3966
  return { token: stored, source: "token_file" };
2888
3967
  }
2889
3968
  if (metadata.state === "invalid") return void 0;
2890
- const refreshToken = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
2891
- 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)) {
2892
3971
  return void 0;
2893
3972
  }
2894
3973
  return { token: stored, source: "token_file" };
@@ -2897,15 +3976,15 @@ function resolveStoredCredential(env = process.env) {
2897
3976
  const directory = primConfigDirectory({ env });
2898
3977
  return resolveAuthCredential({
2899
3978
  env,
2900
- tokenFilePath: join10(directory, "token"),
2901
- refreshTokenPath: join10(directory, "refresh_token"),
2902
- metadataPath: join10(directory, "credential_metadata.json"),
2903
- familyPath: join10(directory, "credential_family.json"),
2904
- migrationPath: join10(directory, "credential_migration.json")
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")
2905
3984
  });
2906
3985
  }
2907
3986
  function credentialFingerprint(value) {
2908
- return createHash5("sha256").update(value).digest("hex");
3987
+ return createHash6("sha256").update(value).digest("hex");
2909
3988
  }
2910
3989
  function parseLegacyBrokerCredentialMetadata(value) {
2911
3990
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -3027,7 +4106,7 @@ export {
3027
4106
  isClaudeCloudSession,
3028
4107
  insideClaudeCode,
3029
4108
  CLOUD_CREDENTIALS_REMEDY,
3030
- CLOUD_REJECTED_CREDENTIALS_REMEDY,
4109
+ CLOUD_REJECTED_CREDENTIALS_NOTICE,
3031
4110
  CLOUD_GITHUB_CONNECT_REMEDY,
3032
4111
  cloudSetupPointer,
3033
4112
  CLOUD_SETUP_POINTER,
@@ -3051,6 +4130,29 @@ export {
3051
4130
  primConfigDirectory,
3052
4131
  clearMachineCooldowns,
3053
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,
3054
4156
  readMachineProfile,
3055
4157
  NETWORK_TOKEN_AUTH,
3056
4158
  environmentCredentials,
@@ -3096,18 +4198,6 @@ export {
3096
4198
  endDemoPause,
3097
4199
  clearDemoPause,
3098
4200
  healDemoPause,
3099
- gitToplevel,
3100
- mainWorktreeRoot,
3101
- currentBranch,
3102
- parseGithubRepositoryName,
3103
- originIdentifiesRepository,
3104
- originGithubRepository,
3105
- isGitIgnored,
3106
- githubRepositoryFullName,
3107
- canonicalGitRoot,
3108
- relatedWorktreeTarget,
3109
- resolveRepositoryContext,
3110
- canonicalRepositoryPath,
3111
4201
  PRIM_ACTIVE_DECLARATION,
3112
4202
  repoActiveFlag,
3113
4203
  setRepoActive,