@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
@@ -54,33 +54,33 @@ var require_ucs2length = __commonJS({
54
54
 
55
55
  // src/hooks/post-tool-use.ts
56
56
  import { readFileSync as readFileSync22 } from "fs";
57
- import { dirname as dirname14, join as join26 } from "path";
57
+ import { dirname as dirname14, join as join27 } from "path";
58
58
  import { fileURLToPath as fileURLToPath5 } from "url";
59
59
 
60
60
  // src/binding.ts
61
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
62
- import { dirname as dirname5, join as join8 } from "path";
61
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
62
+ import { dirname as dirname6, join as join10 } from "path";
63
63
 
64
64
  // src/lib/credentials.ts
65
- import { createHash as createHash4 } from "crypto";
66
- import { readFileSync as readFileSync6 } from "fs";
67
- import { join as join7 } from "path";
65
+ import { createHash as createHash6 } from "crypto";
66
+ import { readFileSync as readFileSync7 } from "fs";
67
+ import { join as join9 } from "path";
68
68
 
69
69
  // src/lib/machine-credentials.ts
70
- import { execFileSync } from "child_process";
71
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
70
+ import { execFileSync as execFileSync2 } from "child_process";
71
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
72
72
  import {
73
73
  chmodSync,
74
74
  existsSync as existsSync3,
75
75
  linkSync,
76
- lstatSync as lstatSync3,
76
+ lstatSync as lstatSync4,
77
77
  mkdirSync as mkdirSync3,
78
- readFileSync as readFileSync5,
79
- rmSync as rmSync5,
78
+ readFileSync as readFileSync6,
79
+ rmSync as rmSync6,
80
80
  writeFileSync as writeFileSync3
81
81
  } from "fs";
82
82
  import { createRequire } from "module";
83
- import { dirname as dirname4, join as join6 } from "path";
83
+ import { dirname as dirname5, join as join8 } from "path";
84
84
  import { fileURLToPath as fileURLToPath3 } from "url";
85
85
 
86
86
  // src/lib/atomic-file.ts
@@ -454,6 +454,8 @@ function isClaudeCloudSession(env = process.env) {
454
454
  }
455
455
  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';
456
456
  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';
457
+ 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}.`;
458
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
457
459
  function cloudSetupPointer(message, env = process.env) {
458
460
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
459
461
  }
@@ -595,10 +597,10 @@ function parseWorkosConnectTokens(value, options = {}) {
595
597
  "access_token",
596
598
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
597
599
  );
598
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
600
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
599
601
  return {
600
602
  accessToken,
601
- refreshToken: refreshToken2,
603
+ refreshToken: refreshToken3,
602
604
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
603
605
  };
604
606
  }
@@ -1201,32 +1203,1264 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
1201
1203
  }
1202
1204
  }
1203
1205
 
1206
+ // src/lib/session-identity.ts
1207
+ import { execFile } from "child_process";
1208
+ import { createHash as createHash4 } from "crypto";
1209
+ import { rmSync as rmSync5 } from "fs";
1210
+ import { join as join7 } from "path";
1211
+ import { promisify } from "util";
1212
+
1213
+ // src/lib/git.ts
1214
+ import { execFileSync } from "child_process";
1215
+ import { createHash as createHash3 } from "crypto";
1216
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
1217
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
1218
+ var GIT_TIMEOUT_MS = 1e3;
1219
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1220
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1221
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1222
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1223
+ function gitChildEnvironment(env = process.env) {
1224
+ return Object.fromEntries(
1225
+ Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
1226
+ );
1227
+ }
1228
+ function gitToplevel(cwd) {
1229
+ try {
1230
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1231
+ cwd,
1232
+ encoding: "utf-8",
1233
+ stdio: ["ignore", "pipe", "ignore"],
1234
+ timeout: GIT_TIMEOUT_MS,
1235
+ env: gitChildEnvironment()
1236
+ }).trim();
1237
+ } catch {
1238
+ return null;
1239
+ }
1240
+ }
1241
+ function gitValue(cwd, args) {
1242
+ try {
1243
+ const value = execFileSync("git", args, {
1244
+ cwd,
1245
+ encoding: "utf-8",
1246
+ stdio: ["ignore", "pipe", "ignore"],
1247
+ timeout: GIT_TIMEOUT_MS,
1248
+ env: gitChildEnvironment()
1249
+ }).trim();
1250
+ return value || void 0;
1251
+ } catch {
1252
+ return void 0;
1253
+ }
1254
+ }
1255
+ function currentBranch(cwd) {
1256
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1257
+ }
1258
+ function parseGithubRepositoryName(path) {
1259
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1260
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1261
+ return null;
1262
+ }
1263
+ return `${parts[0]}/${parts[1]}`;
1264
+ }
1265
+ function githubRepositoryFromRemote(remote) {
1266
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1267
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1268
+ remote
1269
+ );
1270
+ const path = match?.[1] ?? match?.[2];
1271
+ return path ? parseGithubRepositoryName(path) : null;
1272
+ }
1273
+ function checkoutSettingsText(repoRoot) {
1274
+ const path = join6(repoRoot, ".claude", "settings.json");
1275
+ try {
1276
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
1277
+ const stat = lstatSync3(path);
1278
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1279
+ return readFileSync5(path, "utf8");
1280
+ } catch {
1281
+ return null;
1282
+ }
1283
+ }
1284
+ function checkoutDeclaration(repoRoot, name2) {
1285
+ const text = checkoutSettingsText(repoRoot);
1286
+ if (text === null) return null;
1287
+ let parsed;
1288
+ try {
1289
+ parsed = JSON.parse(text);
1290
+ } catch {
1291
+ return null;
1292
+ }
1293
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1294
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
1295
+ return typeof value === "string" ? value : null;
1296
+ }
1297
+ function declaredGithubRepository(repoRoot) {
1298
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1299
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1300
+ }
1301
+ function githubRepositoryFullName(cwd) {
1302
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1303
+ if (remote) {
1304
+ const fromOrigin = githubRepositoryFromRemote(remote);
1305
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1306
+ }
1307
+ const root = gitToplevel(cwd);
1308
+ return root ? declaredGithubRepository(root) : null;
1309
+ }
1310
+ function canonicalGitRoot(cwd) {
1311
+ try {
1312
+ const top = gitToplevel(cwd);
1313
+ return top ? realpathSync.native(top) : null;
1314
+ } catch {
1315
+ return null;
1316
+ }
1317
+ }
1318
+ function relatedWorktreeTarget(path, cwd, origin) {
1319
+ let parent = dirname4(resolve(cwd, path));
1320
+ while (true) {
1321
+ try {
1322
+ realpathSync.native(parent);
1323
+ break;
1324
+ } catch {
1325
+ const next = dirname4(parent);
1326
+ if (next === parent) return null;
1327
+ parent = next;
1328
+ }
1329
+ }
1330
+ const target = resolveRepositoryContext(parent);
1331
+ if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
1332
+ const common = (root) => {
1333
+ const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
1334
+ try {
1335
+ return value ? realpathSync.native(resolve(root, value)) : void 0;
1336
+ } catch {
1337
+ return void 0;
1338
+ }
1339
+ };
1340
+ const originCommon = common(origin.repoRoot);
1341
+ return originCommon && originCommon === common(target.repoRoot) ? target : null;
1342
+ }
1343
+ function normalizeOriginRemote(remote) {
1344
+ const value = remote.trim();
1345
+ if (!value) return void 0;
1346
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1347
+ if (scp?.host && scp.path) {
1348
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1349
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1350
+ }
1351
+ try {
1352
+ const url = new URL(value);
1353
+ url.username = "";
1354
+ url.password = "";
1355
+ url.search = "";
1356
+ url.hash = "";
1357
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1358
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1359
+ return void 0;
1360
+ } catch {
1361
+ return void 0;
1362
+ }
1363
+ }
1364
+ function opaqueRepoKey(source, value) {
1365
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
1366
+ }
1367
+ function resolveRepositoryContext(cwd = process.cwd()) {
1368
+ const top = gitToplevel(cwd);
1369
+ if (!top) return null;
1370
+ let repoRoot;
1371
+ try {
1372
+ repoRoot = realpathSync.native(top);
1373
+ } catch {
1374
+ repoRoot = resolve(top);
1375
+ }
1376
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1377
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1378
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1379
+ if (normalizedOrigin) {
1380
+ return {
1381
+ repoRoot,
1382
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
1383
+ identitySource: "origin",
1384
+ repoFullName
1385
+ };
1386
+ }
1387
+ if (repoFullName) {
1388
+ return {
1389
+ repoRoot,
1390
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1391
+ identitySource: "declared",
1392
+ repoFullName
1393
+ };
1394
+ }
1395
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1396
+ if (roots && roots.length > 0) {
1397
+ return {
1398
+ repoRoot,
1399
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1400
+ identitySource: "root_commit",
1401
+ repoFullName
1402
+ };
1403
+ }
1404
+ return { repoRoot, repoFullName };
1405
+ }
1406
+ function nearestExistingAncestor(path) {
1407
+ const suffix = [];
1408
+ let cursor = path;
1409
+ while (true) {
1410
+ try {
1411
+ lstatSync3(cursor);
1412
+ break;
1413
+ } catch (error) {
1414
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1415
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1416
+ const parent = dirname4(cursor);
1417
+ if (parent === cursor) return null;
1418
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1419
+ cursor = parent;
1420
+ }
1421
+ }
1422
+ try {
1423
+ return { real: realpathSync.native(cursor), suffix };
1424
+ } catch {
1425
+ return null;
1426
+ }
1427
+ }
1428
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1429
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1430
+ return { ok: false, reason: "invalid_path" };
1431
+ }
1432
+ const absolute = resolve(baseDir, filePath);
1433
+ const resolved = nearestExistingAncestor(absolute);
1434
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1435
+ const target = resolve(resolved.real, ...resolved.suffix);
1436
+ const rel = relative(context.repoRoot, target);
1437
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1438
+ if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1439
+ return { ok: false, reason: "outside_repository" };
1440
+ }
1441
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1442
+ }
1443
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1444
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1445
+ return null;
1446
+ const absolute = resolve(cwd, filePath);
1447
+ let target;
1448
+ try {
1449
+ const stat = lstatSync3(absolute);
1450
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1451
+ target = realpathSync.native(absolute);
1452
+ } catch (error) {
1453
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1454
+ return null;
1455
+ }
1456
+ try {
1457
+ const parent = realpathSync.native(dirname4(absolute));
1458
+ if (!lstatSync3(parent).isDirectory()) return null;
1459
+ target = resolve(parent, basename2(absolute));
1460
+ } catch {
1461
+ return null;
1462
+ }
1463
+ }
1464
+ const rel = relative(repositoryRoot, target);
1465
+ if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1466
+ return null;
1467
+ }
1468
+ return sep === "/" ? rel : rel.split(sep).join("/");
1469
+ }
1470
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1471
+ if (typeof contextOrCwd === "string") {
1472
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1473
+ }
1474
+ return canonicalRepositoryPathScoped(
1475
+ filePath,
1476
+ contextOrCwd,
1477
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1478
+ );
1479
+ }
1480
+
1481
+ // src/lib/terminal-safe.ts
1482
+ function replaceIsolatedSurrogates(value) {
1483
+ let out = "";
1484
+ for (let index = 0; index < value.length; index += 1) {
1485
+ const unit = value.charCodeAt(index);
1486
+ if (unit >= 55296 && unit <= 56319) {
1487
+ const next = value.charCodeAt(index + 1);
1488
+ if (next >= 56320 && next <= 57343) {
1489
+ out += value[index] + value[index + 1];
1490
+ index += 1;
1491
+ } else {
1492
+ out += "\uFFFD";
1493
+ }
1494
+ } else if (unit >= 56320 && unit <= 57343) {
1495
+ out += "\uFFFD";
1496
+ } else {
1497
+ out += value[index];
1498
+ }
1499
+ }
1500
+ return out;
1501
+ }
1502
+ function isUnsafeTerminalCodePoint(point) {
1503
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1504
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1505
+ point === 1564 || // Arabic letter mark
1506
+ point === 6158 || // Mongolian vowel separator
1507
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1508
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1509
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1510
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1511
+ point === 65279 || // zero-width no-break space / BOM
1512
+ point >= 917504 && point <= 917631;
1513
+ return c0OrC1 || bidiOrZeroWidth;
1514
+ }
1515
+ function terminalSafeText(value) {
1516
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1517
+ }
1518
+ function terminalSafeLine(value) {
1519
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1520
+ }
1521
+ var stripControlChars = terminalSafeText;
1522
+
1523
+ // src/lib/session-identity.ts
1524
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1525
+ var SESSION_IDENTITY_VALUE = "session";
1526
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1527
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1528
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1529
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1530
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1531
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1532
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1533
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1534
+ var SESSION_IDENTITY_ROUTES = {
1535
+ challenge: "/api/cli/session-identity/challenge",
1536
+ token: "/api/cli/session-identity/token",
1537
+ refresh: "/api/cli/session-identity/token/refresh",
1538
+ link: "/api/cli/session-identity/link"
1539
+ };
1540
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1541
+ var RENEW_BEFORE_MS = 6e4;
1542
+ var GIT_TIMEOUT_MS2 = 1e4;
1543
+ var POLL_BUDGET_MS = 15e3;
1544
+ var POLL_FIRST_DELAY_MS = 500;
1545
+ var POLL_MAX_DELAY_MS = 3e3;
1546
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1547
+ var LOCK_TIMEOUT_MS = 6e4;
1548
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1549
+ function sessionIdentityRequested(env = process.env) {
1550
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1551
+ }
1552
+ function sessionIdentityMode(deps = {}) {
1553
+ const env = deps.env ?? process.env;
1554
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1555
+ }
1556
+ function failure(code, cause, remedy) {
1557
+ return { status: "failed", code, cause, remedy };
1558
+ }
1559
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1560
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1561
+ 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';
1562
+ var SESSION_REVOKED = failure(
1563
+ "session_revoked",
1564
+ "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",
1565
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1566
+ );
1567
+ var CHALLENGE_WINDOW_PASSED = failure(
1568
+ "challenge_expired",
1569
+ "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)",
1570
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1571
+ );
1572
+ var CHALLENGE_GONE = failure(
1573
+ "challenge_not_found",
1574
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1575
+ NEW_SESSION_REMEDY
1576
+ );
1577
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1578
+ function rejectionFailure(reason, repository) {
1579
+ switch (reason) {
1580
+ case "identity_mismatch":
1581
+ return failure(
1582
+ "identity_mismatch",
1583
+ "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",
1584
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1585
+ );
1586
+ case "push_after_expiry":
1587
+ return failure(
1588
+ "push_after_expiry",
1589
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1590
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1591
+ );
1592
+ case "repository_mismatch":
1593
+ return failure(
1594
+ "repository_mismatch",
1595
+ `Primitive received the identity push from a different repository than ${repository}`,
1596
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1597
+ );
1598
+ case "conflicting_push":
1599
+ return failure(
1600
+ "conflicting_push",
1601
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1602
+ NEW_SESSION_REMEDY
1603
+ );
1604
+ case "unsupported_sender":
1605
+ return failure(
1606
+ "unsupported_sender",
1607
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1608
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1609
+ );
1610
+ default:
1611
+ return failure(
1612
+ "challenge_rejected",
1613
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1614
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1615
+ );
1616
+ }
1617
+ }
1618
+ function sessionIdentityMessage(outcome) {
1619
+ if (outcome.status === "link_required")
1620
+ 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.`;
1621
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1622
+ }
1623
+ function hash(value) {
1624
+ return createHash4("sha256").update(value).digest("hex");
1625
+ }
1626
+ function sessionContext(deps) {
1627
+ const env = deps.env ?? process.env;
1628
+ const environment = environmentCredentials(deps);
1629
+ if (!environment)
1630
+ return failure(
1631
+ "environment_credential_missing",
1632
+ "the cloud environment has no environment credential",
1633
+ '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'
1634
+ );
1635
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1636
+ if (!sessionId || !SESSION_ID.test(sessionId))
1637
+ return failure(
1638
+ "session_id_missing",
1639
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1640
+ NEW_SESSION_REMEDY
1641
+ );
1642
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1643
+ const directory = deps.directory ?? primConfigDirectory({ env });
1644
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1645
+ return {
1646
+ directory,
1647
+ apiUrl,
1648
+ clientId: environment.clientId,
1649
+ generation: environment.generation,
1650
+ sessionId,
1651
+ tokenPath: join7(directory, `session_identity_${key}.json`),
1652
+ statePath: join7(directory, `session_identity_${key}.state.json`),
1653
+ lockPath: join7(directory, "session-identity.lock")
1654
+ };
1655
+ }
1656
+ function readRecord(path) {
1657
+ try {
1658
+ const value = readMachineMetadata(path);
1659
+ return value === void 0 ? void 0 : machineRecord(value);
1660
+ } catch {
1661
+ return void 0;
1662
+ }
1663
+ }
1664
+ function finiteNumber(value) {
1665
+ return typeof value === "number" && Number.isFinite(value);
1666
+ }
1667
+ function readToken(context) {
1668
+ const data = readRecord(context.tokenPath);
1669
+ 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))
1670
+ return void 0;
1671
+ const identity = data.identity;
1672
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1673
+ return void 0;
1674
+ return data;
1675
+ }
1676
+ function readState(context) {
1677
+ const data = readRecord(context.statePath);
1678
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1679
+ return void 0;
1680
+ return data;
1681
+ }
1682
+ function writeToken(context, record) {
1683
+ prepareMachineMetadataDirectory(context.directory);
1684
+ writeMachineMetadata(context.tokenPath, record);
1685
+ rmSync5(context.statePath, { force: true });
1686
+ }
1687
+ function writeState(context, state) {
1688
+ try {
1689
+ prepareMachineMetadataDirectory(context.directory);
1690
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1691
+ } catch {
1692
+ }
1693
+ }
1694
+ function tokenValid(record, now = Date.now()) {
1695
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1696
+ }
1697
+ function tokenFresh(record, now = Date.now()) {
1698
+ return tokenValid(record, now) && now < record.refreshAfter;
1699
+ }
1700
+ function toCredential(record) {
1701
+ return {
1702
+ issuer: record.issuer,
1703
+ audience: record.audience,
1704
+ ...record.identity,
1705
+ accessToken: record.accessToken,
1706
+ expiresAt: record.expiresAt,
1707
+ apiUrl: record.apiUrl,
1708
+ generation: record.generation,
1709
+ storage: "environment",
1710
+ session: {
1711
+ userId: record.userId,
1712
+ displayName: record.displayName,
1713
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1714
+ refreshAfter: record.refreshAfter
1715
+ }
1716
+ };
1717
+ }
1718
+ function identified(record, reused) {
1719
+ return {
1720
+ status: "ok",
1721
+ credential: toCredential(record),
1722
+ displayName: record.displayName,
1723
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1724
+ reused
1725
+ };
1726
+ }
1727
+ function cachedSessionCredential(deps = {}) {
1728
+ if (!sessionIdentityMode(deps)) return void 0;
1729
+ let context;
1730
+ try {
1731
+ context = sessionContext(deps);
1732
+ } catch {
1733
+ return void 0;
1734
+ }
1735
+ if ("status" in context) return void 0;
1736
+ const record = readToken(context);
1737
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1738
+ }
1739
+ function outcomeFromState(state) {
1740
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1741
+ return {
1742
+ status: "link_required",
1743
+ githubLogin: state.githubLogin,
1744
+ challengeId: state.challengeId,
1745
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1746
+ };
1747
+ return failure(
1748
+ state.code,
1749
+ state.cause ?? "the last identity check failed",
1750
+ state.remedy ?? RETRY_REMEDY
1751
+ );
1752
+ }
1753
+ function parseInstant(value) {
1754
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1755
+ if (typeof value === "string" && value.length <= 64) {
1756
+ const parsed = Date.parse(value);
1757
+ return Number.isFinite(parsed) ? parsed : void 0;
1758
+ }
1759
+ return void 0;
1760
+ }
1761
+ async function sendJson(url, init, fetchImpl) {
1762
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1763
+ let value;
1764
+ try {
1765
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1766
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1767
+ } catch {
1768
+ value = void 0;
1769
+ }
1770
+ return { status: response.status, value };
1771
+ }
1772
+ function environmentOnly(deps) {
1773
+ return { ...deps, environmentOnly: true };
1774
+ }
1775
+ async function environmentRequest(method, path, body, deps, signal) {
1776
+ const send = async (credential2) => {
1777
+ const headers = { "Content-Type": "application/json" };
1778
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1779
+ if (credential2.tokenInjection) {
1780
+ const response = await forwardMachineRequest(
1781
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1782
+ signal,
1783
+ environmentOnly(deps)
1784
+ );
1785
+ const parsed = await response.json().catch(() => void 0);
1786
+ return {
1787
+ status: response.status,
1788
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1789
+ };
1790
+ }
1791
+ return sendJson(
1792
+ `${credential2.apiUrl}${path}`,
1793
+ {
1794
+ method,
1795
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1796
+ ...text === void 0 ? {} : { body: text },
1797
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1798
+ },
1799
+ deps.fetch ?? fetch
1800
+ );
1801
+ };
1802
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1803
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1804
+ let answer = await send(credential);
1805
+ if (answer.status === 401) {
1806
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1807
+ if (!credential)
1808
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1809
+ answer = await send(credential);
1810
+ }
1811
+ return answer;
1812
+ }
1813
+ function environmentFailure(error, apiUrl) {
1814
+ if (error instanceof MachineAuthError && error.terminal)
1815
+ return failure(
1816
+ "environment_credential_rejected",
1817
+ "Primitive rejected the cloud environment's credential",
1818
+ ENVIRONMENT_CREDENTIAL_REMEDY
1819
+ );
1820
+ const host = (() => {
1821
+ try {
1822
+ return new URL(apiUrl).hostname;
1823
+ } catch {
1824
+ return "Primitive";
1825
+ }
1826
+ })();
1827
+ return failure(
1828
+ "identity_unavailable",
1829
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1830
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1831
+ );
1832
+ }
1833
+ function answerError(answer) {
1834
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1835
+ }
1836
+ async function git(root, args, signal) {
1837
+ try {
1838
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1839
+ cwd: root,
1840
+ encoding: "utf8",
1841
+ timeout: GIT_TIMEOUT_MS2,
1842
+ signal,
1843
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1844
+ maxBuffer: 1024 * 1024
1845
+ });
1846
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1847
+ } catch (error) {
1848
+ const failed = error;
1849
+ return {
1850
+ ok: false,
1851
+ code: typeof failed.code === "number" ? failed.code : void 0,
1852
+ stdout: failed.stdout ?? "",
1853
+ stderr: failed.stderr ?? "",
1854
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1855
+ };
1856
+ }
1857
+ }
1858
+ function gitDetail(stderr) {
1859
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1860
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1861
+ }
1862
+ async function defaultSleep2(milliseconds, signal) {
1863
+ await new Promise((resolve8, reject) => {
1864
+ const timer = setTimeout(resolve8, milliseconds);
1865
+ signal?.addEventListener(
1866
+ "abort",
1867
+ () => {
1868
+ clearTimeout(timer);
1869
+ reject(signal.reason);
1870
+ },
1871
+ { once: true }
1872
+ );
1873
+ });
1874
+ }
1875
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1876
+ const sleep = deps.sleep ?? defaultSleep2;
1877
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1878
+ let delay = POLL_FIRST_DELAY_MS;
1879
+ let unreachable;
1880
+ for (; ; ) {
1881
+ const remaining = deadline - Date.now();
1882
+ if (remaining <= 0) break;
1883
+ await sleep(Math.min(delay, remaining), signal);
1884
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1885
+ let answer;
1886
+ try {
1887
+ answer = await environmentRequest(
1888
+ "GET",
1889
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1890
+ void 0,
1891
+ deps,
1892
+ signal
1893
+ );
1894
+ } catch (error) {
1895
+ signal?.throwIfAborted();
1896
+ unreachable = error;
1897
+ continue;
1898
+ }
1899
+ if (answer.status === 404) return CHALLENGE_GONE;
1900
+ if (answer.status === 401 || answer.status === 403)
1901
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1902
+ if (answer.status < 200 || answer.status > 299) {
1903
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1904
+ continue;
1905
+ }
1906
+ unreachable = void 0;
1907
+ const status = answer.value;
1908
+ if (status?.status === "verified")
1909
+ return {
1910
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1911
+ };
1912
+ if (status?.status === "expired")
1913
+ return failure(
1914
+ "challenge_expired",
1915
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1916
+ NEW_SESSION_REMEDY
1917
+ );
1918
+ if (status?.status === "rejected")
1919
+ return rejectionFailure(status.reason, repository);
1920
+ }
1921
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1922
+ return failure(
1923
+ "webhook_timeout",
1924
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1925
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1926
+ );
1927
+ }
1928
+ function parseTokenAnswer(value) {
1929
+ if (!value) return void 0;
1930
+ const user = value.user;
1931
+ const expiresAt = parseInstant(value.expiresAt);
1932
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1933
+ 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))
1934
+ return void 0;
1935
+ return {
1936
+ accessToken: value.accessToken,
1937
+ expiresAt,
1938
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1939
+ userId: user.id,
1940
+ displayName: user.displayName,
1941
+ organizationId: value.organizationId
1942
+ };
1943
+ }
1944
+ var SERVER_CONTRACT_FAILURE = failure(
1945
+ "server_contract",
1946
+ "Primitive's answer did not identify the linked member",
1947
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1948
+ );
1949
+ async function recordFor(context, answer, extra, deps, signal) {
1950
+ let identity;
1951
+ let environment;
1952
+ try {
1953
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1954
+ identity = await verifyMachineIdentity(
1955
+ context.apiUrl,
1956
+ answer.accessToken,
1957
+ context.clientId,
1958
+ signal,
1959
+ deps.fetch
1960
+ );
1961
+ } catch (error) {
1962
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1963
+ return SERVER_CONTRACT_FAILURE;
1964
+ return environmentFailure(error, context.apiUrl);
1965
+ }
1966
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1967
+ return SERVER_CONTRACT_FAILURE;
1968
+ return {
1969
+ version: 1,
1970
+ apiUrl: context.apiUrl,
1971
+ clientId: context.clientId,
1972
+ generation: context.generation,
1973
+ sessionId: context.sessionId,
1974
+ issuer: environment.issuer,
1975
+ audience: environment.audience,
1976
+ accessToken: answer.accessToken,
1977
+ expiresAt: answer.expiresAt,
1978
+ refreshAfter: answer.refreshAfter,
1979
+ userId: answer.userId,
1980
+ displayName: answer.displayName,
1981
+ organizationId: answer.organizationId,
1982
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1983
+ identity,
1984
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1985
+ };
1986
+ }
1987
+ async function refreshToken(context, record, deps, signal) {
1988
+ let answer;
1989
+ try {
1990
+ answer = await environmentRequest(
1991
+ "POST",
1992
+ SESSION_IDENTITY_ROUTES.refresh,
1993
+ { accessToken: record.accessToken },
1994
+ deps,
1995
+ signal
1996
+ );
1997
+ } catch (error) {
1998
+ signal?.throwIfAborted();
1999
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
2000
+ }
2001
+ const code = answerError(answer);
2002
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
2003
+ return { status: "refused", failure: SESSION_REVOKED };
2004
+ if (answer.status === 401 || answer.status === 403)
2005
+ return {
2006
+ status: "refused",
2007
+ failure: environmentFailure(
2008
+ new MachineAuthError("rejected", "rejected", true),
2009
+ context.apiUrl
2010
+ )
2011
+ };
2012
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2013
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
2014
+ return { status: "unavailable" };
2015
+ return {
2016
+ status: "ok",
2017
+ record: {
2018
+ ...record,
2019
+ accessToken: token.accessToken,
2020
+ expiresAt: token.expiresAt,
2021
+ refreshAfter: token.refreshAfter,
2022
+ displayName: token.displayName
2023
+ }
2024
+ };
2025
+ }
2026
+ function exchangeRefusal(answer, repository) {
2027
+ if (answer.status === 404) return CHALLENGE_GONE;
2028
+ if (answer.status !== 409) return void 0;
2029
+ switch (answerError(answer)) {
2030
+ case "identity_mismatch":
2031
+ return rejectionFailure("identity_mismatch", repository);
2032
+ case "challenge_rejected":
2033
+ return rejectionFailure(answer.value?.reason, repository);
2034
+ case "challenge_expired":
2035
+ return CHALLENGE_WINDOW_PASSED;
2036
+ case "challenge_already_exchanged":
2037
+ return failure(
2038
+ "challenge_already_exchanged",
2039
+ "this session's identity check was already exchanged for a token this VM does not hold",
2040
+ NEW_SESSION_REMEDY
2041
+ );
2042
+ case "challenge_pending":
2043
+ return failure(
2044
+ "webhook_timeout",
2045
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
2046
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2047
+ );
2048
+ default:
2049
+ return void 0;
2050
+ }
2051
+ }
2052
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
2053
+ let answer;
2054
+ try {
2055
+ answer = await environmentRequest(
2056
+ "POST",
2057
+ SESSION_IDENTITY_ROUTES.token,
2058
+ { challengeId: challenge.challengeId },
2059
+ deps,
2060
+ signal
2061
+ );
2062
+ } catch (error) {
2063
+ signal?.throwIfAborted();
2064
+ return environmentFailure(error, context.apiUrl);
2065
+ }
2066
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
2067
+ const login = answer.value?.githubLogin;
2068
+ return {
2069
+ status: "link_required",
2070
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
2071
+ challengeId: challenge.challengeId,
2072
+ challengeExpiresAt: challenge.challengeExpiresAt
2073
+ };
2074
+ }
2075
+ const refused = exchangeRefusal(
2076
+ answer,
2077
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
2078
+ );
2079
+ if (refused) return refused;
2080
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2081
+ if (!token) {
2082
+ if (answer.status === 401 || answer.status === 403)
2083
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2084
+ return answer.status >= 500 ? environmentFailure(
2085
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2086
+ context.apiUrl
2087
+ ) : SERVER_CONTRACT_FAILURE;
2088
+ }
2089
+ return recordFor(
2090
+ context,
2091
+ token,
2092
+ { githubLogin: challenge.githubLogin, repositoryRoot },
2093
+ deps,
2094
+ signal
2095
+ );
2096
+ }
2097
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
2098
+ const env = deps.env ?? process.env;
2099
+ const repository = githubRepositoryFullName(root);
2100
+ if (!repository)
2101
+ return failure(
2102
+ "repository_unidentified",
2103
+ "this checkout does not name its GitHub repository",
2104
+ "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"
2105
+ );
2106
+ const branch = currentBranch(root);
2107
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
2108
+ return failure(
2109
+ "not_session_branch",
2110
+ `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`,
2111
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
2112
+ );
2113
+ attempt.branch = branch;
2114
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
2115
+ if (!baseSha) {
2116
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
2117
+ baseSha = head.stdout.trim();
2118
+ if (!head.ok || !SHA.test(baseSha))
2119
+ return failure(
2120
+ "no_commit",
2121
+ "this checkout has no commit to create the session branch at",
2122
+ NEW_SESSION_REMEDY
2123
+ );
2124
+ }
2125
+ const published = await git(
2126
+ root,
2127
+ [
2128
+ "for-each-ref",
2129
+ "--count=1",
2130
+ "--format=%(refname)",
2131
+ "--contains",
2132
+ baseSha,
2133
+ "refs/remotes/origin/"
2134
+ ],
2135
+ signal
2136
+ );
2137
+ if (!published.ok || published.stdout.trim() === "")
2138
+ return failure(
2139
+ "unpublished_commits",
2140
+ `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`,
2141
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
2142
+ );
2143
+ attempt.baseSha = baseSha;
2144
+ const remote = await git(
2145
+ root,
2146
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2147
+ signal
2148
+ );
2149
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2150
+ if (remote.ok && recorded) {
2151
+ Object.assign(attempt, recorded);
2152
+ return { ...recorded, repository };
2153
+ }
2154
+ if (remote.ok)
2155
+ return failure(
2156
+ "branch_exists",
2157
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2158
+ NEW_SESSION_REMEDY
2159
+ );
2160
+ if (remote.code !== 2)
2161
+ return failure(
2162
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2163
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2164
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2165
+ );
2166
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2167
+ Object.assign(attempt, recorded);
2168
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2169
+ }
2170
+ let answer;
2171
+ try {
2172
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2173
+ answer = await environmentRequest(
2174
+ "POST",
2175
+ SESSION_IDENTITY_ROUTES.challenge,
2176
+ {
2177
+ repositoryFullName: repository,
2178
+ claudeSessionId: context.sessionId,
2179
+ branch,
2180
+ baseSha,
2181
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2182
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2183
+ },
2184
+ deps,
2185
+ signal
2186
+ );
2187
+ } catch (error) {
2188
+ signal?.throwIfAborted();
2189
+ return environmentFailure(error, context.apiUrl);
2190
+ }
2191
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2192
+ return failure(
2193
+ "repository_not_connected",
2194
+ `${repository} is not connected to Primitive`,
2195
+ CLOUD_GITHUB_CONNECT_REMEDY
2196
+ );
2197
+ if (answer.status === 401 || answer.status === 403)
2198
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2199
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2200
+ return failure(
2201
+ "challenge_open",
2202
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2203
+ `wait five minutes, then ${RETRY_REMEDY}`
2204
+ );
2205
+ if (answer.status === 429)
2206
+ return failure(
2207
+ "too_many_challenges",
2208
+ "too many sessions of this cloud environment are being identified at once",
2209
+ `wait a few minutes, then ${RETRY_REMEDY}`
2210
+ );
2211
+ const challengeId = answer.value?.challengeId;
2212
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2213
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2214
+ return answer.status >= 500 ? environmentFailure(
2215
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2216
+ context.apiUrl
2217
+ ) : SERVER_CONTRACT_FAILURE;
2218
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2219
+ attempt.challengeId = challengeId;
2220
+ attempt.challengeExpiresAt = challengeExpiresAt;
2221
+ return pushSessionBranch(
2222
+ root,
2223
+ repository,
2224
+ branch,
2225
+ baseSha,
2226
+ { challengeId, challengeExpiresAt },
2227
+ signal
2228
+ );
2229
+ }
2230
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2231
+ const push = await git(
2232
+ root,
2233
+ [
2234
+ "-c",
2235
+ "core.hooksPath=/dev/null",
2236
+ "-c",
2237
+ "push.followTags=false",
2238
+ "-c",
2239
+ "push.recurseSubmodules=no",
2240
+ "-c",
2241
+ "push.gpgSign=false",
2242
+ "-c",
2243
+ "push.pushOption=",
2244
+ "push",
2245
+ "--no-verify",
2246
+ "--no-follow-tags",
2247
+ "--no-recurse-submodules",
2248
+ "--no-signed",
2249
+ "--quiet",
2250
+ "origin",
2251
+ `${baseSha}:refs/heads/${branch}`
2252
+ ],
2253
+ signal
2254
+ );
2255
+ if (!push.ok)
2256
+ return push.timedOut ? failure(
2257
+ "push_timeout",
2258
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2259
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2260
+ ) : failure(
2261
+ "push_refused",
2262
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2263
+ `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}`
2264
+ );
2265
+ return { ...challenge, repository };
2266
+ }
2267
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2268
+ let context;
2269
+ try {
2270
+ context = sessionContext(deps);
2271
+ } catch (error) {
2272
+ return failure(
2273
+ "environment_credential_invalid",
2274
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2275
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2276
+ );
2277
+ }
2278
+ if ("status" in context) return context;
2279
+ const ctx = context;
2280
+ const startedAt = Date.now();
2281
+ prepareMachineMetadataDirectory(ctx.directory);
2282
+ return withFileLock(
2283
+ ctx.lockPath,
2284
+ async () => {
2285
+ const record = readToken(ctx);
2286
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2287
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2288
+ if (record) {
2289
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2290
+ if (refreshed.status === "ok") {
2291
+ writeToken(ctx, refreshed.record);
2292
+ return identified(refreshed.record, true);
2293
+ }
2294
+ if (refreshed.status === "refused") {
2295
+ rmSync5(ctx.tokenPath, { force: true });
2296
+ writeState(ctx, {
2297
+ sessionId: ctx.sessionId,
2298
+ status: "failed",
2299
+ code: refreshed.failure.code,
2300
+ cause: refreshed.failure.cause,
2301
+ remedy: refreshed.failure.remedy,
2302
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2303
+ at: Date.now()
2304
+ });
2305
+ return refreshed.failure;
2306
+ }
2307
+ if (!forced && tokenValid(record)) return identified(record, true);
2308
+ }
2309
+ const state = readState(ctx);
2310
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2311
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2312
+ if (!options.explicit) {
2313
+ if (!root || !(record || state))
2314
+ return failure(
2315
+ "not_identified",
2316
+ "this session has not identified who started it yet",
2317
+ RETRY_REMEDY
2318
+ );
2319
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2320
+ } else if (state && state.at >= startedAt) {
2321
+ return outcomeFromState(state);
2322
+ }
2323
+ if (!root)
2324
+ return failure(
2325
+ "repository_missing",
2326
+ "this is not a git repository",
2327
+ "run it in the repository the session cloned"
2328
+ );
2329
+ const attempt = { root };
2330
+ const remember = (outcome) => {
2331
+ writeState(ctx, {
2332
+ sessionId: ctx.sessionId,
2333
+ status: outcome.status,
2334
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2335
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2336
+ githubLogin: outcome.githubLogin
2337
+ },
2338
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2339
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2340
+ repositoryRoot: root,
2341
+ branch: attempt.branch ?? state?.branch,
2342
+ baseSha: attempt.baseSha ?? state?.baseSha,
2343
+ at: Date.now()
2344
+ });
2345
+ return outcome;
2346
+ };
2347
+ let challenge;
2348
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2349
+ attempt.challengeId = state.challengeId;
2350
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2351
+ attempt.branch = state.branch;
2352
+ attempt.baseSha = state.baseSha;
2353
+ challenge = {
2354
+ challengeId: state.challengeId,
2355
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2356
+ repository: githubRepositoryFullName(root) ?? "the repository"
2357
+ };
2358
+ } else if (state?.status === "link_required" && state.challengeId) {
2359
+ attempt.challengeId = state.challengeId;
2360
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2361
+ const exchanged2 = await exchangeChallenge(
2362
+ ctx,
2363
+ {
2364
+ challengeId: state.challengeId,
2365
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2366
+ githubLogin: state.githubLogin
2367
+ },
2368
+ root,
2369
+ deps,
2370
+ options.signal
2371
+ );
2372
+ if ("status" in exchanged2) return remember(exchanged2);
2373
+ writeToken(ctx, exchanged2);
2374
+ return identified(exchanged2, false);
2375
+ } else if (!options.explicit) {
2376
+ return state ? outcomeFromState(state) : failure(
2377
+ "not_identified",
2378
+ "this session has not identified who started it yet",
2379
+ RETRY_REMEDY
2380
+ );
2381
+ } else {
2382
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2383
+ if ("status" in pushed) return remember(pushed);
2384
+ challenge = pushed;
2385
+ }
2386
+ const verified = await pollChallenge(
2387
+ ctx.apiUrl,
2388
+ challenge.challengeId,
2389
+ challenge.repository,
2390
+ // A hook process waits only briefly for a late notice.
2391
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2392
+ options.signal
2393
+ );
2394
+ if ("status" in verified) return remember(verified);
2395
+ const exchanged = await exchangeChallenge(
2396
+ ctx,
2397
+ { ...challenge, githubLogin: verified.githubLogin },
2398
+ root,
2399
+ deps,
2400
+ options.signal
2401
+ );
2402
+ if ("status" in exchanged) return remember(exchanged);
2403
+ writeToken(ctx, exchanged);
2404
+ return identified(exchanged, false);
2405
+ },
2406
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2407
+ );
2408
+ }
2409
+ async function acquireSessionCredential(options = {}, deps = {}) {
2410
+ const cached2 = cachedSessionCredential(deps);
2411
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2412
+ if (cached2 && fresh && !options.force) return cached2;
2413
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2414
+ let outcome;
2415
+ try {
2416
+ outcome = await ensureSessionIdentity(
2417
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2418
+ deps
2419
+ );
2420
+ } catch (error) {
2421
+ options.signal?.throwIfAborted();
2422
+ if (error instanceof MachineAuthError) throw error;
2423
+ throw new MachineAuthError(
2424
+ "identity_unavailable",
2425
+ "Identifying who started this cloud session is still in progress; retry shortly."
2426
+ );
2427
+ }
2428
+ if (outcome.status === "ok") return outcome.credential;
2429
+ throw new MachineAuthError(
2430
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2431
+ sessionIdentityMessage(outcome)
2432
+ );
2433
+ }
2434
+
1204
2435
  // src/lib/machine-credentials.ts
