@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
@@ -55,33 +55,33 @@ var require_ucs2length = __commonJS({
55
55
  // src/hooks/prim-hook.ts
56
56
  import { spawn as spawn2 } from "child_process";
57
57
  import { readFileSync as readFileSync23 } from "fs";
58
- import { dirname as dirname15, join as join27 } from "path";
58
+ import { dirname as dirname15, join as join28 } from "path";
59
59
  import { fileURLToPath as fileURLToPath5 } from "url";
60
60
 
61
61
  // src/binding.ts
62
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
63
- import { dirname as dirname5, join as join8 } from "path";
62
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
63
+ import { dirname as dirname6, join as join10 } from "path";
64
64
 
65
65
  // src/lib/credentials.ts
66
- import { createHash as createHash4 } from "crypto";
67
- import { readFileSync as readFileSync6 } from "fs";
68
- import { join as join7 } from "path";
66
+ import { createHash as createHash6 } from "crypto";
67
+ import { readFileSync as readFileSync7 } from "fs";
68
+ import { join as join9 } from "path";
69
69
 
70
70
  // src/lib/machine-credentials.ts
71
- import { execFileSync } from "child_process";
72
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
71
+ import { execFileSync as execFileSync2 } from "child_process";
72
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
73
73
  import {
74
74
  chmodSync,
75
75
  existsSync as existsSync3,
76
76
  linkSync,
77
- lstatSync as lstatSync3,
77
+ lstatSync as lstatSync4,
78
78
  mkdirSync as mkdirSync3,
79
- readFileSync as readFileSync5,
80
- rmSync as rmSync5,
79
+ readFileSync as readFileSync6,
80
+ rmSync as rmSync6,
81
81
  writeFileSync as writeFileSync3
82
82
  } from "fs";
83
83
  import { createRequire } from "module";
84
- import { dirname as dirname4, join as join6 } from "path";
84
+ import { dirname as dirname5, join as join8 } from "path";
85
85
  import { fileURLToPath as fileURLToPath3 } from "url";
86
86
 
87
87
  // src/lib/atomic-file.ts
@@ -455,6 +455,8 @@ function isClaudeCloudSession(env = process.env) {
455
455
  }
456
456
  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';
457
457
  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';
458
+ 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}.`;
459
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
458
460
  function cloudSetupPointer(message, env = process.env) {
459
461
  return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
460
462
  }
@@ -596,10 +598,10 @@ function parseWorkosConnectTokens(value, options = {}) {
596
598
  "access_token",
597
599
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
598
600
  );
599
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
601
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
600
602
  return {
601
603
  accessToken,
602
- refreshToken: refreshToken2,
604
+ refreshToken: refreshToken3,
603
605
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
604
606
  };
605
607
  }
@@ -1202,32 +1204,1267 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
1202
1204
  }
1203
1205
  }
1204
1206
 
1207
+ // src/lib/session-identity.ts
1208
+ import { execFile } from "child_process";
1209
+ import { createHash as createHash4 } from "crypto";
1210
+ import { rmSync as rmSync5 } from "fs";
1211
+ import { join as join7 } from "path";
1212
+ import { promisify } from "util";
1213
+
1214
+ // src/lib/git.ts
1215
+ import { execFileSync } from "child_process";
1216
+ import { createHash as createHash3 } from "crypto";
1217
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
1218
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
1219
+ var GIT_TIMEOUT_MS = 1e3;
1220
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
1221
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1222
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1223
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
1224
+ function gitChildEnvironment(env = process.env) {
1225
+ return Object.fromEntries(
1226
+ Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
1227
+ );
1228
+ }
1229
+ function gitToplevel(cwd) {
1230
+ try {
1231
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
1232
+ cwd,
1233
+ encoding: "utf-8",
1234
+ stdio: ["ignore", "pipe", "ignore"],
1235
+ timeout: GIT_TIMEOUT_MS,
1236
+ env: gitChildEnvironment()
1237
+ }).trim();
1238
+ } catch {
1239
+ return null;
1240
+ }
1241
+ }
1242
+ function gitValue(cwd, args) {
1243
+ try {
1244
+ const value = execFileSync("git", args, {
1245
+ cwd,
1246
+ encoding: "utf-8",
1247
+ stdio: ["ignore", "pipe", "ignore"],
1248
+ timeout: GIT_TIMEOUT_MS,
1249
+ env: gitChildEnvironment()
1250
+ }).trim();
1251
+ return value || void 0;
1252
+ } catch {
1253
+ return void 0;
1254
+ }
1255
+ }
1256
+ function currentBranch(cwd) {
1257
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
1258
+ }
1259
+ function parseGithubRepositoryName(path) {
1260
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1261
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1262
+ return null;
1263
+ }
1264
+ return `${parts[0]}/${parts[1]}`;
1265
+ }
1266
+ function githubRepositoryFromRemote(remote) {
1267
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1268
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1269
+ remote
1270
+ );
1271
+ const path = match?.[1] ?? match?.[2];
1272
+ return path ? parseGithubRepositoryName(path) : null;
1273
+ }
1274
+ function checkoutSettingsText(repoRoot) {
1275
+ const path = join6(repoRoot, ".claude", "settings.json");
1276
+ try {
1277
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
1278
+ const stat = lstatSync3(path);
1279
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1280
+ return readFileSync5(path, "utf8");
1281
+ } catch {
1282
+ return null;
1283
+ }
1284
+ }
1285
+ function checkoutDeclaration(repoRoot, name2) {
1286
+ const text = checkoutSettingsText(repoRoot);
1287
+ if (text === null) return null;
1288
+ let parsed;
1289
+ try {
1290
+ parsed = JSON.parse(text);
1291
+ } catch {
1292
+ return null;
1293
+ }
1294
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1295
+ const value = typeof env === "object" && env !== null ? env[name2] : void 0;
1296
+ return typeof value === "string" ? value : null;
1297
+ }
1298
+ function declaredGithubRepository(repoRoot) {
1299
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1300
+ return value === null ? null : parseGithubRepositoryName(value.trim());
1301
+ }
1302
+ function githubRepositoryFullName(cwd) {
1303
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1304
+ if (remote) {
1305
+ const fromOrigin = githubRepositoryFromRemote(remote);
1306
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1307
+ }
1308
+ const root = gitToplevel(cwd);
1309
+ return root ? declaredGithubRepository(root) : null;
1310
+ }
1311
+ function canonicalGitRoot(cwd) {
1312
+ try {
1313
+ const top = gitToplevel(cwd);
1314
+ return top ? realpathSync.native(top) : null;
1315
+ } catch {
1316
+ return null;
1317
+ }
1318
+ }
1319
+ function relatedWorktreeTarget(path, cwd, origin) {
1320
+ let parent = dirname4(resolve(cwd, path));
1321
+ while (true) {
1322
+ try {
1323
+ realpathSync.native(parent);
1324
+ break;
1325
+ } catch {
1326
+ const next = dirname4(parent);
1327
+ if (next === parent) return null;
1328
+ parent = next;
1329
+ }
1330
+ }
1331
+ const target = resolveRepositoryContext(parent);
1332
+ if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
1333
+ const common = (root) => {
1334
+ const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
1335
+ try {
1336
+ return value ? realpathSync.native(resolve(root, value)) : void 0;
1337
+ } catch {
1338
+ return void 0;
1339
+ }
1340
+ };
1341
+ const originCommon = common(origin.repoRoot);
1342
+ return originCommon && originCommon === common(target.repoRoot) ? target : null;
1343
+ }
1344
+ function normalizeOriginRemote(remote) {
1345
+ const value = remote.trim();
1346
+ if (!value) return void 0;
1347
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1348
+ if (scp?.host && scp.path) {
1349
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1350
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1351
+ }
1352
+ try {
1353
+ const url = new URL(value);
1354
+ url.username = "";
1355
+ url.password = "";
1356
+ url.search = "";
1357
+ url.hash = "";
1358
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1359
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1360
+ return void 0;
1361
+ } catch {
1362
+ return void 0;
1363
+ }
1364
+ }
1365
+ function opaqueRepoKey(source, value) {
1366
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
1367
+ }
1368
+ function resolveRepositoryContext(cwd = process.cwd()) {
1369
+ const top = gitToplevel(cwd);
1370
+ if (!top) return null;
1371
+ let repoRoot;
1372
+ try {
1373
+ repoRoot = realpathSync.native(top);
1374
+ } catch {
1375
+ repoRoot = resolve(top);
1376
+ }
1377
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1378
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1379
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1380
+ if (normalizedOrigin) {
1381
+ return {
1382
+ repoRoot,
1383
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
1384
+ identitySource: "origin",
1385
+ repoFullName
1386
+ };
1387
+ }
1388
+ if (repoFullName) {
1389
+ return {
1390
+ repoRoot,
1391
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1392
+ identitySource: "declared",
1393
+ repoFullName
1394
+ };
1395
+ }
1396
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1397
+ if (roots && roots.length > 0) {
1398
+ return {
1399
+ repoRoot,
1400
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1401
+ identitySource: "root_commit",
1402
+ repoFullName
1403
+ };
1404
+ }
1405
+ return { repoRoot, repoFullName };
1406
+ }
1407
+ function nearestExistingAncestor(path) {
1408
+ const suffix = [];
1409
+ let cursor = path;
1410
+ while (true) {
1411
+ try {
1412
+ lstatSync3(cursor);
1413
+ break;
1414
+ } catch (error) {
1415
+ const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
1416
+ if (code !== "ENOENT" && code !== "ENOTDIR") return null;
1417
+ const parent = dirname4(cursor);
1418
+ if (parent === cursor) return null;
1419
+ suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
1420
+ cursor = parent;
1421
+ }
1422
+ }
1423
+ try {
1424
+ return { real: realpathSync.native(cursor), suffix };
1425
+ } catch {
1426
+ return null;
1427
+ }
1428
+ }
1429
+ function canonicalRepositoryPathScoped(filePath, context, baseDir) {
1430
+ if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
1431
+ return { ok: false, reason: "invalid_path" };
1432
+ }
1433
+ const absolute = resolve(baseDir, filePath);
1434
+ const resolved = nearestExistingAncestor(absolute);
1435
+ if (!resolved) return { ok: false, reason: "invalid_path" };
1436
+ const target = resolve(resolved.real, ...resolved.suffix);
1437
+ const rel = relative(context.repoRoot, target);
1438
+ if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
1439
+ if (isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1440
+ return { ok: false, reason: "outside_repository" };
1441
+ }
1442
+ return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
1443
+ }
1444
+ function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
1445
+ if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
1446
+ return null;
1447
+ const absolute = resolve(cwd, filePath);
1448
+ let target;
1449
+ try {
1450
+ const stat = lstatSync3(absolute);
1451
+ if (!stat.isFile() || stat.isSymbolicLink()) return null;
1452
+ target = realpathSync.native(absolute);
1453
+ } catch (error) {
1454
+ if (!(error instanceof Error) || error.code !== "ENOENT") {
1455
+ return null;
1456
+ }
1457
+ try {
1458
+ const parent = realpathSync.native(dirname4(absolute));
1459
+ if (!lstatSync3(parent).isDirectory()) return null;
1460
+ target = resolve(parent, basename2(absolute));
1461
+ } catch {
1462
+ return null;
1463
+ }
1464
+ }
1465
+ const rel = relative(repositoryRoot, target);
1466
+ if (!rel || isAbsolute3(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
1467
+ return null;
1468
+ }
1469
+ return sep === "/" ? rel : rel.split(sep).join("/");
1470
+ }
1471
+ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
1472
+ if (typeof contextOrCwd === "string") {
1473
+ return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
1474
+ }
1475
+ return canonicalRepositoryPathScoped(
1476
+ filePath,
1477
+ contextOrCwd,
1478
+ baseDirOrRoot ?? contextOrCwd.repoRoot
1479
+ );
1480
+ }
1481
+
1482
+ // src/lib/terminal-safe.ts
1483
+ function replaceIsolatedSurrogates(value) {
1484
+ let out = "";
1485
+ for (let index = 0; index < value.length; index += 1) {
1486
+ const unit = value.charCodeAt(index);
1487
+ if (unit >= 55296 && unit <= 56319) {
1488
+ const next = value.charCodeAt(index + 1);
1489
+ if (next >= 56320 && next <= 57343) {
1490
+ out += value[index] + value[index + 1];
1491
+ index += 1;
1492
+ } else {
1493
+ out += "\uFFFD";
1494
+ }
1495
+ } else if (unit >= 56320 && unit <= 57343) {
1496
+ out += "\uFFFD";
1497
+ } else {
1498
+ out += value[index];
1499
+ }
1500
+ }
1501
+ return out;
1502
+ }
1503
+ function isUnsafeTerminalCodePoint(point) {
1504
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1505
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1506
+ point === 1564 || // Arabic letter mark
1507
+ point === 6158 || // Mongolian vowel separator
1508
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1509
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1510
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1511
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1512
+ point === 65279 || // zero-width no-break space / BOM
1513
+ point >= 917504 && point <= 917631;
1514
+ return c0OrC1 || bidiOrZeroWidth;
1515
+ }
1516
+ function terminalSafeText(value) {
1517
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1518
+ }
1519
+ function terminalSafeLine(value) {
1520
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1521
+ }
1522
+ function isTerminalSafeText(value) {
1523
+ return terminalSafeText(value) === value;
1524
+ }
1525
+ var stripControlChars = terminalSafeText;
1526
+
1527
+ // src/lib/session-identity.ts
1528
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1529
+ var SESSION_IDENTITY_VALUE = "session";
1530
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1531
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1532
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1533
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1534
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1535
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1536
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1537
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1538
+ var SESSION_IDENTITY_ROUTES = {
1539
+ challenge: "/api/cli/session-identity/challenge",
1540
+ token: "/api/cli/session-identity/token",
1541
+ refresh: "/api/cli/session-identity/token/refresh",
1542
+ link: "/api/cli/session-identity/link"
1543
+ };
1544
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1545
+ var RENEW_BEFORE_MS = 6e4;
1546
+ var GIT_TIMEOUT_MS2 = 1e4;
1547
+ var POLL_BUDGET_MS = 15e3;
1548
+ var POLL_FIRST_DELAY_MS = 500;
1549
+ var POLL_MAX_DELAY_MS = 3e3;
1550
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1551
+ var LOCK_TIMEOUT_MS = 6e4;
1552
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1553
+ function sessionIdentityRequested(env = process.env) {
1554
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1555
+ }
1556
+ function sessionIdentityMode(deps = {}) {
1557
+ const env = deps.env ?? process.env;
1558
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1559
+ }
1560
+ function failure(code, cause, remedy) {
1561
+ return { status: "failed", code, cause, remedy };
1562
+ }
1563
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1564
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1565
+ 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';
1566
+ var SESSION_REVOKED = failure(
1567
+ "session_revoked",
1568
+ "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",
1569
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1570
+ );
1571
+ var CHALLENGE_WINDOW_PASSED = failure(
1572
+ "challenge_expired",
1573
+ "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)",
1574
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1575
+ );
1576
+ var CHALLENGE_GONE = failure(
1577
+ "challenge_not_found",
1578
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1579
+ NEW_SESSION_REMEDY
1580
+ );
1581
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1582
+ function rejectionFailure(reason, repository) {
1583
+ switch (reason) {
1584
+ case "identity_mismatch":
1585
+ return failure(
1586
+ "identity_mismatch",
1587
+ "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",
1588
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1589
+ );
1590
+ case "push_after_expiry":
1591
+ return failure(
1592
+ "push_after_expiry",
1593
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1594
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1595
+ );
1596
+ case "repository_mismatch":
1597
+ return failure(
1598
+ "repository_mismatch",
1599
+ `Primitive received the identity push from a different repository than ${repository}`,
1600
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1601
+ );
1602
+ case "conflicting_push":
1603
+ return failure(
1604
+ "conflicting_push",
1605
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1606
+ NEW_SESSION_REMEDY
1607
+ );
1608
+ case "unsupported_sender":
1609
+ return failure(
1610
+ "unsupported_sender",
1611
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1612
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1613
+ );
1614
+ default:
1615
+ return failure(
1616
+ "challenge_rejected",
1617
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1618
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1619
+ );
1620
+ }
1621
+ }
1622
+ function sessionIdentityMessage(outcome) {
1623
+ if (outcome.status === "link_required")
1624
+ 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.`;
1625
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1626
+ }
1627
+ function hash(value) {
1628
+ return createHash4("sha256").update(value).digest("hex");
1629
+ }
1630
+ function sessionContext(deps) {
1631
+ const env = deps.env ?? process.env;
1632
+ const environment = environmentCredentials(deps);
1633
+ if (!environment)
1634
+ return failure(
1635
+ "environment_credential_missing",
1636
+ "the cloud environment has no environment credential",
1637
+ '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'
1638
+ );
1639
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1640
+ if (!sessionId || !SESSION_ID.test(sessionId))
1641
+ return failure(
1642
+ "session_id_missing",
1643
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1644
+ NEW_SESSION_REMEDY
1645
+ );
1646
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1647
+ const directory = deps.directory ?? primConfigDirectory({ env });
1648
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1649
+ return {
1650
+ directory,
1651
+ apiUrl,
1652
+ clientId: environment.clientId,
1653
+ generation: environment.generation,
1654
+ sessionId,
1655
+ tokenPath: join7(directory, `session_identity_${key}.json`),
1656
+ statePath: join7(directory, `session_identity_${key}.state.json`),
1657
+ lockPath: join7(directory, "session-identity.lock")
1658
+ };
1659
+ }
1660
+ function readRecord(path) {
1661
+ try {
1662
+ const value = readMachineMetadata(path);
1663
+ return value === void 0 ? void 0 : machineRecord(value);
1664
+ } catch {
1665
+ return void 0;
1666
+ }
1667
+ }
1668
+ function finiteNumber(value) {
1669
+ return typeof value === "number" && Number.isFinite(value);
1670
+ }
1671
+ function readToken(context) {
1672
+ const data = readRecord(context.tokenPath);
1673
+ 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))
1674
+ return void 0;
1675
+ const identity = data.identity;
1676
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1677
+ return void 0;
1678
+ return data;
1679
+ }
1680
+ function readState(context) {
1681
+ const data = readRecord(context.statePath);
1682
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1683
+ return void 0;
1684
+ return data;
1685
+ }
1686
+ function writeToken(context, record) {
1687
+ prepareMachineMetadataDirectory(context.directory);
1688
+ writeMachineMetadata(context.tokenPath, record);
1689
+ rmSync5(context.statePath, { force: true });
1690
+ }
1691
+ function writeState(context, state) {
1692
+ try {
1693
+ prepareMachineMetadataDirectory(context.directory);
1694
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1695
+ } catch {
1696
+ }
1697
+ }
1698
+ function tokenValid(record, now = Date.now()) {
1699
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1700
+ }
1701
+ function tokenFresh(record, now = Date.now()) {
1702
+ return tokenValid(record, now) && now < record.refreshAfter;
1703
+ }
1704
+ function toCredential(record) {
1705
+ return {
1706
+ issuer: record.issuer,
1707
+ audience: record.audience,
1708
+ ...record.identity,
1709
+ accessToken: record.accessToken,
1710
+ expiresAt: record.expiresAt,
1711
+ apiUrl: record.apiUrl,
1712
+ generation: record.generation,
1713
+ storage: "environment",
1714
+ session: {
1715
+ userId: record.userId,
1716
+ displayName: record.displayName,
1717
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1718
+ refreshAfter: record.refreshAfter
1719
+ }
1720
+ };
1721
+ }
1722
+ function identified(record, reused) {
1723
+ return {
1724
+ status: "ok",
1725
+ credential: toCredential(record),
1726
+ displayName: record.displayName,
1727
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1728
+ reused
1729
+ };
1730
+ }
1731
+ function cachedSessionCredential(deps = {}) {
1732
+ if (!sessionIdentityMode(deps)) return void 0;
1733
+ let context;
1734
+ try {
1735
+ context = sessionContext(deps);
1736
+ } catch {
1737
+ return void 0;
1738
+ }
1739
+ if ("status" in context) return void 0;
1740
+ const record = readToken(context);
1741
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1742
+ }
1743
+ function outcomeFromState(state) {
1744
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1745
+ return {
1746
+ status: "link_required",
1747
+ githubLogin: state.githubLogin,
1748
+ challengeId: state.challengeId,
1749
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1750
+ };
1751
+ return failure(
1752
+ state.code,
1753
+ state.cause ?? "the last identity check failed",
1754
+ state.remedy ?? RETRY_REMEDY
1755
+ );
1756
+ }
1757
+ function parseInstant(value) {
1758
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1759
+ if (typeof value === "string" && value.length <= 64) {
1760
+ const parsed = Date.parse(value);
1761
+ return Number.isFinite(parsed) ? parsed : void 0;
1762
+ }
1763
+ return void 0;
1764
+ }
1765
+ async function sendJson(url, init, fetchImpl) {
1766
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1767
+ let value;
1768
+ try {
1769
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1770
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1771
+ } catch {
1772
+ value = void 0;
1773
+ }
1774
+ return { status: response.status, value };
1775
+ }
1776
+ function environmentOnly(deps) {
1777
+ return { ...deps, environmentOnly: true };
1778
+ }
1779
+ async function environmentRequest(method, path, body, deps, signal) {
1780
+ const send = async (credential2) => {
1781
+ const headers = { "Content-Type": "application/json" };
1782
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1783
+ if (credential2.tokenInjection) {
1784
+ const response = await forwardMachineRequest(
1785
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1786
+ signal,
1787
+ environmentOnly(deps)
1788
+ );
1789
+ const parsed = await response.json().catch(() => void 0);
1790
+ return {
1791
+ status: response.status,
1792
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1793
+ };
1794
+ }
1795
+ return sendJson(
1796
+ `${credential2.apiUrl}${path}`,
1797
+ {
1798
+ method,
1799
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1800
+ ...text === void 0 ? {} : { body: text },
1801
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1802
+ },
1803
+ deps.fetch ?? fetch
1804
+ );
1805
+ };
1806
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1807
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1808
+ let answer = await send(credential);
1809
+ if (answer.status === 401) {
1810
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1811
+ if (!credential)
1812
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1813
+ answer = await send(credential);
1814
+ }
1815
+ return answer;
1816
+ }
1817
+ function environmentFailure(error, apiUrl) {
1818
+ if (error instanceof MachineAuthError && error.terminal)
1819
+ return failure(
1820
+ "environment_credential_rejected",
1821
+ "Primitive rejected the cloud environment's credential",
1822
+ ENVIRONMENT_CREDENTIAL_REMEDY
1823
+ );
1824
+ const host = (() => {
1825
+ try {
1826
+ return new URL(apiUrl).hostname;
1827
+ } catch {
1828
+ return "Primitive";
1829
+ }
1830
+ })();
1831
+ return failure(
1832
+ "identity_unavailable",
1833
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1834
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1835
+ );
1836
+ }
1837
+ function answerError(answer) {
1838
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1839
+ }
1840
+ async function git(root, args, signal) {
1841
+ try {
1842
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1843
+ cwd: root,
1844
+ encoding: "utf8",
1845
+ timeout: GIT_TIMEOUT_MS2,
1846
+ signal,
1847
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1848
+ maxBuffer: 1024 * 1024
1849
+ });
1850
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1851
+ } catch (error) {
1852
+ const failed = error;
1853
+ return {
1854
+ ok: false,
1855
+ code: typeof failed.code === "number" ? failed.code : void 0,
1856
+ stdout: failed.stdout ?? "",
1857
+ stderr: failed.stderr ?? "",
1858
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1859
+ };
1860
+ }
1861
+ }
1862
+ function gitDetail(stderr) {
1863
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1864
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1865
+ }
1866
+ async function defaultSleep2(milliseconds, signal) {
1867
+ await new Promise((resolve9, reject) => {
1868
+ const timer = setTimeout(resolve9, milliseconds);
1869
+ signal?.addEventListener(
1870
+ "abort",
1871
+ () => {
1872
+ clearTimeout(timer);
1873
+ reject(signal.reason);
1874
+ },
1875
+ { once: true }
1876
+ );
1877
+ });
1878
+ }
1879
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1880
+ const sleep = deps.sleep ?? defaultSleep2;
1881
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1882
+ let delay = POLL_FIRST_DELAY_MS;
1883
+ let unreachable;
1884
+ for (; ; ) {
1885
+ const remaining = deadline - Date.now();
1886
+ if (remaining <= 0) break;
1887
+ await sleep(Math.min(delay, remaining), signal);
1888
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1889
+ let answer;
1890
+ try {
1891
+ answer = await environmentRequest(
1892
+ "GET",
1893
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1894
+ void 0,
1895
+ deps,
1896
+ signal
1897
+ );
1898
+ } catch (error) {
1899
+ signal?.throwIfAborted();
1900
+ unreachable = error;
1901
+ continue;
1902
+ }
1903
+ if (answer.status === 404) return CHALLENGE_GONE;
1904
+ if (answer.status === 401 || answer.status === 403)
1905
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1906
+ if (answer.status < 200 || answer.status > 299) {
1907
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1908
+ continue;
1909
+ }
1910
+ unreachable = void 0;
1911
+ const status = answer.value;
1912
+ if (status?.status === "verified")
1913
+ return {
1914
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1915
+ };
1916
+ if (status?.status === "expired")
1917
+ return failure(
1918
+ "challenge_expired",
1919
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1920
+ NEW_SESSION_REMEDY
1921
+ );
1922
+ if (status?.status === "rejected")
1923
+ return rejectionFailure(status.reason, repository);
1924
+ }
1925
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1926
+ return failure(
1927
+ "webhook_timeout",
1928
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1929
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1930
+ );
1931
+ }
1932
+ function parseTokenAnswer(value) {
1933
+ if (!value) return void 0;
1934
+ const user = value.user;
1935
+ const expiresAt = parseInstant(value.expiresAt);
1936
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1937
+ 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))
1938
+ return void 0;
1939
+ return {
1940
+ accessToken: value.accessToken,
1941
+ expiresAt,
1942
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1943
+ userId: user.id,
1944
+ displayName: user.displayName,
1945
+ organizationId: value.organizationId
1946
+ };
1947
+ }
1948
+ var SERVER_CONTRACT_FAILURE = failure(
1949
+ "server_contract",
1950
+ "Primitive's answer did not identify the linked member",
1951
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1952
+ );
1953
+ async function recordFor(context, answer, extra, deps, signal) {
1954
+ let identity;
1955
+ let environment;
1956
+ try {
1957
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1958
+ identity = await verifyMachineIdentity(
1959
+ context.apiUrl,
1960
+ answer.accessToken,
1961
+ context.clientId,
1962
+ signal,
1963
+ deps.fetch
1964
+ );
1965
+ } catch (error) {
1966
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1967
+ return SERVER_CONTRACT_FAILURE;
1968
+ return environmentFailure(error, context.apiUrl);
1969
+ }
1970
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1971
+ return SERVER_CONTRACT_FAILURE;
1972
+ return {
1973
+ version: 1,
1974
+ apiUrl: context.apiUrl,
1975
+ clientId: context.clientId,
1976
+ generation: context.generation,
1977
+ sessionId: context.sessionId,
1978
+ issuer: environment.issuer,
1979
+ audience: environment.audience,
1980
+ accessToken: answer.accessToken,
1981
+ expiresAt: answer.expiresAt,
1982
+ refreshAfter: answer.refreshAfter,
1983
+ userId: answer.userId,
1984
+ displayName: answer.displayName,
1985
+ organizationId: answer.organizationId,
1986
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1987
+ identity,
1988
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1989
+ };
1990
+ }
1991
+ async function refreshToken(context, record, deps, signal) {
1992
+ let answer;
1993
+ try {
1994
+ answer = await environmentRequest(
1995
+ "POST",
1996
+ SESSION_IDENTITY_ROUTES.refresh,
1997
+ { accessToken: record.accessToken },
1998
+ deps,
1999
+ signal
2000
+ );
2001
+ } catch (error) {
2002
+ signal?.throwIfAborted();
2003
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
2004
+ }
2005
+ const code = answerError(answer);
2006
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
2007
+ return { status: "refused", failure: SESSION_REVOKED };
2008
+ if (answer.status === 401 || answer.status === 403)
2009
+ return {
2010
+ status: "refused",
2011
+ failure: environmentFailure(
2012
+ new MachineAuthError("rejected", "rejected", true),
2013
+ context.apiUrl
2014
+ )
2015
+ };
2016
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2017
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
2018
+ return { status: "unavailable" };
2019
+ return {
2020
+ status: "ok",
2021
+ record: {
2022
+ ...record,
2023
+ accessToken: token.accessToken,
2024
+ expiresAt: token.expiresAt,
2025
+ refreshAfter: token.refreshAfter,
2026
+ displayName: token.displayName
2027
+ }
2028
+ };
2029
+ }
2030
+ function exchangeRefusal(answer, repository) {
2031
+ if (answer.status === 404) return CHALLENGE_GONE;
2032
+ if (answer.status !== 409) return void 0;
2033
+ switch (answerError(answer)) {
2034
+ case "identity_mismatch":
2035
+ return rejectionFailure("identity_mismatch", repository);
2036
+ case "challenge_rejected":
2037
+ return rejectionFailure(answer.value?.reason, repository);
2038
+ case "challenge_expired":
2039
+ return CHALLENGE_WINDOW_PASSED;
2040
+ case "challenge_already_exchanged":
2041
+ return failure(
2042
+ "challenge_already_exchanged",
2043
+ "this session's identity check was already exchanged for a token this VM does not hold",
2044
+ NEW_SESSION_REMEDY
2045
+ );
2046
+ case "challenge_pending":
2047
+ return failure(
2048
+ "webhook_timeout",
2049
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
2050
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
2051
+ );
2052
+ default:
2053
+ return void 0;
2054
+ }
2055
+ }
2056
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
2057
+ let answer;
2058
+ try {
2059
+ answer = await environmentRequest(
2060
+ "POST",
2061
+ SESSION_IDENTITY_ROUTES.token,
2062
+ { challengeId: challenge.challengeId },
2063
+ deps,
2064
+ signal
2065
+ );
2066
+ } catch (error) {
2067
+ signal?.throwIfAborted();
2068
+ return environmentFailure(error, context.apiUrl);
2069
+ }
2070
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
2071
+ const login = answer.value?.githubLogin;
2072
+ return {
2073
+ status: "link_required",
2074
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
2075
+ challengeId: challenge.challengeId,
2076
+ challengeExpiresAt: challenge.challengeExpiresAt
2077
+ };
2078
+ }
2079
+ const refused = exchangeRefusal(
2080
+ answer,
2081
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
2082
+ );
2083
+ if (refused) return refused;
2084
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
2085
+ if (!token) {
2086
+ if (answer.status === 401 || answer.status === 403)
2087
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2088
+ return answer.status >= 500 ? environmentFailure(
2089
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2090
+ context.apiUrl
2091
+ ) : SERVER_CONTRACT_FAILURE;
2092
+ }
2093
+ return recordFor(
2094
+ context,
2095
+ token,
2096
+ { githubLogin: challenge.githubLogin, repositoryRoot },
2097
+ deps,
2098
+ signal
2099
+ );
2100
+ }
2101
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
2102
+ const env = deps.env ?? process.env;
2103
+ const repository = githubRepositoryFullName(root);
2104
+ if (!repository)
2105
+ return failure(
2106
+ "repository_unidentified",
2107
+ "this checkout does not name its GitHub repository",
2108
+ "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"
2109
+ );
2110
+ const branch = currentBranch(root);
2111
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
2112
+ return failure(
2113
+ "not_session_branch",
2114
+ `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`,
2115
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
2116
+ );
2117
+ attempt.branch = branch;
2118
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
2119
+ if (!baseSha) {
2120
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
2121
+ baseSha = head.stdout.trim();
2122
+ if (!head.ok || !SHA.test(baseSha))
2123
+ return failure(
2124
+ "no_commit",
2125
+ "this checkout has no commit to create the session branch at",
2126
+ NEW_SESSION_REMEDY
2127
+ );
2128
+ }
2129
+ const published = await git(
2130
+ root,
2131
+ [
2132
+ "for-each-ref",
2133
+ "--count=1",
2134
+ "--format=%(refname)",
2135
+ "--contains",
2136
+ baseSha,
2137
+ "refs/remotes/origin/"
2138
+ ],
2139
+ signal
2140
+ );
2141
+ if (!published.ok || published.stdout.trim() === "")
2142
+ return failure(
2143
+ "unpublished_commits",
2144
+ `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`,
2145
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
2146
+ );
2147
+ attempt.baseSha = baseSha;
2148
+ const remote = await git(
2149
+ root,
2150
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
2151
+ signal
2152
+ );
2153
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
2154
+ if (remote.ok && recorded) {
2155
+ Object.assign(attempt, recorded);
2156
+ return { ...recorded, repository };
2157
+ }
2158
+ if (remote.ok)
2159
+ return failure(
2160
+ "branch_exists",
2161
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
2162
+ NEW_SESSION_REMEDY
2163
+ );
2164
+ if (remote.code !== 2)
2165
+ return failure(
2166
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
2167
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
2168
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
2169
+ );
2170
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
2171
+ Object.assign(attempt, recorded);
2172
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
2173
+ }
2174
+ let answer;
2175
+ try {
2176
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
2177
+ answer = await environmentRequest(
2178
+ "POST",
2179
+ SESSION_IDENTITY_ROUTES.challenge,
2180
+ {
2181
+ repositoryFullName: repository,
2182
+ claudeSessionId: context.sessionId,
2183
+ branch,
2184
+ baseSha,
2185
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
2186
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
2187
+ },
2188
+ deps,
2189
+ signal
2190
+ );
2191
+ } catch (error) {
2192
+ signal?.throwIfAborted();
2193
+ return environmentFailure(error, context.apiUrl);
2194
+ }
2195
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
2196
+ return failure(
2197
+ "repository_not_connected",
2198
+ `${repository} is not connected to Primitive`,
2199
+ CLOUD_GITHUB_CONNECT_REMEDY
2200
+ );
2201
+ if (answer.status === 401 || answer.status === 403)
2202
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
2203
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
2204
+ return failure(
2205
+ "challenge_open",
2206
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
2207
+ `wait five minutes, then ${RETRY_REMEDY}`
2208
+ );
2209
+ if (answer.status === 429)
2210
+ return failure(
2211
+ "too_many_challenges",
2212
+ "too many sessions of this cloud environment are being identified at once",
2213
+ `wait a few minutes, then ${RETRY_REMEDY}`
2214
+ );
2215
+ const challengeId = answer.value?.challengeId;
2216
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
2217
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
2218
+ return answer.status >= 500 ? environmentFailure(
2219
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
2220
+ context.apiUrl
2221
+ ) : SERVER_CONTRACT_FAILURE;
2222
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
2223
+ attempt.challengeId = challengeId;
2224
+ attempt.challengeExpiresAt = challengeExpiresAt;
2225
+ return pushSessionBranch(
2226
+ root,
2227
+ repository,
2228
+ branch,
2229
+ baseSha,
2230
+ { challengeId, challengeExpiresAt },
2231
+ signal
2232
+ );
2233
+ }
2234
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
2235
+ const push = await git(
2236
+ root,
2237
+ [
2238
+ "-c",
2239
+ "core.hooksPath=/dev/null",
2240
+ "-c",
2241
+ "push.followTags=false",
2242
+ "-c",
2243
+ "push.recurseSubmodules=no",
2244
+ "-c",
2245
+ "push.gpgSign=false",
2246
+ "-c",
2247
+ "push.pushOption=",
2248
+ "push",
2249
+ "--no-verify",
2250
+ "--no-follow-tags",
2251
+ "--no-recurse-submodules",
2252
+ "--no-signed",
2253
+ "--quiet",
2254
+ "origin",
2255
+ `${baseSha}:refs/heads/${branch}`
2256
+ ],
2257
+ signal
2258
+ );
2259
+ if (!push.ok)
2260
+ return push.timedOut ? failure(
2261
+ "push_timeout",
2262
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
2263
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
2264
+ ) : failure(
2265
+ "push_refused",
2266
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
2267
+ `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}`
2268
+ );
2269
+ return { ...challenge, repository };
2270
+ }
2271
+ async function ensureSessionIdentity(options = {}, deps = {}) {
2272
+ let context;
2273
+ try {
2274
+ context = sessionContext(deps);
2275
+ } catch (error) {
2276
+ return failure(
2277
+ "environment_credential_invalid",
2278
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
2279
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
2280
+ );
2281
+ }
2282
+ if ("status" in context) return context;
2283
+ const ctx = context;
2284
+ const startedAt = Date.now();
2285
+ prepareMachineMetadataDirectory(ctx.directory);
2286
+ return withFileLock(
2287
+ ctx.lockPath,
2288
+ async () => {
2289
+ const record = readToken(ctx);
2290
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
2291
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
2292
+ if (record) {
2293
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
2294
+ if (refreshed.status === "ok") {
2295
+ writeToken(ctx, refreshed.record);
2296
+ return identified(refreshed.record, true);
2297
+ }
2298
+ if (refreshed.status === "refused") {
2299
+ rmSync5(ctx.tokenPath, { force: true });
2300
+ writeState(ctx, {
2301
+ sessionId: ctx.sessionId,
2302
+ status: "failed",
2303
+ code: refreshed.failure.code,
2304
+ cause: refreshed.failure.cause,
2305
+ remedy: refreshed.failure.remedy,
2306
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
2307
+ at: Date.now()
2308
+ });
2309
+ return refreshed.failure;
2310
+ }
2311
+ if (!forced && tokenValid(record)) return identified(record, true);
2312
+ }
2313
+ const state = readState(ctx);
2314
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
2315
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
2316
+ if (!options.explicit) {
2317
+ if (!root || !(record || state))
2318
+ return failure(
2319
+ "not_identified",
2320
+ "this session has not identified who started it yet",
2321
+ RETRY_REMEDY
2322
+ );
2323
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
2324
+ } else if (state && state.at >= startedAt) {
2325
+ return outcomeFromState(state);
2326
+ }
2327
+ if (!root)
2328
+ return failure(
2329
+ "repository_missing",
2330
+ "this is not a git repository",
2331
+ "run it in the repository the session cloned"
2332
+ );
2333
+ const attempt = { root };
2334
+ const remember = (outcome) => {
2335
+ writeState(ctx, {
2336
+ sessionId: ctx.sessionId,
2337
+ status: outcome.status,
2338
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
2339
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
2340
+ githubLogin: outcome.githubLogin
2341
+ },
2342
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
2343
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
2344
+ repositoryRoot: root,
2345
+ branch: attempt.branch ?? state?.branch,
2346
+ baseSha: attempt.baseSha ?? state?.baseSha,
2347
+ at: Date.now()
2348
+ });
2349
+ return outcome;
2350
+ };
2351
+ let challenge;
2352
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
2353
+ attempt.challengeId = state.challengeId;
2354
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2355
+ attempt.branch = state.branch;
2356
+ attempt.baseSha = state.baseSha;
2357
+ challenge = {
2358
+ challengeId: state.challengeId,
2359
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2360
+ repository: githubRepositoryFullName(root) ?? "the repository"
2361
+ };
2362
+ } else if (state?.status === "link_required" && state.challengeId) {
2363
+ attempt.challengeId = state.challengeId;
2364
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
2365
+ const exchanged2 = await exchangeChallenge(
2366
+ ctx,
2367
+ {
2368
+ challengeId: state.challengeId,
2369
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
2370
+ githubLogin: state.githubLogin
2371
+ },
2372
+ root,
2373
+ deps,
2374
+ options.signal
2375
+ );
2376
+ if ("status" in exchanged2) return remember(exchanged2);
2377
+ writeToken(ctx, exchanged2);
2378
+ return identified(exchanged2, false);
2379
+ } else if (!options.explicit) {
2380
+ return state ? outcomeFromState(state) : failure(
2381
+ "not_identified",
2382
+ "this session has not identified who started it yet",
2383
+ RETRY_REMEDY
2384
+ );
2385
+ } else {
2386
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
2387
+ if ("status" in pushed) return remember(pushed);
2388
+ challenge = pushed;
2389
+ }
2390
+ const verified = await pollChallenge(
2391
+ ctx.apiUrl,
2392
+ challenge.challengeId,
2393
+ challenge.repository,
2394
+ // A hook process waits only briefly for a late notice.
2395
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
2396
+ options.signal
2397
+ );
2398
+ if ("status" in verified) return remember(verified);
2399
+ const exchanged = await exchangeChallenge(
2400
+ ctx,
2401
+ { ...challenge, githubLogin: verified.githubLogin },
2402
+ root,
2403
+ deps,
2404
+ options.signal
2405
+ );
2406
+ if ("status" in exchanged) return remember(exchanged);
2407
+ writeToken(ctx, exchanged);
2408
+ return identified(exchanged, false);
2409
+ },
2410
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
2411
+ );
2412
+ }
2413
+ async function acquireSessionCredential(options = {}, deps = {}) {
2414
+ const cached2 = cachedSessionCredential(deps);
2415
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
2416
+ if (cached2 && fresh && !options.force) return cached2;
2417
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
2418
+ let outcome;
2419
+ try {
2420
+ outcome = await ensureSessionIdentity(
2421
+ { force: options.force, observedToken: cached2?.accessToken, signal },
2422
+ deps
2423
+ );
2424
+ } catch (error) {
2425
+ options.signal?.throwIfAborted();
2426
+ if (error instanceof MachineAuthError) throw error;
2427
+ throw new MachineAuthError(
2428
+ "identity_unavailable",
2429
+ "Identifying who started this cloud session is still in progress; retry shortly."
2430
+ );
2431
+ }
2432
+ if (outcome.status === "ok") return outcome.credential;
2433
+ throw new MachineAuthError(
2434
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
2435
+ sessionIdentityMessage(outcome)
2436
+ );
2437
+ }
2438
+
1205
2439
  // src/lib/machine-credentials.ts
