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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
@@ -53,10 +53,10 @@ var require_ucs2length = __commonJS({
53
53
 
54
54
  // src/lib/machine-broker.ts
55
55
  import { spawn } from "child_process";
56
- import { createHash as createHash3, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
57
- import { lstatSync as lstatSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
56
+ import { createHash as createHash5, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
57
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, rmSync as rmSync6 } from "fs";
58
58
  import { createServer } from "http";
59
- import { basename, join as join6 } from "path";
59
+ import { basename as basename2, join as join8 } from "path";
60
60
  import { fileURLToPath as fileURLToPath3 } from "url";
61
61
 
62
62
  // src/lib/atomic-file.ts
@@ -333,14 +333,66 @@ async function withFileLock(lockDir, operation, options = {}) {
333
333
  }
334
334
  }
335
335
 
336
+ // src/lib/loopback-fetch.ts
337
+ import { request } from "http";
338
+ import { Readable } from "stream";
339
+ function loopbackFetch(url, init = {}) {
340
+ const target = new URL(url);
341
+ if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
342
+ return Promise.reject(new Error(`not a loopback URL: ${url}`));
343
+ return new Promise((resolve3, reject) => {
344
+ const outgoing = request(
345
+ target,
346
+ { method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
347
+ (incoming) => {
348
+ try {
349
+ const headers = new Headers();
350
+ for (const [name, value] of Object.entries(incoming.headers))
351
+ if (typeof value === "string") headers.set(name, value);
352
+ const status = incoming.statusCode ?? 502;
353
+ const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
354
+ resolve3(new Response(body, { status, headers }));
355
+ } catch (error) {
356
+ incoming.destroy();
357
+ reject(error);
358
+ }
359
+ }
360
+ );
361
+ outgoing.once("error", reject);
362
+ outgoing.end(init.body);
363
+ });
364
+ }
365
+
336
366
  // src/lib/machine-credentials.ts
337
- import { execFileSync } from "child_process";
338
- import { createHash as createHash2, randomUUID as randomUUID2 } from "crypto";
339
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync2, mkdirSync as mkdirSync3, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
367
+ import { execFileSync as execFileSync2 } from "child_process";
368
+ import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
369
+ import {
370
+ chmodSync,
371
+ existsSync as existsSync3,
372
+ linkSync,
373
+ lstatSync as lstatSync3,
374
+ mkdirSync as mkdirSync3,
375
+ readFileSync as readFileSync5,
376
+ rmSync as rmSync5,
377
+ writeFileSync as writeFileSync3
378
+ } from "fs";
340
379
  import { createRequire } from "module";
341
- import { dirname as dirname4, join as join5 } from "path";
380
+ import { dirname as dirname5, join as join7 } from "path";
342
381
  import { fileURLToPath as fileURLToPath2 } from "url";
343
382
 
383
+ // src/lib/cloud-env.ts
384
+ function isClaudeCloudSession(env = process.env) {
385
+ return env.CLAUDE_CODE_REMOTE === "true";
386
+ }
387
+ 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';
388
+ 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';
389
+ 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}.`;
390
+ var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
391
+ function cloudSetupPointer(message, env = process.env) {
392
+ return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
393
+ }
394
+ var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
395
+
344
396
  // src/lib/workos-connect.ts
345
397
  var TOKEN_PATH = "/oauth2/token";
346
398
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -477,10 +529,10 @@ function parseWorkosConnectTokens(value, options = {}) {
477
529
  "access_token",
478
530
  WORKOS_CONNECT_RESPONSE_MAX_BYTES
479
531
  );
480
- const refreshToken2 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
532
+ const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
481
533
  return {
482
534
  accessToken,
483
- refreshToken: refreshToken2,
535
+ refreshToken: refreshToken3,
484
536
  expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
485
537
  };
486
538
  }
@@ -536,9 +588,19 @@ function parseMachineConfiguration(value) {
536
588
  ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
537
589
  };
538
590
  }
591
+ function rejectedCredentialsMessage(message, env = process.env) {
592
+ return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
593
+ }
539
594
  function machineSignal(signal) {
540
595
  return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
541
596
  }
597
+ function hostOf(url) {
598
+ try {
599
+ return new URL(url).hostname;
600
+ } catch {
601
+ return "Primitive";
602
+ }
603
+ }
542
604
  async function fetchMachine(url, options, fetchImpl) {
543
605
  try {
544
606
  return await fetchImpl(url, options);
@@ -546,7 +608,9 @@ async function fetchMachine(url, options, fetchImpl) {
546
608
  options.signal?.throwIfAborted();
547
609
  throw new MachineAuthError(
548
610
  "authentication_unavailable",
549
- "Machine authentication is temporarily unavailable. Check the connection and retry."
611
+ // A cloud VM reaches only the hosts its environment allows, and both of
612
+ // Primitive's are blocked by default: name the one that failed.
613
+ isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
550
614
  );
551
615
  }
552
616
  }
@@ -573,8 +637,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
573
637
  );
574
638
  return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
575
639
  }
576
- async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
577
- if (!/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
640
+ async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
641
+ const network = options.secretInjection === "network";
642
+ if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
578
643
  throw new MachineAuthError(
579
644
  "invalid_credentials",
580
645
  "A machine client ID and secret are required.",
@@ -588,11 +653,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
588
653
  redirect: "error",
589
654
  signal: machineSignal(signal),
590
655
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
591
- body: new URLSearchParams({
592
- grant_type: "client_credentials",
593
- client_id: clientId,
594
- client_secret: clientSecret
595
- })
656
+ // With a network secret the agent proxy authenticates the client with
657
+ // HTTP Basic (client_secret_basic); the body carries no credential.
658
+ body: new URLSearchParams(
659
+ network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
660
+ )
596
661
  },
597
662
  fetchImpl
598
663
  );
@@ -600,7 +665,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
600
665
  const terminal = response.status === 400 || response.status === 401 || response.status === 403;
601
666
  throw new MachineAuthError(
602
667
  terminal ? "machine_credentials_rejected" : "token_service_unavailable",
603
- terminal ? "Machine credentials were rejected. Ask your administrator to rotate or enable them." : "The machine token service is temporarily unavailable.",
668
+ terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
669
+ "Machine credentials were rejected. Ask your administrator to rotate or enable them."
670
+ ) : "The machine token service is temporarily unavailable.",
604
671
  terminal,
605
672
  terminal ? void 0 : machineRetryAt(response)
606
673
  );
@@ -620,6 +687,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
620
687
  } catch {
621
688
  throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
622
689
  }
690
+ if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
691
+ throw new MachineAuthError(
692
+ "token_client_mismatch",
693
+ "The token service issued a token for another machine client."
694
+ );
623
695
  if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
624
696
  throw new MachineAuthError(
625
697
  "token_identity_mismatch",
@@ -665,22 +737,66 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
665
737
  const terminal = response.status === 401 || response.status === 403;
666
738
  throw new MachineAuthError(
667
739
  terminal ? "machine_access_rejected" : "verification_unavailable",
668
- terminal ? "The API rejected this machine. Ask your administrator to check its registration and scopes." : "Machine verification is temporarily unavailable.",
740
+ terminal ? rejectedCredentialsMessage(
741
+ "The API rejected this machine. Ask your administrator to check its registration and scopes."
742
+ ) : "Machine verification is temporarily unavailable.",
669
743
  terminal
670
744
  );
671
745
  }
672
746
  return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
673
747
  }
748
+ function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
749
+ const rejected = () => new MachineAuthError(
750
+ "network_token_rejected",
751
+ `Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
752
+ true
753
+ );
754
+ if (status === 401 || status === 403) throw rejected();
755
+ if (status < 200 || status > 299)
756
+ throw new MachineAuthError(
757
+ "verification_unavailable",
758
+ "Machine verification is temporarily unavailable."
759
+ );
760
+ let data;
761
+ try {
762
+ data = machineRecord(value);
763
+ } catch {
764
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
765
+ }
766
+ if (data.authenticated !== true) throw rejected();
767
+ const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
768
+ if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
769
+ throw new MachineAuthError(
770
+ "network_secret_mismatch",
771
+ `The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
772
+ true
773
+ );
774
+ return parseMachineIdentity(data, clientId);
775
+ }
776
+ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
777
+ const response = await fetchMachine(
778
+ `${machineApiUrl(apiUrl)}/api/cli/auth/status`,
779
+ { redirect: "error", signal: machineSignal(signal) },
780
+ fetchImpl
781
+ );
782
+ const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
783
+ return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
784
+ }
674
785
 
675
786
  // src/lib/machine-retry.ts
676
787
  import { createHash } from "crypto";
677
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
788
+ import { lstatSync, readFileSync as readFileSync3, readdirSync, rmSync as rmSync3 } from "fs";
678
789
  import { join as join3 } from "path";
679
- async function withMachineCooldown(directory, apiUrl, clientId, signal, request2) {
790
+ var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
791
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
792
+ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
680
793
  signal?.throwIfAborted();
681
794
  const key = createHash("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
682
795
  const path = join3(directory, `machine_retry_${key}.json`);
683
- let state = { failures: 0, retryAt: 0 };
796
+ let state = {
797
+ failures: 0,
798
+ retryAt: 0
799
+ };
684
800
  try {
685
801
  const stat = lstatSync(path);
686
802
  if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
@@ -695,12 +811,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
695
811
  if (state.retryAt > Date.now())
696
812
  throw new MachineAuthError(
697
813
  "token_service_unavailable",
698
- "Machine authentication is cooling down after a temporary failure. Retry later.",
814
+ !isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
815
+ // Cloud setup keeps this wait too, so pointing at it would loop.
816
+ `${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
817
+ ) : (
818
+ // The cooldown hides the failure that started it; cloud setup
819
+ // retries at once and names the cause.
820
+ cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
821
+ ),
699
822
  false,
700
823
  state.retryAt
701
824
  );
702
825
  try {
703
- const result = await request2();
826
+ const result = await request3();
704
827
  rmSync3(path, { force: true });
705
828
  return result;
706
829
  } catch (error) {
@@ -712,8 +835,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
712
835
  ].includes(error.code)) {
713
836
  const failures = Math.min(16, state.failures + 1);
714
837
  const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
715
- const retryAt = error.retryAt ?? Date.now() + Math.ceil(backoff * (1 + Math.random()));
716
- atomicWriteFile(path, JSON.stringify({ failures, retryAt }), { mode: 384 });
838
+ const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
839
+ atomicWriteFile(
840
+ path,
841
+ JSON.stringify({
842
+ failures,
843
+ retryAt,
844
+ ...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
845
+ }),
846
+ { mode: 384 }
847
+ );
717
848
  throw new MachineAuthError(error.code, error.message, false, retryAt);
718
849
  }
719
850
  throw error;
@@ -748,32 +879,1115 @@ function primConfigDirectory(options = {}) {
748
879
  return resolvePrimConfigDirectory(options).path;
749
880
  }
750
881
 
882
+ // src/lib/session-identity.ts
883
+ import { execFile } from "child_process";
884
+ import { createHash as createHash3 } from "crypto";
885
+ import { rmSync as rmSync4 } from "fs";
886
+ import { join as join6 } from "path";
887
+ import { promisify } from "util";
888
+
889
+ // src/lib/git.ts
890
+ import { execFileSync } from "child_process";
891
+ import { createHash as createHash2 } from "crypto";
892
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync } from "fs";
893
+ import { basename, dirname as dirname4, isAbsolute as isAbsolute3, join as join5, relative, resolve, sep } from "path";
894
+ var GIT_TIMEOUT_MS = 1e3;
895
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
896
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
897
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
898
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
899
+ function gitChildEnvironment(env = process.env) {
900
+ return Object.fromEntries(
901
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
902
+ );
903
+ }
904
+ function gitToplevel(cwd) {
905
+ try {
906
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
907
+ cwd,
908
+ encoding: "utf-8",
909
+ stdio: ["ignore", "pipe", "ignore"],
910
+ timeout: GIT_TIMEOUT_MS,
911
+ env: gitChildEnvironment()
912
+ }).trim();
913
+ } catch {
914
+ return null;
915
+ }
916
+ }
917
+ function gitValue(cwd, args) {
918
+ try {
919
+ const value = execFileSync("git", args, {
920
+ cwd,
921
+ encoding: "utf-8",
922
+ stdio: ["ignore", "pipe", "ignore"],
923
+ timeout: GIT_TIMEOUT_MS,
924
+ env: gitChildEnvironment()
925
+ }).trim();
926
+ return value || void 0;
927
+ } catch {
928
+ return void 0;
929
+ }
930
+ }
931
+ function currentBranch(cwd) {
932
+ return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
933
+ }
934
+ function parseGithubRepositoryName(path) {
935
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
936
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
937
+ return null;
938
+ }
939
+ return `${parts[0]}/${parts[1]}`;
940
+ }
941
+ function githubRepositoryFromRemote(remote) {
942
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
943
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
944
+ remote
945
+ );
946
+ const path = match?.[1] ?? match?.[2];
947
+ return path ? parseGithubRepositoryName(path) : null;
948
+ }
949
+ function checkoutSettingsText(repoRoot) {
950
+ const path = join5(repoRoot, ".claude", "settings.json");
951
+ try {
952
+ if (!lstatSync2(join5(repoRoot, ".claude")).isDirectory()) return null;
953
+ const stat = lstatSync2(path);
954
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
955
+ return readFileSync4(path, "utf8");
956
+ } catch {
957
+ return null;
958
+ }
959
+ }
960
+ function checkoutDeclaration(repoRoot, name) {
961
+ const text = checkoutSettingsText(repoRoot);
962
+ if (text === null) return null;
963
+ let parsed;
964
+ try {
965
+ parsed = JSON.parse(text);
966
+ } catch {
967
+ return null;
968
+ }
969
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
970
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
971
+ return typeof value === "string" ? value : null;
972
+ }
973
+ function declaredGithubRepository(repoRoot) {
974
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
975
+ return value === null ? null : parseGithubRepositoryName(value.trim());
976
+ }
977
+ function githubRepositoryFullName(cwd) {
978
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
979
+ if (remote) {
980
+ const fromOrigin = githubRepositoryFromRemote(remote);
981
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
982
+ }
983
+ const root = gitToplevel(cwd);
984
+ return root ? declaredGithubRepository(root) : null;
985
+ }
986
+ function normalizeOriginRemote(remote) {
987
+ const value = remote.trim();
988
+ if (!value) return void 0;
989
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
990
+ if (scp?.host && scp.path) {
991
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
992
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
993
+ }
994
+ try {
995
+ const url = new URL(value);
996
+ url.username = "";
997
+ url.password = "";
998
+ url.search = "";
999
+ url.hash = "";
1000
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1001
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1002
+ return void 0;
1003
+ } catch {
1004
+ return void 0;
1005
+ }
1006
+ }
1007
+
1008
+ // src/lib/terminal-safe.ts
1009
+ function replaceIsolatedSurrogates(value) {
1010
+ let out = "";
1011
+ for (let index = 0; index < value.length; index += 1) {
1012
+ const unit = value.charCodeAt(index);
1013
+ if (unit >= 55296 && unit <= 56319) {
1014
+ const next = value.charCodeAt(index + 1);
1015
+ if (next >= 56320 && next <= 57343) {
1016
+ out += value[index] + value[index + 1];
1017
+ index += 1;
1018
+ } else {
1019
+ out += "\uFFFD";
1020
+ }
1021
+ } else if (unit >= 56320 && unit <= 57343) {
1022
+ out += "\uFFFD";
1023
+ } else {
1024
+ out += value[index];
1025
+ }
1026
+ }
1027
+ return out;
1028
+ }
1029
+ function isUnsafeTerminalCodePoint(point) {
1030
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1031
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
1032
+ point === 1564 || // Arabic letter mark
1033
+ point === 6158 || // Mongolian vowel separator
1034
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
1035
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1036
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1037
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
1038
+ point === 65279 || // zero-width no-break space / BOM
1039
+ point >= 917504 && point <= 917631;
1040
+ return c0OrC1 || bidiOrZeroWidth;
1041
+ }
1042
+ function terminalSafeText(value) {
1043
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1044
+ }
1045
+ function terminalSafeLine(value) {
1046
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1047
+ }
1048
+ var stripControlChars = terminalSafeText;
1049
+
1050
+ // src/lib/session-identity.ts
1051
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
1052
+ var SESSION_IDENTITY_VALUE = "session";
1053
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
1054
+ var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
1055
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
1056
+ var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
1057
+ var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
1058
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
1059
+ var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
1060
+ var CHALLENGE_REUSE_MARGIN_MS = 3e4;
1061
+ var SESSION_IDENTITY_ROUTES = {
1062
+ challenge: "/api/cli/session-identity/challenge",
1063
+ token: "/api/cli/session-identity/token",
1064
+ refresh: "/api/cli/session-identity/token/refresh",
1065
+ link: "/api/cli/session-identity/link"
1066
+ };
1067
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
1068
+ var RENEW_BEFORE_MS = 6e4;
1069
+ var GIT_TIMEOUT_MS2 = 1e4;
1070
+ var POLL_BUDGET_MS = 15e3;
1071
+ var POLL_FIRST_DELAY_MS = 500;
1072
+ var POLL_MAX_DELAY_MS = 3e3;
1073
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
1074
+ var LOCK_TIMEOUT_MS = 6e4;
1075
+ var RESPONSE_MAX_BYTES = 64 * 1024;
1076
+ function sessionIdentityRequested(env = process.env) {
1077
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
1078
+ }
1079
+ function sessionIdentityMode(deps = {}) {
1080
+ const env = deps.env ?? process.env;
1081
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
1082
+ }
1083
+ function failure(code, cause, remedy) {
1084
+ return { status: "failed", code, cause, remedy };
1085
+ }
1086
+ var RETRY_REMEDY = "run `prim setup --cloud` to try again";
1087
+ var NEW_SESSION_REMEDY = "start a new cloud session";
1088
+ 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';
1089
+ var SESSION_REVOKED = failure(
1090
+ "session_revoked",
1091
+ "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",
1092
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
1093
+ );
1094
+ var CHALLENGE_WINDOW_PASSED = failure(
1095
+ "challenge_expired",
1096
+ "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)",
1097
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
1098
+ );
1099
+ var CHALLENGE_GONE = failure(
1100
+ "challenge_not_found",
1101
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
1102
+ NEW_SESSION_REMEDY
1103
+ );
1104
+ var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
1105
+ function rejectionFailure(reason, repository) {
1106
+ switch (reason) {
1107
+ case "identity_mismatch":
1108
+ return failure(
1109
+ "identity_mismatch",
1110
+ "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",
1111
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
1112
+ );
1113
+ case "push_after_expiry":
1114
+ return failure(
1115
+ "push_after_expiry",
1116
+ `GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
1117
+ `${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
1118
+ );
1119
+ case "repository_mismatch":
1120
+ return failure(
1121
+ "repository_mismatch",
1122
+ `Primitive received the identity push from a different repository than ${repository}`,
1123
+ `check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
1124
+ );
1125
+ case "conflicting_push":
1126
+ return failure(
1127
+ "conflicting_push",
1128
+ `more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
1129
+ NEW_SESSION_REMEDY
1130
+ );
1131
+ case "unsupported_sender":
1132
+ return failure(
1133
+ "unsupported_sender",
1134
+ `the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
1135
+ `check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
1136
+ );
1137
+ default:
1138
+ return failure(
1139
+ "challenge_rejected",
1140
+ `Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
1141
+ `${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
1142
+ );
1143
+ }
1144
+ }
1145
+ function sessionIdentityMessage(outcome) {
1146
+ if (outcome.status === "link_required")
1147
+ 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.`;
1148
+ return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
1149
+ }
1150
+ function hash(value) {
1151
+ return createHash3("sha256").update(value).digest("hex");
1152
+ }
1153
+ function sessionContext(deps) {
1154
+ const env = deps.env ?? process.env;
1155
+ const environment = environmentCredentials(deps);
1156
+ if (!environment)
1157
+ return failure(
1158
+ "environment_credential_missing",
1159
+ "the cloud environment has no environment credential",
1160
+ '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'
1161
+ );
1162
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
1163
+ if (!sessionId || !SESSION_ID.test(sessionId))
1164
+ return failure(
1165
+ "session_id_missing",
1166
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
1167
+ NEW_SESSION_REMEDY
1168
+ );
1169
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
1170
+ const directory = deps.directory ?? primConfigDirectory({ env });
1171
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
1172
+ return {
1173
+ directory,
1174
+ apiUrl,
1175
+ clientId: environment.clientId,
1176
+ generation: environment.generation,
1177
+ sessionId,
1178
+ tokenPath: join6(directory, `session_identity_${key}.json`),
1179
+ statePath: join6(directory, `session_identity_${key}.state.json`),
1180
+ lockPath: join6(directory, "session-identity.lock")
1181
+ };
1182
+ }
1183
+ function readRecord(path) {
1184
+ try {
1185
+ const value = readMachineMetadata(path);
1186
+ return value === void 0 ? void 0 : machineRecord(value);
1187
+ } catch {
1188
+ return void 0;
1189
+ }
1190
+ }
1191
+ function finiteNumber(value) {
1192
+ return typeof value === "number" && Number.isFinite(value);
1193
+ }
1194
+ function readToken(context) {
1195
+ const data = readRecord(context.tokenPath);
1196
+ 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))
1197
+ return void 0;
1198
+ const identity = data.identity;
1199
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
1200
+ return void 0;
1201
+ return data;
1202
+ }
1203
+ function readState(context) {
1204
+ const data = readRecord(context.statePath);
1205
+ if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
1206
+ return void 0;
1207
+ return data;
1208
+ }
1209
+ function writeToken(context, record) {
1210
+ prepareMachineMetadataDirectory(context.directory);
1211
+ writeMachineMetadata(context.tokenPath, record);
1212
+ rmSync4(context.statePath, { force: true });
1213
+ }
1214
+ function writeState(context, state) {
1215
+ try {
1216
+ prepareMachineMetadataDirectory(context.directory);
1217
+ writeMachineMetadata(context.statePath, { version: 1, ...state });
1218
+ } catch {
1219
+ }
1220
+ }
1221
+ function tokenValid(record, now = Date.now()) {
1222
+ return now < record.expiresAt - RENEW_BEFORE_MS;
1223
+ }
1224
+ function tokenFresh(record, now = Date.now()) {
1225
+ return tokenValid(record, now) && now < record.refreshAfter;
1226
+ }
1227
+ function toCredential(record) {
1228
+ return {
1229
+ issuer: record.issuer,
1230
+ audience: record.audience,
1231
+ ...record.identity,
1232
+ accessToken: record.accessToken,
1233
+ expiresAt: record.expiresAt,
1234
+ apiUrl: record.apiUrl,
1235
+ generation: record.generation,
1236
+ storage: "environment",
1237
+ session: {
1238
+ userId: record.userId,
1239
+ displayName: record.displayName,
1240
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1241
+ refreshAfter: record.refreshAfter
1242
+ }
1243
+ };
1244
+ }
1245
+ function identified(record, reused) {
1246
+ return {
1247
+ status: "ok",
1248
+ credential: toCredential(record),
1249
+ displayName: record.displayName,
1250
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
1251
+ reused
1252
+ };
1253
+ }
1254
+ function cachedSessionCredential(deps = {}) {
1255
+ if (!sessionIdentityMode(deps)) return void 0;
1256
+ let context;
1257
+ try {
1258
+ context = sessionContext(deps);
1259
+ } catch {
1260
+ return void 0;
1261
+ }
1262
+ if ("status" in context) return void 0;
1263
+ const record = readToken(context);
1264
+ return record && tokenValid(record) ? toCredential(record) : void 0;
1265
+ }
1266
+ function outcomeFromState(state) {
1267
+ if (state.status === "link_required" && state.githubLogin && state.challengeId)
1268
+ return {
1269
+ status: "link_required",
1270
+ githubLogin: state.githubLogin,
1271
+ challengeId: state.challengeId,
1272
+ challengeExpiresAt: state.challengeExpiresAt ?? 0
1273
+ };
1274
+ return failure(
1275
+ state.code,
1276
+ state.cause ?? "the last identity check failed",
1277
+ state.remedy ?? RETRY_REMEDY
1278
+ );
1279
+ }
1280
+ function parseInstant(value) {
1281
+ if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
1282
+ if (typeof value === "string" && value.length <= 64) {
1283
+ const parsed = Date.parse(value);
1284
+ return Number.isFinite(parsed) ? parsed : void 0;
1285
+ }
1286
+ return void 0;
1287
+ }
1288
+ async function sendJson(url, init, fetchImpl) {
1289
+ const response = await fetchImpl(url, { ...init, redirect: "error" });
1290
+ let value;
1291
+ try {
1292
+ const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
1293
+ value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
1294
+ } catch {
1295
+ value = void 0;
1296
+ }
1297
+ return { status: response.status, value };
1298
+ }
1299
+ function environmentOnly(deps) {
1300
+ return { ...deps, environmentOnly: true };
1301
+ }
1302
+ async function environmentRequest(method, path, body, deps, signal) {
1303
+ const send = async (credential2) => {
1304
+ const headers = { "Content-Type": "application/json" };
1305
+ const text = body === void 0 ? void 0 : JSON.stringify(body);
1306
+ if (credential2.tokenInjection) {
1307
+ const response = await forwardMachineRequest(
1308
+ { method, path, headers, ...text === void 0 ? {} : { body: text } },
1309
+ signal,
1310
+ environmentOnly(deps)
1311
+ );
1312
+ const parsed = await response.json().catch(() => void 0);
1313
+ return {
1314
+ status: response.status,
1315
+ value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
1316
+ };
1317
+ }
1318
+ return sendJson(
1319
+ `${credential2.apiUrl}${path}`,
1320
+ {
1321
+ method,
1322
+ headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
1323
+ ...text === void 0 ? {} : { body: text },
1324
+ signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
1325
+ },
1326
+ deps.fetch ?? fetch
1327
+ );
1328
+ };
1329
+ let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
1330
+ if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
1331
+ let answer = await send(credential);
1332
+ if (answer.status === 401) {
1333
+ credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
1334
+ if (!credential)
1335
+ throw new MachineAuthError("identity_unavailable", "No environment credential.");
1336
+ answer = await send(credential);
1337
+ }
1338
+ return answer;
1339
+ }
1340
+ function environmentFailure(error, apiUrl) {
1341
+ if (error instanceof MachineAuthError && error.terminal)
1342
+ return failure(
1343
+ "environment_credential_rejected",
1344
+ "Primitive rejected the cloud environment's credential",
1345
+ ENVIRONMENT_CREDENTIAL_REMEDY
1346
+ );
1347
+ const host = (() => {
1348
+ try {
1349
+ return new URL(apiUrl).hostname;
1350
+ } catch {
1351
+ return "Primitive";
1352
+ }
1353
+ })();
1354
+ return failure(
1355
+ "identity_unavailable",
1356
+ `Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
1357
+ `check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
1358
+ );
1359
+ }
1360
+ function answerError(answer) {
1361
+ return typeof answer.value?.error === "string" ? answer.value.error : void 0;
1362
+ }
1363
+ async function git(root, args, signal) {
1364
+ try {
1365
+ const { stdout, stderr } = await promisify(execFile)("git", args, {
1366
+ cwd: root,
1367
+ encoding: "utf8",
1368
+ timeout: GIT_TIMEOUT_MS2,
1369
+ signal,
1370
+ env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
1371
+ maxBuffer: 1024 * 1024
1372
+ });
1373
+ return { ok: true, code: 0, stdout, stderr, timedOut: false };
1374
+ } catch (error) {
1375
+ const failed = error;
1376
+ return {
1377
+ ok: false,
1378
+ code: typeof failed.code === "number" ? failed.code : void 0,
1379
+ stdout: failed.stdout ?? "",
1380
+ stderr: failed.stderr ?? "",
1381
+ timedOut: failed.killed === true || failed.signal === "SIGTERM"
1382
+ };
1383
+ }
1384
+ }
1385
+ function gitDetail(stderr) {
1386
+ const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
1387
+ return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
1388
+ }
1389
+ async function defaultSleep2(milliseconds, signal) {
1390
+ await new Promise((resolve3, reject) => {
1391
+ const timer = setTimeout(resolve3, milliseconds);
1392
+ signal?.addEventListener(
1393
+ "abort",
1394
+ () => {
1395
+ clearTimeout(timer);
1396
+ reject(signal.reason);
1397
+ },
1398
+ { once: true }
1399
+ );
1400
+ });
1401
+ }
1402
+ async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
1403
+ const sleep = deps.sleep ?? defaultSleep2;
1404
+ const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
1405
+ let delay = POLL_FIRST_DELAY_MS;
1406
+ let unreachable;
1407
+ for (; ; ) {
1408
+ const remaining = deadline - Date.now();
1409
+ if (remaining <= 0) break;
1410
+ await sleep(Math.min(delay, remaining), signal);
1411
+ delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
1412
+ let answer;
1413
+ try {
1414
+ answer = await environmentRequest(
1415
+ "GET",
1416
+ `${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
1417
+ void 0,
1418
+ deps,
1419
+ signal
1420
+ );
1421
+ } catch (error) {
1422
+ signal?.throwIfAborted();
1423
+ unreachable = error;
1424
+ continue;
1425
+ }
1426
+ if (answer.status === 404) return CHALLENGE_GONE;
1427
+ if (answer.status === 401 || answer.status === 403)
1428
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
1429
+ if (answer.status < 200 || answer.status > 299) {
1430
+ unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
1431
+ continue;
1432
+ }
1433
+ unreachable = void 0;
1434
+ const status = answer.value;
1435
+ if (status?.status === "verified")
1436
+ return {
1437
+ ...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
1438
+ };
1439
+ if (status?.status === "expired")
1440
+ return failure(
1441
+ "challenge_expired",
1442
+ `the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
1443
+ NEW_SESSION_REMEDY
1444
+ );
1445
+ if (status?.status === "rejected")
1446
+ return rejectionFailure(status.reason, repository);
1447
+ }
1448
+ if (unreachable) return environmentFailure(unreachable, apiUrl);
1449
+ return failure(
1450
+ "webhook_timeout",
1451
+ `GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
1452
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1453
+ );
1454
+ }
1455
+ function parseTokenAnswer(value) {
1456
+ if (!value) return void 0;
1457
+ const user = value.user;
1458
+ const expiresAt = parseInstant(value.expiresAt);
1459
+ const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
1460
+ 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))
1461
+ return void 0;
1462
+ return {
1463
+ accessToken: value.accessToken,
1464
+ expiresAt,
1465
+ refreshAfter: Math.min(refreshAfter, expiresAt),
1466
+ userId: user.id,
1467
+ displayName: user.displayName,
1468
+ organizationId: value.organizationId
1469
+ };
1470
+ }
1471
+ var SERVER_CONTRACT_FAILURE = failure(
1472
+ "server_contract",
1473
+ "Primitive's answer did not identify the linked member",
1474
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
1475
+ );
1476
+ async function recordFor(context, answer, extra, deps, signal) {
1477
+ let identity;
1478
+ let environment;
1479
+ try {
1480
+ environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
1481
+ identity = await verifyMachineIdentity(
1482
+ context.apiUrl,
1483
+ answer.accessToken,
1484
+ context.clientId,
1485
+ signal,
1486
+ deps.fetch
1487
+ );
1488
+ } catch (error) {
1489
+ if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
1490
+ return SERVER_CONTRACT_FAILURE;
1491
+ return environmentFailure(error, context.apiUrl);
1492
+ }
1493
+ if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
1494
+ return SERVER_CONTRACT_FAILURE;
1495
+ return {
1496
+ version: 1,
1497
+ apiUrl: context.apiUrl,
1498
+ clientId: context.clientId,
1499
+ generation: context.generation,
1500
+ sessionId: context.sessionId,
1501
+ issuer: environment.issuer,
1502
+ audience: environment.audience,
1503
+ accessToken: answer.accessToken,
1504
+ expiresAt: answer.expiresAt,
1505
+ refreshAfter: answer.refreshAfter,
1506
+ userId: answer.userId,
1507
+ displayName: answer.displayName,
1508
+ organizationId: answer.organizationId,
1509
+ ...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
1510
+ identity,
1511
+ ...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
1512
+ };
1513
+ }
1514
+ async function refreshToken(context, record, deps, signal) {
1515
+ let answer;
1516
+ try {
1517
+ answer = await environmentRequest(
1518
+ "POST",
1519
+ SESSION_IDENTITY_ROUTES.refresh,
1520
+ { accessToken: record.accessToken },
1521
+ deps,
1522
+ signal
1523
+ );
1524
+ } catch (error) {
1525
+ signal?.throwIfAborted();
1526
+ return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
1527
+ }
1528
+ const code = answerError(answer);
1529
+ if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
1530
+ return { status: "refused", failure: SESSION_REVOKED };
1531
+ if (answer.status === 401 || answer.status === 403)
1532
+ return {
1533
+ status: "refused",
1534
+ failure: environmentFailure(
1535
+ new MachineAuthError("rejected", "rejected", true),
1536
+ context.apiUrl
1537
+ )
1538
+ };
1539
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1540
+ if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
1541
+ return { status: "unavailable" };
1542
+ return {
1543
+ status: "ok",
1544
+ record: {
1545
+ ...record,
1546
+ accessToken: token.accessToken,
1547
+ expiresAt: token.expiresAt,
1548
+ refreshAfter: token.refreshAfter,
1549
+ displayName: token.displayName
1550
+ }
1551
+ };
1552
+ }
1553
+ function exchangeRefusal(answer, repository) {
1554
+ if (answer.status === 404) return CHALLENGE_GONE;
1555
+ if (answer.status !== 409) return void 0;
1556
+ switch (answerError(answer)) {
1557
+ case "identity_mismatch":
1558
+ return rejectionFailure("identity_mismatch", repository);
1559
+ case "challenge_rejected":
1560
+ return rejectionFailure(answer.value?.reason, repository);
1561
+ case "challenge_expired":
1562
+ return CHALLENGE_WINDOW_PASSED;
1563
+ case "challenge_already_exchanged":
1564
+ return failure(
1565
+ "challenge_already_exchanged",
1566
+ "this session's identity check was already exchanged for a token this VM does not hold",
1567
+ NEW_SESSION_REMEDY
1568
+ );
1569
+ case "challenge_pending":
1570
+ return failure(
1571
+ "webhook_timeout",
1572
+ `GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
1573
+ `check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
1574
+ );
1575
+ default:
1576
+ return void 0;
1577
+ }
1578
+ }
1579
+ async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
1580
+ let answer;
1581
+ try {
1582
+ answer = await environmentRequest(
1583
+ "POST",
1584
+ SESSION_IDENTITY_ROUTES.token,
1585
+ { challengeId: challenge.challengeId },
1586
+ deps,
1587
+ signal
1588
+ );
1589
+ } catch (error) {
1590
+ signal?.throwIfAborted();
1591
+ return environmentFailure(error, context.apiUrl);
1592
+ }
1593
+ if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
1594
+ const login = answer.value?.githubLogin;
1595
+ return {
1596
+ status: "link_required",
1597
+ githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
1598
+ challengeId: challenge.challengeId,
1599
+ challengeExpiresAt: challenge.challengeExpiresAt
1600
+ };
1601
+ }
1602
+ const refused = exchangeRefusal(
1603
+ answer,
1604
+ repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
1605
+ );
1606
+ if (refused) return refused;
1607
+ const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
1608
+ if (!token) {
1609
+ if (answer.status === 401 || answer.status === 403)
1610
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1611
+ return answer.status >= 500 ? environmentFailure(
1612
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1613
+ context.apiUrl
1614
+ ) : SERVER_CONTRACT_FAILURE;
1615
+ }
1616
+ return recordFor(
1617
+ context,
1618
+ token,
1619
+ { githubLogin: challenge.githubLogin, repositoryRoot },
1620
+ deps,
1621
+ signal
1622
+ );
1623
+ }
1624
+ async function challengeAndPush(context, root, previous, deps, attempt, signal) {
1625
+ const env = deps.env ?? process.env;
1626
+ const repository = githubRepositoryFullName(root);
1627
+ if (!repository)
1628
+ return failure(
1629
+ "repository_unidentified",
1630
+ "this checkout does not name its GitHub repository",
1631
+ "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"
1632
+ );
1633
+ const branch = currentBranch(root);
1634
+ if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
1635
+ return failure(
1636
+ "not_session_branch",
1637
+ `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`,
1638
+ `${NEW_SESSION_REMEDY} and let it identify you before switching branches`
1639
+ );
1640
+ attempt.branch = branch;
1641
+ let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
1642
+ if (!baseSha) {
1643
+ const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
1644
+ baseSha = head.stdout.trim();
1645
+ if (!head.ok || !SHA.test(baseSha))
1646
+ return failure(
1647
+ "no_commit",
1648
+ "this checkout has no commit to create the session branch at",
1649
+ NEW_SESSION_REMEDY
1650
+ );
1651
+ }
1652
+ const published = await git(
1653
+ root,
1654
+ [
1655
+ "for-each-ref",
1656
+ "--count=1",
1657
+ "--format=%(refname)",
1658
+ "--contains",
1659
+ baseSha,
1660
+ "refs/remotes/origin/"
1661
+ ],
1662
+ signal
1663
+ );
1664
+ if (!published.ok || published.stdout.trim() === "")
1665
+ return failure(
1666
+ "unpublished_commits",
1667
+ `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`,
1668
+ `${NEW_SESSION_REMEDY} and let it identify you before committing`
1669
+ );
1670
+ attempt.baseSha = baseSha;
1671
+ const remote = await git(
1672
+ root,
1673
+ ["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
1674
+ signal
1675
+ );
1676
+ const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
1677
+ if (remote.ok && recorded) {
1678
+ Object.assign(attempt, recorded);
1679
+ return { ...recorded, repository };
1680
+ }
1681
+ if (remote.ok)
1682
+ return failure(
1683
+ "branch_exists",
1684
+ `the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
1685
+ NEW_SESSION_REMEDY
1686
+ );
1687
+ if (remote.code !== 2)
1688
+ return failure(
1689
+ remote.timedOut ? "push_timeout" : "remote_unavailable",
1690
+ `prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
1691
+ `check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
1692
+ );
1693
+ if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
1694
+ Object.assign(attempt, recorded);
1695
+ return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
1696
+ }
1697
+ let answer;
1698
+ try {
1699
+ const email = env[USER_EMAIL_VARIABLE]?.trim();
1700
+ answer = await environmentRequest(
1701
+ "POST",
1702
+ SESSION_IDENTITY_ROUTES.challenge,
1703
+ {
1704
+ repositoryFullName: repository,
1705
+ claudeSessionId: context.sessionId,
1706
+ branch,
1707
+ baseSha,
1708
+ // Only a cross-check: one Primitive would refuse is left out, not sent.
1709
+ ...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
1710
+ },
1711
+ deps,
1712
+ signal
1713
+ );
1714
+ } catch (error) {
1715
+ signal?.throwIfAborted();
1716
+ return environmentFailure(error, context.apiUrl);
1717
+ }
1718
+ if (answer.status === 404 && answerError(answer) === "repository_not_connected")
1719
+ return failure(
1720
+ "repository_not_connected",
1721
+ `${repository} is not connected to Primitive`,
1722
+ CLOUD_GITHUB_CONNECT_REMEDY
1723
+ );
1724
+ if (answer.status === 401 || answer.status === 403)
1725
+ return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
1726
+ if (answer.status === 409 && answerError(answer) === "challenge_already_open")
1727
+ return failure(
1728
+ "challenge_open",
1729
+ `an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
1730
+ `wait five minutes, then ${RETRY_REMEDY}`
1731
+ );
1732
+ if (answer.status === 429)
1733
+ return failure(
1734
+ "too_many_challenges",
1735
+ "too many sessions of this cloud environment are being identified at once",
1736
+ `wait a few minutes, then ${RETRY_REMEDY}`
1737
+ );
1738
+ const challengeId = answer.value?.challengeId;
1739
+ const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
1740
+ if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
1741
+ return answer.status >= 500 ? environmentFailure(
1742
+ new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
1743
+ context.apiUrl
1744
+ ) : SERVER_CONTRACT_FAILURE;
1745
+ if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
1746
+ attempt.challengeId = challengeId;
1747
+ attempt.challengeExpiresAt = challengeExpiresAt;
1748
+ return pushSessionBranch(
1749
+ root,
1750
+ repository,
1751
+ branch,
1752
+ baseSha,
1753
+ { challengeId, challengeExpiresAt },
1754
+ signal
1755
+ );
1756
+ }
1757
+ async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
1758
+ const push = await git(
1759
+ root,
1760
+ [
1761
+ "-c",
1762
+ "core.hooksPath=/dev/null",
1763
+ "-c",
1764
+ "push.followTags=false",
1765
+ "-c",
1766
+ "push.recurseSubmodules=no",
1767
+ "-c",
1768
+ "push.gpgSign=false",
1769
+ "-c",
1770
+ "push.pushOption=",
1771
+ "push",
1772
+ "--no-verify",
1773
+ "--no-follow-tags",
1774
+ "--no-recurse-submodules",
1775
+ "--no-signed",
1776
+ "--quiet",
1777
+ "origin",
1778
+ `${baseSha}:refs/heads/${branch}`
1779
+ ],
1780
+ signal
1781
+ );
1782
+ if (!push.ok)
1783
+ return push.timedOut ? failure(
1784
+ "push_timeout",
1785
+ `creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
1786
+ `check the session's network access to GitHub, then ${RETRY_REMEDY}`
1787
+ ) : failure(
1788
+ "push_refused",
1789
+ `creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
1790
+ `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}`
1791
+ );
1792
+ return { ...challenge, repository };
1793
+ }
1794
+ async function ensureSessionIdentity(options = {}, deps = {}) {
1795
+ let context;
1796
+ try {
1797
+ context = sessionContext(deps);
1798
+ } catch (error) {
1799
+ return failure(
1800
+ "environment_credential_invalid",
1801
+ error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
1802
+ "correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
1803
+ );
1804
+ }
1805
+ if ("status" in context) return context;
1806
+ const ctx = context;
1807
+ const startedAt2 = Date.now();
1808
+ prepareMachineMetadataDirectory(ctx.directory);
1809
+ return withFileLock(
1810
+ ctx.lockPath,
1811
+ async () => {
1812
+ const record = readToken(ctx);
1813
+ const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
1814
+ if (record && !forced && tokenFresh(record)) return identified(record, true);
1815
+ if (record) {
1816
+ const refreshed = await refreshToken(ctx, record, deps, options.signal);
1817
+ if (refreshed.status === "ok") {
1818
+ writeToken(ctx, refreshed.record);
1819
+ return identified(refreshed.record, true);
1820
+ }
1821
+ if (refreshed.status === "refused") {
1822
+ rmSync4(ctx.tokenPath, { force: true });
1823
+ writeState(ctx, {
1824
+ sessionId: ctx.sessionId,
1825
+ status: "failed",
1826
+ code: refreshed.failure.code,
1827
+ cause: refreshed.failure.cause,
1828
+ remedy: refreshed.failure.remedy,
1829
+ ...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
1830
+ at: Date.now()
1831
+ });
1832
+ return refreshed.failure;
1833
+ }
1834
+ if (!forced && tokenValid(record)) return identified(record, true);
1835
+ }
1836
+ const state = readState(ctx);
1837
+ if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
1838
+ const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
1839
+ if (!options.explicit) {
1840
+ if (!root || !(record || state))
1841
+ return failure(
1842
+ "not_identified",
1843
+ "this session has not identified who started it yet",
1844
+ RETRY_REMEDY
1845
+ );
1846
+ if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
1847
+ } else if (state && state.at >= startedAt2) {
1848
+ return outcomeFromState(state);
1849
+ }
1850
+ if (!root)
1851
+ return failure(
1852
+ "repository_missing",
1853
+ "this is not a git repository",
1854
+ "run it in the repository the session cloned"
1855
+ );
1856
+ const attempt = { root };
1857
+ const remember = (outcome) => {
1858
+ writeState(ctx, {
1859
+ sessionId: ctx.sessionId,
1860
+ status: outcome.status,
1861
+ code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
1862
+ ...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
1863
+ githubLogin: outcome.githubLogin
1864
+ },
1865
+ challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
1866
+ challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
1867
+ repositoryRoot: root,
1868
+ branch: attempt.branch ?? state?.branch,
1869
+ baseSha: attempt.baseSha ?? state?.baseSha,
1870
+ at: Date.now()
1871
+ });
1872
+ return outcome;
1873
+ };
1874
+ let challenge;
1875
+ if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
1876
+ attempt.challengeId = state.challengeId;
1877
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
1878
+ attempt.branch = state.branch;
1879
+ attempt.baseSha = state.baseSha;
1880
+ challenge = {
1881
+ challengeId: state.challengeId,
1882
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
1883
+ repository: githubRepositoryFullName(root) ?? "the repository"
1884
+ };
1885
+ } else if (state?.status === "link_required" && state.challengeId) {
1886
+ attempt.challengeId = state.challengeId;
1887
+ attempt.challengeExpiresAt = state.challengeExpiresAt;
1888
+ const exchanged2 = await exchangeChallenge(
1889
+ ctx,
1890
+ {
1891
+ challengeId: state.challengeId,
1892
+ challengeExpiresAt: state.challengeExpiresAt ?? 0,
1893
+ githubLogin: state.githubLogin
1894
+ },
1895
+ root,
1896
+ deps,
1897
+ options.signal
1898
+ );
1899
+ if ("status" in exchanged2) return remember(exchanged2);
1900
+ writeToken(ctx, exchanged2);
1901
+ return identified(exchanged2, false);
1902
+ } else if (!options.explicit) {
1903
+ return state ? outcomeFromState(state) : failure(
1904
+ "not_identified",
1905
+ "this session has not identified who started it yet",
1906
+ RETRY_REMEDY
1907
+ );
1908
+ } else {
1909
+ const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
1910
+ if ("status" in pushed) return remember(pushed);
1911
+ challenge = pushed;
1912
+ }
1913
+ const verified = await pollChallenge(
1914
+ ctx.apiUrl,
1915
+ challenge.challengeId,
1916
+ challenge.repository,
1917
+ // A hook process waits only briefly for a late notice.
1918
+ options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
1919
+ options.signal
1920
+ );
1921
+ if ("status" in verified) return remember(verified);
1922
+ const exchanged = await exchangeChallenge(
1923
+ ctx,
1924
+ { ...challenge, githubLogin: verified.githubLogin },
1925
+ root,
1926
+ deps,
1927
+ options.signal
1928
+ );
1929
+ if ("status" in exchanged) return remember(exchanged);
1930
+ writeToken(ctx, exchanged);
1931
+ return identified(exchanged, false);
1932
+ },
1933
+ { signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
1934
+ );
1935
+ }
1936
+ async function acquireSessionCredential(options = {}, deps = {}) {
1937
+ const cached2 = cachedSessionCredential(deps);
1938
+ const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
1939
+ if (cached2 && fresh && !options.force) return cached2;
1940
+ const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1941
+ let outcome;
1942
+ try {
1943
+ outcome = await ensureSessionIdentity(
1944
+ { force: options.force, observedToken: cached2?.accessToken, signal },
1945
+ deps
1946
+ );
1947
+ } catch (error) {
1948
+ options.signal?.throwIfAborted();
1949
+ if (error instanceof MachineAuthError) throw error;
1950
+ throw new MachineAuthError(
1951
+ "identity_unavailable",
1952
+ "Identifying who started this cloud session is still in progress; retry shortly."
1953
+ );
1954
+ }
1955
+ if (outcome.status === "ok") return outcome.credential;
1956
+ throw new MachineAuthError(
1957
+ outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
1958
+ sessionIdentityMessage(outcome)
1959
+ );
1960
+ }
1961
+
751
1962
  // src/lib/machine-credentials.ts
1963
+ function sessionScoped(deps) {
1964
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
1965
+ }
752
1966
  var require2 = createRequire(import.meta.url);
753
1967
  var SERVICE = "ai.primitive.prim.machine";
754
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
1968
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
755
1969
  var PROFILE_FILE = "machine_profile.json";
756
- var RENEW_BEFORE_MS = 6e4;
1970
+ var RENEW_BEFORE_MS2 = 6e4;
757
1971
  var cached;
758
1972
  function configurationDirectory(deps) {
759
1973
  return deps.directory ?? primConfigDirectory({ env: deps.env });
760
1974
  }
761
1975
  function apiUrlFor(deps) {
762
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
1976
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
763
1977
  }
764
- function hash(value) {
765
- return createHash2("sha256").update(value).digest("hex");
1978
+ function hash2(value) {
1979
+ return createHash4("sha256").update(value).digest("hex");
766
1980
  }
767
1981
  function recordPath(directory, generation) {
768
- return join5(directory, `machine_${generation}.json`);
1982
+ return join7(directory, `machine_${generation}.json`);
769
1983
  }
770
1984
  function storageKey(directory, generation) {
771
- return `${hash(directory)}:${generation}`;
1985
+ return `${hash2(directory)}:${generation}`;
772
1986
  }
773
1987
  function environmentContextPath(deps, clientId) {
774
- return join5(
1988
+ return join7(
775
1989
  configurationDirectory(deps),
776
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
1990
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
777
1991
  );
778
1992
  }
779
1993
  function writeEnvironmentContext(credential, deps) {
@@ -832,14 +2046,14 @@ function readEnvironmentContext(environment, deps) {
832
2046
  }
833
2047
  }
834
2048
  function keyringEntry(key) {
835
- let directory = dirname4(fileURLToPath2(import.meta.url));
2049
+ let directory = dirname5(fileURLToPath2(import.meta.url));
836
2050
  for (let depth = 0; depth < 5; depth++) {
837
- const loader = join5(directory, "native", "keyring.cjs");
2051
+ const loader = join7(directory, "native", "keyring.cjs");
838
2052
  if (existsSync3(loader)) {
839
2053
  const module2 = require2(loader);
840
2054
  return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
841
2055
  }
842
- directory = dirname4(directory);
2056
+ directory = dirname5(directory);
843
2057
  }
844
2058
  const module = require2("@napi-rs/keyring");
845
2059
  return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
@@ -851,7 +2065,7 @@ function protectPath(path, directory) {
851
2065
  }
852
2066
  const encodedPath = Buffer.from(path).toString("base64");
853
2067
  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)`;
854
- execFileSync(
2068
+ execFileSync2(
855
2069
  "powershell.exe",
856
2070
  [
857
2071
  "-NoProfile",
@@ -864,7 +2078,7 @@ function protectPath(path, directory) {
864
2078
  }
865
2079
  function ensureDirectory(directory) {
866
2080
  mkdirSync3(directory, { recursive: true, mode: 448 });
867
- if (lstatSync2(directory).isSymbolicLink())
2081
+ if (lstatSync3(directory).isSymbolicLink())
868
2082
  throw new MachineAuthError(
869
2083
  "unsafe_storage",
870
2084
  "Credential directory must not be a symbolic link."
@@ -876,17 +2090,20 @@ function writePrivate(path, value) {
876
2090
  `, { mode: 384 });
877
2091
  protectPath(path, false);
878
2092
  }
2093
+ function readMachineMetadata(path) {
2094
+ return readPrivate(path);
2095
+ }
879
2096
  function readPrivate(path) {
880
2097
  let raw;
881
2098
  try {
882
- const stat = lstatSync2(path);
2099
+ const stat = lstatSync3(path);
883
2100
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
884
2101
  throw new MachineAuthError(
885
2102
  "unsafe_storage",
886
2103
  "Machine credential files must be owner-only regular files."
887
2104
  );
888
2105
  }
889
- raw = readFileSync4(path, "utf8");
2106
+ raw = readFileSync5(path, "utf8");
890
2107
  } catch (error) {
891
2108
  if (error.code === "ENOENT") return void 0;
892
2109
  throw error;
@@ -931,13 +2148,101 @@ function parseProfile(value) {
931
2148
  };
932
2149
  }
933
2150
  function readMachineProfile(deps = {}) {
934
- const value = readPrivate(join5(configurationDirectory(deps), PROFILE_FILE));
2151
+ const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
935
2152
  return value === void 0 ? void 0 : parseProfile(value);
936
2153
  }
2154
+ var NETWORK_SECRET_AUTH = "network-secret";
2155
+ var NETWORK_TOKEN_AUTH = "network-token";
2156
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
2157
+ var brokerKeys = /* @__PURE__ */ new Map();
2158
+ function networkSecretBrokerKey(deps, clientId) {
2159
+ const directory = configurationDirectory(deps);
2160
+ const path = join7(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
2161
+ const known = brokerKeys.get(path);
2162
+ if (known) return known;
2163
+ ensureDirectory(directory);
2164
+ const read = () => {
2165
+ try {
2166
+ const stat = lstatSync3(path);
2167
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
2168
+ throw new MachineAuthError(
2169
+ "unsafe_storage",
2170
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
2171
+ true
2172
+ );
2173
+ const value = readFileSync5(path, "utf8").trim();
2174
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
2175
+ } catch (error) {
2176
+ if (error.code === "ENOENT") return void 0;
2177
+ throw error;
2178
+ }
2179
+ };
2180
+ for (let attempt = 0; attempt < 2; attempt += 1) {
2181
+ const existing = read();
2182
+ if (existing?.key) {
2183
+ brokerKeys.set(path, existing.key);
2184
+ return existing.key;
2185
+ }
2186
+ if (existing)
2187
+ throw new MachineAuthError(
2188
+ "unsafe_storage",
2189
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
2190
+ true
2191
+ );
2192
+ const staged = `${path}.${process.pid}.${randomBytes2(6).toString("hex")}`;
2193
+ try {
2194
+ writeFileSync3(staged, `${randomBytes2(32).toString("hex")}
2195
+ `, { mode: 384, flag: "wx" });
2196
+ protectPath(staged, false);
2197
+ linkSync(staged, path);
2198
+ } catch (error) {
2199
+ if (error.code !== "EEXIST") throw error;
2200
+ } finally {
2201
+ rmSync5(staged, { force: true });
2202
+ }
2203
+ }
2204
+ const key = read()?.key;
2205
+ if (!key)
2206
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
2207
+ brokerKeys.set(path, key);
2208
+ return key;
2209
+ }
937
2210
  function environmentCredentials(deps) {
938
2211
  const env = deps.env ?? process.env;
939
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
940
- if (clientId === void 0 && clientSecret === void 0) return void 0;
2212
+ const {
2213
+ PRIM_M2M_CLIENT_ID: clientId,
2214
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
2215
+ PRIM_M2M_CLIENT_AUTH: auth
2216
+ } = env;
2217
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
2218
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
2219
+ throw new MachineAuthError(
2220
+ "incomplete_machine_credentials",
2221
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
2222
+ );
2223
+ if (auth !== void 0) {
2224
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
2225
+ throw new MachineAuthError(
2226
+ "incomplete_machine_credentials",
2227
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
2228
+ );
2229
+ if (clientSecret !== void 0)
2230
+ throw new MachineAuthError(
2231
+ "conflicting_credentials",
2232
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
2233
+ );
2234
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
2235
+ const credentials = {
2236
+ clientId,
2237
+ generation,
2238
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
2239
+ };
2240
+ Object.defineProperty(credentials, "clientSecret", {
2241
+ enumerable: true,
2242
+ get: () => networkSecretBrokerKey(deps, clientId)
2243
+ });
2244
+ return credentials;
2245
+ }
941
2246
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
942
2247
  throw new MachineAuthError(
943
2248
  "incomplete_machine_credentials",
@@ -947,12 +2252,12 @@ function environmentCredentials(deps) {
947
2252
  return {
948
2253
  clientId,
949
2254
  clientSecret,
950
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
2255
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
951
2256
  };
952
2257
  }
953
2258
  function hasMachineConfiguration(deps = {}) {
954
2259
  const env = deps.env ?? process.env;
955
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join5(configurationDirectory(deps), PROFILE_FILE));
2260
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join7(configurationDirectory(deps), PROFILE_FILE));
956
2261
  if (configured && env.PRIM_TOKEN?.trim()) {
957
2262
  throw new MachineAuthError(
958
2263
  "conflicting_credentials",
@@ -964,6 +2269,7 @@ function hasMachineConfiguration(deps = {}) {
964
2269
  }
965
2270
  function machineContext(deps = {}) {
966
2271
  if (!hasMachineConfiguration(deps)) return void 0;
2272
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
967
2273
  const environment = environmentCredentials(deps);
968
2274
  if (environment) {
969
2275
  if (environmentTerminal === environment.generation) return void 0;
@@ -978,6 +2284,7 @@ function machineContext(deps = {}) {
978
2284
  return profile;
979
2285
  }
980
2286
  function cachedMachineCredential(deps = {}) {
2287
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
981
2288
  const context = machineContext(deps);
982
2289
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
983
2290
  }
@@ -986,9 +2293,11 @@ function machineSessionEnded(deps = {}) {
986
2293
  const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
987
2294
  if (!generation) return false;
988
2295
  if (environmentCredentials(deps)) return environmentTerminal === generation;
989
- return readPrivate(join5(configurationDirectory(deps), "machine_terminal.json")) === generation;
2296
+ return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
990
2297
  }
991
2298
  var environmentTerminal;
2299
+ var NETWORK_REJECTION_PAUSE_MS = 3e4;
2300
+ var networkRejection;
992
2301
  async function loadRecord(profile, deps, signal) {
993
2302
  const directory = configurationDirectory(deps);
994
2303
  let value;
@@ -1048,10 +2357,12 @@ async function persistRecord(record, deps, signal) {
1048
2357
  }
1049
2358
  async function acquireMachineCredential(options = {}, deps = {}) {
1050
2359
  if (!hasMachineConfiguration(deps)) return void 0;
2360
+ if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
1051
2361
  const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
1052
2362
  const apiUrl = apiUrlFor(deps);
1053
2363
  const environment = environmentCredentials(deps);
1054
2364
  if (environment) {
2365
+ const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
1055
2366
  const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
1056
2367
  const directory2 = configurationDirectory(deps);
1057
2368
  ensureDirectory(directory2);
@@ -1069,22 +2380,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1069
2380
  writeEnvironmentContext(cached, deps);
1070
2381
  return cached;
1071
2382
  } catch (error) {
1072
- if (error instanceof MachineAuthError && error.terminal)
2383
+ if (error instanceof MachineAuthError && error.terminal && !networkManaged)
1073
2384
  environmentTerminal = environment.generation;
1074
2385
  throw error;
1075
2386
  }
1076
2387
  }
1077
2388
  return withFileLock(
1078
- join5(directory2, "credentials.lock"),
2389
+ join7(directory2, "credentials.lock"),
1079
2390
  async () => {
1080
2391
  if (machineSessionEnded(deps))
1081
2392
  throw new MachineAuthError(
1082
2393
  "machine_credentials_rejected",
1083
- "Rotate the injected machine credentials.",
2394
+ rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
1084
2395
  true
1085
2396
  );
1086
- if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
2397
+ if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
1087
2398
  return cached;
2399
+ if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
2400
+ throw networkRejection.error;
1088
2401
  try {
1089
2402
  const { configuration, tokens, identity } = await withMachineCooldown(
1090
2403
  directory2,
@@ -1093,13 +2406,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1093
2406
  signal,
1094
2407
  async () => {
1095
2408
  const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
2409
+ if (environment.tokenInjection) {
2410
+ const identity3 = await verifyInjectedMachineIdentity(
2411
+ apiUrl,
2412
+ environment.clientId,
2413
+ signal,
2414
+ deps.fetch
2415
+ );
2416
+ const tokens3 = {
2417
+ accessToken: "",
2418
+ expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
2419
+ };
2420
+ return { configuration: configuration2, tokens: tokens3, identity: identity3 };
2421
+ }
1096
2422
  const tokens2 = await exchangeMachineCredentials(
1097
2423
  configuration2,
1098
2424
  environment.clientId,
1099
- environment.clientSecret,
2425
+ // The broker key is not a client secret; the proxy supplies that.
2426
+ environment.secretInjection ? "" : environment.clientSecret,
1100
2427
  signal,
1101
- deps.fetch
1102
- );
2428
+ deps.fetch,
2429
+ { secretInjection: environment.secretInjection }
2430
+ ).catch((error) => {
2431
+ if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
2432
+ throw new MachineAuthError(
2433
+ "network_secret_mismatch",
2434
+ `The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
2435
+ true
2436
+ );
2437
+ throw error;
2438
+ });
1103
2439
  const identity2 = await verifyMachineIdentity(
1104
2440
  apiUrl,
1105
2441
  tokens2.accessToken,
@@ -1116,17 +2452,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1116
2452
  ...identity,
1117
2453
  apiUrl,
1118
2454
  generation: environment.generation,
1119
- storage: "environment"
2455
+ storage: "environment",
2456
+ ...environment.tokenInjection ? { tokenInjection: "network" } : {}
1120
2457
  };
1121
2458
  writeEnvironmentContext(cached, deps);
1122
2459
  return cached;
1123
2460
  } catch (error) {
2461
+ if (networkManaged && error instanceof MachineAuthError && error.terminal) {
2462
+ networkRejection = {
2463
+ generation: environment.generation,
2464
+ until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
2465
+ error
2466
+ };
2467
+ if (cached?.generation === environment.generation) cached = void 0;
2468
+ const contextPath = environmentContextPath(deps, environment.clientId);
2469
+ try {
2470
+ if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
2471
+ rmSync5(contextPath, { force: true });
2472
+ } catch {
2473
+ }
2474
+ throw error;
2475
+ }
1124
2476
  if (error instanceof MachineAuthError && error.terminal) {
1125
2477
  environmentTerminal = environment.generation;
1126
2478
  const contextPath = environmentContextPath(deps, environment.clientId);
1127
2479
  try {
1128
2480
  if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
1129
- rmSync4(contextPath, { force: true });
2481
+ rmSync5(contextPath, { force: true });
1130
2482
  } catch {
1131
2483
  }
1132
2484
  }
@@ -1140,7 +2492,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1140
2492
  const expected = machineContext(deps);
1141
2493
  const directory = configurationDirectory(deps);
1142
2494
  return withFileLock(
1143
- join5(directory, "credentials.lock"),
2495
+ join7(directory, "credentials.lock"),
1144
2496
  async () => {
1145
2497
  const profile = readMachineProfile(deps);
1146
2498
  if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
@@ -1155,7 +2507,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1155
2507
  true
1156
2508
  );
1157
2509
  let record = await loadRecord(profile, deps, signal);
1158
- if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS) {
2510
+ if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
1159
2511
  try {
1160
2512
  const { tokens, identity } = await withMachineCooldown(
1161
2513
  directory,
@@ -1190,7 +2542,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1190
2542
  await persistRecord(record, deps, signal);
1191
2543
  } catch (error) {
1192
2544
  if (error instanceof MachineAuthError && error.terminal)
1193
- writePrivate(join5(directory, "machine_terminal.json"), profile.generation);
2545
+ writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
1194
2546
  throw error;
1195
2547
  }
1196
2548
  }
@@ -1201,35 +2553,73 @@ async function acquireMachineCredential(options = {}, deps = {}) {
1201
2553
  { signal }
1202
2554
  );
1203
2555
  }
2556
+ async function forwardMachineRequest(request3, signal, deps = {}) {
2557
+ const environment = environmentCredentials(deps);
2558
+ if (!environment?.tokenInjection)
2559
+ throw new MachineAuthError(
2560
+ "identity_changed",
2561
+ "Machine identity changed; restart the operation."
2562
+ );
2563
+ const directory = configurationDirectory(deps);
2564
+ ensureDirectory(directory);
2565
+ return forwardBrokerRequest({
2566
+ directory,
2567
+ apiUrl: apiUrlFor(deps),
2568
+ environment,
2569
+ env: deps.env ?? process.env,
2570
+ request: request3,
2571
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
2572
+ });
2573
+ }
1204
2574
  function machineJournalBucket(identity) {
1205
- return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2575
+ return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
2576
+ }
2577
+ function identityPending(actor) {
2578
+ return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
2579
+ }
2580
+ function machinePendingBucket(identity) {
2581
+ return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
2582
+ }
2583
+ function prepareMachineMetadataDirectory(directory) {
2584
+ ensureDirectory(directory);
2585
+ }
2586
+ function writeMachineMetadata(path, value) {
2587
+ writePrivate(path, value);
1206
2588
  }
1207
2589
 
1208
2590
  // src/lib/machine-broker.ts
1209
2591
  var MAX_RESPONSE_BYTES = 96 * 1024;
2592
+ var MAX_CREDENTIAL_REQUEST_BYTES = 2048;
2593
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
2594
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
2595
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
2596
+ var FORWARD_REQUEST_PROOF = "forward-request";
2597
+ var FORWARD_ANSWER_PROOF = "forward-answer";
2598
+ var FORWARD_TIMEOUT_MS = 3e4;
2599
+ var FORWARD_METHODS = ["GET", "POST", "DELETE"];
1210
2600
  var IDLE_MS = 5 * 6e4;
1211
2601
  function descriptorPath(directory, generation) {
1212
- return join6(directory, `machine_broker_${generation}.json`);
2602
+ return join8(directory, `machine_broker_${generation}.json`);
1213
2603
  }
1214
2604
  function readDescriptor(path) {
1215
2605
  try {
1216
- const stat = lstatSync3(path);
2606
+ const stat = lstatSync4(path);
1217
2607
  if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
1218
2608
  return void 0;
1219
- const data = JSON.parse(readFileSync5(path, "utf8"));
2609
+ const data = JSON.parse(readFileSync6(path, "utf8"));
1220
2610
  return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
1221
2611
  } catch {
1222
2612
  return void 0;
1223
2613
  }
1224
2614
  }
1225
- function signature(secret, nonce, body) {
1226
- return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
2615
+ function signature(secret, nonce, body, purpose) {
2616
+ return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
1227
2617
  }
1228
2618
  function matches(left, right) {
1229
2619
  return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
1230
2620
  }
1231
2621
  function tokenHash(token) {
1232
- return token ? createHash3("sha256").update(token).digest("hex") : void 0;
2622
+ return token ? createHash5("sha256").update(token).digest("hex") : void 0;
1233
2623
  }
1234
2624
  async function brokerRequest(descriptor, environment, options) {
1235
2625
  const body = JSON.stringify({
@@ -1238,10 +2628,9 @@ async function brokerRequest(descriptor, environment, options) {
1238
2628
  observedTokenHash: tokenHash(options.observedToken),
1239
2629
  timestamp: Date.now()
1240
2630
  });
1241
- const response = await fetch(`http://127.0.0.1:${descriptor.port}/credential`, {
2631
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
1242
2632
  method: "POST",
1243
2633
  body,
1244
- redirect: "error",
1245
2634
  signal: options.signal,
1246
2635
  headers: {
1247
2636
  "Content-Type": "application/json",
@@ -1272,6 +2661,15 @@ async function brokerRequest(descriptor, environment, options) {
1272
2661
  );
1273
2662
  return credential;
1274
2663
  }
2664
+ function brokerEnvironment(options) {
2665
+ const routed = options.environment.secretInjection || options.environment.tokenInjection;
2666
+ return {
2667
+ ...options.env,
2668
+ PRIM_API_URL: options.apiUrl,
2669
+ PRIM_CONFIG_DIR: options.directory,
2670
+ ...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
2671
+ };
2672
+ }
1275
2673
  async function acquireBrokerCredential(options) {
1276
2674
  const path = descriptorPath(options.directory, options.environment.generation);
1277
2675
  const existing = readDescriptor(path);
@@ -1283,15 +2681,28 @@ async function acquireBrokerCredential(options) {
1283
2681
  if (error instanceof MachineAuthError) throw error;
1284
2682
  }
1285
2683
  }
1286
- const descriptor = await withFileLock(
1287
- join6(options.directory, "machine-broker.lock"),
2684
+ const descriptor = await ensureBroker(options);
2685
+ try {
2686
+ return await brokerRequest(descriptor, options.environment, options);
2687
+ } catch (error) {
2688
+ options.signal.throwIfAborted();
2689
+ if (error instanceof MachineAuthError) throw error;
2690
+ throw new MachineAuthError(
2691
+ "broker_unavailable",
2692
+ "Machine credential broker is unavailable. Retry the command."
2693
+ );
2694
+ }
2695
+ }
2696
+ async function ensureBroker(options) {
2697
+ const path = descriptorPath(options.directory, options.environment.generation);
2698
+ return withFileLock(
2699
+ join8(options.directory, "machine-broker.lock"),
1288
2700
  async () => {
1289
2701
  const current = readDescriptor(path);
1290
2702
  if (current) {
1291
2703
  try {
1292
- const response = await fetch(`http://127.0.0.1:${current.port}/health`, {
1293
- signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)]),
1294
- redirect: "error"
2704
+ const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
2705
+ signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
1295
2706
  });
1296
2707
  if (response.ok && await response.text() === current.nonce) return current;
1297
2708
  } catch {
@@ -1299,7 +2710,7 @@ async function acquireBrokerCredential(options) {
1299
2710
  }
1300
2711
  }
1301
2712
  const bundled = fileURLToPath3(import.meta.url);
1302
- const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
2713
+ const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
1303
2714
  if (!entry)
1304
2715
  throw new MachineAuthError(
1305
2716
  "broker_unavailable",
@@ -1310,7 +2721,7 @@ async function acquireBrokerCredential(options) {
1310
2721
  detached: true,
1311
2722
  stdio: ["ignore", "ignore", "ignore", "ipc"],
1312
2723
  windowsHide: true,
1313
- env: { ...options.env, PRIM_API_URL: options.apiUrl, PRIM_CONFIG_DIR: options.directory }
2724
+ env: brokerEnvironment(options)
1314
2725
  });
1315
2726
  let settled = false;
1316
2727
  const finish = (error) => {
@@ -1362,44 +2773,202 @@ async function acquireBrokerCredential(options) {
1362
2773
  },
1363
2774
  { signal: options.signal }
1364
2775
  );
2776
+ }
2777
+ async function forwardOnce(descriptor, environment, request3, signal) {
2778
+ const body = JSON.stringify({
2779
+ generation: environment.generation,
2780
+ timestamp: Date.now(),
2781
+ method: request3.method,
2782
+ path: request3.path,
2783
+ headers: request3.headers ?? {},
2784
+ ...request3.body === void 0 ? {} : { body: request3.body }
2785
+ });
2786
+ const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
2787
+ method: "POST",
2788
+ body,
2789
+ signal,
2790
+ headers: {
2791
+ "Content-Type": "application/json",
2792
+ "X-Prim-Proof": signature(
2793
+ environment.clientSecret,
2794
+ descriptor.nonce,
2795
+ body,
2796
+ FORWARD_REQUEST_PROOF
2797
+ )
2798
+ }
2799
+ });
2800
+ const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
2801
+ if (typeof envelope.body !== "string" || !matches(
2802
+ signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
2803
+ envelope.proof
2804
+ ))
2805
+ throw new MachineAuthError(
2806
+ "broker_unavailable",
2807
+ "Machine credential broker could not be authenticated. Retry the command."
2808
+ );
2809
+ const data = machineRecord(JSON.parse(envelope.body));
2810
+ if (data.error) {
2811
+ const error = machineRecord(data.error);
2812
+ throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
2813
+ }
2814
+ const status = data.status;
2815
+ if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
2816
+ throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
2817
+ const headers = new Headers();
2818
+ for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
2819
+ if (typeof value === "string") headers.set(name, value);
2820
+ const text = typeof data.body === "string" ? data.body : "";
2821
+ return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
2822
+ }
2823
+ async function forwardBrokerRequest(options) {
2824
+ const path = descriptorPath(options.directory, options.environment.generation);
2825
+ const unavailable = () => new MachineAuthError(
2826
+ "broker_unavailable",
2827
+ "Machine credential broker is unavailable. Retry the command."
2828
+ );
2829
+ const existing = readDescriptor(path);
2830
+ if (existing) {
2831
+ try {
2832
+ return await forwardOnce(existing, options.environment, options.request, options.signal);
2833
+ } catch (error) {
2834
+ options.signal.throwIfAborted();
2835
+ if (error instanceof MachineAuthError) throw error;
2836
+ if (error.code !== "ECONNREFUSED") throw unavailable();
2837
+ }
2838
+ }
2839
+ const descriptor = await ensureBroker(options);
1365
2840
  try {
1366
- return await brokerRequest(descriptor, options.environment, options);
2841
+ return await forwardOnce(descriptor, options.environment, options.request, options.signal);
1367
2842
  } catch (error) {
1368
2843
  options.signal.throwIfAborted();
1369
2844
  if (error instanceof MachineAuthError) throw error;
1370
- throw new MachineAuthError(
1371
- "broker_unavailable",
1372
- "Machine credential broker is unavailable. Retry the command."
2845
+ throw unavailable();
2846
+ }
2847
+ }
2848
+ function forwardableHeaders(value) {
2849
+ const headers = {};
2850
+ if (!value || typeof value !== "object" || Array.isArray(value)) return headers;
2851
+ for (const [name, content] of Object.entries(value)) {
2852
+ const lower = name.toLowerCase();
2853
+ if (typeof content === "string" && content.length <= 256 && !/[\p{Cc}]/u.test(content) && (lower === "content-type" || /^x-prim-[a-z0-9-]+$/u.test(lower)))
2854
+ headers[name] = content;
2855
+ }
2856
+ return headers;
2857
+ }
2858
+ async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
2859
+ const refuse = (message) => ({
2860
+ error: { code: "invalid_request", message, terminal: false }
2861
+ });
2862
+ if (typeof data.method !== "string" || !FORWARD_METHODS.includes(data.method))
2863
+ return refuse("The forwarded request's method is not allowed.");
2864
+ if (data.body !== void 0 && typeof data.body !== "string")
2865
+ return refuse("The forwarded request's body is not text.");
2866
+ let target;
2867
+ try {
2868
+ if (typeof data.path !== "string" || !data.path.startsWith("/")) throw new Error("path");
2869
+ target = new URL(data.path, `${apiUrl}/`);
2870
+ if (target.origin !== apiUrl || target.username || target.password) throw new Error("origin");
2871
+ } catch {
2872
+ return refuse("The forwarded request does not target the configured API.");
2873
+ }
2874
+ try {
2875
+ const answer = await fetchImpl(target, {
2876
+ method: data.method,
2877
+ headers: forwardableHeaders(data.headers),
2878
+ body: data.method === "GET" ? void 0 : data.body,
2879
+ redirect: "error",
2880
+ signal: AbortSignal.any([signal, AbortSignal.timeout(FORWARD_TIMEOUT_MS)])
2881
+ });
2882
+ const headers = {};
2883
+ for (const name of ["content-type", "retry-after"]) {
2884
+ const value = answer.headers.get(name);
2885
+ if (value) headers[name] = value;
2886
+ }
2887
+ const chunks = [];
2888
+ let received = 0;
2889
+ if (answer.body)
2890
+ for await (const chunk of answer.body) {
2891
+ received += chunk.length;
2892
+ if (received > MAX_API_RESPONSE_BYTES)
2893
+ return {
2894
+ error: {
2895
+ code: "invalid_response",
2896
+ message: "The API answered with more than prim accepts.",
2897
+ terminal: false
2898
+ }
2899
+ };
2900
+ chunks.push(chunk);
2901
+ }
2902
+ return { status: answer.status, headers, body: Buffer.concat(chunks).toString("utf8") };
2903
+ } catch (error) {
2904
+ const timedOut = error instanceof Error && error.name === "TimeoutError";
2905
+ return {
2906
+ error: {
2907
+ code: timedOut ? "request_timeout" : "authentication_unavailable",
2908
+ message: timedOut ? "Primitive did not answer through the cloud environment's proxy in time. The request may or may not have been applied." : "The request to Primitive through the cloud environment's proxy failed. Check the connection and retry.",
2909
+ terminal: false
2910
+ }
2911
+ };
2912
+ }
2913
+ }
2914
+ async function credentialResult(apiUrl, data, signal) {
2915
+ try {
2916
+ const current = cachedMachineCredential({ localEnvironment: true });
2917
+ const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
2918
+ const credential = await acquireMachineCredential(
2919
+ { force, signal },
2920
+ { localEnvironment: true }
1373
2921
  );
2922
+ if (!credential || credential.apiUrl !== apiUrl) throw new Error("Missing machine identity");
2923
+ return { credential };
2924
+ } catch (error) {
2925
+ return {
2926
+ error: error instanceof MachineAuthError ? {
2927
+ code: error.code,
2928
+ message: error.message,
2929
+ terminal: error.terminal,
2930
+ retryAt: error.retryAt
2931
+ } : {
2932
+ code: "broker_unavailable",
2933
+ message: "Machine authentication is temporarily unavailable.",
2934
+ terminal: false
2935
+ }
2936
+ };
1374
2937
  }
1375
2938
  }
1376
- async function startMachineBroker() {
1377
- const environment = environmentCredentials({});
1378
- if (!environment) throw new Error("Machine broker requires injected credentials");
1379
- const directory = primConfigDirectory();
1380
- const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
1381
- const path = descriptorPath(directory, environment.generation);
1382
- const nonce = randomBytes2(32).toString("hex");
1383
- const server = createServer(async (request2, response) => {
2939
+ function createBrokerServer(options) {
2940
+ const { environment, apiUrl, nonce } = options;
2941
+ const server = createServer(async (request3, response) => {
1384
2942
  response.setHeader("Cache-Control", "no-store");
1385
- if (request2.method === "GET" && request2.url === "/health") {
2943
+ if (request3.method === "GET" && request3.url === "/health") {
1386
2944
  response.end(nonce);
1387
2945
  return;
1388
2946
  }
1389
- if (request2.method !== "POST" || request2.url !== "/credential") {
2947
+ const forwarding = request3.url === "/forward" && environment.tokenInjection === "network";
2948
+ if (request3.method !== "POST" || request3.url !== "/credential" && !forwarding) {
1390
2949
  response.writeHead(404).end();
1391
2950
  return;
1392
2951
  }
1393
- let raw = "";
2952
+ const limit = forwarding ? MAX_FORWARD_REQUEST_BYTES : MAX_CREDENTIAL_REQUEST_BYTES;
1394
2953
  try {
1395
- for await (const chunk of request2) {
1396
- raw += chunk.toString();
1397
- if (Buffer.byteLength(raw) > 2048) {
2954
+ const chunks = [];
2955
+ let received = 0;
2956
+ for await (const chunk of request3) {
2957
+ received += chunk.length;
2958
+ if (received > limit) {
1398
2959
  response.writeHead(413).end();
1399
2960
  return;
1400
2961
  }
2962
+ chunks.push(chunk);
1401
2963
  }
1402
- if (!matches(signature(environment.clientSecret, nonce, raw), request2.headers["x-prim-proof"])) {
2964
+ const raw = Buffer.concat(chunks).toString("utf8");
2965
+ const proof = signature(
2966
+ environment.clientSecret,
2967
+ nonce,
2968
+ raw,
2969
+ forwarding ? FORWARD_REQUEST_PROOF : void 0
2970
+ );
2971
+ if (!matches(proof, request3.headers["x-prim-proof"])) {
1403
2972
  response.writeHead(403).end();
1404
2973
  return;
1405
2974
  }
@@ -1408,40 +2977,24 @@ async function startMachineBroker() {
1408
2977
  response.writeHead(403).end();
1409
2978
  return;
1410
2979
  }
1411
- idle.refresh();
2980
+ options.onRequest?.();
1412
2981
  const controller = new AbortController();
1413
2982
  response.once("close", () => {
1414
2983
  if (!response.writableFinished) controller.abort();
1415
2984
  });
1416
- let result;
1417
- try {
1418
- const current = cachedMachineCredential();
1419
- const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
1420
- const credential = await acquireMachineCredential(
1421
- { force, signal: controller.signal },
1422
- { localEnvironment: true }
1423
- );
1424
- if (!credential || credential.apiUrl !== apiUrl)
1425
- throw new Error("Missing machine identity");
1426
- result = { credential };
1427
- } catch (error) {
1428
- result = {
1429
- error: error instanceof MachineAuthError ? {
1430
- code: error.code,
1431
- message: error.message,
1432
- terminal: error.terminal,
1433
- retryAt: error.retryAt
1434
- } : {
1435
- code: "broker_unavailable",
1436
- message: "Machine authentication is temporarily unavailable.",
1437
- terminal: false
1438
- }
1439
- };
1440
- }
2985
+ const result = forwarding ? await forwardToApi(apiUrl, data, controller.signal) : await credentialResult(apiUrl, data, controller.signal);
1441
2986
  const body = JSON.stringify(result);
1442
2987
  response.setHeader("Content-Type", "application/json");
1443
2988
  response.end(
1444
- JSON.stringify({ body, proof: signature(environment.clientSecret, nonce, body) })
2989
+ JSON.stringify({
2990
+ body,
2991
+ proof: signature(
2992
+ environment.clientSecret,
2993
+ nonce,
2994
+ body,
2995
+ forwarding ? FORWARD_ANSWER_PROOF : void 0
2996
+ )
2997
+ })
1445
2998
  );
1446
2999
  } catch {
1447
3000
  response.writeHead(400).end();
@@ -1450,11 +3003,26 @@ async function startMachineBroker() {
1450
3003
  server.maxConnections = 64;
1451
3004
  server.requestTimeout = 1e4;
1452
3005
  server.headersTimeout = 1e4;
3006
+ return server;
3007
+ }
3008
+ async function startMachineBroker() {
3009
+ const environment = environmentCredentials({});
3010
+ if (!environment) throw new Error("Machine broker requires injected credentials");
3011
+ const directory = primConfigDirectory();
3012
+ const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
3013
+ const path = descriptorPath(directory, environment.generation);
3014
+ const nonce = randomBytes3(32).toString("hex");
3015
+ const server = createBrokerServer({
3016
+ environment,
3017
+ apiUrl,
3018
+ nonce,
3019
+ onRequest: () => idle.refresh()
3020
+ });
1453
3021
  const close = () => {
1454
3022
  clearTimeout(idle);
1455
3023
  server.closeAllConnections();
1456
3024
  server.close();
1457
- if (readDescriptor(path)?.nonce === nonce) rmSync5(path, { force: true });
3025
+ if (readDescriptor(path)?.nonce === nonce) rmSync6(path, { force: true });
1458
3026
  };
1459
3027
  const idle = setTimeout(close, IDLE_MS);
1460
3028
  process.once("SIGTERM", close);
@@ -1472,27 +3040,27 @@ async function startMachineBroker() {
1472
3040
  }
1473
3041
 
1474
3042
  // src/daemon/principal.ts
1475
- import { createHash as createHash5 } from "crypto";
3043
+ import { createHash as createHash7 } from "crypto";
1476
3044
 
1477
3045
  // src/lib/credentials.ts
1478
- import { createHash as createHash4 } from "crypto";
1479
- import { readFileSync as readFileSync6 } from "fs";
1480
- import { join as join7 } from "path";
3046
+ import { createHash as createHash6 } from "crypto";
3047
+ import { readFileSync as readFileSync7 } from "fs";
3048
+ import { join as join9 } from "path";
1481
3049
  var CONFIG_DIRECTORY = primConfigDirectory();
1482
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
1483
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
1484
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
1485
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
1486
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
1487
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
1488
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
1489
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
3050
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
3051
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
3052
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
3053
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
3054
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
3055
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
3056
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
3057
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
1490
3058
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
1491
3059
  var CREDENTIAL_MIGRATION_VERSION = 1;
1492
3060
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
1493
3061
  function readTrimmed(path) {
1494
3062
  try {
1495
- const value = readFileSync6(path, "utf8").trim();
3063
+ const value = readFileSync7(path, "utf8").trim();
1496
3064
  return value || void 0;
1497
3065
  } catch {
1498
3066
  return void 0;
@@ -1501,7 +3069,7 @@ function readTrimmed(path) {
1501
3069
  function resolveAuthCredential(options = {}) {
1502
3070
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
1503
3071
  const machine = cachedMachineCredential({ env: options.env });
1504
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
3072
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
1505
3073
  }
1506
3074
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
1507
3075
  if (envToken) return { token: envToken, source: "environment" };
@@ -1514,22 +3082,22 @@ function resolveAuthCredential(options = {}) {
1514
3082
  );
1515
3083
  if (metadata.state === "legacy_broker") {
1516
3084
  if (metadata.metadata) {
1517
- const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1518
- if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
3085
+ const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3086
+ if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
1519
3087
  return void 0;
1520
3088
  }
1521
3089
  }
1522
3090
  return { token: stored, source: "token_file" };
1523
3091
  }
1524
3092
  if (metadata.state === "invalid") return void 0;
1525
- const refreshToken2 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
1526
- if (!refreshToken2 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken2)) {
3093
+ const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
3094
+ if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
1527
3095
  return void 0;
1528
3096
  }
1529
3097
  return { token: stored, source: "token_file" };
1530
3098
  }
1531
3099
  function credentialFingerprint(value) {
1532
- return createHash4("sha256").update(value).digest("hex");
3100
+ return createHash6("sha256").update(value).digest("hex");
1533
3101
  }
1534
3102
  function parseLegacyBrokerCredentialMetadata(value) {
1535
3103
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -1549,7 +3117,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
1549
3117
  function readBoundedCredentialJson(path) {
1550
3118
  let raw;
1551
3119
  try {
1552
- raw = readFileSync6(path, "utf8");
3120
+ raw = readFileSync7(path, "utf8");
1553
3121
  } catch (error) {
1554
3122
  return error.code === "ENOENT" ? void 0 : null;
1555
3123
  }
@@ -1627,7 +3195,7 @@ function boundedClaim(value) {
1627
3195
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
1628
3196
  }
1629
3197
  function sha256(value) {
1630
- return createHash5("sha256").update(value).digest("hex");
3198
+ return createHash7("sha256").update(value).digest("hex");
1631
3199
  }
1632
3200
  function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
1633
3201
  if (hasMachineConfiguration()) {
@@ -1710,9 +3278,9 @@ function parseDaemonResponseEnvelope(value) {
1710
3278
  }
1711
3279
 
1712
3280
  // src/daemon/server.ts
1713
- import { chmodSync as chmodSync8, existsSync as existsSync11, mkdirSync as mkdirSync9, readFileSync as readFileSync13, unlinkSync as unlinkSync3 } from "fs";
3281
+ import { chmodSync as chmodSync8, existsSync as existsSync12, mkdirSync as mkdirSync10, readFileSync as readFileSync15, unlinkSync as unlinkSync3 } from "fs";
1714
3282
  import { createServer as createServer2 } from "net";
1715
- import { join as join18 } from "path";
3283
+ import { join as join21 } from "path";
1716
3284
  import { fileURLToPath as fileURLToPath4 } from "url";
1717
3285
 
1718
3286
  // src/decisions/identity.ts
@@ -1793,14 +3361,14 @@ function publicDecisionResponse(value) {
1793
3361
  }
1794
3362
 
1795
3363
  // src/client.ts
1796
- import { createHash as createHash6 } from "crypto";
1797
- import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
1798
- import { dirname as dirname5 } from "path";
3364
+ import { createHash as createHash8 } from "crypto";
3365
+ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
3366
+ import { dirname as dirname6 } from "path";
1799
3367
 
1800
3368
  // src/daemon/client-instance-id.ts
1801
- import { randomBytes as randomBytes3 } from "crypto";
1802
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
1803
- import { join as join8 } from "path";
3369
+ import { randomBytes as randomBytes4 } from "crypto";
3370
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
3371
+ import { join as join10 } from "path";
1804
3372
  var CONFIG_DIRECTORY_MODE = 448;
1805
3373
  var INSTANCE_FILE_MODE = 384;
1806
3374
  var INSTANCE_ENTROPY_BYTES = 32;
@@ -1813,7 +3381,7 @@ function isClientInstanceId(value) {
1813
3381
  }
1814
3382
  function ensurePrivateConfigDirectory(configDir) {
1815
3383
  ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
1816
- const metadata = lstatSync4(configDir);
3384
+ const metadata = lstatSync5(configDir);
1817
3385
  if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
1818
3386
  throw new Error("prim config path must be a private directory");
1819
3387
  }
@@ -1823,7 +3391,7 @@ function ensurePrivateConfigDirectory(configDir) {
1823
3391
  function readExisting(path) {
1824
3392
  let metadata;
1825
3393
  try {
1826
- metadata = lstatSync4(path);
3394
+ metadata = lstatSync5(path);
1827
3395
  } catch (error) {
1828
3396
  if (error.code === "ENOENT") {
1829
3397
  return;
@@ -1837,7 +3405,7 @@ function readExisting(path) {
1837
3405
  if (metadata.size > MAX_STORED_BYTES) {
1838
3406
  throw new Error("stored client instance identity is invalid");
1839
3407
  }
1840
- const raw = readFileSync7(path, "utf8");
3408
+ const raw = readFileSync8(path, "utf8");
1841
3409
  const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
1842
3410
  if (raw !== value && raw !== `${value}
1843
3411
  ` || !isClientInstanceId(value)) {
@@ -1851,8 +3419,8 @@ function atomicWrite(path, value) {
1851
3419
  }
1852
3420
  async function getOrCreateClientInstanceId(options) {
1853
3421
  const configDir = options.configDir;
1854
- const path = join8(configDir, "client_instance_id");
1855
- const lockPath = join8(configDir, "client-instance.lock");
3422
+ const path = join10(configDir, "client_instance_id");
3423
+ const lockPath = join10(configDir, "client-instance.lock");
1856
3424
  ensurePrivateConfigDirectory(configDir);
1857
3425
  return withFileLock(
1858
3426
  lockPath,
@@ -1861,7 +3429,7 @@ async function getOrCreateClientInstanceId(options) {
1861
3429
  if (existing !== void 0) {
1862
3430
  return existing;
1863
3431
  }
1864
- const generated = `${INSTANCE_PREFIX}${randomBytes3(INSTANCE_ENTROPY_BYTES).toString(
3432
+ const generated = `${INSTANCE_PREFIX}${randomBytes4(INSTANCE_ENTROPY_BYTES).toString(
1865
3433
  "base64url"
1866
3434
  )}`;
1867
3435
  if (!isClientInstanceId(generated)) {
@@ -1896,57 +3464,18 @@ async function ingestUploaderHeaders() {
1896
3464
  return headers;
1897
3465
  }
1898
3466
 
1899
- // src/lib/terminal-safe.ts
1900
- function replaceIsolatedSurrogates(value) {
1901
- let out = "";
1902
- for (let index = 0; index < value.length; index += 1) {
1903
- const unit = value.charCodeAt(index);
1904
- if (unit >= 55296 && unit <= 56319) {
1905
- const next = value.charCodeAt(index + 1);
1906
- if (next >= 56320 && next <= 57343) {
1907
- out += value[index] + value[index + 1];
1908
- index += 1;
1909
- } else {
1910
- out += "\uFFFD";
1911
- }
1912
- } else if (unit >= 56320 && unit <= 57343) {
1913
- out += "\uFFFD";
1914
- } else {
1915
- out += value[index];
1916
- }
1917
- }
1918
- return out;
1919
- }
1920
- function isUnsafeTerminalCodePoint(point) {
1921
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
1922
- const bidiOrZeroWidth = point === 173 || // soft hyphen
1923
- point === 1564 || // Arabic letter mark
1924
- point === 6158 || // Mongolian vowel separator
1925
- point >= 8203 && point <= 8207 || // zero-width + directional marks
1926
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
1927
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
1928
- point >= 65529 && point <= 65531 || // interlinear annotation controls
1929
- point === 65279 || // zero-width no-break space / BOM
1930
- point >= 917504 && point <= 917631;
1931
- return c0OrC1 || bidiOrZeroWidth;
1932
- }
1933
- function terminalSafeText(value) {
1934
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
1935
- }
1936
- function terminalSafeLine(value) {
1937
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
1938
- }
1939
- var stripControlChars = terminalSafeText;
1940
-
1941
3467
  // src/client.ts
1942
3468
  var CONFIG_DIR_MODE = 448;
1943
3469
  var CREDENTIAL_FILE_MODE = 384;
1944
3470
  var REFRESH_THRESHOLD_MS = 6e4;
1945
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
3471
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
1946
3472
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
3473
+ function authExpiredMessage() {
3474
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
3475
+ }
1947
3476
  function readTrimmed2(path) {
1948
3477
  try {
1949
- const value = readFileSync8(path, "utf8").trim();
3478
+ const value = readFileSync9(path, "utf8").trim();
1950
3479
  return value || void 0;
1951
3480
  } catch {
1952
3481
  return void 0;
@@ -1956,13 +3485,13 @@ function getSiteUrl() {
1956
3485
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
1957
3486
  }
1958
3487
  function getSiteUrlForEnvironment(primApiUrl) {
1959
- return primApiUrl?.trim() || DEFAULT_API_URL2;
3488
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
1960
3489
  }
1961
3490
  function expiresAtFor(token, expiresIn) {
1962
3491
  return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
1963
3492
  }
1964
3493
  function ensureConfigDirectory() {
1965
- const directory = dirname5(TOKEN_FILE_PATH);
3494
+ const directory = dirname6(TOKEN_FILE_PATH);
1966
3495
  mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
1967
3496
  chmodSync3(directory, CONFIG_DIR_MODE);
1968
3497
  }
@@ -1972,7 +3501,7 @@ function atomicWrite2(path, content) {
1972
3501
  }
1973
3502
  function removeCredentialFile(path) {
1974
3503
  if (!existsSync4(path)) return false;
1975
- rmSync6(path, { force: true });
3504
+ rmSync7(path, { force: true });
1976
3505
  return true;
1977
3506
  }
1978
3507
  function getTokenExpiresAt() {
@@ -1987,23 +3516,23 @@ function isTokenExpiringSoon(credential) {
1987
3516
  const expiresAt = getTokenExpiresAt();
1988
3517
  return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
1989
3518
  }
1990
- function refreshFingerprint(refreshToken2) {
1991
- return createHash6("sha256").update(refreshToken2).digest("hex");
3519
+ function refreshFingerprint(refreshToken3) {
3520
+ return createHash8("sha256").update(refreshToken3).digest("hex");
1992
3521
  }
1993
- function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
3522
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
1994
3523
  return {
1995
3524
  version: 1,
1996
3525
  family: "legacy_broker",
1997
3526
  accessTokenHash: refreshFingerprint(accessToken),
1998
- refreshTokenHash: refreshFingerprint(refreshToken2)
3527
+ refreshTokenHash: refreshFingerprint(refreshToken3)
1999
3528
  };
2000
3529
  }
2001
- function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
3530
+ function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
2002
3531
  const hashes = {
2003
3532
  accessTokenHash: refreshFingerprint(accessToken),
2004
- refreshTokenHash: refreshFingerprint(refreshToken2)
3533
+ refreshTokenHash: refreshFingerprint(refreshToken3)
2005
3534
  };
2006
- return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
3535
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
2007
3536
  }
2008
3537
  function writeCredentialMigrationSentinel() {
2009
3538
  atomicWrite2(
@@ -2015,11 +3544,11 @@ function writeCredentialMigrationSentinel() {
2015
3544
  `
2016
3545
  );
2017
3546
  }
2018
- function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
2019
- if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
3547
+ function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
3548
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
2020
3549
  return { state: "invalid" };
2021
3550
  }
2022
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3551
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2023
3552
  if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
2024
3553
  return { state: "invalid" };
2025
3554
  }
@@ -2036,17 +3565,17 @@ function preserveMarkerlessLegacyGeneration() {
2036
3565
  const metadata = readStoredCredentialMetadata();
2037
3566
  if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
2038
3567
  const accessToken = readTrimmed2(TOKEN_FILE_PATH);
2039
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
2040
- if (!(accessToken && refreshToken2)) return;
2041
- const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
3568
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
3569
+ if (!(accessToken && refreshToken3)) return;
3570
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
2042
3571
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2043
3572
  `);
2044
3573
  }
2045
3574
  function terminalFingerprint() {
2046
3575
  return readTrimmed2(TERMINAL_REFRESH_PATH);
2047
3576
  }
2048
- function writeTerminalFingerprint(refreshToken2) {
2049
- atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
3577
+ function writeTerminalFingerprint(refreshToken3) {
3578
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
2050
3579
  `);
2051
3580
  }
2052
3581
  function clearTerminalFingerprint() {
@@ -2055,20 +3584,20 @@ function clearTerminalFingerprint() {
2055
3584
  function isSessionEnded() {
2056
3585
  if (hasMachineConfiguration()) return machineSessionEnded();
2057
3586
  if (resolveAuthCredential()?.source !== "token_file") return false;
2058
- const refreshToken2 = readTrimmed2(REFRESH_TOKEN_PATH);
3587
+ const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
2059
3588
  const ended = terminalFingerprint();
2060
- return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
3589
+ return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
2061
3590
  }
2062
3591
  function withCredentialLock(operation, options = {}) {
2063
3592
  return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
2064
3593
  }
2065
3594
  function commitCredentialsUnlocked(credentials) {
2066
3595
  const accessToken = credentials.accessToken.trim();
2067
- const refreshToken2 = credentials.refreshToken.trim();
2068
- if (!accessToken || !refreshToken2) {
3596
+ const refreshToken3 = credentials.refreshToken.trim();
3597
+ if (!accessToken || !refreshToken3) {
2069
3598
  throw new Error("OAuth credentials require both access and refresh tokens");
2070
3599
  }
2071
- const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
3600
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
2072
3601
  if (credentials.metadata !== void 0) {
2073
3602
  preserveMarkerlessLegacyGeneration();
2074
3603
  writeCredentialMigrationSentinel();
@@ -2076,10 +3605,10 @@ function commitCredentialsUnlocked(credentials) {
2076
3605
  `);
2077
3606
  atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
2078
3607
  `);
2079
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3608
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2080
3609
  `);
2081
3610
  } else {
2082
- atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
3611
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
2083
3612
  `);
2084
3613
  atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
2085
3614
  `);
@@ -2116,15 +3645,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
2116
3645
  `
2117
3646
  );
2118
3647
  }
2119
- function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
3648
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
2120
3649
  const current = readStoredCredentialMetadata();
2121
3650
  if (expected.state === "legacy_broker") {
2122
3651
  if (current.state !== "legacy_broker") return false;
2123
3652
  if (!expected.metadata) return current.metadata === void 0;
2124
- 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;
3653
+ 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;
2125
3654
  }
2126
3655
  if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
2127
- 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;
3656
+ 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;
2128
3657
  }
2129
3658
  function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
2130
3659
  if (!expected || readCredentialMigrationState() !== "valid") return void 0;
@@ -2293,7 +3822,7 @@ async function performTokenRefresh(options = {}) {
2293
3822
  );
2294
3823
  }
2295
3824
  var _refreshInFlight;
2296
- function refreshToken(options = {}) {
3825
+ function refreshToken2(options = {}) {
2297
3826
  if (hasMachineConfiguration())
2298
3827
  return acquireMachineCredential(options).then((credential) => credential?.accessToken);
2299
3828
  if (_refreshInFlight) return _refreshInFlight;
@@ -2325,7 +3854,7 @@ var CliManagementResponseError = class extends Error {
2325
3854
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
2326
3855
  async function managementResponseValue(response) {
2327
3856
  if (response.status === 401) {
2328
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3857
+ throw new HttpError(401, authExpiredMessage());
2329
3858
  }
2330
3859
  let value;
2331
3860
  try {
@@ -2347,23 +3876,50 @@ function selectedCredential() {
2347
3876
  }
2348
3877
  return _cachedCredential;
2349
3878
  }
3879
+ async function requestHeaders(method, path) {
3880
+ return {
3881
+ "Content-Type": "application/json",
3882
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
3883
+ };
3884
+ }
2350
3885
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
2351
3886
  return fetch(`${siteUrl}${path}`, {
2352
3887
  method,
2353
- headers: {
2354
- Authorization: `Bearer ${token}`,
2355
- "Content-Type": "application/json",
2356
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
2357
- },
3888
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
2358
3889
  body: body === void 0 ? void 0 : JSON.stringify(body),
2359
3890
  signal: options?.signal,
2360
3891
  redirect: options?.redirect
2361
3892
  });
2362
3893
  }
3894
+ async function fetchAsMachine(credential, method, path, body, options) {
3895
+ if (!credential.tokenInjection)
3896
+ return fetchWithToken(
3897
+ method,
3898
+ path,
3899
+ body,
3900
+ { ...options, redirect: "error" },
3901
+ credential.accessToken,
3902
+ credential.apiUrl
3903
+ );
3904
+ try {
3905
+ return await forwardMachineRequest(
3906
+ {
3907
+ method,
3908
+ path,
3909
+ headers: await requestHeaders(method, path),
3910
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
3911
+ },
3912
+ options.signal
3913
+ );
3914
+ } catch (error) {
3915
+ if (!(error instanceof MachineAuthError)) throw error;
3916
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
3917
+ }
3918
+ }
2363
3919
  async function responseValue(response) {
2364
3920
  if (!response.ok) {
2365
3921
  if (response.status === 401) {
2366
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3922
+ throw new HttpError(401, authExpiredMessage());
2367
3923
  }
2368
3924
  const errorBody = await response.json().catch(() => null);
2369
3925
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -2390,14 +3946,7 @@ async function machineClient(options = {}, management = false) {
2390
3946
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
2391
3947
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
2392
3948
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2393
- let response = await fetchWithToken(
2394
- method,
2395
- path,
2396
- body,
2397
- { ...requestOptions, redirect: "error" },
2398
- current.accessToken,
2399
- selected.apiUrl
2400
- );
3949
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
2401
3950
  if (response.status === 401) {
2402
3951
  const renewed = await acquireMachineCredential({
2403
3952
  force: true,
@@ -2406,19 +3955,14 @@ async function machineClient(options = {}, management = false) {
2406
3955
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
2407
3956
  throw new HttpError(409, "Machine identity changed; restart the operation.");
2408
3957
  }
2409
- response = await fetchWithToken(
2410
- method,
2411
- path,
2412
- body,
2413
- { ...requestOptions, redirect: "error" },
2414
- renewed.accessToken,
2415
- renewed.apiUrl
2416
- );
3958
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
2417
3959
  }
2418
3960
  if (response.status === 401)
2419
3961
  throw new HttpError(
2420
3962
  401,
2421
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3963
+ 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(
3964
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
3965
+ )
2422
3966
  );
2423
3967
  return parse(response);
2424
3968
  };
@@ -2428,7 +3972,7 @@ async function machineClient(options = {}, management = false) {
2428
3972
  delete: (path, body, opts) => send("DELETE", path, body, opts)
2429
3973
  };
2430
3974
  }
2431
- async function request(method, path, body, options) {
3975
+ async function request2(method, path, body, options) {
2432
3976
  const machine = await machineClient(options);
2433
3977
  if (machine)
2434
3978
  return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
@@ -2437,17 +3981,17 @@ async function request(method, path, body, options) {
2437
3981
  let refreshAttempted = false;
2438
3982
  if (credential && isTokenExpiringSoon(credential)) {
2439
3983
  refreshAttempted = true;
2440
- const token = await refreshToken({
3984
+ const token = await refreshToken2({
2441
3985
  signal: options?.signal,
2442
3986
  quiet: options?.quietRefresh
2443
3987
  });
2444
3988
  if (token) credential = { token, source: "token_file" };
2445
3989
  }
2446
3990
  if (!credential) {
2447
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3991
+ throw new HttpError(401, authExpiredMessage());
2448
3992
  }
2449
3993
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
2450
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
3994
+ throw new HttpError(401, authExpiredMessage());
2451
3995
  }
2452
3996
  const tokenUsed = credential.token;
2453
3997
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -2456,7 +4000,7 @@ async function request(method, path, body, options) {
2456
4000
  let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
2457
4001
  if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
2458
4002
  refreshAttempted = true;
2459
- retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
4003
+ retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
2460
4004
  }
2461
4005
  if (retryToken) {
2462
4006
  _cachedCredential = {
@@ -2470,8 +4014,8 @@ async function request(method, path, body, options) {
2470
4014
  }
2471
4015
  function getClient() {
2472
4016
  return {
2473
- get: (path, options) => request("GET", path, void 0, options),
2474
- post: (path, body, options) => request("POST", path, body, options)
4017
+ get: (path, options) => request2("GET", path, void 0, options),
4018
+ post: (path, body, options) => request2("POST", path, body, options)
2475
4019
  };
2476
4020
  }
2477
4021
  async function getPinnedClient(options = {}) {
@@ -2480,14 +4024,14 @@ async function getPinnedClient(options = {}) {
2480
4024
  const siteUrl = getSiteUrl();
2481
4025
  let credential = selectedCredential();
2482
4026
  if (credential && isTokenExpiringSoon(credential)) {
2483
- const token2 = await refreshToken({
4027
+ const token2 = await refreshToken2({
2484
4028
  signal: options.signal,
2485
4029
  quiet: options.quietRefresh
2486
4030
  });
2487
4031
  if (token2) credential = { token: token2, source: "token_file" };
2488
4032
  }
2489
4033
  if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
2490
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
4034
+ throw new HttpError(401, authExpiredMessage());
2491
4035
  }
2492
4036
  const token = credential.token;
2493
4037
  const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
@@ -2499,10 +4043,10 @@ async function getPinnedClient(options = {}) {
2499
4043
 
2500
4044
  // src/flusher.ts
2501
4045
  import { createReadStream, renameSync as renameSync3, statSync as statSync2, unlinkSync } from "fs";
2502
- import { dirname as dirname10, join as join14 } from "path";
4046
+ import { dirname as dirname10, join as join17 } from "path";
2503
4047
 
2504
4048
  // src/dead-letter.ts
2505
- import { createHash as createHash7, randomBytes as randomBytes4 } from "crypto";
4049
+ import { createHash as createHash9, randomBytes as randomBytes5 } from "crypto";
2506
4050
  import {
2507
4051
  constants as constants2,
2508
4052
  chmodSync as chmodSync4,
@@ -2513,25 +4057,25 @@ import {
2513
4057
  mkdirSync as mkdirSync5,
2514
4058
  openSync as openSync2,
2515
4059
  renameSync as renameSync2,
2516
- rmSync as rmSync7,
2517
- writeFileSync as writeFileSync3
4060
+ rmSync as rmSync8,
4061
+ writeFileSync as writeFileSync4
2518
4062
  } from "fs";
2519
- import { dirname as dirname6, join as join10 } from "path";
4063
+ import { dirname as dirname7, join as join12 } from "path";
2520
4064
  var DIRECTORY_MODE2 = 448;
2521
4065
  var FILE_MODE2 = 384;
2522
4066
  var DEAD_LETTER_DIRNAME = "dead-letter";
2523
4067
  function deadLetterDirectoryForRotation(flushingPath) {
2524
- return join10(dirname6(flushingPath), DEAD_LETTER_DIRNAME);
4068
+ return join12(dirname7(flushingPath), DEAD_LETTER_DIRNAME);
2525
4069
  }
2526
4070
  function deadLetterPathForRawLine(flushingPath, rawLine) {
2527
- const quarantineId = createHash7("sha256").update(rawLine).digest("hex");
2528
- return join10(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
4071
+ const quarantineId = createHash9("sha256").update(rawLine).digest("hex");
4072
+ return join12(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
2529
4073
  }
2530
4074
  function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
2531
4075
  const directory = deadLetterDirectoryForRotation(flushingPath);
2532
4076
  mkdirSync5(directory, { recursive: true, mode: DIRECTORY_MODE2 });
2533
4077
  chmodSync4(directory, DIRECTORY_MODE2);
2534
- persistDirectory(dirname6(directory));
4078
+ persistDirectory(dirname7(directory));
2535
4079
  return directory;
2536
4080
  }
2537
4081
  function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
@@ -2539,16 +4083,16 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
2539
4083
  persistDirectory(directory);
2540
4084
  return;
2541
4085
  }
2542
- const temporaryPath = join10(
4086
+ const temporaryPath = join12(
2543
4087
  directory,
2544
- `.${quarantineId}.${String(process.pid)}.${randomBytes4(8).toString("hex")}.tmp`
4088
+ `.${quarantineId}.${String(process.pid)}.${randomBytes5(8).toString("hex")}.tmp`
2545
4089
  );
2546
4090
  const flags = constants2.O_CREAT | constants2.O_EXCL | constants2.O_WRONLY | constants2.O_NOFOLLOW;
2547
4091
  try {
2548
4092
  const fd = openSync2(temporaryPath, flags, FILE_MODE2);
2549
4093
  try {
2550
4094
  fchmodSync2(fd, FILE_MODE2);
2551
- writeFileSync3(fd, `${JSON.stringify(record)}
4095
+ writeFileSync4(fd, `${JSON.stringify(record)}
2552
4096
  `, "utf8");
2553
4097
  fsyncSync2(fd);
2554
4098
  } finally {
@@ -2557,7 +4101,7 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
2557
4101
  renameSync2(temporaryPath, path);
2558
4102
  persistDirectory(directory);
2559
4103
  } finally {
2560
- rmSync7(temporaryPath, { force: true });
4104
+ rmSync8(temporaryPath, { force: true });
2561
4105
  }
2562
4106
  }
2563
4107
  function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
@@ -2566,12 +4110,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
2566
4110
  const serializedMove = JSON.stringify(move);
2567
4111
  const record = {
2568
4112
  version: 1,
2569
- quarantineId: createHash7("sha256").update(serializedMove).digest("hex"),
4113
+ quarantineId: createHash9("sha256").update(serializedMove).digest("hex"),
2570
4114
  quarantinedAt: now(),
2571
4115
  reason,
2572
4116
  move
2573
4117
  };
2574
- const path = join10(directory, `${record.quarantineId}.json`);
4118
+ const path = join12(directory, `${record.quarantineId}.json`);
2575
4119
  persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
2576
4120
  return record;
2577
4121
  }
@@ -2582,7 +4126,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
2582
4126
  const record = {
2583
4127
  version: 1,
2584
4128
  recordKind: "raw_line_v1",
2585
- quarantineId: createHash7("sha256").update(bytes).digest("hex"),
4129
+ quarantineId: createHash9("sha256").update(bytes).digest("hex"),
2586
4130
  quarantinedAt: now(),
2587
4131
  reason: "invalid_move",
2588
4132
  rawLineEncoding: "base64",
@@ -2603,12 +4147,12 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
2603
4147
  import {
2604
4148
  chmodSync as chmodSync5,
2605
4149
  existsSync as existsSync6,
2606
- readFileSync as readFileSync9,
2607
- readdirSync,
2608
- rmSync as rmSync8,
4150
+ readFileSync as readFileSync10,
4151
+ readdirSync as readdirSync2,
4152
+ rmSync as rmSync9,
2609
4153
  rmdirSync
2610
4154
  } from "fs";
2611
- import { basename as basename2, dirname as dirname7, join as join11 } from "path";
4155
+ import { basename as basename3, dirname as dirname8, join as join13 } from "path";
2612
4156
  var DIRECTORY_MODE3 = 448;
2613
4157
  var FILE_MODE3 = 384;
2614
4158
  var DRAIN_PROGRESS_DIRNAME = "drain-progress";
@@ -2617,10 +4161,10 @@ function rotationIdentity(stat) {
2617
4161
  return { size: stat.size, ino: stat.ino, dev: stat.dev };
2618
4162
  }
2619
4163
  function drainProgressDirectory(flushingPath) {
2620
- return join11(dirname7(flushingPath), DRAIN_PROGRESS_DIRNAME);
4164
+ return join13(dirname8(flushingPath), DRAIN_PROGRESS_DIRNAME);
2621
4165
  }
2622
4166
  function drainProgressPath(flushingPath) {
2623
- return join11(drainProgressDirectory(flushingPath), `${basename2(flushingPath)}.json`);
4167
+ return join13(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
2624
4168
  }
2625
4169
  function isByteCount(value) {
2626
4170
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
@@ -2628,7 +4172,7 @@ function isByteCount(value) {
2628
4172
  function drainResumeOffset(flushingPath, rotation) {
2629
4173
  let parsed;
2630
4174
  try {
2631
- parsed = JSON.parse(readFileSync9(drainProgressPath(flushingPath), "utf8"));
4175
+ parsed = JSON.parse(readFileSync10(drainProgressPath(flushingPath), "utf8"));
2632
4176
  } catch {
2633
4177
  return 0;
2634
4178
  }
@@ -2661,24 +4205,24 @@ function removeEmptyDirectory(directory) {
2661
4205
  }
2662
4206
  }
2663
4207
  function removeDrainCheckpoint(flushingPath) {
2664
- rmSync8(drainProgressPath(flushingPath), { force: true });
4208
+ rmSync9(drainProgressPath(flushingPath), { force: true });
2665
4209
  removeEmptyDirectory(drainProgressDirectory(flushingPath));
2666
4210
  }
2667
4211
  function sweepOrphanedDrainCheckpoints(bucketDirectory) {
2668
- const directory = join11(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
4212
+ const directory = join13(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
2669
4213
  let names;
2670
4214
  try {
2671
- names = readdirSync(directory);
4215
+ names = readdirSync2(directory);
2672
4216
  } catch {
2673
4217
  return;
2674
4218
  }
2675
4219
  for (const name of names) {
2676
4220
  const rotation = CHECKPOINT_NAME.exec(name)?.[1];
2677
- if (rotation === void 0 || existsSync6(join11(bucketDirectory, rotation))) {
4221
+ if (rotation === void 0 || existsSync6(join13(bucketDirectory, rotation))) {
2678
4222
  continue;
2679
4223
  }
2680
4224
  try {
2681
- rmSync8(join11(directory, name), { force: true });
4225
+ rmSync9(join13(directory, name), { force: true });
2682
4226
  } catch {
2683
4227
  }
2684
4228
  }
@@ -29375,22 +30919,38 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
29375
30919
 
29376
30920
  // src/lib/activation.ts
29377
30921
  import { execFileSync as execFileSync4 } from "child_process";
29378
- import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
30922
+ import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
29379
30923
  import { homedir as homedir2 } from "os";
29380
- import { join as join12 } from "path";
30924
+ import { join as join15 } from "path";
30925
+
30926
+ // src/lib/cloud-prepared.ts
30927
+ import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
30928
+ import { join as join14 } from "path";
30929
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
30930
+ function cloudPreparedPath(env = process.env) {
30931
+ return join14(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
30932
+ }
30933
+ function isPreparedCloudSession(env = process.env) {
30934
+ if (!isClaudeCloudSession(env)) return false;
30935
+ try {
30936
+ return existsSync7(cloudPreparedPath(env));
30937
+ } catch {
30938
+ return false;
30939
+ }
30940
+ }
29381
30941
 
29382
30942
  // src/lib/demo-pause.ts
29383
- import { execFileSync as execFileSync2 } from "child_process";
30943
+ import { execFileSync as execFileSync3 } from "child_process";
29384
30944
  var DEMO_PAUSE_MS = 30 * 6e4;
29385
30945
  var PAUSE_KEY = "prim.demoPause";
29386
- var GIT_TIMEOUT_MS = 1e3;
29387
- function git(cwd, args) {
30946
+ var GIT_TIMEOUT_MS3 = 1e3;
30947
+ function git2(cwd, args) {
29388
30948
  try {
29389
- return execFileSync2("git", args, {
30949
+ return execFileSync3("git", args, {
29390
30950
  cwd,
29391
30951
  encoding: "utf-8",
29392
30952
  stdio: ["ignore", "pipe", "ignore"],
29393
- timeout: GIT_TIMEOUT_MS
30953
+ timeout: GIT_TIMEOUT_MS3
29394
30954
  });
29395
30955
  } catch {
29396
30956
  return void 0;
@@ -29398,10 +30958,10 @@ function git(cwd, args) {
29398
30958
  }
29399
30959
  function setLocal(cwd, key, value) {
29400
30960
  try {
29401
- execFileSync2(
30961
+ execFileSync3(
29402
30962
  "git",
29403
30963
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
29404
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
30964
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
29405
30965
  );
29406
30966
  } catch (error) {
29407
30967
  if (value !== null || error.status !== 5) throw error;
@@ -29415,7 +30975,7 @@ function parsePause(value) {
29415
30975
  function readCaptureConfig(cwd) {
29416
30976
  let active;
29417
30977
  let pause;
29418
- const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
30978
+ const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
29419
30979
  for (const line of out.split("\n")) {
29420
30980
  const space = line.indexOf(" ");
29421
30981
  const key = line.slice(0, space).toLowerCase();
@@ -29440,60 +31000,13 @@ function healDemoPause(cwd, pause, options = {}) {
29440
31000
  }
29441
31001
  }
29442
31002
 
29443
- // src/lib/git.ts
29444
- import { execFileSync as execFileSync3 } from "child_process";
29445
- import { createHash as createHash8 } from "crypto";
29446
- import { lstatSync as lstatSync5, realpathSync } from "fs";
29447
- import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
29448
- var GIT_TIMEOUT_MS2 = 1e3;
29449
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
29450
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
29451
- function gitToplevel(cwd) {
29452
- try {
29453
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
29454
- cwd,
29455
- encoding: "utf-8",
29456
- stdio: ["ignore", "pipe", "ignore"],
29457
- timeout: GIT_TIMEOUT_MS2
29458
- }).trim();
29459
- } catch {
29460
- return null;
29461
- }
29462
- }
29463
- function gitValue(cwd, args) {
29464
- try {
29465
- const value = execFileSync3("git", args, {
29466
- cwd,
29467
- encoding: "utf-8",
29468
- stdio: ["ignore", "pipe", "ignore"],
29469
- timeout: GIT_TIMEOUT_MS2
29470
- }).trim();
29471
- return value || void 0;
29472
- } catch {
29473
- return void 0;
29474
- }
29475
- }
29476
- function githubRepositoryFullName(cwd) {
29477
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
29478
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
29479
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
29480
- remote
29481
- );
29482
- const path = match?.[1] ?? match?.[2];
29483
- if (!path) return null;
29484
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
29485
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
29486
- return null;
29487
- }
29488
- return `${parts[0]}/${parts[1]}`;
29489
- }
29490
-
29491
31003
  // src/lib/activation.ts
29492
31004
  var PRIM_ACTIVE_KEY = "prim.active";
31005
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
29493
31006
  var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
29494
31007
  var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
29495
31008
  var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
29496
- var GIT_TIMEOUT_MS3 = 1e3;
31009
+ var GIT_TIMEOUT_MS4 = 1e3;
29497
31010
  var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
29498
31011
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
29499
31012
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -29503,7 +31016,7 @@ function repoActiveFlag(cwd, strict = false) {
29503
31016
  cwd,
29504
31017
  encoding: "utf-8",
29505
31018
  stdio: ["ignore", "pipe", "ignore"],
29506
- timeout: GIT_TIMEOUT_MS3
31019
+ timeout: GIT_TIMEOUT_MS4
29507
31020
  }).trim();
29508
31021
  if (value === "true") return "true";
29509
31022
  if (value === "false") return "false";
@@ -29524,7 +31037,7 @@ function localGitConfigValue(cwd, key) {
29524
31037
  cwd,
29525
31038
  encoding: "utf-8",
29526
31039
  stdio: ["ignore", "pipe", "ignore"],
29527
- timeout: GIT_TIMEOUT_MS3
31040
+ timeout: GIT_TIMEOUT_MS4
29528
31041
  }).trim();
29529
31042
  return value || void 0;
29530
31043
  } catch {
@@ -29535,7 +31048,7 @@ function setLocalGitConfigValue(cwd, key, value) {
29535
31048
  execFileSync4("git", ["config", "--local", key, value], {
29536
31049
  cwd,
29537
31050
  stdio: ["ignore", "ignore", "pipe"],
29538
- timeout: GIT_TIMEOUT_MS3
31051
+ timeout: GIT_TIMEOUT_MS4
29539
31052
  });
29540
31053
  }
29541
31054
  function repoSyncId(cwd) {
@@ -29553,14 +31066,13 @@ function repositoryBindingState(cwd) {
29553
31066
  if (marker !== void 0) return "invalid";
29554
31067
  return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
29555
31068
  }
29556
- function hasProjectPrimInstall(cwd) {
29557
- const root = gitToplevel(cwd);
31069
+ function projectPrimInstallAt(root) {
29558
31070
  if (root === null || root === homedir2()) return false;
29559
31071
  for (const rel of PROJECT_INSTALL_FILES) {
29560
- const path = join12(root, rel);
29561
- if (existsSync7(path)) {
31072
+ const path = join15(root, rel);
31073
+ if (existsSync8(path)) {
29562
31074
  try {
29563
- const content = readFileSync10(path, "utf-8");
31075
+ const content = readFileSync12(path, "utf-8");
29564
31076
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
29565
31077
  } catch {
29566
31078
  }
@@ -29568,12 +31080,27 @@ function hasProjectPrimInstall(cwd) {
29568
31080
  }
29569
31081
  return false;
29570
31082
  }
31083
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
31084
+ function declaresInactiveAt(root) {
31085
+ if (root === null || root === homedir2()) return false;
31086
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
31087
+ const text = checkoutSettingsText(root);
31088
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
31089
+ try {
31090
+ JSON.parse(text);
31091
+ return false;
31092
+ } catch {
31093
+ return true;
31094
+ }
31095
+ }
29571
31096
  function isRepoActiveForCapture(cwd, options = {}) {
29572
31097
  let { active: flag, pause } = readCaptureConfig(cwd);
29573
31098
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
29574
31099
  if (flag === "true") return true;
29575
31100
  if (flag === "false") return false;
29576
- return hasProjectPrimInstall(cwd);
31101
+ const root = gitToplevel(cwd);
31102
+ if (declaresInactiveAt(root)) return false;
31103
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
29577
31104
  }
29578
31105
  function decisionIngestionStatus(cwd) {
29579
31106
  return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
@@ -29859,11 +31386,15 @@ function classifyJournalBuckets(buckets, binding) {
29859
31386
  continue;
29860
31387
  }
29861
31388
  if (binding.captureAuthorityKind === "workos_m2m") {
29862
- if (binding.clientId && bucket === machineJournalBucket({
29863
- apiUrl: machineApiUrl(getSiteUrl()),
31389
+ const apiUrl = machineApiUrl(getSiteUrl());
31390
+ if (binding.clientId && (bucket === machineJournalBucket({
31391
+ apiUrl,
29864
31392
  clientId: binding.clientId,
29865
31393
  authorizedUserId: binding.authorizedUserId
29866
- }))
31394
+ }) || // What this client captured before its identity was verified. Those
31395
+ // belong to whoever the server says the client is, which is now
31396
+ // known; no verified identity's bucket is opened this way.
31397
+ bucket === machinePendingBucket({ apiUrl, clientId: binding.clientId })))
29867
31398
  deliverableBuckets.add(bucket);
29868
31399
  else
29869
31400
  retainedBuckets.push({
@@ -29886,14 +31417,17 @@ function classifyJournalBuckets(buckets, binding) {
29886
31417
  }
29887
31418
  function buildOrganizationBoundMoveRequest(batch, binding) {
29888
31419
  const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
29889
- const request2 = {
31420
+ const request3 = {
29890
31421
  batch: batch.map((move) => {
29891
31422
  if (typeof move !== "object" || move === null || Array.isArray(move)) {
29892
31423
  return move;
29893
31424
  }
29894
31425
  const { captureActor, ...wireMove } = move;
29895
31426
  if (binding.captureAuthorityKind === "workos_m2m") {
29896
- if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId)
31427
+ if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || // An identity-pending actor names only its client and is bound to
31428
+ // the identity verified for it. Any other actor is a claim about a
31429
+ // verified identity and must match this one exactly.
31430
+ !identityPending(captureActor) && (captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId))
29897
31431
  throw new InvalidJournalEnvelopeError();
29898
31432
  } else if (captureActor) throw new InvalidJournalEnvelopeError();
29899
31433
  return {
@@ -29909,10 +31443,10 @@ function buildOrganizationBoundMoveRequest(batch, binding) {
29909
31443
  };
29910
31444
  })
29911
31445
  };
29912
- if (!isMoveIngestRequest(request2)) {
31446
+ if (!isMoveIngestRequest(request3)) {
29913
31447
  throw new InvalidJournalEnvelopeError();
29914
31448
  }
29915
- return request2;
31449
+ return request3;
29916
31450
  }
29917
31451
  async function inspectJournalDelivery(buckets, options = {}) {
29918
31452
  const bucketList = [...new Set(buckets)];
@@ -29947,17 +31481,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
29947
31481
  import {
29948
31482
  appendFileSync,
29949
31483
  closeSync as closeSync3,
29950
- existsSync as existsSync8,
31484
+ existsSync as existsSync9,
29951
31485
  fstatSync,
29952
- mkdirSync as mkdirSync6,
31486
+ mkdirSync as mkdirSync7,
29953
31487
  openSync as openSync3,
29954
31488
  opendirSync,
29955
- readFileSync as readFileSync11,
31489
+ readFileSync as readFileSync13,
29956
31490
  readSync,
29957
- readdirSync as readdirSync2
31491
+ readdirSync as readdirSync3
29958
31492
  } from "fs";
29959
- import { dirname as dirname9, join as join13 } from "path";
29960
- var JOURNAL_DIR = join13(primConfigDirectory(), "moves");
31493
+ import { dirname as dirname9, join as join16 } from "path";
31494
+ var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
29961
31495
  var JOURNAL_BASENAME = "journal.ndjson";
29962
31496
  var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
29963
31497
  var PENDING_STATS_MAX_FILES = 128;
@@ -29969,7 +31503,7 @@ function envSlug(apiUrl) {
29969
31503
  return slug;
29970
31504
  }
29971
31505
  function currentEnvDir() {
29972
- return join13(JOURNAL_DIR, envSlug(getSiteUrl()));
31506
+ return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
29973
31507
  }
29974
31508
  function parseMoves(content) {
29975
31509
  const moves = [];
@@ -29987,15 +31521,15 @@ function parseMoves(content) {
29987
31521
  function listBuckets() {
29988
31522
  const out = [];
29989
31523
  const envDir = currentEnvDir();
29990
- if (!existsSync8(envDir)) {
31524
+ if (!existsSync9(envDir)) {
29991
31525
  return out;
29992
31526
  }
29993
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31527
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
29994
31528
  if (!entry.isDirectory()) {
29995
31529
  continue;
29996
31530
  }
29997
- const path = join13(envDir, entry.name, JOURNAL_BASENAME);
29998
- if (existsSync8(path)) {
31531
+ const path = join16(envDir, entry.name, JOURNAL_BASENAME);
31532
+ if (existsSync9(path)) {
29999
31533
  out.push({ bucket: entry.name, path });
30000
31534
  }
30001
31535
  }
@@ -30057,7 +31591,7 @@ function parseFlushingPid(name) {
30057
31591
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
30058
31592
  }
30059
31593
  function listFlushingInDir(dir, bucket, options = {}) {
30060
- if (!existsSync8(dir)) {
31594
+ if (!existsSync9(dir)) {
30061
31595
  return [];
30062
31596
  }
30063
31597
  const out = [];
@@ -30071,7 +31605,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
30071
31605
  entry = entries.readSync();
30072
31606
  continue;
30073
31607
  }
30074
- const path = join13(dir, entry.name);
31608
+ const path = join16(dir, entry.name);
30075
31609
  let sample;
30076
31610
  try {
30077
31611
  sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
@@ -30098,18 +31632,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
30098
31632
  }
30099
31633
  function listFlushing(options = {}) {
30100
31634
  const envDir = currentEnvDir();
30101
- if (!existsSync8(envDir)) {
31635
+ if (!existsSync9(envDir)) {
30102
31636
  return [];
30103
31637
  }
30104
31638
  const out = [];
30105
31639
  let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
30106
31640
  const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
30107
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31641
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
30108
31642
  if (out.length >= maxFiles) {
30109
31643
  break;
30110
31644
  }
30111
31645
  if (entry.isDirectory()) {
30112
- const found = listFlushingInDir(join13(envDir, entry.name), entry.name, {
31646
+ const found = listFlushingInDir(join16(envDir, entry.name), entry.name, {
30113
31647
  sampleBytes: remainingBytes,
30114
31648
  maxFiles: maxFiles - out.length
30115
31649
  });
@@ -30124,12 +31658,12 @@ function listFlushing(options = {}) {
30124
31658
  }
30125
31659
  function sweepOrphanedDrainProgress() {
30126
31660
  const envDir = currentEnvDir();
30127
- if (!existsSync8(envDir)) {
31661
+ if (!existsSync9(envDir)) {
30128
31662
  return;
30129
31663
  }
30130
- for (const entry of readdirSync2(envDir, { withFileTypes: true })) {
31664
+ for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
30131
31665
  if (entry.isDirectory()) {
30132
- sweepOrphanedDrainCheckpoints(join13(envDir, entry.name));
31666
+ sweepOrphanedDrainCheckpoints(join16(envDir, entry.name));
30133
31667
  }
30134
31668
  }
30135
31669
  }
@@ -30308,11 +31842,11 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
30308
31842
  const postBatch = async (batch2) => {
30309
31843
  const moves = batch2.map((entry) => entry.move);
30310
31844
  try {
30311
- const request2 = buildOrganizationBoundMoveRequest(moves, binding);
30312
- if (Buffer.byteLength(JSON.stringify(request2)) > MAX_INGEST_REQUEST_BYTES) {
31845
+ const request3 = buildOrganizationBoundMoveRequest(moves, binding);
31846
+ if (Buffer.byteLength(JSON.stringify(request3)) > MAX_INGEST_REQUEST_BYTES) {
30313
31847
  throw new IngestRequestTooLargeError();
30314
31848
  }
30315
- const response = await client2.post("/api/cli/moves/ingest", request2, {
31849
+ const response = await client2.post("/api/cli/moves/ingest", request3, {
30316
31850
  signal: AbortSignal.timeout(HTTP_TIMEOUT_MS)
30317
31851
  });
30318
31852
  requireDurableIngestAcknowledgement(response, moves.length, collectionScopeRoots(moves));
@@ -30457,12 +31991,12 @@ async function recoverOrphans(candidates, options) {
30457
31991
  if (summary.failedBuckets.has(file.bucket)) {
30458
31992
  continue;
30459
31993
  }
30460
- const { counts, failure } = await settleDrain((onProgress) => drain(file.path, onProgress));
31994
+ const { counts, failure: failure2 } = await settleDrain((onProgress) => drain(file.path, onProgress));
30461
31995
  summary.flushed += counts.flushed;
30462
31996
  summary.quarantined += counts.quarantined;
30463
- if (failure) {
31997
+ if (failure2) {
30464
31998
  summary.failedDrainFlushed += counts.flushed;
30465
- summary.errors.push(failure.error);
31999
+ summary.errors.push(failure2.error);
30466
32000
  summary.failedBuckets.add(file.bucket);
30467
32001
  }
30468
32002
  }
@@ -30521,14 +32055,14 @@ async function flushOnce() {
30521
32055
  if (recovered.failedBuckets.has(bucket)) {
30522
32056
  continue;
30523
32057
  }
30524
- const { counts, failure } = await settleDrain(
32058
+ const { counts, failure: failure2 } = await settleDrain(
30525
32059
  (onProgress) => drainPath(path, client2, binding, onProgress)
30526
32060
  );
30527
32061
  total += counts.flushed;
30528
32062
  quarantined += counts.quarantined;
30529
- if (failure) {
32063
+ if (failure2) {
30530
32064
  failedDrainFlushed += counts.flushed;
30531
- errors.push(failure.error);
32065
+ errors.push(failure2.error);
30532
32066
  }
30533
32067
  }
30534
32068
  if (errors.length > 0) {
@@ -30543,7 +32077,7 @@ async function flushOnce() {
30543
32077
  return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
30544
32078
  }
30545
32079
  var flushInFlight;
30546
- var FLUSH_LOCK_PATH = join14(dirname10(JOURNAL_DIR), ".flush.lock");
32080
+ var FLUSH_LOCK_PATH = join17(dirname10(JOURNAL_DIR), ".flush.lock");
30547
32081
  var FLUSH_LOCK_TIMEOUT_MS = 250;
30548
32082
  function isFlushLockContended(error) {
30549
32083
  return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
@@ -30745,14 +32279,14 @@ var StatuslineIngestionCache = class {
30745
32279
 
30746
32280
  // src/daemon/client.ts
30747
32281
  import { createConnection } from "net";
30748
- import { join as join15 } from "path";
30749
- var SOCK_PATH = join15(primConfigDirectory(), "sock");
32282
+ import { join as join18 } from "path";
32283
+ var SOCK_PATH = join18(primConfigDirectory(), "sock");
30750
32284
  var DEFAULT_TIMEOUT_MS2 = 250;
30751
32285
  var nextRequestId = 1;
30752
32286
  function daemonRequest(method, params = {}, opts = {}) {
30753
32287
  const id = nextRequestId++;
30754
32288
  const caller = resolveDaemonPrincipal();
30755
- const request2 = {
32289
+ const request3 = {
30756
32290
  id,
30757
32291
  method,
30758
32292
  params,
@@ -30791,7 +32325,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30791
32325
  });
30792
32326
  socket.on("connect", () => {
30793
32327
  try {
30794
- socket?.write(`${JSON.stringify(request2)}
32328
+ socket?.write(`${JSON.stringify(request3)}
30795
32329
  `);
30796
32330
  } catch {
30797
32331
  clearTimeout(timer);
@@ -30836,7 +32370,7 @@ function daemonRequest(method, params = {}, opts = {}) {
30836
32370
  }
30837
32371
 
30838
32372
  // src/daemon/decision-digest-cache.ts
30839
- import { randomBytes as randomBytes5 } from "crypto";
32373
+ import { randomBytes as randomBytes6 } from "crypto";
30840
32374
  var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
30841
32375
  var DECISION_DIGEST_CACHE_LIMIT = 100;
30842
32376
  var DECISION_DIGEST_CACHE_WINDOW = "24h";
@@ -30866,7 +32400,7 @@ function errorMessage(error) {
30866
32400
  return error instanceof Error ? error.message : String(error);
30867
32401
  }
30868
32402
  function privatePageToken() {
30869
- return randomBytes5(16).toString("hex");
32403
+ return randomBytes6(16).toString("hex");
30870
32404
  }
30871
32405
  var DecisionDigestCache = class {
30872
32406
  constructor(load, now = Date.now, options = {}) {
@@ -31017,8 +32551,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
31017
32551
  }
31018
32552
 
31019
32553
  // src/daemon/health.ts
31020
- import { chmodSync as chmodSync6, existsSync as existsSync9, mkdirSync as mkdirSync7, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "fs";
31021
- import { dirname as dirname11, join as join16 } from "path";
32554
+ import { chmodSync as chmodSync6, existsSync as existsSync10, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
32555
+ import { dirname as dirname11, join as join19 } from "path";
31022
32556
  var CONFIG_DIR_MODE2 = 448;
31023
32557
  var HEALTH_FILE_MODE = 384;
31024
32558
  var INGESTION_SLA_MS = 3e4;
@@ -31026,7 +32560,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
31026
32560
  var HEARTBEAT_RETRY_CAP_MS = 3e4;
31027
32561
  var INGESTION_RETRY_BASE_MS = 5e3;
31028
32562
  var INGESTION_RETRY_CAP_MS = 15e3;
31029
- var DAEMON_HEALTH_PATH = join16(primConfigDirectory(), "daemon-health.json");
32563
+ var DAEMON_HEALTH_PATH = join19(primConfigDirectory(), "daemon-health.json");
31030
32564
  function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
31031
32565
  return {
31032
32566
  schemaVersion: 1,
@@ -31068,11 +32602,11 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
31068
32602
  }
31069
32603
  function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
31070
32604
  const dir = dirname11(path);
31071
- if (!existsSync9(dir)) {
31072
- mkdirSync7(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
32605
+ if (!existsSync10(dir)) {
32606
+ mkdirSync8(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
31073
32607
  }
31074
- const tmp = join16(dir, `.${process.pid}.daemon-health.tmp`);
31075
- writeFileSync4(tmp, `${JSON.stringify(state, null, 2)}
32608
+ const tmp = join19(dir, `.${process.pid}.daemon-health.tmp`);
32609
+ writeFileSync6(tmp, `${JSON.stringify(state, null, 2)}
31076
32610
  `, { mode: HEALTH_FILE_MODE });
31077
32611
  chmodSync6(tmp, HEALTH_FILE_MODE);
31078
32612
  renameSync4(tmp, path);
@@ -31082,22 +32616,22 @@ function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
31082
32616
  import { randomUUID as randomUUID3 } from "crypto";
31083
32617
  import {
31084
32618
  chmodSync as chmodSync7,
31085
- existsSync as existsSync10,
31086
- mkdirSync as mkdirSync8,
31087
- readFileSync as readFileSync12,
32619
+ existsSync as existsSync11,
32620
+ mkdirSync as mkdirSync9,
32621
+ readFileSync as readFileSync14,
31088
32622
  renameSync as renameSync5,
31089
- rmSync as rmSync9,
32623
+ rmSync as rmSync11,
31090
32624
  statSync as statSync3,
31091
32625
  unlinkSync as unlinkSync2,
31092
- writeFileSync as writeFileSync5
32626
+ writeFileSync as writeFileSync7
31093
32627
  } from "fs";
31094
- import { join as join17 } from "path";
32628
+ import { join as join20 } from "path";
31095
32629
  var DIR_MODE = 448;
31096
32630
  var FILE_MODE4 = 384;
31097
32631
  var DAEMON_STARTUP_GRACE_MS = 5e3;
31098
32632
  function readLockRecord(path) {
31099
32633
  try {
31100
- const value = JSON.parse(readFileSync12(path, "utf-8"));
32634
+ const value = JSON.parse(readFileSync14(path, "utf-8"));
31101
32635
  if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
31102
32636
  return value;
31103
32637
  }
@@ -31107,17 +32641,17 @@ function readLockRecord(path) {
31107
32641
  }
31108
32642
  function numericPid(path) {
31109
32643
  try {
31110
- const pid = Number(readFileSync12(path, "utf-8").trim());
32644
+ const pid = Number(readFileSync14(path, "utf-8").trim());
31111
32645
  return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
31112
32646
  } catch {
31113
32647
  return;
31114
32648
  }
31115
32649
  }
31116
32650
  function readDaemonOwner(configDir) {
31117
- return readLockRecord(join17(configDir, "daemon.lock", "owner.json"));
32651
+ return readLockRecord(join20(configDir, "daemon.lock", "owner.json"));
31118
32652
  }
31119
32653
  function readDaemonPid(configDir) {
31120
- const path = join17(configDir, "daemon.pid");
32654
+ const path = join20(configDir, "daemon.pid");
31121
32655
  const pid = numericPid(path);
31122
32656
  if (pid === void 0) {
31123
32657
  return;
@@ -31132,16 +32666,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31132
32666
  const pid = opts.pid ?? process.pid;
31133
32667
  const now = opts.now ?? Date.now();
31134
32668
  const isAlive = opts.isAlive ?? processIsAlive;
31135
- const lockDir = join17(configDir, "daemon.lock");
31136
- const ownerPath2 = join17(lockDir, "owner.json");
31137
- const pidPath = join17(configDir, "daemon.pid");
32669
+ const lockDir = join20(configDir, "daemon.lock");
32670
+ const ownerPath2 = join20(lockDir, "owner.json");
32671
+ const pidPath = join20(configDir, "daemon.pid");
31138
32672
  const instanceId2 = randomUUID3();
31139
- if (!existsSync10(configDir)) {
31140
- mkdirSync8(configDir, { recursive: true, mode: DIR_MODE });
32673
+ if (!existsSync11(configDir)) {
32674
+ mkdirSync9(configDir, { recursive: true, mode: DIR_MODE });
31141
32675
  }
31142
32676
  for (; ; ) {
31143
32677
  try {
31144
- mkdirSync8(lockDir, { mode: DIR_MODE });
32678
+ mkdirSync9(lockDir, { mode: DIR_MODE });
31145
32679
  break;
31146
32680
  } catch (err) {
31147
32681
  if (err.code !== "EEXIST") {
@@ -31168,7 +32702,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31168
32702
  const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
31169
32703
  try {
31170
32704
  renameSync5(lockDir, stale);
31171
- rmSync9(stale, { recursive: true, force: true });
32705
+ rmSync11(stale, { recursive: true, force: true });
31172
32706
  } catch (renameErr) {
31173
32707
  if (renameErr.code !== "ENOENT") {
31174
32708
  throw renameErr;
@@ -31185,15 +32719,15 @@ function acquireDaemonOwnership(configDir, opts = {}) {
31185
32719
  instanceId: instanceId2
31186
32720
  };
31187
32721
  const record = { pid, instanceId: instanceId2, startedAt: now };
31188
- writeFileSync5(ownerPath2, `${JSON.stringify(record)}
32722
+ writeFileSync7(ownerPath2, `${JSON.stringify(record)}
31189
32723
  `, { mode: FILE_MODE4 });
31190
32724
  chmodSync7(ownerPath2, FILE_MODE4);
31191
32725
  const legacyPid = numericPid(pidPath);
31192
32726
  if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
31193
- rmSync9(lockDir, { recursive: true, force: true });
32727
+ rmSync11(lockDir, { recursive: true, force: true });
31194
32728
  throw new Error(`daemon already running (pid=${String(legacyPid)})`);
31195
32729
  }
31196
- writeFileSync5(pidPath, String(pid), { mode: FILE_MODE4 });
32730
+ writeFileSync7(pidPath, String(pid), { mode: FILE_MODE4 });
31197
32731
  chmodSync7(pidPath, FILE_MODE4);
31198
32732
  return ownership2;
31199
32733
  }
@@ -31224,7 +32758,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
31224
32758
  }
31225
32759
  }
31226
32760
  }
31227
- rmSync9(ownership2.lockDir, { recursive: true, force: true });
32761
+ rmSync11(ownership2.lockDir, { recursive: true, force: true });
31228
32762
  if (cleanupError) {
31229
32763
  throw cleanupError;
31230
32764
  }
@@ -31261,15 +32795,15 @@ function isLegacyHeartbeatResponse(value) {
31261
32795
  ) && hasOptionalField(value, "unavailable", (candidate) => typeof candidate === "string");
31262
32796
  }
31263
32797
  function buildPresenceHeartbeatRequest(sessionId, clientInstanceId2) {
31264
- const request2 = {
32798
+ const request3 = {
31265
32799
  sessionId,
31266
32800
  clientInstanceId: clientInstanceId2,
31267
32801
  decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
31268
32802
  };
31269
- if (!isPresenceHeartbeatRequest(request2)) {
32803
+ if (!isPresenceHeartbeatRequest(request3)) {
31270
32804
  throw new Error("presence heartbeat identity or session is invalid");
31271
32805
  }
31272
- return request2;
32806
+ return request3;
31273
32807
  }
31274
32808
  function normalizePresenceHeartbeatResponse(value) {
31275
32809
  if (isPresenceHeartbeatResponse(value)) {
@@ -31319,7 +32853,7 @@ function parseStatuslineRequest(buffer) {
31319
32853
 
31320
32854
  // src/daemon/server.ts
31321
32855
  var CONFIG_DIR = primConfigDirectory();
31322
- var SOCK_PATH2 = join18(CONFIG_DIR, "sock");
32856
+ var SOCK_PATH2 = join21(CONFIG_DIR, "sock");
31323
32857
  var CONFIG_DIR_MODE3 = 448;
31324
32858
  var SOCKET_MODE = 384;
31325
32859
  var MAX_SOCKET_CONNECTIONS = 64;
@@ -31388,7 +32922,7 @@ function resolveRuntimeVersion() {
31388
32922
  }
31389
32923
  try {
31390
32924
  const here = fileURLToPath4(new URL(".", import.meta.url));
31391
- const pkg = JSON.parse(readFileSync13(join18(here, "..", "..", "package.json"), "utf-8"));
32925
+ const pkg = JSON.parse(readFileSync15(join21(here, "..", "..", "package.json"), "utf-8"));
31392
32926
  return pkg.version ?? "unknown";
31393
32927
  } catch {
31394
32928
  return "unknown";
@@ -31427,7 +32961,7 @@ function assertCallerPrincipalMatches(caller) {
31427
32961
  return credentialKey;
31428
32962
  }
31429
32963
  function ensureDaemonDirectoryPermissions() {
31430
- mkdirSync9(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
32964
+ mkdirSync10(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
31431
32965
  chmodSync8(CONFIG_DIR, CONFIG_DIR_MODE3);
31432
32966
  }
31433
32967
  function persistHealth() {
@@ -31514,7 +33048,7 @@ async function takeOwnership() {
31514
33048
  (pid) => pid !== void 0 && processIsAlive(pid)
31515
33049
  )
31516
33050
  );
31517
- if (existsSync11(SOCK_PATH2) || candidatePids.size > 0) {
33051
+ if (existsSync12(SOCK_PATH2) || candidatePids.size > 0) {
31518
33052
  const snapshot = await daemonRequest(
31519
33053
  "status_snapshot",
31520
33054
  {},
@@ -31659,7 +33193,7 @@ async function ensureTokenFresh() {
31659
33193
  }
31660
33194
  if (Date.now() >= expiresAt - TOKEN_REFRESH_THRESHOLD_MS) {
31661
33195
  try {
31662
- await refreshToken({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
33196
+ await refreshToken2({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
31663
33197
  } catch {
31664
33198
  }
31665
33199
  }
@@ -31964,15 +33498,15 @@ function handleConnection(conn) {
31964
33498
  }
31965
33499
  try {
31966
33500
  const line = utf8Decoder2.decode(jsonBuffer.subarray(0, newlineIdx));
31967
- const request2 = parseDaemonRequestEnvelope(JSON.parse(line));
31968
- if (!request2) {
33501
+ const request3 = parseDaemonRequestEnvelope(JSON.parse(line));
33502
+ if (!request3) {
31969
33503
  conn.end();
31970
33504
  return;
31971
33505
  }
31972
33506
  dispatched = true;
31973
33507
  conn.pause();
31974
- void dispatchRequest(request2).then(writeJsonResponse, () => {
31975
- writeJsonResponse({ id: request2.id, ok: false, error: "daemon request failed" });
33508
+ void dispatchRequest(request3).then(writeJsonResponse, () => {
33509
+ writeJsonResponse({ id: request3.id, ok: false, error: "daemon request failed" });
31976
33510
  });
31977
33511
  } catch {
31978
33512
  conn.end();