2436
+ function sessionScoped(deps) {
2437
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2438
+ }
1205
2439
  var require2 = createRequire(import.meta.url);
1206
2440
  var SERVICE = "ai.primitive.prim.machine";
1207
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2441
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1208
2442
  var PROFILE_FILE = "machine_profile.json";
1209
- var RENEW_BEFORE_MS = 6e4;
2443
+ var RENEW_BEFORE_MS2 = 6e4;
1210
2444
  var cached;
1211
2445
  function configurationDirectory(deps) {
1212
2446
  return deps.directory ?? primConfigDirectory({ env: deps.env });
1213
2447
  }
1214
2448
  function apiUrlFor(deps) {
1215
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2449
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
1216
2450
  }
1217
- function hash(value) {
1218
- return createHash3("sha256").update(value).digest("hex");
2451
+ function hash2(value) {
2452
+ return createHash5("sha256").update(value).digest("hex");
1219
2453
  }
1220
2454
  function recordPath(directory, generation) {
1221
- return join6(directory, `machine_${generation}.json`);
2455
+ return join8(directory, `machine_${generation}.json`);
1222
2456
  }
1223
2457
  function storageKey(directory, generation) {
1224
- return `${hash(directory)}:${generation}`;
2458
+ return `${hash2(directory)}:${generation}`;
1225
2459
  }
1226
2460
  function environmentContextPath(deps, clientId) {
1227
- return join6(
2461
+ return join8(
1228
2462
  configurationDirectory(deps),
1229
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2463
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1230
2464
  );
1231
2465
  }
1232
2466
  function writeEnvironmentContext(credential, deps) {
@@ -1285,14 +2519,14 @@ function readEnvironmentContext(environment, deps) {
1285
2519
  }
1286
2520
  }
1287
2521
  function keyringEntry(key) {
1288
- let directory = dirname4(fileURLToPath3(import.meta.url));
2522
+ let directory = dirname5(fileURLToPath3(import.meta.url));
1289
2523
  for (let depth = 0; depth < 5; depth++) {
1290
- const loader = join6(directory, "native", "keyring.cjs");
2524
+ const loader = join8(directory, "native", "keyring.cjs");
1291
2525
  if (existsSync3(loader)) {
1292
2526
  const module2 = require2(loader);
1293
2527
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1294
2528
  }
1295
- directory = dirname4(directory);
2529
+ directory = dirname5(directory);
1296
2530
  }
1297
2531
  const module = require2("@napi-rs/keyring");
1298
2532
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -1304,7 +2538,7 @@ function protectPath(path, directory) {
1304
2538
  }
1305
2539
  const encodedPath = Buffer.from(path).toString("base64");
1306
2540
  const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
1307
- execFileSync(
2541
+ execFileSync2(
1308
2542
  "powershell.exe",
1309
2543
  [
1310
2544
  "-NoProfile",
@@ -1317,7 +2551,7 @@ function protectPath(path, directory) {
1317
2551
  }
1318
2552
  function ensureDirectory(directory) {
1319
2553
  mkdirSync3(directory, { recursive: true, mode: 448 });
1320
- if (lstatSync3(directory).isSymbolicLink())
2554
+ if (lstatSync4(directory).isSymbolicLink())
1321
2555
  throw new MachineAuthError(
1322
2556
  "unsafe_storage",
1323
2557
  "Credential directory must not be a symbolic link."
@@ -1329,17 +2563,20 @@ function writePrivate(path, value) {
1329
2563
  `, { mode: 384 });
1330
2564
  protectPath(path, false);
1331
2565
  }
2566
+ function readMachineMetadata(path) {
2567
+ return readPrivate(path);
2568
+ }
1332
2569
  function readPrivate(path) {
1333
2570
  let raw;
1334
2571
  try {
1335
- const stat = lstatSync3(path);
2572
+ const stat = lstatSync4(path);
1336
2573
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1337
2574
  throw new MachineAuthError(
1338
2575
  "unsafe_storage",
1339
2576
  "Machine credential files must be owner-only regular files."
1340
2577
  );
1341
2578
  }
1342
- raw = readFileSync5(path, "utf8");
2579
+ raw = readFileSync6(path, "utf8");
1343
2580
  } catch (error) {
1344
2581
  if (error.code === "ENOENT") return void 0;
1345
2582
  throw error;
@@ -1384,7 +2621,7 @@ function parseProfile(value) {
1384
2621
  };
1385
2622
  }
1386
2623
  function readMachineProfile(deps = {}) {
1387
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
2624
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
1388
2625
  return value === void 0 ? void 0 : parseProfile(value);
1389
2626
  }
1390
2627
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -1393,20 +2630,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
1393
2630
  var brokerKeys = /* @__PURE__ */ new Map();
1394
2631
  function networkSecretBrokerKey(deps, clientId) {
1395
2632
  const directory = configurationDirectory(deps);
1396
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2633
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
1397
2634
  const known = brokerKeys.get(path);
1398
2635
  if (known) return known;
1399
2636
  ensureDirectory(directory);
1400
2637
  const read = () => {
1401
2638
  try {
1402
- const stat = lstatSync3(path);
2639
+ const stat = lstatSync4(path);
1403
2640
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
1404
2641
  throw new MachineAuthError(
1405
2642
  "unsafe_storage",
1406
2643
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
1407
2644
  true
1408
2645
  );
1409
- const value = readFileSync5(path, "utf8").trim();
2646
+ const value = readFileSync6(path, "utf8").trim();
1410
2647
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
1411
2648
  } catch (error) {
1412
2649
  if (error.code === "ENOENT") return void 0;
@@ -1434,7 +2671,7 @@ function networkSecretBrokerKey(deps, clientId) {
1434
2671
  } catch (error) {
1435
2672
  if (error.code !== "EEXIST") throw error;
1436
2673
  } finally {
1437
- rmSync5(staged, { force: true });
2674
+ rmSync6(staged, { force: true });
1438
2675
  }
1439
2676
  }
1440
2677
  const key = read()?.key;
@@ -1467,7 +2704,7 @@ function environmentCredentials(deps) {
1467
2704
  "conflicting_credentials",
1468
2705
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
1469
2706
  );
1470
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2707
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1471
2708
  const credentials = {
1472
2709
  clientId,
1473
2710
  generation,
@@ -1488,12 +2725,12 @@ function environmentCredentials(deps) {
1488
2725
  return {
1489
2726
  clientId,
1490
2727
  clientSecret,
1491
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2728
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1492
2729
  };
1493
2730
  }
1494
2731
  function hasMachineConfiguration(deps = {}) {
1495
2732
  const env = deps.env ?? process.env;
1496
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
2733
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
1497
2734
  if (configured && env.PRIM_TOKEN?.trim()) {
1498
2735
  throw new MachineAuthError(
1499
2736
  "conflicting_credentials",
@@ -1505,6 +2742,7 @@ function hasMachineConfiguration(deps = {}) {
1505
2742
  }
1506
2743
  function machineContext(deps = {}) {
1507
2744
  if (!hasMachineConfiguration(deps)) return void 0;
2745
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1508
2746
  const environment = environmentCredentials(deps);
1509
2747
  if (environment) {
1510
2748
  if (environmentTerminal === environment.generation) return void 0;
@@ -1519,6 +2757,7 @@ function machineContext(deps = {}) {
1519
2757
  return profile;
1520
2758
  }
1521
2759
  function cachedMachineCredential(deps = {}) {
2760
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1522
2761
  const context = machineContext(deps);
1523
2762
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1524
2763
  }
@@ -1527,7 +2766,7 @@ function machineSessionEnded(deps = {}) {
1527
2766
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1528
2767
  if (!generation) return false;
1529
2768
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1530
- return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
2769
+ return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
1531
2770
  }
1532
2771
  var environmentTerminal;
1533
2772
  var NETWORK_REJECTION_PAUSE_MS = 3e4;
@@ -1591,6 +2830,7 @@ async function persistRecord(record, deps, signal) {
1591
2830
  }
1592
2831
  async function acquireMachineCredential(options = {}, deps = {}) {
1593
2832
  if (!hasMachineConfiguration(deps)) return void 0;
2833
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1594
2834
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1595
2835
  const apiUrl = apiUrlFor(deps);
1596
2836
  const environment = environmentCredentials(deps);
@@ -1619,7 +2859,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1619
2859
  }
1620
2860
  }
1621
2861
  return withFileLock(
1622
- join6(directory2, "credentials.lock"),
2862
+ join8(directory2, "credentials.lock"),
1623
2863
  async () => {
1624
2864
  if (machineSessionEnded(deps))
1625
2865
  throw new MachineAuthError(
@@ -1627,7 +2867,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1627
2867
  rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1628
2868
  true
1629
2869
  );
1630
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2870
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1631
2871
  return cached;
1632
2872
  if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
1633
2873
  throw networkRejection.error;
@@ -1701,7 +2941,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1701
2941
  const contextPath = environmentContextPath(deps, environment.clientId);
1702
2942
  try {
1703
2943
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1704
- rmSync5(contextPath, { force: true });
2944
+ rmSync6(contextPath, { force: true });
1705
2945
  } catch {
1706
2946
  }
1707
2947
  throw error;
@@ -1711,7 +2951,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1711
2951
  const contextPath = environmentContextPath(deps, environment.clientId);
1712
2952
  try {
1713
2953
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1714
- rmSync5(contextPath, { force: true });
2954
+ rmSync6(contextPath, { force: true });
1715
2955
  } catch {
1716
2956
  }
1717
2957
  }
@@ -1725,7 +2965,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1725
2965
  const expected = machineContext(deps);
1726
2966
  const directory = configurationDirectory(deps);
1727
2967
  return withFileLock(
1728
- join6(directory, "credentials.lock"),
2968
+ join8(directory, "credentials.lock"),
1729
2969
  async () => {
1730
2970
  const profile = readMachineProfile(deps);
1731
2971
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1740,7 +2980,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1740
2980
  true
1741
2981
  );
1742
2982
  let record = await loadRecord(profile, deps, signal);
1743
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2983
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1744
2984
  try {
1745
2985
  const { tokens, identity } = await withMachineCooldown(
1746
2986
  directory,
@@ -1775,7 +3015,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1775
3015
  await persistRecord(record, deps, signal);
1776
3016
  } catch (error) {
1777
3017
  if (error instanceof MachineAuthError && error.terminal)
1778
- writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
3018
+ writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
1779
3019
  throw error;
1780
3020
  }
1781
3021
  }
@@ -1821,31 +3061,37 @@ function machineCaptureActor(deps = {}) {
1821
3061
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
1822
3062
  }
1823
3063
  function machineJournalBucket(identity) {
1824
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
3064
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1825
3065
  }
1826
3066
  function identityPending(actor) {
1827
3067
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1828
3068
  }
1829
3069
  function machinePendingBucket(identity) {
1830
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
3070
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
3071
+ }
3072
+ function prepareMachineMetadataDirectory(directory) {
3073
+ ensureDirectory(directory);
3074
+ }
3075
+ function writeMachineMetadata(path, value) {
3076
+ writePrivate(path, value);
1831
3077
  }
1832
3078
 
1833
3079
  // src/lib/credentials.ts
1834
3080
  var CONFIG_DIRECTORY = primConfigDirectory();
1835
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1836
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1837
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1838
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1839
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1840
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1841
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1842
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3081
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
3082
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
3083
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
3084
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
3085
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
3086
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
3087
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
3088
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1843
3089
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1844
3090
  var CREDENTIAL_MIGRATION_VERSION = 1;
1845
3091
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1846
3092
  function readTrimmed(path) {
1847
3093
  try {
1848
- const value = readFileSync6(path, "utf8").trim();
3094
+ const value = readFileSync7(path, "utf8").trim();
1849
3095
  return value || void 0;
1850
3096
  } catch {
1851
3097
  return void 0;
@@ -1867,22 +3113,22 @@ function resolveAuthCredential(options = {}) {
1867
3113
  );
1868
3114
  if (metadata.state === "legacy_broker") {
1869
3115
  if (metadata.metadata) {
1870
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1871
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3116
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3117
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1872
3118
  return void 0;
1873
3119
  }
1874
3120
  }
1875
3121
  return { token: stored, source: "token_file" };
1876
3122
  }
1877
3123
  if (metadata.state === "invalid") return void 0;
1878
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1879
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3124
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3125
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1880
3126
  return void 0;
1881
3127
  }
1882
3128
  return { token: stored, source: "token_file" };
1883
3129
  }
1884
3130
  function credentialFingerprint(value) {
1885
- return createHash4("sha256").update(value).digest("hex");
3131
+ return createHash6("sha256").update(value).digest("hex");
1886
3132
  }
1887
3133
  function parseLegacyBrokerCredentialMetadata(value) {
1888
3134
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1902,7 +3148,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1902
3148
  function readBoundedCredentialJson(path) {
1903
3149
  let raw;
1904
3150
  try {
1905
- raw = readFileSync6(path, "utf8");
3151
+ raw = readFileSync7(path, "utf8");
1906
3152
  } catch (error) {
1907
3153
  return error.code === "ENOENT" ? void 0 : null;
1908
3154
  }
@@ -1979,14 +3225,14 @@ function jwtOrganizationId(token) {
1979
3225
 
1980
3226
  // src/binding.ts
1981
3227
  var PRIM_CONFIG_DIR = primConfigDirectory();
1982
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
3228
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
1983
3229
  var WORKSPACE_FILE = ".prim/workspace.json";
1984
3230
  function readJsonSafe(path) {
1985
3231
  if (!existsSync4(path)) {
1986
3232
  return;
1987
3233
  }
1988
3234
  try {
1989
- return JSON.parse(readFileSync7(path, "utf-8"));
3235
+ return JSON.parse(readFileSync8(path, "utf-8"));
1990
3236
  } catch {
1991
3237
  return;
1992
3238
  }
@@ -1995,17 +3241,17 @@ function fromSessionMarker(sessionId) {
1995
3241
  if (!sessionId) {
1996
3242
  return;
1997
3243
  }
1998
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
3244
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
1999
3245
  return marker?.orgId;
2000
3246
  }
2001
3247
  function fromWorkspaceFile(startDir) {
2002
3248
  let dir = startDir;
2003
3249
  while (true) {
2004
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
3250
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
2005
3251
  if (config?.orgId) {
2006
3252
  return config.orgId;
2007
3253
  }
2008
- const parent = dirname5(dir);
3254
+ const parent = dirname6(dir);
2009
3255
  if (parent === dir) {
2010
3256
  return;
2011
3257
  }
@@ -2042,29 +3288,29 @@ import { existsSync as existsSync9 } from "fs";
2042
3288
 
2043
3289
  // src/demo/diagnostics.ts
2044
3290
  import { existsSync as existsSync8 } from "fs";
2045
- import { join as join12 } from "path";
3291
+ import { join as join14 } from "path";
2046
3292
 
2047
3293
  // src/lib/hook-runtime.ts
2048
- import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
3294
+ import { createHash as createHash7, randomBytes as randomBytes4 } from "crypto";
2049
3295
  import {
2050
3296
  constants as constants2,
2051
3297
  accessSync,
2052
3298
  chmodSync as chmodSync2,
2053
3299
  copyFileSync,
2054
3300
  existsSync as existsSync6,
2055
- lstatSync as lstatSync4,
3301
+ lstatSync as lstatSync5,
2056
3302
  mkdirSync as mkdirSync4,
2057
3303
  mkdtempSync,
2058
- readFileSync as readFileSync8,
3304
+ readFileSync as readFileSync9,
2059
3305
  readdirSync as readdirSync2,
2060
- realpathSync,
3306
+ realpathSync as realpathSync2,
2061
3307
  renameSync as renameSync2,
2062
- rmSync as rmSync6,
3308
+ rmSync as rmSync7,
2063
3309
  statSync as statSync2,
2064
3310
  utimesSync,
2065
3311
  writeFileSync as writeFileSync4
2066
3312
  } from "fs";
2067
- import { delimiter, dirname as dirname7, isAbsolute as isAbsolute3, join as join10, resolve } from "path";
3313
+ import { delimiter, dirname as dirname8, isAbsolute as isAbsolute4, join as join12, resolve as resolve2 } from "path";
2068
3314
 
2069
3315
  // src/lib/git-hook-contract.ts
2070
3316
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -2114,7 +3360,7 @@ exit 0
2114
3360
  // src/lib/native-keyring.ts
2115
3361
  import { existsSync as existsSync5 } from "fs";
2116
3362
  import { createRequire as createRequire2 } from "module";
2117
- import { dirname as dirname6, join as join9 } from "path";
3363
+ import { dirname as dirname7, join as join11 } from "path";
2118
3364
  import { fileURLToPath as fileURLToPath4 } from "url";
2119
3365
  var require3 = createRequire2(import.meta.url);
2120
3366
 
@@ -2165,9 +3411,9 @@ exec "$prim_node" "$prim_entry" "$@"
2165
3411
  `;
2166
3412
 
2167
3413
  // src/demo/state.ts
2168
- import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
2169
- import { existsSync as existsSync7, lstatSync as lstatSync5, readFileSync as readFileSync9, readdirSync as readdirSync3 } from "fs";
2170
- import { join as join11, resolve as resolve2 } from "path";
3414
+ import { createHash as createHash8, randomUUID as randomUUID3 } from "crypto";
3415
+ import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync10, readdirSync as readdirSync3 } from "fs";
3416
+ import { join as join13, resolve as resolve3 } from "path";
2171
3417
 
2172
3418
  // src/generated/cli-http-v1.validators.js
2173
3419
  var import_ucs2length = __toESM(require_ucs2length(), 1);
@@ -28855,15 +30101,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
28855
30101
 
28856
30102
  // src/demo/state.ts
28857
30103
  var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
28858
- var demoDirectory = () => join11(primConfigDirectory(), "demo");
30104
+ var demoDirectory = () => join13(primConfigDirectory(), "demo");
28859
30105
  var runPath = (id2) => {
28860
30106
  if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
28861
- return join11(demoDirectory(), "runs", `${id2}.json`);
30107
+ return join13(demoDirectory(), "runs", `${id2}.json`);
28862
30108
  };
28863
30109
  function readDemoJson(path) {
28864
- const stat = lstatSync5(path);
30110
+ const stat = lstatSync6(path);
28865
30111
  if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
28866
- return JSON.parse(readFileSync9(path, "utf8"));
30112
+ return JSON.parse(readFileSync10(path, "utf8"));
28867
30113
  }
28868
30114
  function saveDemoJson(path, value) {
28869
30115
  atomicWriteFile(path, `${JSON.stringify(value)}
@@ -28900,11 +30146,11 @@ function demoCommand(run, action, choice, reason) {
28900
30146
  ].map(quote).join(" ");
28901
30147
  }
28902
30148
  function sessionKey(agent, session) {
28903
- return createHash6("sha256").update(`${agent}\0${session}`).digest("hex");
30149
+ return createHash8("sha256").update(`${agent}\0${session}`).digest("hex");
28904
30150
  }
28905
30151
  function exclusionPath(key) {
28906
30152
  if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
28907
- return join11(demoDirectory(), "excluded-sessions", `${key}.json`);
30153
+ return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
28908
30154
  }
28909
30155
  function sessionExcluded(agent, session) {
28910
30156
  if (typeof session !== "string" || !session) return false;
@@ -28943,7 +30189,7 @@ function demoArgv(command) {
28943
30189
  }
28944
30190
 
28945
30191
  // src/demo/diagnostics.ts
28946
- var observationPath = (id2) => join12(demoDirectory(), "observations", `${id2}.json`);
30192
+ var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
28947
30193
  function observeRun(id2, observation) {
28948
30194
  try {
28949
30195
  saveDemoJson(observationPath(id2), observation);
@@ -29032,14 +30278,14 @@ function observeDemoInvocation(envelope, agent, checkExclusion = true) {
29032
30278
  import { execFileSync as execFileSync4 } from "child_process";
29033
30279
  import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
29034
30280
  import { homedir as homedir2 } from "os";
29035
- import { join as join15 } from "path";
30281
+ import { join as join16 } from "path";
29036
30282
 
29037
30283
  // src/lib/cloud-prepared.ts
29038
- import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "fs";
29039
- import { join as join13 } from "path";
30284
+ import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync8, writeFileSync as writeFileSync5 } from "fs";
30285
+ import { join as join15 } from "path";
29040
30286
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
29041
30287
  function cloudPreparedPath(env = process.env) {
29042
- return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30288
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
29043
30289
  }
29044
30290
  function isPreparedCloudSession(env = process.env) {
29045
30291
  if (!isClaudeCloudSession(env)) return false;
@@ -29051,17 +30297,17 @@ function isPreparedCloudSession(env = process.env) {
29051
30297
  }
29052
30298
 
29053
30299
  // src/lib/demo-pause.ts
29054
- import { execFileSync as execFileSync2 } from "child_process";
30300
+ import { execFileSync as execFileSync3 } from "child_process";
29055
30301
  var DEMO_PAUSE_MS = 30 * 6e4;
29056
30302
  var PAUSE_KEY = "prim.demoPause";
29057
- var GIT_TIMEOUT_MS = 1e3;
29058
- function git(cwd, args) {
30303
+ var GIT_TIMEOUT_MS3 = 1e3;
30304
+ function git2(cwd, args) {
29059
30305
  try {
29060
- return execFileSync2("git", args, {
30306
+ return execFileSync3("git", args, {
29061
30307
  cwd,
29062
30308
  encoding: "utf-8",
29063
30309
  stdio: ["ignore", "pipe", "ignore"],
29064
- timeout: GIT_TIMEOUT_MS
30310
+ timeout: GIT_TIMEOUT_MS3
29065
30311
  });
29066
30312
  } catch {
29067
30313
  return void 0;
@@ -29069,10 +30315,10 @@ function git(cwd, args) {
29069
30315
  }
29070
30316
  function setLocal(cwd, key, value) {
29071
30317
  try {
29072
- execFileSync2(
30318
+ execFileSync3(
29073
30319
  "git",
29074
30320
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
29075
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
30321
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
29076
30322
  );
29077
30323
  } catch (error) {
29078
30324
  if (value !== null || error.status !== 5) throw error;
@@ -29086,7 +30332,7 @@ function parsePause(value) {
29086
30332
  function readCaptureConfig(cwd) {
29087
30333
  let active;
29088
30334
  let pause;
29089
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
30335
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
29090
30336
  for (const line of out.split("\n")) {
29091
30337
  const space3 = line.indexOf(" ");
29092
30338
  const key = line.slice(0, space3).toLowerCase();
@@ -29111,273 +30357,13 @@ function healDemoPause(cwd, pause, options = {}) {
29111
30357
  }
29112
30358
  }
29113
30359
 
29114
- // src/lib/git.ts
29115
- import { execFileSync as execFileSync3 } from "child_process";
29116
- import { createHash as createHash7 } from "crypto";
29117
- import { lstatSync as lstatSync6, readFileSync as readFileSync11, realpathSync as realpathSync2 } from "fs";
29118
- import { basename as basename2, dirname as dirname8, isAbsolute as isAbsolute4, join as join14, relative, resolve as resolve3, sep } from "path";
29119
- var GIT_TIMEOUT_MS2 = 1e3;
29120
- var MAX_SETTINGS_BYTES = 1024 * 1024;
29121
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
29122
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
29123
- function gitToplevel(cwd) {
29124
- try {
29125
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
29126
- cwd,
29127
- encoding: "utf-8",
29128
- stdio: ["ignore", "pipe", "ignore"],
29129
- timeout: GIT_TIMEOUT_MS2
29130
- }).trim();
29131
- } catch {
29132
- return null;
29133
- }
29134
- }
29135
- function gitValue(cwd, args) {
29136
- try {
29137
- const value = execFileSync3("git", args, {
29138
- cwd,
29139
- encoding: "utf-8",
29140
- stdio: ["ignore", "pipe", "ignore"],
29141
- timeout: GIT_TIMEOUT_MS2
29142
- }).trim();
29143
- return value || void 0;
29144
- } catch {
29145
- return void 0;
29146
- }
29147
- }
29148
- function currentBranch(cwd) {
29149
- return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
29150
- }
29151
- function parseGithubRepositoryName(path) {
29152
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
29153
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
29154
- return null;
29155
- }
29156
- return `${parts[0]}/${parts[1]}`;
29157
- }
29158
- function githubRepositoryFromRemote(remote) {
29159
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
29160
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29161
- remote
29162
- );
29163
- const path = match?.[1] ?? match?.[2];
29164
- return path ? parseGithubRepositoryName(path) : null;
29165
- }
29166
- function checkoutSettingsText(repoRoot) {
29167
- const path = join14(repoRoot, ".claude", "settings.json");
29168
- try {
29169
- if (!lstatSync6(join14(repoRoot, ".claude")).isDirectory()) return null;
29170
- const stat = lstatSync6(path);
29171
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
29172
- return readFileSync11(path, "utf8");
29173
- } catch {
29174
- return null;
29175
- }
29176
- }
29177
- function checkoutDeclaration(repoRoot, name2) {
29178
- const text = checkoutSettingsText(repoRoot);
29179
- if (text === null) return null;
29180
- let parsed;
29181
- try {
29182
- parsed = JSON.parse(text);
29183
- } catch {
29184
- return null;
29185
- }
29186
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
29187
- const value = typeof env === "object" && env !== null ? env[name2] : void 0;
29188
- return typeof value === "string" ? value : null;
29189
- }
29190
- function declaredGithubRepository(repoRoot) {
29191
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
29192
- return value === null ? null : parseGithubRepositoryName(value.trim());
29193
- }
29194
- function githubRepositoryFullName(cwd) {
29195
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
29196
- if (remote) {
29197
- const fromOrigin = githubRepositoryFromRemote(remote);
29198
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
29199
- }
29200
- const root = gitToplevel(cwd);
29201
- return root ? declaredGithubRepository(root) : null;
29202
- }
29203
- function canonicalGitRoot(cwd) {
29204
- try {
29205
- const top = gitToplevel(cwd);
29206
- return top ? realpathSync2.native(top) : null;
29207
- } catch {
29208
- return null;
29209
- }
29210
- }
29211
- function relatedWorktreeTarget(path, cwd, origin) {
29212
- let parent = dirname8(resolve3(cwd, path));
29213
- while (true) {
29214
- try {
29215
- realpathSync2.native(parent);
29216
- break;
29217
- } catch {
29218
- const next = dirname8(parent);
29219
- if (next === parent) return null;
29220
- parent = next;
29221
- }
29222
- }
29223
- const target = resolveRepositoryContext(parent);
29224
- if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
29225
- const common = (root) => {
29226
- const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
29227
- try {
29228
- return value ? realpathSync2.native(resolve3(root, value)) : void 0;
29229
- } catch {
29230
- return void 0;
29231
- }
29232
- };
29233
- const originCommon = common(origin.repoRoot);
29234
- return originCommon && originCommon === common(target.repoRoot) ? target : null;
29235
- }
29236
- function normalizeOriginRemote(remote) {
29237
- const value = remote.trim();
29238
- if (!value) return void 0;
29239
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
29240
- if (scp?.host && scp.path) {
29241
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
29242
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
29243
- }
29244
- try {
29245
- const url = new URL(value);
29246
- url.username = "";
29247
- url.password = "";
29248
- url.search = "";
29249
- url.hash = "";
29250
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
29251
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
29252
- return void 0;
29253
- } catch {
29254
- return void 0;
29255
- }
29256
- }
29257
- function opaqueRepoKey(source, value) {
29258
- return `repo_v1_${createHash7("sha256").update(`${source}\0${value}`).digest("hex")}`;
29259
- }
29260
- function resolveRepositoryContext(cwd = process.cwd()) {
29261
- const top = gitToplevel(cwd);
29262
- if (!top) return null;
29263
- let repoRoot;
29264
- try {
29265
- repoRoot = realpathSync2.native(top);
29266
- } catch {
29267
- repoRoot = resolve3(top);
29268
- }
29269
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
29270
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
29271
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
29272
- if (normalizedOrigin) {
29273
- return {
29274
- repoRoot,
29275
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
29276
- identitySource: "origin",
29277
- repoFullName
29278
- };
29279
- }
29280
- if (repoFullName) {
29281
- return {
29282
- repoRoot,
29283
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
29284
- identitySource: "declared",
29285
- repoFullName
29286
- };
29287
- }
29288
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
29289
- if (roots && roots.length > 0) {
29290
- return {
29291
- repoRoot,
29292
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
29293
- identitySource: "root_commit",
29294
- repoFullName
29295
- };
29296
- }
29297
- return { repoRoot, repoFullName };
29298
- }
29299
- function nearestExistingAncestor(path) {
29300
- const suffix = [];
29301
- let cursor = path;
29302
- while (true) {
29303
- try {
29304
- lstatSync6(cursor);
29305
- break;
29306
- } catch (error) {
29307
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
29308
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
29309
- const parent = dirname8(cursor);
29310
- if (parent === cursor) return null;
29311
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
29312
- cursor = parent;
29313
- }
29314
- }
29315
- try {
29316
- return { real: realpathSync2.native(cursor), suffix };
29317
- } catch {
29318
- return null;
29319
- }
29320
- }
29321
- function canonicalRepositoryPathScoped(filePath, context, baseDir) {
29322
- if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
29323
- return { ok: false, reason: "invalid_path" };
29324
- }
29325
- const absolute = resolve3(baseDir, filePath);
29326
- const resolved = nearestExistingAncestor(absolute);
29327
- if (!resolved) return { ok: false, reason: "invalid_path" };
29328
- const target = resolve3(resolved.real, ...resolved.suffix);
29329
- const rel = relative(context.repoRoot, target);
29330
- if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
29331
- if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
29332
- return { ok: false, reason: "outside_repository" };
29333
- }
29334
- return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
29335
- }
29336
- function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
29337
- if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
29338
- return null;
29339
- const absolute = resolve3(cwd, filePath);
29340
- let target;
29341
- try {
29342
- const stat = lstatSync6(absolute);
29343
- if (!stat.isFile() || stat.isSymbolicLink()) return null;
29344
- target = realpathSync2.native(absolute);
29345
- } catch (error) {
29346
- if (!(error instanceof Error) || error.code !== "ENOENT") {
29347
- return null;
29348
- }
29349
- try {
29350
- const parent = realpathSync2.native(dirname8(absolute));
29351
- if (!lstatSync6(parent).isDirectory()) return null;
29352
- target = resolve3(parent, basename2(absolute));
29353
- } catch {
29354
- return null;
29355
- }
29356
- }
29357
- const rel = relative(repositoryRoot, target);
29358
- if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
29359
- return null;
29360
- }
29361
- return sep === "/" ? rel : rel.split(sep).join("/");
29362
- }
29363
- function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
29364
- if (typeof contextOrCwd === "string") {
29365
- return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
29366
- }
29367
- return canonicalRepositoryPathScoped(
29368
- filePath,
29369
- contextOrCwd,
29370
- baseDirOrRoot ?? contextOrCwd.repoRoot
29371
- );
29372
- }
29373
-
29374
30360
  // src/lib/activation.ts
29375
30361
  var PRIM_ACTIVE_KEY = "prim.active";
29376
30362
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
29377
30363
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
29378
30364
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
29379
30365
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
29380
- var GIT_TIMEOUT_MS3 = 1e3;
30366
+ var GIT_TIMEOUT_MS4 = 1e3;
29381
30367
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
29382
30368
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
29383
30369
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -29387,7 +30373,7 @@ function repoActiveFlag(cwd, strict = false) {
29387
30373
  cwd,
29388
30374
  encoding: "utf-8",
29389
30375
  stdio: ["ignore", "pipe", "ignore"],
29390
- timeout: GIT_TIMEOUT_MS3
30376
+ timeout: GIT_TIMEOUT_MS4
29391
30377
  }).trim();
29392
30378
  if (value === "true") return "true";
29393
30379
  if (value === "false") return "false";
@@ -29408,7 +30394,7 @@ function localGitConfigValue(cwd, key) {
29408
30394
  cwd,
29409
30395
  encoding: "utf-8",
29410
30396
  stdio: ["ignore", "pipe", "ignore"],
29411
- timeout: GIT_TIMEOUT_MS3
30397
+ timeout: GIT_TIMEOUT_MS4
29412
30398
  }).trim();
29413
30399
  return value || void 0;
29414
30400
  } catch {
@@ -29419,7 +30405,7 @@ function setLocalGitConfigValue(cwd, key, value) {
29419
30405
  execFileSync4("git", ["config", "--local", key, value], {
29420
30406
  cwd,
29421
30407
  stdio: ["ignore", "ignore", "pipe"],
29422
- timeout: GIT_TIMEOUT_MS3
30408
+ timeout: GIT_TIMEOUT_MS4
29423
30409
  });
29424
30410
  }
29425
30411
  function repoSyncId(cwd) {
@@ -29440,7 +30426,7 @@ function repositoryBindingState(cwd) {
29440
30426
  function projectPrimInstallAt(root) {
29441
30427
  if (root === null || root === homedir2()) return false;
29442
30428
  for (const rel of PROJECT_INSTALL_FILES) {
29443
- const path = join15(root, rel);
30429
+ const path = join16(root, rel);
29444
30430
  if (existsSync11(path)) {
29445
30431
  try {
29446
30432
  const content2 = readFileSync12(path, "utf-8");
@@ -29555,14 +30541,14 @@ function publicDecisionResponse(value) {
29555
30541
  }
29556
30542
 
29557
30543
  // src/client.ts
29558
- import { createHash as createHash8 } from "crypto";
29559
- import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync8 } from "fs";
30544
+ import { createHash as createHash9 } from "crypto";
30545
+ import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
29560
30546
  import { dirname as dirname9 } from "path";
29561
30547
 
29562
30548
  // src/daemon/client-instance-id.ts
29563
30549
  import { randomBytes as randomBytes5 } from "crypto";
29564
30550
  import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
29565
- import { join as join16 } from "path";
30551
+ import { join as join17 } from "path";
29566
30552
  var CONFIG_DIRECTORY_MODE = 448;
29567
30553
  var INSTANCE_FILE_MODE = 384;
29568
30554
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -29613,8 +30599,8 @@ function atomicWrite(path, value) {
29613
30599
  }
29614
30600
  async function getOrCreateClientInstanceId(options) {
29615
30601
  const configDir = options.configDir;
29616
- const path = join16(configDir, "client_instance_id");
29617
- const lockPath = join16(configDir, "client-instance.lock");
30602
+ const path = join17(configDir, "client_instance_id");
30603
+ const lockPath = join17(configDir, "client-instance.lock");
29618
30604
  ensurePrivateConfigDirectory(configDir);
29619
30605
  return withFileLock(
29620
30606
  lockPath,
@@ -29658,53 +30644,11 @@ async function ingestUploaderHeaders() {
29658
30644
  return headers;
29659
30645
  }
29660
30646
 
29661
- // src/lib/terminal-safe.ts
29662
- function replaceIsolatedSurrogates(value) {
29663
- let out = "";
29664
- for (let index = 0; index < value.length; index += 1) {
29665
- const unit = value.charCodeAt(index);
29666
- if (unit >= 55296 && unit <= 56319) {
29667
- const next = value.charCodeAt(index + 1);
29668
- if (next >= 56320 && next <= 57343) {
29669
- out += value[index] + value[index + 1];
29670
- index += 1;
29671
- } else {
29672
- out += "\uFFFD";
29673
- }
29674
- } else if (unit >= 56320 && unit <= 57343) {
29675
- out += "\uFFFD";
29676
- } else {
29677
- out += value[index];
29678
- }
29679
- }
29680
- return out;
29681
- }
29682
- function isUnsafeTerminalCodePoint(point) {
29683
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
29684
- const bidiOrZeroWidth = point === 173 || // soft hyphen
29685
- point === 1564 || // Arabic letter mark
29686
- point === 6158 || // Mongolian vowel separator
29687
- point >= 8203 && point <= 8207 || // zero-width + directional marks
29688
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
29689
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
29690
- point >= 65529 && point <= 65531 || // interlinear annotation controls
29691
- point === 65279 || // zero-width no-break space / BOM
29692
- point >= 917504 && point <= 917631;
29693
- return c0OrC1 || bidiOrZeroWidth;
29694
- }
29695
- function terminalSafeText(value) {
29696
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
29697
- }
29698
- function terminalSafeLine(value) {
29699
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
29700
- }
29701
- var stripControlChars = terminalSafeText;
29702
-
29703
30647
  // src/client.ts
29704
30648
  var CONFIG_DIR_MODE = 448;
29705
30649
  var CREDENTIAL_FILE_MODE = 384;
29706
30650
  var REFRESH_THRESHOLD_MS = 6e4;
29707
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
30651
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
29708
30652
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
29709
30653
  function authExpiredMessage() {
29710
30654
  return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
@@ -29721,7 +30665,7 @@ function getSiteUrl() {
29721
30665
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
29722
30666
  }
29723
30667
  function getSiteUrlForEnvironment(primApiUrl) {
29724
- return primApiUrl?.trim() || DEFAULT_API_URL2;
30668
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
29725
30669
  }
29726
30670
  function expiresAtFor(token, expiresIn) {
29727
30671
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
@@ -29737,7 +30681,7 @@ function atomicWrite2(path, content2) {
29737
30681
  }
29738
30682
  function removeCredentialFile(path) {
29739
30683
  if (!existsSync12(path)) return false;
29740
- rmSync8(path, { force: true });
30684
+ rmSync9(path, { force: true });
29741
30685
  return true;
29742
30686
  }
29743
30687
  function getTokenExpiresAt() {
@@ -29752,23 +30696,23 @@ function isTokenExpiringSoon(credential) {
29752
30696
  const expiresAt = getTokenExpiresAt();
29753
30697
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
29754
30698
  }
29755
- function refreshFingerprint(refreshToken2) {
29756
- return createHash8("sha256").update(refreshToken2).digest("hex");
30699
+ function refreshFingerprint(refreshToken3) {
30700
+ return createHash9("sha256").update(refreshToken3).digest("hex");
29757
30701
  }
29758
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
30702
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
29759
30703
  return {
29760
30704
  version: 1,
29761
30705
  family: "legacy_broker",
29762
30706
  accessTokenHash: refreshFingerprint(accessToken),
29763
- refreshTokenHash: refreshFingerprint(refreshToken2)
30707
+ refreshTokenHash: refreshFingerprint(refreshToken3)
29764
30708
  };
29765
30709
  }
29766
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
30710
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
29767
30711
  const hashes = {
29768
30712
  accessTokenHash: refreshFingerprint(accessToken),
29769
- refreshTokenHash: refreshFingerprint(refreshToken2)
30713
+ refreshTokenHash: refreshFingerprint(refreshToken3)
29770
30714
  };
29771
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
30715
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
29772
30716
  }
29773
30717
  function writeCredentialMigrationSentinel() {
29774
30718
  atomicWrite2(
@@ -29780,11 +30724,11 @@ function writeCredentialMigrationSentinel() {
29780
30724
  `
29781
30725
  );
29782
30726
  }
29783
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
29784
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
30727
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
30728
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
29785
30729
  return { state: "invalid" };
29786
30730
  }
29787
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
30731
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
29788
30732
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
29789
30733
  return { state: "invalid" };
29790
30734
  }
@@ -29801,17 +30745,17 @@ function preserveMarkerlessLegacyGeneration() {
29801
30745
  const metadata = readStoredCredentialMetadata();
29802
30746
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
29803
30747
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
29804
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
29805
- if (!(accessToken && refreshToken2)) return;
29806
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
30748
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
30749
+ if (!(accessToken && refreshToken3)) return;
30750
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
29807
30751
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
29808
30752
  `);
29809
30753
  }
29810
30754
  function terminalFingerprint() {
29811
30755
  return readTrimmed2(TERMINAL_REFRESH_PATH);
29812
30756
  }
29813
- function writeTerminalFingerprint(refreshToken2) {
29814
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
30757
+ function writeTerminalFingerprint(refreshToken3) {
30758
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
29815
30759
  `);
29816
30760
  }
29817
30761
  function clearTerminalFingerprint() {
@@ -29820,20 +30764,20 @@ function clearTerminalFingerprint() {
29820
30764
  function isSessionEnded() {
29821
30765
  if (hasMachineConfiguration()) return machineSessionEnded();
29822
30766
  if (resolveAuthCredential()?.source !== "token_file") return false;
29823
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
30767
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
29824
30768
  const ended = terminalFingerprint();
29825
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
30769
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
29826
30770
  }
29827
30771
  function withCredentialLock(operation, options = {}) {
29828
30772
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
29829
30773
  }
29830
30774
  function commitCredentialsUnlocked(credentials) {
29831
30775
  const accessToken = credentials.accessToken.trim();
29832
- const refreshToken2 = credentials.refreshToken.trim();
29833
- if (!accessToken || !refreshToken2) {
30776
+ const refreshToken3 = credentials.refreshToken.trim();
30777
+ if (!accessToken || !refreshToken3) {
29834
30778
  throw new Error("OAuth credentials require both access and refresh tokens");
29835
30779
  }
29836
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
30780
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
29837
30781
  if (credentials.metadata !== void 0) {
29838
30782
  preserveMarkerlessLegacyGeneration();
29839
30783
  writeCredentialMigrationSentinel();
@@ -29841,10 +30785,10 @@ function commitCredentialsUnlocked(credentials) {
29841
30785
  `);
29842
30786
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
29843
30787
  `);
29844
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
30788
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
29845
30789
  `);
29846
30790
  } else {
29847
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
30791
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
29848
30792
  `);
29849
30793
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
29850
30794
  `);
@@ -29881,15 +30825,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
29881
30825
  `
29882
30826
  );
29883
30827
  }
29884
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
30828
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
29885
30829
  const current = readStoredCredentialMetadata();
29886
30830
  if (expected.state === "legacy_broker") {
29887
30831
  if (current.state !== "legacy_broker") return false;
29888
30832
  if (!expected.metadata) return current.metadata === void 0;
29889
- return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
30833
+ return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
29890
30834
  }
29891
30835
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
29892
- return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
30836
+ return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
29893
30837
  }
29894
30838
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
29895
30839
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -30058,7 +31002,7 @@ async function performTokenRefresh(options = {}) {
30058
31002
  );
30059
31003
  }
30060
31004
  var _refreshInFlight;
30061
- function refreshToken(options = {}) {
31005
+ function refreshToken2(options = {}) {
30062
31006
  if (hasMachineConfiguration())
30063
31007
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
30064
31008
  if (_refreshInFlight) return _refreshInFlight;
@@ -30196,7 +31140,7 @@ async function machineClient(options = {}, management = false) {
30196
31140
  if (response.status === 401)
30197
31141
  throw new HttpError(
30198
31142
  401,
30199
- 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(
31143
+ selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : 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(
30200
31144
  "Machine access was rejected. Ask your administrator to check or rotate its credentials."
30201
31145
  )
30202
31146
  );
@@ -30217,7 +31161,7 @@ async function request2(method, path, body, options) {
30217
31161
  let refreshAttempted = false;
30218
31162
  if (credential && isTokenExpiringSoon(credential)) {
30219
31163
  refreshAttempted = true;
30220
- const token = await refreshToken({
31164
+ const token = await refreshToken2({
30221
31165
  signal: options?.signal,
30222
31166
  quiet: options?.quietRefresh
30223
31167
  });
@@ -30236,7 +31180,7 @@ async function request2(method, path, body, options) {
30236
31180
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
30237
31181
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
30238
31182
  refreshAttempted = true;
30239
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
31183
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
30240
31184
  }
30241
31185
  if (retryToken) {
30242
31186
  _cachedCredential = {
@@ -30260,7 +31204,7 @@ async function getPinnedClient(options = {}) {
30260
31204
  const siteUrl = getSiteUrl();
30261
31205
  let credential = selectedCredential();
30262
31206
  if (credential && isTokenExpiringSoon(credential)) {
30263
- const token2 = await refreshToken({
31207
+ const token2 = await refreshToken2({
30264
31208
  signal: options.signal,
30265
31209
  quiet: options.quietRefresh
30266
31210
  });
@@ -30648,8 +31592,8 @@ import {
30648
31592
  unlinkSync,
30649
31593
  writeFileSync as writeFileSync6
30650
31594
  } from "fs";
30651
- import { dirname as dirname10, isAbsolute as isAbsolute5, join as join18, resolve as resolve5 } from "path";
30652
- var WORKSPACE_ID_RELATIVE_PATH = join18("prim", "workspace-id");
31595
+ import { dirname as dirname10, isAbsolute as isAbsolute5, join as join19, resolve as resolve5 } from "path";
31596
+ var WORKSPACE_ID_RELATIVE_PATH = join19("prim", "workspace-id");
30653
31597
  var MAX_ANCESTORS = 64;
30654
31598
  var MAX_GIT_FILE_BYTES = 4096;
30655
31599
  var MAX_ID_FILE_BYTES = 128;
@@ -30708,11 +31652,11 @@ function resolveWorkspaceIdPath(cwd) {
30708
31652
  function resolveFromFilesystem(cwd) {
30709
31653
  let current = resolve5(cwd);
30710
31654
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
30711
- const dotGit = join18(current, ".git");
31655
+ const dotGit = join19(current, ".git");
30712
31656
  try {
30713
31657
  const stat = lstatSync8(dotGit);
30714
31658
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
30715
- return join18(dotGit, WORKSPACE_ID_RELATIVE_PATH);
31659
+ return join19(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30716
31660
  }
30717
31661
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
30718
31662
  const contents = readFileSync15(dotGit, "utf8");
@@ -30720,7 +31664,7 @@ function resolveFromFilesystem(cwd) {
30720
31664
  if (match?.[1]) {
30721
31665
  const gitDirectory = isAbsolute5(match[1]) ? resolve5(match[1]) : resolve5(current, match[1]);
30722
31666
  if (isGitDirectory(gitDirectory)) {
30723
- return join18(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
31667
+ return join19(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30724
31668
  }
30725
31669
  }
30726
31670
  }
@@ -30739,7 +31683,7 @@ function resolveFromFilesystem(cwd) {
30739
31683
  }
30740
31684
  function isGitDirectory(path) {
30741
31685
  try {
30742
- return statSync3(join18(path, "HEAD")).isFile();
31686
+ return statSync3(join19(path, "HEAD")).isFile();
30743
31687
  } catch {
30744
31688
  return false;
30745
31689
  }
@@ -30777,7 +31721,7 @@ function inspectPath(path) {
30777
31721
  function createWorkspaceId(path) {
30778
31722
  const parent = dirname10(path);
30779
31723
  const workspaceId = randomUUID4();
30780
- const temporaryPath = join18(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
31724
+ const temporaryPath = join19(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30781
31725
  let temporaryCreated = false;
30782
31726
  let publishing = false;
30783
31727
  try {
@@ -30847,7 +31791,7 @@ function parseAgent(argv) {
30847
31791
  }
30848
31792
 
30849
31793
  // src/hooks/codex-context.ts
30850
- import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
31794
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
30851
31795
  import {
30852
31796
  chmodSync as chmodSync6,
30853
31797
  existsSync as existsSync13,
@@ -30855,21 +31799,21 @@ import {
30855
31799
  readFileSync as readFileSync16,
30856
31800
  readdirSync as readdirSync4,
30857
31801
  renameSync as renameSync3,
30858
- rmSync as rmSync9,
31802
+ rmSync as rmSync10,
30859
31803
  statSync as statSync4,
30860
31804
  unlinkSync as unlinkSync2,
30861
31805
  writeFileSync as writeFileSync7
30862
31806
  } from "fs";
30863
- import { join as join20 } from "path";
31807
+ import { join as join21 } from "path";
30864
31808
 
30865
31809
  // src/daemon/principal.ts
30866
- import { createHash as createHash9 } from "crypto";
31810
+ import { createHash as createHash10 } from "crypto";
30867
31811
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
30868
31812
  function boundedClaim(value) {
30869
31813
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
30870
31814
  }
30871
31815
  function sha256(value) {
30872
- return createHash9("sha256").update(value).digest("hex");
31816
+ return createHash10("sha256").update(value).digest("hex");
30873
31817
  }
30874
31818
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
30875
31819
  if (hasMachineConfiguration()) {
@@ -30923,8 +31867,8 @@ function parseDaemonResponseEnvelope(value) {
30923
31867
 
30924
31868
  // src/daemon/client.ts
30925
31869
  import { createConnection } from "net";
30926
- import { join as join19 } from "path";
30927
- var SOCK_PATH = join19(primConfigDirectory(), "sock");
31870
+ import { join as join20 } from "path";
31871
+ var SOCK_PATH = join20(primConfigDirectory(), "sock");
30928
31872
  var DEFAULT_TIMEOUT_MS2 = 250;
30929
31873
  var nextRequestId = 1;
30930
31874
  function daemonRequest(method, params = {}, opts = {}) {
@@ -31227,10 +32171,10 @@ function appendCodexContext(output, context) {
31227
32171
  return next;
31228
32172
  }
31229
32173
  function stateRoot(namespace) {
31230
- return join20(primConfigDirectory(), namespace, "decision-digests");
32174
+ return join21(primConfigDirectory(), namespace, "decision-digests");
31231
32175
  }
31232
32176
  function draftStateRoot(namespace) {
31233
- return join20(primConfigDirectory(), namespace, "decision-draft-deliveries");
32177
+ return join21(primConfigDirectory(), namespace, "decision-draft-deliveries");
31234
32178
  }
31235
32179
  function workspaceFor(cwd) {
31236
32180
  try {
@@ -31241,13 +32185,13 @@ function workspaceFor(cwd) {
31241
32185
  }
31242
32186
  function statePath(args) {
31243
32187
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
31244
- const key = createHash10("sha256").update(identity).digest("hex");
31245
- return join20(stateRoot(args.namespace), `${key}.json`);
32188
+ const key = createHash11("sha256").update(identity).digest("hex");
32189
+ return join21(stateRoot(args.namespace), `${key}.json`);
31246
32190
  }
31247
32191
  function draftStatePath(args) {
31248
32192
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
31249
- const key = createHash10("sha256").update(identity).digest("hex");
31250
- return join20(draftStateRoot(args.namespace), `${key}.json`);
32193
+ const key = createHash11("sha256").update(identity).digest("hex");
32194
+ return join21(draftStateRoot(args.namespace), `${key}.json`);
31251
32195
  }
31252
32196
  function parseState(value) {
31253
32197
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -31285,7 +32229,7 @@ function parseDraftState(value) {
31285
32229
  updatedAt: record.updatedAt
31286
32230
  };
31287
32231
  }
31288
- function readState(path) {
32232
+ function readState2(path) {
31289
32233
  if (!existsSync13(path)) return void 0;
31290
32234
  try {
31291
32235
  return parseState(JSON.parse(readFileSync16(path, "utf8")));
@@ -31304,7 +32248,7 @@ function readDraftState(path) {
31304
32248
  function writeStateFile(path, directory, state) {
31305
32249
  mkdirSync8(directory, { recursive: true, mode: 448 });
31306
32250
  chmodSync6(directory, 448);
31307
- const temporary = join20(
32251
+ const temporary = join21(
31308
32252
  directory,
31309
32253
  `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
31310
32254
  );
@@ -31335,7 +32279,7 @@ function cleanupStateFiles(directory, now) {
31335
32279
  const files = [];
31336
32280
  const residue = [];
31337
32281
  for (const name2 of names) {
31338
- const path = join20(directory, name2);
32282
+ const path = join21(directory, name2);
31339
32283
  try {
31340
32284
  const mtimeMs = statSync4(path).mtimeMs;
31341
32285
  if (name2.endsWith(".json")) {
@@ -31357,7 +32301,7 @@ function cleanupStateFiles(directory, now) {
31357
32301
  for (const path of residue) {
31358
32302
  try {
31359
32303
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
31360
- rmSync9(path, { recursive: true, force: true });
32304
+ rmSync10(path, { recursive: true, force: true });
31361
32305
  }
31362
32306
  } catch {
31363
32307
  }
@@ -31443,7 +32387,7 @@ async function commitState(path, args, namespace) {
31443
32387
  await withFileLock(
31444
32388
  `${path}.lock`,
31445
32389
  () => {
31446
- const latest = readState(path);
32390
+ const latest = readState2(path);
31447
32391
  writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
31448
32392
  cleanupStateFiles(stateRoot(namespace), args.now);
31449
32393
  },
@@ -31490,7 +32434,7 @@ async function prepareCodexContext(options) {
31490
32434
  const siteUrl = getSiteUrl();
31491
32435
  const workspace = workspaceFor(options.cwd);
31492
32436
  const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
31493
- const previous = readState(path);
32437
+ const previous = readState2(path);
31494
32438
  const principal = resolveDaemonPrincipal();
31495
32439
  const privatePath = principal ? draftStatePath({
31496
32440
  cwd: options.cwd,
@@ -31642,7 +32586,7 @@ async function prepareCodexContext(options) {
31642
32586
  // src/commands/cursor-install.ts
31643
32587
  import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
31644
32588
  import { homedir as homedir4 } from "os";
31645
- import { isAbsolute as isAbsolute6, join as join22 } from "path";
32589
+ import { isAbsolute as isAbsolute6, join as join23 } from "path";
31646
32590
 
31647
32591
  // src/lib/preflight-host.ts
31648
32592
  import { execFileSync as execFileSync6 } from "child_process";
@@ -31650,7 +32594,7 @@ import { execFileSync as execFileSync6 } from "child_process";
31650
32594
  // src/commands/claude-install.ts
31651
32595
  import { existsSync as existsSync14, lstatSync as lstatSync9, readFileSync as readFileSync17 } from "fs";
31652
32596
  import { homedir as homedir3 } from "os";
31653
- import { join as join21 } from "path";
32597
+ import { join as join22 } from "path";
31654
32598
  var CAPTURE_BIN = "prim-hook";
31655
32599
  var GATE_BIN = "prim-pre-tool-use";
31656
32600
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -31659,7 +32603,7 @@ var SESSION_END_BIN = "prim-session-end";
31659
32603
  var STATUSLINE_BIN = "prim-statusline";
31660
32604
  var STATUSLINE_ARGS = "";
31661
32605
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
31662
- var USER_SCOPE_PATH = join21(homedir3(), ".claude", "settings.json");
32606
+ var USER_SCOPE_PATH = join22(homedir3(), ".claude", "settings.json");
31663
32607
  function projectRoot() {
31664
32608
  return gitToplevel() ?? process.cwd();
31665
32609
  }
@@ -31739,11 +32683,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
31739
32683
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
31740
32684
  if (explicit && isAbsolute6(explicit)) return explicit;
31741
32685
  const xdg = env.XDG_CONFIG_HOME?.trim();
31742
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join22(xdg, "cursor");
31743
- return join22(home, ".cursor");
32686
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join23(xdg, "cursor");
32687
+ return join23(home, ".cursor");
31744
32688
  }
31745
32689
  function cursorHooksPath(scope, root = projectRoot()) {
31746
- return scope === "user" ? join22(cursorConfigDirectory(), "hooks.json") : join22(root, ".cursor", "hooks.json");
32690
+ return scope === "user" ? join23(cursorConfigDirectory(), "hooks.json") : join23(root, ".cursor", "hooks.json");
31747
32691
  }
31748
32692
  function plainObject(value) {
31749
32693
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -31974,7 +32918,7 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
31974
32918
 
31975
32919
  // src/hooks/redact.ts
31976
32920
  import { existsSync as existsSync16, readFileSync as readFileSync19, statSync as statSync5 } from "fs";
31977
- import { join as join23 } from "path";
32921
+ import { join as join24 } from "path";
31978
32922
  import { Worker } from "worker_threads";
31979
32923
  var USER_HOME_RULES = [
31980
32924
  {
@@ -32055,7 +32999,7 @@ function normalizedWorkspaceFlags(value) {
32055
32999
  return [...new Set(`g${requested}`)].sort().join("");
32056
33000
  }
32057
33001
  function loadWorkspaceRules(cwd) {
32058
- const path = join23(cwd, WORKSPACE_FILE2);
33002
+ const path = join24(cwd, WORKSPACE_FILE2);
32059
33003
  if (!existsSync16(path)) return [];
32060
33004
  let cfg;
32061
33005
  try {
@@ -38419,7 +39363,7 @@ var TokenGroup = class {
38419
39363
  }
38420
39364
  token(input, stack) {
38421
39365
  let { parser: parser3 } = stack.p;
38422
- readToken(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
39366
+ readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
38423
39367
  }
38424
39368
  };
38425
39369
  TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
@@ -38433,7 +39377,7 @@ var LocalTokenGroup = class {
38433
39377
  let start = input.pos, skipped = 0;
38434
39378
  for (; ; ) {
38435
39379
  let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
38436
- readToken(this.data, input, stack, 0, this.data, this.precTable);
39380
+ readToken2(this.data, input, stack, 0, this.data, this.precTable);
38437
39381
  if (input.token.value > -1)
38438
39382
  break;
38439
39383
  if (this.elseToken == null)
@@ -38466,7 +39410,7 @@ var ExternalTokenizer = class {
38466
39410
  this.extend = !!options.extend;
38467
39411
  }
38468
39412
  };
38469
- function readToken(data, input, stack, group, precTable, precOffset) {
39413
+ function readToken2(data, input, stack, group, precTable, precOffset) {
38470
39414
  let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
38471
39415
  scan: for (; ; ) {
38472
39416
  if ((groupMask & data[state]) == 0)
@@ -40279,7 +41223,7 @@ var newline2 = 10;
40279
41223
  var carriageReturn = 13;
40280
41224
  var space2 = 32;
40281
41225
  var tab = 9;
40282
- var hash2 = 35;
41226
+ var hash3 = 35;
40283
41227
  var parenOpen = 40;
40284
41228
  var dot2 = 46;
40285
41229
  var braceOpen = 123;
@@ -40332,7 +41276,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
40332
41276
  input.advance();
40333
41277
  spaces2++;
40334
41278
  }
40335
- if (input.next == newline2 || input.next == carriageReturn || input.next == hash2)
41279
+ if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
40336
41280
  input.acceptToken(blankLineStart, -spaces2);
40337
41281
  } else if (isLineBreak(input.next)) {
40338
41282
  input.acceptToken(newline$1, 1);
@@ -40351,7 +41295,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
40351
41295
  input.advance();
40352
41296
  chars++;
40353
41297
  }
40354
- if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash2) {
41298
+ if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
40355
41299
  if (depth < context.indent) input.acceptToken(dedent, -chars);
40356
41300
  else input.acceptToken(indent);
40357
41301
  }
@@ -40425,7 +41369,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
40425
41369
  for (let off = 0; ; off++) {
40426
41370
  let next = input.peek(off);
40427
41371
  if (next == space2 || next == tab) continue;
40428
- if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash2)
41372
+ if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
40429
41373
  input.acceptToken(printKeyword);
40430
41374
  return;
40431
41375
  }
@@ -41636,7 +42580,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
41636
42580
  }
41637
42581
 
41638
42582
  // src/hooks/normalize.ts
41639
- import { createHash as createHash11 } from "crypto";
42583
+ import { createHash as createHash12 } from "crypto";
41640
42584
  import { realpathSync as realpathSync4 } from "fs";
41641
42585
  import { isAbsolute as isAbsolute8, resolve as resolve7 } from "path";
41642
42586
  var HERMES_EVENT_MAP = {
@@ -41681,7 +42625,7 @@ function requiredId(value, field) {
41681
42625
  }
41682
42626
  function cursorToolUseId(value) {
41683
42627
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
41684
- return `cursor:tool:v1:${createHash11("sha256").update(value).digest("hex")}`;
42628
+ return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
41685
42629
  }
41686
42630
  function workspaceCandidates(value) {
41687
42631
  if (!Array.isArray(value)) return [];
@@ -41778,7 +42722,7 @@ function normalizeEnvelope(parsed, agent) {
41778
42722
  ]);
41779
42723
  return {
41780
42724
  ...parsed,
41781
- tool_use_id: `codex:fallback:v1:${createHash11("sha256").update(stableToolIdentity).digest("hex")}`
42725
+ tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
41782
42726
  };
41783
42727
  }
41784
42728
  return parsed;
@@ -41922,7 +42866,7 @@ import {
41922
42866
  readSync,
41923
42867
  readdirSync as readdirSync6
41924
42868
  } from "fs";
41925
- import { dirname as dirname13, join as join25 } from "path";
42869
+ import { dirname as dirname13, join as join26 } from "path";
41926
42870
 
41927
42871
  // src/drain-progress.ts
41928
42872
  import {
@@ -41930,13 +42874,13 @@ import {
41930
42874
  existsSync as existsSync17,
41931
42875
  readFileSync as readFileSync20,
41932
42876
  readdirSync as readdirSync5,
41933
- rmSync as rmSync10,
42877
+ rmSync as rmSync11,
41934
42878
  rmdirSync
41935
42879
  } from "fs";
41936
- import { basename as basename3, dirname as dirname12, join as join24 } from "path";
42880
+ import { basename as basename3, dirname as dirname12, join as join25 } from "path";
41937
42881
 
41938
42882
  // src/journal.ts
41939
- var JOURNAL_DIR = join25(primConfigDirectory(), "moves");
42883
+ var JOURNAL_DIR = join26(primConfigDirectory(), "moves");
41940
42884
  var UNBOUND_BUCKET = "_unbound";
41941
42885
  var JOURNAL_BASENAME = "journal.ndjson";
41942
42886
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -41948,7 +42892,7 @@ function envSlug(apiUrl) {
41948
42892
  return slug;
41949
42893
  }
41950
42894
  function currentEnvDir() {
41951
- return join25(JOURNAL_DIR, envSlug(getSiteUrl()));
42895
+ return join26(JOURNAL_DIR, envSlug(getSiteUrl()));
41952
42896
  }
41953
42897
  var DIR_MODE = 448;
41954
42898
  var FILE_MODE2 = 384;
@@ -41964,10 +42908,10 @@ function appendMoveToPath(path, move) {
41964
42908
  }
41965
42909
  function bucketDir(orgId) {
41966
42910
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
41967
- return join25(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
42911
+ return join26(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
41968
42912
  }
41969
42913
  function journalPath(orgId) {
41970
- return join25(bucketDir(orgId), JOURNAL_BASENAME);
42914
+ return join26(bucketDir(orgId), JOURNAL_BASENAME);
41971
42915
  }
41972
42916
  function appendMove(move, orgId) {
41973
42917
  const actor = machineCaptureActor();
@@ -41997,7 +42941,7 @@ async function deliverPostToolMove(move, orgId) {
41997
42941
  }
41998
42942
 
41999
42943
  // src/hooks/prim-hook-core.ts
42000
- import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
42944
+ import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
42001
42945
  import { platform } from "os";
42002
42946
 
42003
42947
  // src/protocol/move.ts
@@ -42071,9 +43015,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
42071
43015
  const toolOutcome = toolOutcomeFor(parsed, agent);
42072
43016
  let moveId;
42073
43017
  if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
42074
- moveId = `posttool:v1:${createHash12("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
43018
+ moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
42075
43019
  } else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
42076
- moveId = `posttool:fallback:v1:${createHash12("sha256").update(
43020
+ moveId = `posttool:fallback:v1:${createHash13("sha256").update(
42077
43021
  JSON.stringify([
42078
43022
  agent,
42079
43023
  sessionId,
@@ -42149,7 +43093,7 @@ function editingToolsFor(agent) {
42149
43093
  var here = dirname14(fileURLToPath5(import.meta.url));
42150
43094
  function resolveCliVersion() {
42151
43095
  try {
42152
- const pkg = JSON.parse(readFileSync22(join26(here, "..", "..", "package.json"), "utf-8"));
43096
+ const pkg = JSON.parse(readFileSync22(join27(here, "..", "..", "package.json"), "utf-8"));
42153
43097
  return pkg.version ?? "unknown";
42154
43098
  } catch {
42155
43099
  return "unknown";