2440
+ function sessionScoped(deps) {
2441
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
2442
+ }
1206
2443
  var require2 = createRequire(import.meta.url);
1207
2444
  var SERVICE = "ai.primitive.prim.machine";
1208
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
2445
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1209
2446
  var PROFILE_FILE = "machine_profile.json";
1210
- var RENEW_BEFORE_MS = 6e4;
2447
+ var RENEW_BEFORE_MS2 = 6e4;
1211
2448
  var cached;
1212
2449
  function configurationDirectory(deps) {
1213
2450
  return deps.directory ?? primConfigDirectory({ env: deps.env });
1214
2451
  }
1215
2452
  function apiUrlFor(deps) {
1216
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
2453
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
1217
2454
  }
1218
- function hash(value) {
1219
- return createHash3("sha256").update(value).digest("hex");
2455
+ function hash2(value) {
2456
+ return createHash5("sha256").update(value).digest("hex");
1220
2457
  }
1221
2458
  function recordPath(directory, generation) {
1222
- return join6(directory, `machine_${generation}.json`);
2459
+ return join8(directory, `machine_${generation}.json`);
1223
2460
  }
1224
2461
  function storageKey(directory, generation) {
1225
- return `${hash(directory)}:${generation}`;
2462
+ return `${hash2(directory)}:${generation}`;
1226
2463
  }
1227
2464
  function environmentContextPath(deps, clientId) {
1228
- return join6(
2465
+ return join8(
1229
2466
  configurationDirectory(deps),
1230
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
2467
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1231
2468
  );
1232
2469
  }
1233
2470
  function writeEnvironmentContext(credential, deps) {
@@ -1286,14 +2523,14 @@ function readEnvironmentContext(environment, deps) {
1286
2523
  }
1287
2524
  }
1288
2525
  function keyringEntry(key) {
1289
- let directory = dirname4(fileURLToPath3(import.meta.url));
2526
+ let directory = dirname5(fileURLToPath3(import.meta.url));
1290
2527
  for (let depth = 0; depth < 5; depth++) {
1291
- const loader = join6(directory, "native", "keyring.cjs");
2528
+ const loader = join8(directory, "native", "keyring.cjs");
1292
2529
  if (existsSync3(loader)) {
1293
2530
  const module2 = require2(loader);
1294
2531
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
1295
2532
  }
1296
- directory = dirname4(directory);
2533
+ directory = dirname5(directory);
1297
2534
  }
1298
2535
  const module = require2("@napi-rs/keyring");
1299
2536
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -1305,7 +2542,7 @@ function protectPath(path, directory) {
1305
2542
  }
1306
2543
  const encodedPath = Buffer.from(path).toString("base64");
1307
2544
  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)`;
1308
- execFileSync(
2545
+ execFileSync2(
1309
2546
  "powershell.exe",
1310
2547
  [
1311
2548
  "-NoProfile",
@@ -1318,7 +2555,7 @@ function protectPath(path, directory) {
1318
2555
  }
1319
2556
  function ensureDirectory(directory) {
1320
2557
  mkdirSync3(directory, { recursive: true, mode: 448 });
1321
- if (lstatSync3(directory).isSymbolicLink())
2558
+ if (lstatSync4(directory).isSymbolicLink())
1322
2559
  throw new MachineAuthError(
1323
2560
  "unsafe_storage",
1324
2561
  "Credential directory must not be a symbolic link."
@@ -1330,17 +2567,20 @@ function writePrivate(path, value) {
1330
2567
  `, { mode: 384 });
1331
2568
  protectPath(path, false);
1332
2569
  }
2570
+ function readMachineMetadata(path) {
2571
+ return readPrivate(path);
2572
+ }
1333
2573
  function readPrivate(path) {
1334
2574
  let raw;
1335
2575
  try {
1336
- const stat = lstatSync3(path);
2576
+ const stat = lstatSync4(path);
1337
2577
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
1338
2578
  throw new MachineAuthError(
1339
2579
  "unsafe_storage",
1340
2580
  "Machine credential files must be owner-only regular files."
1341
2581
  );
1342
2582
  }
1343
- raw = readFileSync5(path, "utf8");
2583
+ raw = readFileSync6(path, "utf8");
1344
2584
  } catch (error) {
1345
2585
  if (error.code === "ENOENT") return void 0;
1346
2586
  throw error;
@@ -1385,7 +2625,7 @@ function parseProfile(value) {
1385
2625
  };
1386
2626
  }
1387
2627
  function readMachineProfile(deps = {}) {
1388
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
2628
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
1389
2629
  return value === void 0 ? void 0 : parseProfile(value);
1390
2630
  }
1391
2631
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -1394,20 +2634,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
1394
2634
  var brokerKeys = /* @__PURE__ */ new Map();
1395
2635
  function networkSecretBrokerKey(deps, clientId) {
1396
2636
  const directory = configurationDirectory(deps);
1397
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2637
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
1398
2638
  const known = brokerKeys.get(path);
1399
2639
  if (known) return known;
1400
2640
  ensureDirectory(directory);
1401
2641
  const read = () => {
1402
2642
  try {
1403
- const stat = lstatSync3(path);
2643
+ const stat = lstatSync4(path);
1404
2644
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
1405
2645
  throw new MachineAuthError(
1406
2646
  "unsafe_storage",
1407
2647
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
1408
2648
  true
1409
2649
  );
1410
- const value = readFileSync5(path, "utf8").trim();
2650
+ const value = readFileSync6(path, "utf8").trim();
1411
2651
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
1412
2652
  } catch (error) {
1413
2653
  if (error.code === "ENOENT") return void 0;
@@ -1435,7 +2675,7 @@ function networkSecretBrokerKey(deps, clientId) {
1435
2675
  } catch (error) {
1436
2676
  if (error.code !== "EEXIST") throw error;
1437
2677
  } finally {
1438
- rmSync5(staged, { force: true });
2678
+ rmSync6(staged, { force: true });
1439
2679
  }
1440
2680
  }
1441
2681
  const key = read()?.key;
@@ -1468,7 +2708,7 @@ function environmentCredentials(deps) {
1468
2708
  "conflicting_credentials",
1469
2709
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
1470
2710
  );
1471
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2711
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
1472
2712
  const credentials = {
1473
2713
  clientId,
1474
2714
  generation,
@@ -1489,12 +2729,12 @@ function environmentCredentials(deps) {
1489
2729
  return {
1490
2730
  clientId,
1491
2731
  clientSecret,
1492
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2732
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
1493
2733
  };
1494
2734
  }
1495
2735
  function hasMachineConfiguration(deps = {}) {
1496
2736
  const env = deps.env ?? process.env;
1497
- 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));
2737
+ 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));
1498
2738
  if (configured && env.PRIM_TOKEN?.trim()) {
1499
2739
  throw new MachineAuthError(
1500
2740
  "conflicting_credentials",
@@ -1506,6 +2746,7 @@ function hasMachineConfiguration(deps = {}) {
1506
2746
  }
1507
2747
  function machineContext(deps = {}) {
1508
2748
  if (!hasMachineConfiguration(deps)) return void 0;
2749
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1509
2750
  const environment = environmentCredentials(deps);
1510
2751
  if (environment) {
1511
2752
  if (environmentTerminal === environment.generation) return void 0;
@@ -1520,6 +2761,7 @@ function machineContext(deps = {}) {
1520
2761
  return profile;
1521
2762
  }
1522
2763
  function cachedMachineCredential(deps = {}) {
2764
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
1523
2765
  const context = machineContext(deps);
1524
2766
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
1525
2767
  }
@@ -1528,7 +2770,7 @@ function machineSessionEnded(deps = {}) {
1528
2770
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
1529
2771
  if (!generation) return false;
1530
2772
  if (environmentCredentials(deps)) return environmentTerminal === generation;
1531
- return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
2773
+ return readPrivate(join8(configurationDirectory(deps), "machine_terminal.json")) === generation;
1532
2774
  }
1533
2775
  var environmentTerminal;
1534
2776
  var NETWORK_REJECTION_PAUSE_MS = 3e4;
@@ -1592,6 +2834,7 @@ async function persistRecord(record, deps, signal) {
1592
2834
  }
1593
2835
  async function acquireMachineCredential(options = {}, deps = {}) {
1594
2836
  if (!hasMachineConfiguration(deps)) return void 0;
2837
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1595
2838
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1596
2839
  const apiUrl = apiUrlFor(deps);
1597
2840
  const environment = environmentCredentials(deps);
@@ -1620,7 +2863,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1620
2863
  }
1621
2864
  }
1622
2865
  return withFileLock(
1623
- join6(directory2, "credentials.lock"),
2866
+ join8(directory2, "credentials.lock"),
1624
2867
  async () => {
1625
2868
  if (machineSessionEnded(deps))
1626
2869
  throw new MachineAuthError(
@@ -1628,7 +2871,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1628
2871
  rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1629
2872
  true
1630
2873
  );
1631
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2874
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1632
2875
  return cached;
1633
2876
  if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
1634
2877
  throw networkRejection.error;
@@ -1702,7 +2945,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1702
2945
  const contextPath = environmentContextPath(deps, environment.clientId);
1703
2946
  try {
1704
2947
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1705
- rmSync5(contextPath, { force: true });
2948
+ rmSync6(contextPath, { force: true });
1706
2949
  } catch {
1707
2950
  }
1708
2951
  throw error;
@@ -1712,7 +2955,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1712
2955
  const contextPath = environmentContextPath(deps, environment.clientId);
1713
2956
  try {
1714
2957
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1715
- rmSync5(contextPath, { force: true });
2958
+ rmSync6(contextPath, { force: true });
1716
2959
  } catch {
1717
2960
  }
1718
2961
  }
@@ -1726,7 +2969,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1726
2969
  const expected = machineContext(deps);
1727
2970
  const directory = configurationDirectory(deps);
1728
2971
  return withFileLock(
1729
- join6(directory, "credentials.lock"),
2972
+ join8(directory, "credentials.lock"),
1730
2973
  async () => {
1731
2974
  const profile = readMachineProfile(deps);
1732
2975
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1741,7 +2984,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1741
2984
  true
1742
2985
  );
1743
2986
  let record = await loadRecord(profile, deps, signal);
1744
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2987
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1745
2988
  try {
1746
2989
  const { tokens, identity } = await withMachineCooldown(
1747
2990
  directory,
@@ -1776,7 +3019,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1776
3019
  await persistRecord(record, deps, signal);
1777
3020
  } catch (error) {
1778
3021
  if (error instanceof MachineAuthError && error.terminal)
1779
- writePrivate(join6(directory, "machine_terminal.json"), profile.generation);
3022
+ writePrivate(join8(directory, "machine_terminal.json"), profile.generation);
1780
3023
  throw error;
1781
3024
  }
1782
3025
  }
@@ -1822,31 +3065,37 @@ function machineCaptureActor(deps = {}) {
1822
3065
  return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
1823
3066
  }
1824
3067
  function machineJournalBucket(identity) {
1825
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
3068
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
1826
3069
  }
1827
3070
  function identityPending(actor) {
1828
3071
  return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
1829
3072
  }
1830
3073
  function machinePendingBucket(identity) {
1831
- return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
3074
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
3075
+ }
3076
+ function prepareMachineMetadataDirectory(directory) {
3077
+ ensureDirectory(directory);
3078
+ }
3079
+ function writeMachineMetadata(path, value) {
3080
+ writePrivate(path, value);
1832
3081
  }
1833
3082
 
1834
3083
  // src/lib/credentials.ts
1835
3084
  var CONFIG_DIRECTORY = primConfigDirectory();
1836
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1837
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1838
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1839
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1840
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1841
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1842
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1843
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3085
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
3086
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
3087
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
3088
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
3089
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
3090
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
3091
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
3092
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1844
3093
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1845
3094
  var CREDENTIAL_MIGRATION_VERSION = 1;
1846
3095
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1847
3096
  function readTrimmed(path) {
1848
3097
  try {
1849
- const value = readFileSync6(path, "utf8").trim();
3098
+ const value = readFileSync7(path, "utf8").trim();
1850
3099
  return value || void 0;
1851
3100
  } catch {
1852
3101
  return void 0;
@@ -1868,22 +3117,22 @@ function resolveAuthCredential(options = {}) {
1868
3117
  );
1869
3118
  if (metadata.state === "legacy_broker") {
1870
3119
  if (metadata.metadata) {
1871
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1872
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3120
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3121
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1873
3122
  return void 0;
1874
3123
  }
1875
3124
  }
1876
3125
  return { token: stored, source: "token_file" };
1877
3126
  }
1878
3127
  if (metadata.state === "invalid") return void 0;
1879
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1880
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3128
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3129
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1881
3130
  return void 0;
1882
3131
  }
1883
3132
  return { token: stored, source: "token_file" };
1884
3133
  }
1885
3134
  function credentialFingerprint(value) {
1886
- return createHash4("sha256").update(value).digest("hex");
3135
+ return createHash6("sha256").update(value).digest("hex");
1887
3136
  }
1888
3137
  function parseLegacyBrokerCredentialMetadata(value) {
1889
3138
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1903,7 +3152,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1903
3152
  function readBoundedCredentialJson(path) {
1904
3153
  let raw;
1905
3154
  try {
1906
- raw = readFileSync6(path, "utf8");
3155
+ raw = readFileSync7(path, "utf8");
1907
3156
  } catch (error) {
1908
3157
  return error.code === "ENOENT" ? void 0 : null;
1909
3158
  }
@@ -1980,14 +3229,14 @@ function jwtOrganizationId(token) {
1980
3229
 
1981
3230
  // src/binding.ts
1982
3231
  var PRIM_CONFIG_DIR = primConfigDirectory();
1983
- var SESSIONS_DIR = join8(PRIM_CONFIG_DIR, "sessions");
3232
+ var SESSIONS_DIR = join10(PRIM_CONFIG_DIR, "sessions");
1984
3233
  var WORKSPACE_FILE = ".prim/workspace.json";
1985
3234
  function readJsonSafe(path) {
1986
3235
  if (!existsSync4(path)) {
1987
3236
  return;
1988
3237
  }
1989
3238
  try {
1990
- return JSON.parse(readFileSync7(path, "utf-8"));
3239
+ return JSON.parse(readFileSync8(path, "utf-8"));
1991
3240
  } catch {
1992
3241
  return;
1993
3242
  }
@@ -1996,17 +3245,17 @@ function fromSessionMarker(sessionId) {
1996
3245
  if (!sessionId) {
1997
3246
  return;
1998
3247
  }
1999
- const marker = readJsonSafe(join8(SESSIONS_DIR, `${sessionId}.json`));
3248
+ const marker = readJsonSafe(join10(SESSIONS_DIR, `${sessionId}.json`));
2000
3249
  return marker?.orgId;
2001
3250
  }
2002
3251
  function fromWorkspaceFile(startDir) {
2003
3252
  let dir = startDir;
2004
3253
  while (true) {
2005
- const config = readJsonSafe(join8(dir, WORKSPACE_FILE));
3254
+ const config = readJsonSafe(join10(dir, WORKSPACE_FILE));
2006
3255
  if (config?.orgId) {
2007
3256
  return config.orgId;
2008
3257
  }
2009
- const parent = dirname5(dir);
3258
+ const parent = dirname6(dir);
2010
3259
  if (parent === dir) {
2011
3260
  return;
2012
3261
  }
@@ -2116,14 +3365,14 @@ function publicDecisionResponse(value) {
2116
3365
  }
2117
3366
 
2118
3367
  // src/client.ts
2119
- import { createHash as createHash5 } from "crypto";
2120
- import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync6 } from "fs";
2121
- import { dirname as dirname6 } from "path";
3368
+ import { createHash as createHash7 } from "crypto";
3369
+ import { chmodSync as chmodSync3, existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync10, rmSync as rmSync7 } from "fs";
3370
+ import { dirname as dirname7 } from "path";
2122
3371
 
2123
3372
  // src/daemon/client-instance-id.ts
2124
3373
  import { randomBytes as randomBytes4 } from "crypto";
2125
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync8 } from "fs";
2126
- import { join as join9 } from "path";
3374
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync9 } from "fs";
3375
+ import { join as join11 } from "path";
2127
3376
  var CONFIG_DIRECTORY_MODE = 448;
2128
3377
  var INSTANCE_FILE_MODE = 384;
2129
3378
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -2136,7 +3385,7 @@ function isClientInstanceId(value) {
2136
3385
  }
2137
3386
  function ensurePrivateConfigDirectory(configDir) {
2138
3387
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
2139
- const metadata = lstatSync4(configDir);
3388
+ const metadata = lstatSync5(configDir);
2140
3389
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
2141
3390
  throw new Error("prim config path must be a private directory");
2142
3391
  }
@@ -2146,7 +3395,7 @@ function ensurePrivateConfigDirectory(configDir) {
2146
3395
  function readExisting(path) {
2147
3396
  let metadata;
2148
3397
  try {
2149
- metadata = lstatSync4(path);
3398
+ metadata = lstatSync5(path);
2150
3399
  } catch (error) {
2151
3400
  if (error.code === "ENOENT") {
2152
3401
  return;
@@ -2160,7 +3409,7 @@ function readExisting(path) {
2160
3409
  if (metadata.size > MAX_STORED_BYTES) {
2161
3410
  throw new Error("stored client instance identity is invalid");
2162
3411
  }
2163
- const raw = readFileSync8(path, "utf8");
3412
+ const raw = readFileSync9(path, "utf8");
2164
3413
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
2165
3414
  if (raw !== value && raw !== `${value}
2166
3415
  ` || !isClientInstanceId(value)) {
@@ -2174,8 +3423,8 @@ function atomicWrite(path, value) {
2174
3423
  }
2175
3424
  async function getOrCreateClientInstanceId(options) {
2176
3425
  const configDir = options.configDir;
2177
- const path = join9(configDir, "client_instance_id");
2178
- const lockPath = join9(configDir, "client-instance.lock");
3426
+ const path = join11(configDir, "client_instance_id");
3427
+ const lockPath = join11(configDir, "client-instance.lock");
2179
3428
  ensurePrivateConfigDirectory(configDir);
2180
3429
  return withFileLock(
2181
3430
  lockPath,
@@ -2219,63 +3468,18 @@ async function ingestUploaderHeaders() {
2219
3468
  return headers;
2220
3469
  }
2221
3470
 
2222
- // src/lib/terminal-safe.ts
2223
- function replaceIsolatedSurrogates(value) {
2224
- let out = "";
2225
- for (let index = 0; index < value.length; index += 1) {
2226
- const unit = value.charCodeAt(index);
2227
- if (unit >= 55296 && unit <= 56319) {
2228
- const next = value.charCodeAt(index + 1);
2229
- if (next >= 56320 && next <= 57343) {
2230
- out += value[index] + value[index + 1];
2231
- index += 1;
2232
- } else {
2233
- out += "\uFFFD";
2234
- }
2235
- } else if (unit >= 56320 && unit <= 57343) {
2236
- out += "\uFFFD";
2237
- } else {
2238
- out += value[index];
2239
- }
2240
- }
2241
- return out;
2242
- }
2243
- function isUnsafeTerminalCodePoint(point) {
2244
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
2245
- const bidiOrZeroWidth = point === 173 || // soft hyphen
2246
- point === 1564 || // Arabic letter mark
2247
- point === 6158 || // Mongolian vowel separator
2248
- point >= 8203 && point <= 8207 || // zero-width + directional marks
2249
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
2250
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
2251
- point >= 65529 && point <= 65531 || // interlinear annotation controls
2252
- point === 65279 || // zero-width no-break space / BOM
2253
- point >= 917504 && point <= 917631;
2254
- return c0OrC1 || bidiOrZeroWidth;
2255
- }
2256
- function terminalSafeText(value) {
2257
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
2258
- }
2259
- function terminalSafeLine(value) {
2260
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
2261
- }
2262
- function isTerminalSafeText(value) {
2263
- return terminalSafeText(value) === value;
2264
- }
2265
- var stripControlChars = terminalSafeText;
2266
-
2267
3471
  // src/client.ts
2268
3472
  var CONFIG_DIR_MODE = 448;
2269
3473
  var CREDENTIAL_FILE_MODE = 384;
2270
3474
  var REFRESH_THRESHOLD_MS = 6e4;
2271
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3475
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
2272
3476
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
2273
3477
  function authExpiredMessage() {
2274
3478
  return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
2275
3479
  }
2276
3480
  function readTrimmed2(path) {
2277
3481
  try {
2278
- const value = readFileSync9(path, "utf8").trim();
3482
+ const value = readFileSync10(path, "utf8").trim();
2279
3483
  return value || void 0;
2280
3484
  } catch {
2281
3485
  return void 0;
@@ -2285,13 +3489,13 @@ function getSiteUrl() {
2285
3489
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
2286
3490
  }
2287
3491
  function getSiteUrlForEnvironment(primApiUrl) {
2288
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3492
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
2289
3493
  }
2290
3494
  function expiresAtFor(token, expiresIn) {
2291
3495
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
2292
3496
  }
2293
3497
  function ensureConfigDirectory() {
2294
- const directory = dirname6(TOKEN_FILE_PATH);
3498
+ const directory = dirname7(TOKEN_FILE_PATH);
2295
3499
  mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
2296
3500
  chmodSync3(directory, CONFIG_DIR_MODE);
2297
3501
  }
@@ -2301,7 +3505,7 @@ function atomicWrite2(path, content2) {
2301
3505
  }
2302
3506
  function removeCredentialFile(path) {
2303
3507
  if (!existsSync5(path)) return false;
2304
- rmSync6(path, { force: true });
3508
+ rmSync7(path, { force: true });
2305
3509
  return true;
2306
3510
  }
2307
3511
  function getTokenExpiresAt() {
@@ -2316,23 +3520,23 @@ function isTokenExpiringSoon(credential) {
2316
3520
  const expiresAt = getTokenExpiresAt();
2317
3521
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
2318
3522
  }
2319
- function refreshFingerprint(refreshToken2) {
2320
- return createHash5("sha256").update(refreshToken2).digest("hex");
3523
+ function refreshFingerprint(refreshToken3) {
3524
+ return createHash7("sha256").update(refreshToken3).digest("hex");
2321
3525
  }
2322
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3526
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
2323
3527
  return {
2324
3528
  version: 1,
2325
3529
  family: "legacy_broker",
2326
3530
  accessTokenHash: refreshFingerprint(accessToken),
2327
- refreshTokenHash: refreshFingerprint(refreshToken2)
3531
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2328
3532
  };
2329
3533
  }
2330
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3534
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
2331
3535
  const hashes = {
2332
3536
  accessTokenHash: refreshFingerprint(accessToken),
2333
- refreshTokenHash: refreshFingerprint(refreshToken2)
3537
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2334
3538
  };
2335
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3539
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
2336
3540
  }
2337
3541
  function writeCredentialMigrationSentinel() {
2338
3542
  atomicWrite2(
@@ -2344,11 +3548,11 @@ function writeCredentialMigrationSentinel() {
2344
3548
  `
2345
3549
  );
2346
3550
  }
2347
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
2348
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3551
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3552
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
2349
3553
  return { state: "invalid" };
2350
3554
  }
2351
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3555
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2352
3556
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
2353
3557
  return { state: "invalid" };
2354
3558
  }
@@ -2365,17 +3569,17 @@ function preserveMarkerlessLegacyGeneration() {
2365
3569
  const metadata = readStoredCredentialMetadata();
2366
3570
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
2367
3571
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
2368
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
2369
- if (!(accessToken && refreshToken2)) return;
2370
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3572
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3573
+ if (!(accessToken && refreshToken3)) return;
3574
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2371
3575
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2372
3576
  `);
2373
3577
  }
2374
3578
  function terminalFingerprint() {
2375
3579
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2376
3580
  }
2377
- function writeTerminalFingerprint(refreshToken2) {
2378
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3581
+ function writeTerminalFingerprint(refreshToken3) {
3582
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2379
3583
  `);
2380
3584
  }
2381
3585
  function clearTerminalFingerprint() {
@@ -2384,20 +3588,20 @@ function clearTerminalFingerprint() {
2384
3588
  function isSessionEnded() {
2385
3589
  if (hasMachineConfiguration()) return machineSessionEnded();
2386
3590
  if (resolveAuthCredential()?.source !== "token_file") return false;
2387
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3591
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2388
3592
  const ended = terminalFingerprint();
2389
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3593
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2390
3594
  }
2391
3595
  function withCredentialLock(operation, options = {}) {
2392
3596
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2393
3597
  }
2394
3598
  function commitCredentialsUnlocked(credentials) {
2395
3599
  const accessToken = credentials.accessToken.trim();
2396
- const refreshToken2 = credentials.refreshToken.trim();
2397
- if (!accessToken || !refreshToken2) {
3600
+ const refreshToken3 = credentials.refreshToken.trim();
3601
+ if (!accessToken || !refreshToken3) {
2398
3602
  throw new Error("OAuth credentials require both access and refresh tokens");
2399
3603
  }
2400
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3604
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2401
3605
  if (credentials.metadata !== void 0) {
2402
3606
  preserveMarkerlessLegacyGeneration();
2403
3607
  writeCredentialMigrationSentinel();
@@ -2405,10 +3609,10 @@ function commitCredentialsUnlocked(credentials) {
2405
3609
  `);
2406
3610
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2407
3611
  `);
2408
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3612
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2409
3613
  `);
2410
3614
  } else {
2411
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3615
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2412
3616
  `);
2413
3617
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2414
3618
  `);
@@ -2445,15 +3649,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2445
3649
  `
2446
3650
  );
2447
3651
  }
2448
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3652
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2449
3653
  const current = readStoredCredentialMetadata();
2450
3654
  if (expected.state === "legacy_broker") {
2451
3655
  if (current.state !== "legacy_broker") return false;
2452
3656
  if (!expected.metadata) return current.metadata === void 0;
2453
- 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;
3657
+ 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;
2454
3658
  }
2455
3659
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2456
- 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;
3660
+ 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;
2457
3661
  }
2458
3662
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2459
3663
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2622,7 +3826,7 @@ async function performTokenRefresh(options = {}) {
2622
3826
  );
2623
3827
  }
2624
3828
  var _refreshInFlight;
2625
- function refreshToken(options = {}) {
3829
+ function refreshToken2(options = {}) {
2626
3830
  if (hasMachineConfiguration())
2627
3831
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2628
3832
  if (_refreshInFlight) return _refreshInFlight;
@@ -2760,7 +3964,7 @@ async function machineClient(options = {}, management = false) {
2760
3964
  if (response.status === 401)
2761
3965
  throw new HttpError(
2762
3966
  401,
2763
- 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(
3967
+ 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(
2764
3968
  "Machine access was rejected. Ask your administrator to check or rotate its credentials."
2765
3969
  )
2766
3970
  );
@@ -2781,7 +3985,7 @@ async function request2(method, path, body, options) {
2781
3985
  let refreshAttempted = false;
2782
3986
  if (credential && isTokenExpiringSoon(credential)) {
2783
3987
  refreshAttempted = true;
2784
- const token = await refreshToken({
3988
+ const token = await refreshToken2({
2785
3989
  signal: options?.signal,
2786
3990
  quiet: options?.quietRefresh
2787
3991
  });
@@ -2800,7 +4004,7 @@ async function request2(method, path, body, options) {
2800
4004
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2801
4005
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2802
4006
  refreshAttempted = true;
2803
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4007
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2804
4008
  }
2805
4009
  if (retryToken) {
2806
4010
  _cachedCredential = {
@@ -3005,29 +4209,29 @@ import { existsSync as existsSync10 } from "fs";
3005
4209
 
3006
4210
  // src/demo/diagnostics.ts
3007
4211
  import { existsSync as existsSync9 } from "fs";
3008
- import { join as join14 } from "path";
4212
+ import { join as join16 } from "path";
3009
4213
 
3010
4214
  // src/lib/hook-runtime.ts
3011
- import { createHash as createHash6, randomBytes as randomBytes5 } from "crypto";
4215
+ import { createHash as createHash8, randomBytes as randomBytes5 } from "crypto";
3012
4216
  import {
3013
4217
  constants as constants2,
3014
4218
  accessSync,
3015
4219
  chmodSync as chmodSync4,
3016
4220
  copyFileSync,
3017
4221
  existsSync as existsSync7,
3018
- lstatSync as lstatSync5,
4222
+ lstatSync as lstatSync6,
3019
4223
  mkdirSync as mkdirSync5,
3020
4224
  mkdtempSync,
3021
- readFileSync as readFileSync10,
4225
+ readFileSync as readFileSync11,
3022
4226
  readdirSync as readdirSync2,
3023
- realpathSync,
4227
+ realpathSync as realpathSync2,
3024
4228
  renameSync as renameSync2,
3025
- rmSync as rmSync7,
4229
+ rmSync as rmSync8,
3026
4230
  statSync as statSync2,
3027
4231
  utimesSync,
3028
4232
  writeFileSync as writeFileSync4
3029
4233
  } from "fs";
3030
- import { delimiter, dirname as dirname8, isAbsolute as isAbsolute3, join as join12, resolve as resolve2 } from "path";
4234
+ import { delimiter, dirname as dirname9, isAbsolute as isAbsolute4, join as join14, resolve as resolve3 } from "path";
3031
4235
 
3032
4236
  // src/lib/git-hook-contract.ts
3033
4237
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -3077,7 +4281,7 @@ exit 0
3077
4281
  // src/lib/native-keyring.ts
3078
4282
  import { existsSync as existsSync6 } from "fs";
3079
4283
  import { createRequire as createRequire2 } from "module";
3080
- import { dirname as dirname7, join as join11 } from "path";
4284
+ import { dirname as dirname8, join as join13 } from "path";
3081
4285
  import { fileURLToPath as fileURLToPath4 } from "url";
3082
4286
  var require3 = createRequire2(import.meta.url);
3083
4287
 
@@ -3128,9 +4332,9 @@ exec "$prim_node" "$prim_entry" "$@"
3128
4332
  `;
3129
4333
 
3130
4334
  // src/demo/state.ts
3131
- import { createHash as createHash7, randomUUID as randomUUID3 } from "crypto";
3132
- import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11, readdirSync as readdirSync3 } from "fs";
3133
- import { join as join13, resolve as resolve3 } from "path";
4335
+ import { createHash as createHash9, randomUUID as randomUUID3 } from "crypto";
4336
+ import { existsSync as existsSync8, lstatSync as lstatSync7, readFileSync as readFileSync12, readdirSync as readdirSync3 } from "fs";
4337
+ import { join as join15, resolve as resolve4 } from "path";
3134
4338
 
3135
4339
  // src/generated/cli-http-v1.validators.js
3136
4340
  var import_ucs2length = __toESM(require_ucs2length(), 1);
@@ -29816,15 +31020,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29816
31020
 
29817
31021
  // src/demo/state.ts
29818
31022
  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;
29819
- var demoDirectory = () => join13(primConfigDirectory(), "demo");
31023
+ var demoDirectory = () => join15(primConfigDirectory(), "demo");
29820
31024
  var runPath = (id2) => {
29821
31025
  if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
29822
- return join13(demoDirectory(), "runs", `${id2}.json`);
31026
+ return join15(demoDirectory(), "runs", `${id2}.json`);
29823
31027
  };
29824
31028
  function readDemoJson(path) {
29825
- const stat = lstatSync6(path);
31029
+ const stat = lstatSync7(path);
29826
31030
  if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
29827
- return JSON.parse(readFileSync11(path, "utf8"));
31031
+ return JSON.parse(readFileSync12(path, "utf8"));
29828
31032
  }
29829
31033
  function saveDemoJson(path, value) {
29830
31034
  atomicWriteFile(path, `${JSON.stringify(value)}
@@ -29861,11 +31065,11 @@ function demoCommand(run, action, choice, reason) {
29861
31065
  ].map(quote).join(" ");
29862
31066
  }
29863
31067
  function sessionKey(agent, session) {
29864
- return createHash7("sha256").update(`${agent}\0${session}`).digest("hex");
31068
+ return createHash9("sha256").update(`${agent}\0${session}`).digest("hex");
29865
31069
  }
29866
31070
  function exclusionPath(key) {
29867
31071
  if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
29868
- return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
31072
+ return join15(demoDirectory(), "excluded-sessions", `${key}.json`);
29869
31073
  }
29870
31074
  function sessionExcluded(agent, session) {
29871
31075
  if (typeof session !== "string" || !session) return false;
@@ -29904,7 +31108,7 @@ function demoArgv(command) {
29904
31108
  }
29905
31109
 
29906
31110
  // src/demo/diagnostics.ts
29907
- var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
31111
+ var observationPath = (id2) => join16(demoDirectory(), "observations", `${id2}.json`);
29908
31112
  function observeRun(id2, observation) {
29909
31113
  try {
29910
31114
  saveDemoJson(observationPath(id2), observation);
@@ -29998,25 +31202,25 @@ import {
29998
31202
  mkdirSync as mkdirSync6,
29999
31203
  openSync as openSync2,
30000
31204
  opendirSync,
30001
- readFileSync as readFileSync13,
31205
+ readFileSync as readFileSync14,
30002
31206
  readSync,
30003
31207
  readdirSync as readdirSync5
30004
31208
  } from "fs";
30005
- import { dirname as dirname10, join as join16 } from "path";
31209
+ import { dirname as dirname11, join as join18 } from "path";
30006
31210
 
30007
31211
  // src/drain-progress.ts
30008
31212
  import {
30009
31213
  chmodSync as chmodSync5,
30010
31214
  existsSync as existsSync11,
30011
- readFileSync as readFileSync12,
31215
+ readFileSync as readFileSync13,
30012
31216
  readdirSync as readdirSync4,
30013
- rmSync as rmSync8,
31217
+ rmSync as rmSync9,
30014
31218
  rmdirSync
30015
31219
  } from "fs";
30016
- import { basename as basename2, dirname as dirname9, join as join15 } from "path";
31220
+ import { basename as basename3, dirname as dirname10, join as join17 } from "path";
30017
31221
 
30018
31222
  // src/journal.ts
30019
- var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
31223
+ var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
30020
31224
  var UNBOUND_BUCKET = "_unbound";
30021
31225
  var JOURNAL_BASENAME = "journal.ndjson";
30022
31226
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
@@ -30028,14 +31232,14 @@ function envSlug(apiUrl) {
30028
31232
  return slug;
30029
31233
  }
30030
31234
  function currentEnvDir() {
30031
- return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
31235
+ return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
30032
31236
  }
30033
31237
  var DIR_MODE = 448;
30034
31238
  var FILE_MODE2 = 384;
30035
31239
  var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
30036
31240
  var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
30037
31241
  function appendMoveToPath(path, move) {
30038
- const dir = dirname10(path);
31242
+ const dir = dirname11(path);
30039
31243
  if (!existsSync12(dir)) {
30040
31244
  mkdirSync6(dir, { recursive: true, mode: DIR_MODE });
30041
31245
  }
@@ -30044,10 +31248,10 @@ function appendMoveToPath(path, move) {
30044
31248
  }
30045
31249
  function bucketDir(orgId) {
30046
31250
  const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
30047
- return join16(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
31251
+ return join18(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
30048
31252
  }
30049
31253
  function journalPath(orgId) {
30050
- return join16(bucketDir(orgId), JOURNAL_BASENAME);
31254
+ return join18(bucketDir(orgId), JOURNAL_BASENAME);
30051
31255
  }
30052
31256
  function appendMove(move, orgId) {
30053
31257
  const actor = machineCaptureActor();
@@ -30062,14 +31266,14 @@ var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
30062
31266
  import { execFileSync as execFileSync4 } from "child_process";
30063
31267
  import { existsSync as existsSync14, readFileSync as readFileSync16 } from "fs";
30064
31268
  import { homedir as homedir2 } from "os";
30065
- import { join as join19 } from "path";
31269
+ import { join as join20 } from "path";
30066
31270
 
30067
31271
  // src/lib/cloud-prepared.ts
30068
- import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync14, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
30069
- import { join as join17 } from "path";
31272
+ import { existsSync as existsSync13, mkdirSync as mkdirSync7, readFileSync as readFileSync15, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
31273
+ import { join as join19 } from "path";
30070
31274
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
30071
31275
  function cloudPreparedPath(env = process.env) {
30072
- return join17(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
31276
+ return join19(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30073
31277
  }
30074
31278
  function isPreparedCloudSession(env = process.env) {
30075
31279
  if (!isClaudeCloudSession(env)) return false;
@@ -30081,17 +31285,17 @@ function isPreparedCloudSession(env = process.env) {
30081
31285
  }
30082
31286
 
30083
31287
  // src/lib/demo-pause.ts
30084
- import { execFileSync as execFileSync2 } from "child_process";
31288
+ import { execFileSync as execFileSync3 } from "child_process";
30085
31289
  var DEMO_PAUSE_MS = 30 * 6e4;
30086
31290
  var PAUSE_KEY = "prim.demoPause";
30087
- var GIT_TIMEOUT_MS = 1e3;
30088
- function git(cwd, args) {
31291
+ var GIT_TIMEOUT_MS3 = 1e3;
31292
+ function git2(cwd, args) {
30089
31293
  try {
30090
- return execFileSync2("git", args, {
31294
+ return execFileSync3("git", args, {
30091
31295
  cwd,
30092
31296
  encoding: "utf-8",
30093
31297
  stdio: ["ignore", "pipe", "ignore"],
30094
- timeout: GIT_TIMEOUT_MS
31298
+ timeout: GIT_TIMEOUT_MS3
30095
31299
  });
30096
31300
  } catch {
30097
31301
  return void 0;
@@ -30099,10 +31303,10 @@ function git(cwd, args) {
30099
31303
  }
30100
31304
  function setLocal(cwd, key, value) {
30101
31305
  try {
30102
- execFileSync2(
31306
+ execFileSync3(
30103
31307
  "git",
30104
31308
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
30105
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
31309
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
30106
31310
  );
30107
31311
  } catch (error) {
30108
31312
  if (value !== null || error.status !== 5) throw error;
@@ -30116,7 +31320,7 @@ function parsePause(value) {
30116
31320
  function readCaptureConfig(cwd) {
30117
31321
  let active;
30118
31322
  let pause;
30119
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
31323
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
30120
31324
  for (const line of out.split("\n")) {
30121
31325
  const space3 = line.indexOf(" ");
30122
31326
  const key = line.slice(0, space3).toLowerCase();
@@ -30141,273 +31345,13 @@ function healDemoPause(cwd, pause, options = {}) {
30141
31345
  }
30142
31346
  }
30143
31347
 
30144
- // src/lib/git.ts
30145
- import { execFileSync as execFileSync3 } from "child_process";
30146
- import { createHash as createHash8 } from "crypto";
30147
- import { lstatSync as lstatSync7, readFileSync as readFileSync15, realpathSync as realpathSync2 } from "fs";
30148
- import { basename as basename3, dirname as dirname11, isAbsolute as isAbsolute4, join as join18, relative, resolve as resolve4, sep } from "path";
30149
- var GIT_TIMEOUT_MS2 = 1e3;
30150
- var MAX_SETTINGS_BYTES = 1024 * 1024;
30151
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
30152
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
30153
- function gitToplevel(cwd) {
30154
- try {
30155
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
30156
- cwd,
30157
- encoding: "utf-8",
30158
- stdio: ["ignore", "pipe", "ignore"],
30159
- timeout: GIT_TIMEOUT_MS2
30160
- }).trim();
30161
- } catch {
30162
- return null;
30163
- }
30164
- }
30165
- function gitValue(cwd, args) {
30166
- try {
30167
- const value = execFileSync3("git", args, {
30168
- cwd,
30169
- encoding: "utf-8",
30170
- stdio: ["ignore", "pipe", "ignore"],
30171
- timeout: GIT_TIMEOUT_MS2
30172
- }).trim();
30173
- return value || void 0;
30174
- } catch {
30175
- return void 0;
30176
- }
30177
- }
30178
- function currentBranch(cwd) {
30179
- return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
30180
- }
30181
- function parseGithubRepositoryName(path) {
30182
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
30183
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
30184
- return null;
30185
- }
30186
- return `${parts[0]}/${parts[1]}`;
30187
- }
30188
- function githubRepositoryFromRemote(remote) {
30189
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
30190
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
30191
- remote
30192
- );
30193
- const path = match?.[1] ?? match?.[2];
30194
- return path ? parseGithubRepositoryName(path) : null;
30195
- }
30196
- function checkoutSettingsText(repoRoot) {
30197
- const path = join18(repoRoot, ".claude", "settings.json");
30198
- try {
30199
- if (!lstatSync7(join18(repoRoot, ".claude")).isDirectory()) return null;
30200
- const stat = lstatSync7(path);
30201
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
30202
- return readFileSync15(path, "utf8");
30203
- } catch {
30204
- return null;
30205
- }
30206
- }
30207
- function checkoutDeclaration(repoRoot, name2) {
30208
- const text = checkoutSettingsText(repoRoot);
30209
- if (text === null) return null;
30210
- let parsed;
30211
- try {
30212
- parsed = JSON.parse(text);
30213
- } catch {
30214
- return null;
30215
- }
30216
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
30217
- const value = typeof env === "object" && env !== null ? env[name2] : void 0;
30218
- return typeof value === "string" ? value : null;
30219
- }
30220
- function declaredGithubRepository(repoRoot) {
30221
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
30222
- return value === null ? null : parseGithubRepositoryName(value.trim());
30223
- }
30224
- function githubRepositoryFullName(cwd) {
30225
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
30226
- if (remote) {
30227
- const fromOrigin = githubRepositoryFromRemote(remote);
30228
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
30229
- }
30230
- const root = gitToplevel(cwd);
30231
- return root ? declaredGithubRepository(root) : null;
30232
- }
30233
- function canonicalGitRoot(cwd) {
30234
- try {
30235
- const top = gitToplevel(cwd);
30236
- return top ? realpathSync2.native(top) : null;
30237
- } catch {
30238
- return null;
30239
- }
30240
- }
30241
- function relatedWorktreeTarget(path, cwd, origin) {
30242
- let parent = dirname11(resolve4(cwd, path));
30243
- while (true) {
30244
- try {
30245
- realpathSync2.native(parent);
30246
- break;
30247
- } catch {
30248
- const next = dirname11(parent);
30249
- if (next === parent) return null;
30250
- parent = next;
30251
- }
30252
- }
30253
- const target = resolveRepositoryContext(parent);
30254
- if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
30255
- const common = (root) => {
30256
- const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
30257
- try {
30258
- return value ? realpathSync2.native(resolve4(root, value)) : void 0;
30259
- } catch {
30260
- return void 0;
30261
- }
30262
- };
30263
- const originCommon = common(origin.repoRoot);
30264
- return originCommon && originCommon === common(target.repoRoot) ? target : null;
30265
- }
30266
- function normalizeOriginRemote(remote) {
30267
- const value = remote.trim();
30268
- if (!value) return void 0;
30269
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
30270
- if (scp?.host && scp.path) {
30271
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30272
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
30273
- }
30274
- try {
30275
- const url = new URL(value);
30276
- url.username = "";
30277
- url.password = "";
30278
- url.search = "";
30279
- url.hash = "";
30280
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
30281
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
30282
- return void 0;
30283
- } catch {
30284
- return void 0;
30285
- }
30286
- }
30287
- function opaqueRepoKey(source, value) {
30288
- return `repo_v1_${createHash8("sha256").update(`${source}\0${value}`).digest("hex")}`;
30289
- }
30290
- function resolveRepositoryContext(cwd = process.cwd()) {
30291
- const top = gitToplevel(cwd);
30292
- if (!top) return null;
30293
- let repoRoot;
30294
- try {
30295
- repoRoot = realpathSync2.native(top);
30296
- } catch {
30297
- repoRoot = resolve4(top);
30298
- }
30299
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
30300
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
30301
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
30302
- if (normalizedOrigin) {
30303
- return {
30304
- repoRoot,
30305
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
30306
- identitySource: "origin",
30307
- repoFullName
30308
- };
30309
- }
30310
- if (repoFullName) {
30311
- return {
30312
- repoRoot,
30313
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
30314
- identitySource: "declared",
30315
- repoFullName
30316
- };
30317
- }
30318
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
30319
- if (roots && roots.length > 0) {
30320
- return {
30321
- repoRoot,
30322
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
30323
- identitySource: "root_commit",
30324
- repoFullName
30325
- };
30326
- }
30327
- return { repoRoot, repoFullName };
30328
- }
30329
- function nearestExistingAncestor(path) {
30330
- const suffix = [];
30331
- let cursor = path;
30332
- while (true) {
30333
- try {
30334
- lstatSync7(cursor);
30335
- break;
30336
- } catch (error) {
30337
- const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
30338
- if (code !== "ENOENT" && code !== "ENOTDIR") return null;
30339
- const parent = dirname11(cursor);
30340
- if (parent === cursor) return null;
30341
- suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
30342
- cursor = parent;
30343
- }
30344
- }
30345
- try {
30346
- return { real: realpathSync2.native(cursor), suffix };
30347
- } catch {
30348
- return null;
30349
- }
30350
- }
30351
- function canonicalRepositoryPathScoped(filePath, context, baseDir) {
30352
- if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
30353
- return { ok: false, reason: "invalid_path" };
30354
- }
30355
- const absolute = resolve4(baseDir, filePath);
30356
- const resolved = nearestExistingAncestor(absolute);
30357
- if (!resolved) return { ok: false, reason: "invalid_path" };
30358
- const target = resolve4(resolved.real, ...resolved.suffix);
30359
- const rel = relative(context.repoRoot, target);
30360
- if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
30361
- if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
30362
- return { ok: false, reason: "outside_repository" };
30363
- }
30364
- return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
30365
- }
30366
- function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
30367
- if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
30368
- return null;
30369
- const absolute = resolve4(cwd, filePath);
30370
- let target;
30371
- try {
30372
- const stat = lstatSync7(absolute);
30373
- if (!stat.isFile() || stat.isSymbolicLink()) return null;
30374
- target = realpathSync2.native(absolute);
30375
- } catch (error) {
30376
- if (!(error instanceof Error) || error.code !== "ENOENT") {
30377
- return null;
30378
- }
30379
- try {
30380
- const parent = realpathSync2.native(dirname11(absolute));
30381
- if (!lstatSync7(parent).isDirectory()) return null;
30382
- target = resolve4(parent, basename3(absolute));
30383
- } catch {
30384
- return null;
30385
- }
30386
- }
30387
- const rel = relative(repositoryRoot, target);
30388
- if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
30389
- return null;
30390
- }
30391
- return sep === "/" ? rel : rel.split(sep).join("/");
30392
- }
30393
- function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
30394
- if (typeof contextOrCwd === "string") {
30395
- return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
30396
- }
30397
- return canonicalRepositoryPathScoped(
30398
- filePath,
30399
- contextOrCwd,
30400
- baseDirOrRoot ?? contextOrCwd.repoRoot
30401
- );
30402
- }
30403
-
30404
31348
  // src/lib/activation.ts
30405
31349
  var PRIM_ACTIVE_KEY = "prim.active";
30406
31350
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
30407
31351
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
30408
31352
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
30409
31353
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
30410
- var GIT_TIMEOUT_MS3 = 1e3;
31354
+ var GIT_TIMEOUT_MS4 = 1e3;
30411
31355
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
30412
31356
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
30413
31357
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -30417,7 +31361,7 @@ function repoActiveFlag(cwd, strict = false) {
30417
31361
  cwd,
30418
31362
  encoding: "utf-8",
30419
31363
  stdio: ["ignore", "pipe", "ignore"],
30420
- timeout: GIT_TIMEOUT_MS3
31364
+ timeout: GIT_TIMEOUT_MS4
30421
31365
  }).trim();
30422
31366
  if (value === "true") return "true";
30423
31367
  if (value === "false") return "false";
@@ -30438,7 +31382,7 @@ function localGitConfigValue(cwd, key) {
30438
31382
  cwd,
30439
31383
  encoding: "utf-8",
30440
31384
  stdio: ["ignore", "pipe", "ignore"],
30441
- timeout: GIT_TIMEOUT_MS3
31385
+ timeout: GIT_TIMEOUT_MS4
30442
31386
  }).trim();
30443
31387
  return value || void 0;
30444
31388
  } catch {
@@ -30463,7 +31407,7 @@ function repositoryBindingState(cwd) {
30463
31407
  function projectPrimInstallAt(root) {
30464
31408
  if (root === null || root === homedir2()) return false;
30465
31409
  for (const rel of PROJECT_INSTALL_FILES) {
30466
- const path = join19(root, rel);
31410
+ const path = join20(root, rel);
30467
31411
  if (existsSync14(path)) {
30468
31412
  try {
30469
31413
  const content2 = readFileSync16(path, "utf-8");
@@ -30790,14 +31734,14 @@ function cachedCollectScopeAdmits(cwd, facts) {
30790
31734
  // src/lib/commit-heartbeat.ts
30791
31735
  import { execFileSync as execFileSync5 } from "child_process";
30792
31736
  import { mkdirSync as mkdirSync8, readFileSync as readFileSync17, readdirSync as readdirSync6, unlinkSync } from "fs";
30793
- import { dirname as dirname12, join as join20, resolve as resolve5 } from "path";
30794
- var GIT_TIMEOUT_MS4 = 1e3;
31737
+ import { dirname as dirname12, join as join21, resolve as resolve5 } from "path";
31738
+ var GIT_TIMEOUT_MS5 = 1e3;
30795
31739
  function gitPath(cwd, relative3) {
30796
31740
  const value = execFileSync5("git", ["rev-parse", "--git-path", relative3], {
30797
31741
  cwd,
30798
31742
  encoding: "utf8",
30799
31743
  stdio: ["ignore", "pipe", "ignore"],
30800
- timeout: GIT_TIMEOUT_MS4
31744
+ timeout: GIT_TIMEOUT_MS5
30801
31745
  }).replace(/\r?\n$/u, "");
30802
31746
  if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
30803
31747
  return resolve5(cwd, value);
@@ -30842,8 +31786,8 @@ import {
30842
31786
  unlinkSync as unlinkSync2,
30843
31787
  writeFileSync as writeFileSync6
30844
31788
  } from "fs";
30845
- import { dirname as dirname13, isAbsolute as isAbsolute5, join as join21, resolve as resolve6 } from "path";
30846
- var WORKSPACE_ID_RELATIVE_PATH = join21("prim", "workspace-id");
31789
+ import { dirname as dirname13, isAbsolute as isAbsolute5, join as join22, resolve as resolve6 } from "path";
31790
+ var WORKSPACE_ID_RELATIVE_PATH = join22("prim", "workspace-id");
30847
31791
  var MAX_ANCESTORS = 64;
30848
31792
  var MAX_GIT_FILE_BYTES = 4096;
30849
31793
  var MAX_ID_FILE_BYTES = 128;
@@ -30902,11 +31846,11 @@ function resolveWorkspaceIdPath(cwd) {
30902
31846
  function resolveFromFilesystem(cwd) {
30903
31847
  let current = resolve6(cwd);
30904
31848
  for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
30905
- const dotGit = join21(current, ".git");
31849
+ const dotGit = join22(current, ".git");
30906
31850
  try {
30907
31851
  const stat = lstatSync8(dotGit);
30908
31852
  if (stat.isDirectory() && isGitDirectory(dotGit)) {
30909
- return join21(dotGit, WORKSPACE_ID_RELATIVE_PATH);
31853
+ return join22(dotGit, WORKSPACE_ID_RELATIVE_PATH);
30910
31854
  }
30911
31855
  if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
30912
31856
  const contents = readFileSync18(dotGit, "utf8");
@@ -30914,7 +31858,7 @@ function resolveFromFilesystem(cwd) {
30914
31858
  if (match?.[1]) {
30915
31859
  const gitDirectory = isAbsolute5(match[1]) ? resolve6(match[1]) : resolve6(current, match[1]);
30916
31860
  if (isGitDirectory(gitDirectory)) {
30917
- return join21(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
31861
+ return join22(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
30918
31862
  }
30919
31863
  }
30920
31864
  }
@@ -30933,7 +31877,7 @@ function resolveFromFilesystem(cwd) {
30933
31877
  }
30934
31878
  function isGitDirectory(path) {
30935
31879
  try {
30936
- return statSync3(join21(path, "HEAD")).isFile();
31880
+ return statSync3(join22(path, "HEAD")).isFile();
30937
31881
  } catch {
30938
31882
  return false;
30939
31883
  }
@@ -30971,7 +31915,7 @@ function inspectPath(path) {
30971
31915
  function createWorkspaceId(path) {
30972
31916
  const parent = dirname13(path);
30973
31917
  const workspaceId = randomUUID4();
30974
- const temporaryPath = join21(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
31918
+ const temporaryPath = join22(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
30975
31919
  let temporaryCreated = false;
30976
31920
  let publishing = false;
30977
31921
  try {
@@ -31041,7 +31985,7 @@ function parseAgent(argv) {
31041
31985
  }
31042
31986
 
31043
31987
  // src/hooks/codex-context.ts
31044
- import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
31988
+ import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
31045
31989
  import {
31046
31990
  chmodSync as chmodSync7,
31047
31991
  existsSync as existsSync15,
@@ -31049,21 +31993,21 @@ import {
31049
31993
  readFileSync as readFileSync19,
31050
31994
  readdirSync as readdirSync7,
31051
31995
  renameSync as renameSync3,
31052
- rmSync as rmSync10,
31996
+ rmSync as rmSync11,
31053
31997
  statSync as statSync4,
31054
31998
  unlinkSync as unlinkSync3,
31055
31999
  writeFileSync as writeFileSync7
31056
32000
  } from "fs";
31057
- import { join as join23 } from "path";
32001
+ import { join as join24 } from "path";
31058
32002
 
31059
32003
  // src/daemon/principal.ts
31060
- import { createHash as createHash9 } from "crypto";
32004
+ import { createHash as createHash10 } from "crypto";
31061
32005
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
31062
32006
  function boundedClaim(value) {
31063
32007
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
31064
32008
  }
31065
32009
  function sha256(value) {
31066
- return createHash9("sha256").update(value).digest("hex");
32010
+ return createHash10("sha256").update(value).digest("hex");
31067
32011
  }
31068
32012
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
31069
32013
  if (hasMachineConfiguration()) {
@@ -31117,8 +32061,8 @@ function parseDaemonResponseEnvelope(value) {
31117
32061
 
31118
32062
  // src/daemon/client.ts
31119
32063
  import { createConnection } from "net";
31120
- import { join as join22 } from "path";
31121
- var SOCK_PATH = join22(primConfigDirectory(), "sock");
32064
+ import { join as join23 } from "path";
32065
+ var SOCK_PATH = join23(primConfigDirectory(), "sock");
31122
32066
  var DEFAULT_TIMEOUT_MS2 = 250;
31123
32067
  var nextRequestId = 1;
31124
32068
  function daemonRequest(method, params = {}, opts = {}) {
@@ -31367,10 +32311,10 @@ var STATE_VERSION = 1;
31367
32311
  var DRAFT_STATE_VERSION = 2;
31368
32312
  var NO_CURSOR = -1;
31369
32313
  function stateRoot(namespace) {
31370
- return join23(primConfigDirectory(), namespace, "decision-digests");
32314
+ return join24(primConfigDirectory(), namespace, "decision-digests");
31371
32315
  }
31372
32316
  function draftStateRoot(namespace) {
31373
- return join23(primConfigDirectory(), namespace, "decision-draft-deliveries");
32317
+ return join24(primConfigDirectory(), namespace, "decision-draft-deliveries");
31374
32318
  }
31375
32319
  function workspaceFor(cwd) {
31376
32320
  try {
@@ -31381,13 +32325,13 @@ function workspaceFor(cwd) {
31381
32325
  }
31382
32326
  function statePath(args) {
31383
32327
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
31384
- const key = createHash10("sha256").update(identity).digest("hex");
31385
- return join23(stateRoot(args.namespace), `${key}.json`);
32328
+ const key = createHash11("sha256").update(identity).digest("hex");
32329
+ return join24(stateRoot(args.namespace), `${key}.json`);
31386
32330
  }
31387
32331
  function draftStatePath(args) {
31388
32332
  const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
31389
- const key = createHash10("sha256").update(identity).digest("hex");
31390
- return join23(draftStateRoot(args.namespace), `${key}.json`);
32333
+ const key = createHash11("sha256").update(identity).digest("hex");
32334
+ return join24(draftStateRoot(args.namespace), `${key}.json`);
31391
32335
  }
31392
32336
  function parseState(value) {
31393
32337
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
@@ -31425,7 +32369,7 @@ function parseDraftState(value) {
31425
32369
  updatedAt: record.updatedAt
31426
32370
  };
31427
32371
  }
31428
- function readState(path) {
32372
+ function readState2(path) {
31429
32373
  if (!existsSync15(path)) return void 0;
31430
32374
  try {
31431
32375
  return parseState(JSON.parse(readFileSync19(path, "utf8")));
@@ -31444,7 +32388,7 @@ function readDraftState(path) {
31444
32388
  function writeStateFile(path, directory, state) {
31445
32389
  mkdirSync10(directory, { recursive: true, mode: 448 });
31446
32390
  chmodSync7(directory, 448);
31447
- const temporary = join23(
32391
+ const temporary = join24(
31448
32392
  directory,
31449
32393
  `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
31450
32394
  );
@@ -31475,7 +32419,7 @@ function cleanupStateFiles(directory, now) {
31475
32419
  const files = [];
31476
32420
  const residue = [];
31477
32421
  for (const name2 of names) {
31478
- const path = join23(directory, name2);
32422
+ const path = join24(directory, name2);
31479
32423
  try {
31480
32424
  const mtimeMs = statSync4(path).mtimeMs;
31481
32425
  if (name2.endsWith(".json")) {
@@ -31497,7 +32441,7 @@ function cleanupStateFiles(directory, now) {
31497
32441
  for (const path of residue) {
31498
32442
  try {
31499
32443
  if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
31500
- rmSync10(path, { recursive: true, force: true });
32444
+ rmSync11(path, { recursive: true, force: true });
31501
32445
  }
31502
32446
  } catch {
31503
32447
  }
@@ -31583,7 +32527,7 @@ async function commitState(path, args, namespace) {
31583
32527
  await withFileLock(
31584
32528
  `${path}.lock`,
31585
32529
  () => {
31586
- const latest = readState(path);
32530
+ const latest = readState2(path);
31587
32531
  writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
31588
32532
  cleanupStateFiles(stateRoot(namespace), args.now);
31589
32533
  },
@@ -31630,7 +32574,7 @@ async function prepareCodexContext(options) {
31630
32574
  const siteUrl = getSiteUrl();
31631
32575
  const workspace = workspaceFor(options.cwd);
31632
32576
  const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
31633
- const previous = readState(path);
32577
+ const previous = readState2(path);
31634
32578
  const principal = resolveDaemonPrincipal();
31635
32579
  const privatePath = principal ? draftStatePath({
31636
32580
  cwd: options.cwd,
@@ -31815,7 +32759,7 @@ async function processCodexMessageContext(envelope, deps = defaultDeps) {
31815
32759
  // src/commands/cursor-install.ts
31816
32760
  import { existsSync as existsSync17, readFileSync as readFileSync21 } from "fs";
31817
32761
  import { homedir as homedir4 } from "os";
31818
- import { isAbsolute as isAbsolute6, join as join25 } from "path";
32762
+ import { isAbsolute as isAbsolute6, join as join26 } from "path";
31819
32763
 
31820
32764
  // src/lib/preflight-host.ts
31821
32765
  import { execFileSync as execFileSync7 } from "child_process";
@@ -31823,7 +32767,7 @@ import { execFileSync as execFileSync7 } from "child_process";
31823
32767
  // src/commands/claude-install.ts
31824
32768
  import { existsSync as existsSync16, lstatSync as lstatSync9, readFileSync as readFileSync20 } from "fs";
31825
32769
  import { homedir as homedir3 } from "os";
31826
- import { join as join24 } from "path";
32770
+ import { join as join25 } from "path";
31827
32771
  var CAPTURE_BIN = "prim-hook";
31828
32772
  var GATE_BIN = "prim-pre-tool-use";
31829
32773
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -31832,7 +32776,7 @@ var SESSION_END_BIN = "prim-session-end";
31832
32776
  var STATUSLINE_BIN = "prim-statusline";
31833
32777
  var STATUSLINE_ARGS = "";
31834
32778
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
31835
- var USER_SCOPE_PATH = join24(homedir3(), ".claude", "settings.json");
32779
+ var USER_SCOPE_PATH = join25(homedir3(), ".claude", "settings.json");
31836
32780
  function projectRoot() {
31837
32781
  return gitToplevel() ?? process.cwd();
31838
32782
  }
@@ -31912,11 +32856,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
31912
32856
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
31913
32857
  if (explicit && isAbsolute6(explicit)) return explicit;
31914
32858
  const xdg = env.XDG_CONFIG_HOME?.trim();
31915
- if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join25(xdg, "cursor");
31916
- return join25(home, ".cursor");
32859
+ if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join26(xdg, "cursor");
32860
+ return join26(home, ".cursor");
31917
32861
  }
31918
32862
  function cursorHooksPath(scope, root = projectRoot()) {
31919
- return scope === "user" ? join25(cursorConfigDirectory(), "hooks.json") : join25(root, ".cursor", "hooks.json");
32863
+ return scope === "user" ? join26(cursorConfigDirectory(), "hooks.json") : join26(root, ".cursor", "hooks.json");
31920
32864
  }
31921
32865
  function plainObject(value) {
31922
32866
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -32198,7 +33142,7 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
32198
33142
 
32199
33143
  // src/hooks/redact.ts
32200
33144
  import { existsSync as existsSync18, readFileSync as readFileSync22, statSync as statSync5 } from "fs";
32201
- import { join as join26 } from "path";
33145
+ import { join as join27 } from "path";
32202
33146
  import { Worker } from "worker_threads";
32203
33147
  var USER_HOME_RULES = [
32204
33148
  {
@@ -32279,7 +33223,7 @@ function normalizedWorkspaceFlags(value) {
32279
33223
  return [...new Set(`g${requested}`)].sort().join("");
32280
33224
  }
32281
33225
  function loadWorkspaceRules(cwd) {
32282
- const path = join26(cwd, WORKSPACE_FILE2);
33226
+ const path = join27(cwd, WORKSPACE_FILE2);
32283
33227
  if (!existsSync18(path)) return [];
32284
33228
  let cfg;
32285
33229
  try {
@@ -38643,7 +39587,7 @@ var TokenGroup = class {
38643
39587
  }
38644
39588
  token(input, stack) {
38645
39589
  let { parser: parser3 } = stack.p;
38646
- readToken(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
39590
+ readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
38647
39591
  }
38648
39592
  };
38649
39593
  TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
@@ -38657,7 +39601,7 @@ var LocalTokenGroup = class {
38657
39601
  let start = input.pos, skipped = 0;
38658
39602
  for (; ; ) {
38659
39603
  let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
38660
- readToken(this.data, input, stack, 0, this.data, this.precTable);
39604
+ readToken2(this.data, input, stack, 0, this.data, this.precTable);
38661
39605
  if (input.token.value > -1)
38662
39606
  break;
38663
39607
  if (this.elseToken == null)
@@ -38690,7 +39634,7 @@ var ExternalTokenizer = class {
38690
39634
  this.extend = !!options.extend;
38691
39635
  }
38692
39636
  };
38693
- function readToken(data, input, stack, group, precTable, precOffset) {
39637
+ function readToken2(data, input, stack, group, precTable, precOffset) {
38694
39638
  let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
38695
39639
  scan: for (; ; ) {
38696
39640
  if ((groupMask & data[state]) == 0)
@@ -40503,7 +41447,7 @@ var newline2 = 10;
40503
41447
  var carriageReturn = 13;
40504
41448
  var space2 = 32;
40505
41449
  var tab = 9;
40506
- var hash2 = 35;
41450
+ var hash3 = 35;
40507
41451
  var parenOpen = 40;
40508
41452
  var dot2 = 46;
40509
41453
  var braceOpen = 123;
@@ -40556,7 +41500,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
40556
41500
  input.advance();
40557
41501
  spaces2++;
40558
41502
  }
40559
- if (input.next == newline2 || input.next == carriageReturn || input.next == hash2)
41503
+ if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
40560
41504
  input.acceptToken(blankLineStart, -spaces2);
40561
41505
  } else if (isLineBreak(input.next)) {
40562
41506
  input.acceptToken(newline$1, 1);
@@ -40575,7 +41519,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
40575
41519
  input.advance();
40576
41520
  chars++;
40577
41521
  }
40578
- if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash2) {
41522
+ if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
40579
41523
  if (depth < context.indent) input.acceptToken(dedent, -chars);
40580
41524
  else input.acceptToken(indent);
40581
41525
  }
@@ -40649,7 +41593,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
40649
41593
  for (let off = 0; ; off++) {
40650
41594
  let next = input.peek(off);
40651
41595
  if (next == space2 || next == tab) continue;
40652
- if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash2)
41596
+ if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
40653
41597
  input.acceptToken(printKeyword);
40654
41598
  return;
40655
41599
  }
@@ -41860,7 +42804,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
41860
42804
  }
41861
42805
 
41862
42806
  // src/hooks/normalize.ts
41863
- import { createHash as createHash11 } from "crypto";
42807
+ import { createHash as createHash12 } from "crypto";
41864
42808
  import { realpathSync as realpathSync4 } from "fs";
41865
42809
  import { isAbsolute as isAbsolute8, resolve as resolve8 } from "path";
41866
42810
  var HERMES_EVENT_MAP = {
@@ -41905,7 +42849,7 @@ function requiredId(value, field) {
41905
42849
  }
41906
42850
  function cursorToolUseId(value) {
41907
42851
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
41908
- return `cursor:tool:v1:${createHash11("sha256").update(value).digest("hex")}`;
42852
+ return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
41909
42853
  }
41910
42854
  function workspaceCandidates(value) {
41911
42855
  if (!Array.isArray(value)) return [];
@@ -42002,7 +42946,7 @@ function normalizeEnvelope(parsed, agent) {
42002
42946
  ]);
42003
42947
  return {
42004
42948
  ...parsed,
42005
- tool_use_id: `codex:fallback:v1:${createHash11("sha256").update(stableToolIdentity).digest("hex")}`
42949
+ tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
42006
42950
  };
42007
42951
  }
42008
42952
  return parsed;
@@ -42018,7 +42962,7 @@ function normalizeEnvelope(parsed, agent) {
42018
42962
  }
42019
42963
 
42020
42964
  // src/hooks/prim-hook-core.ts
42021
- import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
42965
+ import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
42022
42966
  import { platform } from "os";
42023
42967
 
42024
42968
  // src/protocol/move.ts
@@ -42092,9 +43036,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
42092
43036
  const toolOutcome = toolOutcomeFor(parsed, agent);
42093
43037
  let moveId;
42094
43038
  if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
42095
- moveId = `posttool:v1:${createHash12("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
43039
+ moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
42096
43040
  } else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
42097
- moveId = `posttool:fallback:v1:${createHash12("sha256").update(
43041
+ moveId = `posttool:fallback:v1:${createHash13("sha256").update(
42098
43042
  JSON.stringify([
42099
43043
  agent,
42100
43044
  sessionId,
@@ -42145,14 +43089,14 @@ function emitOutput(output, acknowledge) {
42145
43089
  }
42146
43090
  function resolveCliVersion() {
42147
43091
  try {
42148
- const pkg = JSON.parse(readFileSync23(join27(here, "..", "..", "package.json"), "utf-8"));
43092
+ const pkg = JSON.parse(readFileSync23(join28(here, "..", "..", "package.json"), "utf-8"));
42149
43093
  return pkg.version ?? "unknown";
42150
43094
  } catch {
42151
43095
  return "unknown";
42152
43096
  }
42153
43097
  }
42154
43098
  function spawnBackgroundFlush() {
42155
- const entry = join27(here, "..", "index.js");
43099
+ const entry = join28(here, "..", "index.js");
42156
43100
  spawn2(process.execPath, [entry, "moves", "flush"], {
42157
43101
  detached: true,
42158
43102
  stdio: "ignore",