@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
- package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
- package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
- package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
- package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
- package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
- package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
- package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
- package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
- package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1311 -364
- package/dist/hook-runtime/daemon/server.js +1311 -364
- package/dist/hook-runtime/hooks/post-commit.js +395 -242
- package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
- package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
- package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
- package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
- package/dist/hook-runtime/hooks/session-end.js +369 -216
- package/dist/hook-runtime/hooks/session-start.js +1209 -219
- package/dist/hook-runtime/index.js +2406 -1036
- package/dist/hook-runtime/statusline-main.js +360 -207
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +63 -20
- package/dist/index.js +387 -43
- package/dist/statusline-main.js +360 -207
- package/package.json +1 -1
|
@@ -54,10 +54,10 @@ var require_ucs2length = __commonJS({
|
|
|
54
54
|
|
|
55
55
|
// src/lib/machine-broker.ts
|
|
56
56
|
import { spawn } from "child_process";
|
|
57
|
-
import { createHash as
|
|
58
|
-
import { lstatSync as
|
|
57
|
+
import { createHash as createHash5, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
58
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync6, rmSync as rmSync6 } from "fs";
|
|
59
59
|
import { createServer } from "http";
|
|
60
|
-
import { basename, join as
|
|
60
|
+
import { basename as basename2, join as join8 } from "path";
|
|
61
61
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
62
62
|
|
|
63
63
|
// src/lib/atomic-file.ts
|
|
@@ -365,20 +365,20 @@ function loopbackFetch(url, init = {}) {
|
|
|
365
365
|
}
|
|
366
366
|
|
|
367
367
|
// src/lib/machine-credentials.ts
|
|
368
|
-
import { execFileSync } from "child_process";
|
|
369
|
-
import { createHash as
|
|
368
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
369
|
+
import { createHash as createHash4, randomBytes as randomBytes2, randomUUID as randomUUID2 } from "crypto";
|
|
370
370
|
import {
|
|
371
371
|
chmodSync,
|
|
372
372
|
existsSync as existsSync3,
|
|
373
373
|
linkSync,
|
|
374
|
-
lstatSync as
|
|
374
|
+
lstatSync as lstatSync3,
|
|
375
375
|
mkdirSync as mkdirSync3,
|
|
376
|
-
readFileSync as
|
|
377
|
-
rmSync as
|
|
376
|
+
readFileSync as readFileSync5,
|
|
377
|
+
rmSync as rmSync5,
|
|
378
378
|
writeFileSync as writeFileSync3
|
|
379
379
|
} from "fs";
|
|
380
380
|
import { createRequire } from "module";
|
|
381
|
-
import { dirname as
|
|
381
|
+
import { dirname as dirname5, join as join7 } from "path";
|
|
382
382
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
383
383
|
|
|
384
384
|
// src/lib/cloud-env.ts
|
|
@@ -387,6 +387,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
387
387
|
}
|
|
388
388
|
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';
|
|
389
389
|
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';
|
|
390
|
+
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}.`;
|
|
391
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
390
392
|
function cloudSetupPointer(message, env = process.env) {
|
|
391
393
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
392
394
|
}
|
|
@@ -528,10 +530,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
528
530
|
"access_token",
|
|
529
531
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
530
532
|
);
|
|
531
|
-
const
|
|
533
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
532
534
|
return {
|
|
533
535
|
accessToken,
|
|
534
|
-
refreshToken:
|
|
536
|
+
refreshToken: refreshToken3,
|
|
535
537
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
536
538
|
};
|
|
537
539
|
}
|
|
@@ -849,61 +851,1144 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
849
851
|
throw error;
|
|
850
852
|
}
|
|
851
853
|
}
|
|
852
|
-
|
|
853
|
-
// src/lib/paths.ts
|
|
854
|
-
import { homedir } from "os";
|
|
855
|
-
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
856
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
857
|
-
function absolutePath(value, variable) {
|
|
858
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
859
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
854
|
+
|
|
855
|
+
// src/lib/paths.ts
|
|
856
|
+
import { homedir } from "os";
|
|
857
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
858
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
859
|
+
function absolutePath(value, variable) {
|
|
860
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
861
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
862
|
+
}
|
|
863
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
864
|
+
const normalized = normalize(value);
|
|
865
|
+
return normalized === value ? value : void 0;
|
|
866
|
+
}
|
|
867
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
868
|
+
const env = options.env ?? process.env;
|
|
869
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
870
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
871
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
872
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
873
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
874
|
+
if (!home) {
|
|
875
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
876
|
+
}
|
|
877
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
878
|
+
}
|
|
879
|
+
function primConfigDirectory(options = {}) {
|
|
880
|
+
return resolvePrimConfigDirectory(options).path;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
// src/lib/session-identity.ts
|
|
884
|
+
import { execFile } from "child_process";
|
|
885
|
+
import { createHash as createHash3 } from "crypto";
|
|
886
|
+
import { rmSync as rmSync4 } from "fs";
|
|
887
|
+
import { join as join6 } from "path";
|
|
888
|
+
import { promisify } from "util";
|
|
889
|
+
|
|
890
|
+
// src/lib/git.ts
|
|
891
|
+
import { execFileSync } from "child_process";
|
|
892
|
+
import { createHash as createHash2 } from "crypto";
|
|
893
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync } from "fs";
|
|
894
|
+
import { basename, dirname as dirname4, isAbsolute as isAbsolute3, join as join5, relative, resolve, sep } from "path";
|
|
895
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
896
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
897
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
898
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
899
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
900
|
+
function gitChildEnvironment(env = process.env) {
|
|
901
|
+
return Object.fromEntries(
|
|
902
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
903
|
+
);
|
|
904
|
+
}
|
|
905
|
+
function gitToplevel(cwd) {
|
|
906
|
+
try {
|
|
907
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
908
|
+
cwd,
|
|
909
|
+
encoding: "utf-8",
|
|
910
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
911
|
+
timeout: GIT_TIMEOUT_MS,
|
|
912
|
+
env: gitChildEnvironment()
|
|
913
|
+
}).trim();
|
|
914
|
+
} catch {
|
|
915
|
+
return null;
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
function gitValue(cwd, args) {
|
|
919
|
+
try {
|
|
920
|
+
const value = execFileSync("git", args, {
|
|
921
|
+
cwd,
|
|
922
|
+
encoding: "utf-8",
|
|
923
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
924
|
+
timeout: GIT_TIMEOUT_MS,
|
|
925
|
+
env: gitChildEnvironment()
|
|
926
|
+
}).trim();
|
|
927
|
+
return value || void 0;
|
|
928
|
+
} catch {
|
|
929
|
+
return void 0;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
function currentBranch(cwd) {
|
|
933
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
934
|
+
}
|
|
935
|
+
function parseGithubRepositoryName(path) {
|
|
936
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
937
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
938
|
+
return null;
|
|
939
|
+
}
|
|
940
|
+
return `${parts[0]}/${parts[1]}`;
|
|
941
|
+
}
|
|
942
|
+
function githubRepositoryFromRemote(remote) {
|
|
943
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
944
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
945
|
+
remote
|
|
946
|
+
);
|
|
947
|
+
const path = match?.[1] ?? match?.[2];
|
|
948
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
949
|
+
}
|
|
950
|
+
function checkoutSettingsText(repoRoot) {
|
|
951
|
+
const path = join5(repoRoot, ".claude", "settings.json");
|
|
952
|
+
try {
|
|
953
|
+
if (!lstatSync2(join5(repoRoot, ".claude")).isDirectory()) return null;
|
|
954
|
+
const stat = lstatSync2(path);
|
|
955
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
956
|
+
return readFileSync4(path, "utf8");
|
|
957
|
+
} catch {
|
|
958
|
+
return null;
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
962
|
+
const text = checkoutSettingsText(repoRoot);
|
|
963
|
+
if (text === null) return null;
|
|
964
|
+
let parsed;
|
|
965
|
+
try {
|
|
966
|
+
parsed = JSON.parse(text);
|
|
967
|
+
} catch {
|
|
968
|
+
return null;
|
|
969
|
+
}
|
|
970
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
971
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
972
|
+
return typeof value === "string" ? value : null;
|
|
973
|
+
}
|
|
974
|
+
function declaredGithubRepository(repoRoot) {
|
|
975
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
976
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
977
|
+
}
|
|
978
|
+
function githubRepositoryFullName(cwd) {
|
|
979
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
980
|
+
if (remote) {
|
|
981
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
982
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
983
|
+
}
|
|
984
|
+
const root = gitToplevel(cwd);
|
|
985
|
+
return root ? declaredGithubRepository(root) : null;
|
|
986
|
+
}
|
|
987
|
+
function normalizeOriginRemote(remote) {
|
|
988
|
+
const value = remote.trim();
|
|
989
|
+
if (!value) return void 0;
|
|
990
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
991
|
+
if (scp?.host && scp.path) {
|
|
992
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
993
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
994
|
+
}
|
|
995
|
+
try {
|
|
996
|
+
const url = new URL(value);
|
|
997
|
+
url.username = "";
|
|
998
|
+
url.password = "";
|
|
999
|
+
url.search = "";
|
|
1000
|
+
url.hash = "";
|
|
1001
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1002
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1003
|
+
return void 0;
|
|
1004
|
+
} catch {
|
|
1005
|
+
return void 0;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
// src/lib/terminal-safe.ts
|
|
1010
|
+
function replaceIsolatedSurrogates(value) {
|
|
1011
|
+
let out = "";
|
|
1012
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1013
|
+
const unit = value.charCodeAt(index);
|
|
1014
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1015
|
+
const next = value.charCodeAt(index + 1);
|
|
1016
|
+
if (next >= 56320 && next <= 57343) {
|
|
1017
|
+
out += value[index] + value[index + 1];
|
|
1018
|
+
index += 1;
|
|
1019
|
+
} else {
|
|
1020
|
+
out += "\uFFFD";
|
|
1021
|
+
}
|
|
1022
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1023
|
+
out += "\uFFFD";
|
|
1024
|
+
} else {
|
|
1025
|
+
out += value[index];
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
return out;
|
|
1029
|
+
}
|
|
1030
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1031
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1032
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1033
|
+
point === 1564 || // Arabic letter mark
|
|
1034
|
+
point === 6158 || // Mongolian vowel separator
|
|
1035
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1036
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1037
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1038
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1039
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1040
|
+
point >= 917504 && point <= 917631;
|
|
1041
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1042
|
+
}
|
|
1043
|
+
function terminalSafeText(value) {
|
|
1044
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1045
|
+
}
|
|
1046
|
+
function terminalSafeLine(value) {
|
|
1047
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1048
|
+
}
|
|
1049
|
+
var stripControlChars = terminalSafeText;
|
|
1050
|
+
|
|
1051
|
+
// src/lib/session-identity.ts
|
|
1052
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1053
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1054
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1055
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1056
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1057
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1058
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1059
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1060
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1061
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1062
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1063
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1064
|
+
token: "/api/cli/session-identity/token",
|
|
1065
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1066
|
+
link: "/api/cli/session-identity/link"
|
|
1067
|
+
};
|
|
1068
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1069
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1070
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1071
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1072
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1073
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1074
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1075
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1076
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1077
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1078
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1079
|
+
}
|
|
1080
|
+
function sessionIdentityMode(deps = {}) {
|
|
1081
|
+
const env = deps.env ?? process.env;
|
|
1082
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1083
|
+
}
|
|
1084
|
+
function failure(code, cause, remedy) {
|
|
1085
|
+
return { status: "failed", code, cause, remedy };
|
|
1086
|
+
}
|
|
1087
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1088
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1089
|
+
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';
|
|
1090
|
+
var SESSION_REVOKED = failure(
|
|
1091
|
+
"session_revoked",
|
|
1092
|
+
"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",
|
|
1093
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1094
|
+
);
|
|
1095
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1096
|
+
"challenge_expired",
|
|
1097
|
+
"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)",
|
|
1098
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1099
|
+
);
|
|
1100
|
+
var CHALLENGE_GONE = failure(
|
|
1101
|
+
"challenge_not_found",
|
|
1102
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1103
|
+
NEW_SESSION_REMEDY
|
|
1104
|
+
);
|
|
1105
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1106
|
+
function rejectionFailure(reason, repository) {
|
|
1107
|
+
switch (reason) {
|
|
1108
|
+
case "identity_mismatch":
|
|
1109
|
+
return failure(
|
|
1110
|
+
"identity_mismatch",
|
|
1111
|
+
"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",
|
|
1112
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1113
|
+
);
|
|
1114
|
+
case "push_after_expiry":
|
|
1115
|
+
return failure(
|
|
1116
|
+
"push_after_expiry",
|
|
1117
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1118
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1119
|
+
);
|
|
1120
|
+
case "repository_mismatch":
|
|
1121
|
+
return failure(
|
|
1122
|
+
"repository_mismatch",
|
|
1123
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1124
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1125
|
+
);
|
|
1126
|
+
case "conflicting_push":
|
|
1127
|
+
return failure(
|
|
1128
|
+
"conflicting_push",
|
|
1129
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1130
|
+
NEW_SESSION_REMEDY
|
|
1131
|
+
);
|
|
1132
|
+
case "unsupported_sender":
|
|
1133
|
+
return failure(
|
|
1134
|
+
"unsupported_sender",
|
|
1135
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1136
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1137
|
+
);
|
|
1138
|
+
default:
|
|
1139
|
+
return failure(
|
|
1140
|
+
"challenge_rejected",
|
|
1141
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1142
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1143
|
+
);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
function sessionIdentityMessage(outcome) {
|
|
1147
|
+
if (outcome.status === "link_required")
|
|
1148
|
+
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.`;
|
|
1149
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1150
|
+
}
|
|
1151
|
+
function hash(value) {
|
|
1152
|
+
return createHash3("sha256").update(value).digest("hex");
|
|
1153
|
+
}
|
|
1154
|
+
function sessionContext(deps) {
|
|
1155
|
+
const env = deps.env ?? process.env;
|
|
1156
|
+
const environment = environmentCredentials(deps);
|
|
1157
|
+
if (!environment)
|
|
1158
|
+
return failure(
|
|
1159
|
+
"environment_credential_missing",
|
|
1160
|
+
"the cloud environment has no environment credential",
|
|
1161
|
+
'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'
|
|
1162
|
+
);
|
|
1163
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1164
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1165
|
+
return failure(
|
|
1166
|
+
"session_id_missing",
|
|
1167
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1168
|
+
NEW_SESSION_REMEDY
|
|
1169
|
+
);
|
|
1170
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1171
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1172
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1173
|
+
return {
|
|
1174
|
+
directory,
|
|
1175
|
+
apiUrl,
|
|
1176
|
+
clientId: environment.clientId,
|
|
1177
|
+
generation: environment.generation,
|
|
1178
|
+
sessionId,
|
|
1179
|
+
tokenPath: join6(directory, `session_identity_${key}.json`),
|
|
1180
|
+
statePath: join6(directory, `session_identity_${key}.state.json`),
|
|
1181
|
+
lockPath: join6(directory, "session-identity.lock")
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
function readRecord(path) {
|
|
1185
|
+
try {
|
|
1186
|
+
const value = readMachineMetadata(path);
|
|
1187
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1188
|
+
} catch {
|
|
1189
|
+
return void 0;
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
function finiteNumber(value) {
|
|
1193
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1194
|
+
}
|
|
1195
|
+
function readToken(context) {
|
|
1196
|
+
const data = readRecord(context.tokenPath);
|
|
1197
|
+
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))
|
|
1198
|
+
return void 0;
|
|
1199
|
+
const identity = data.identity;
|
|
1200
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
1201
|
+
return void 0;
|
|
1202
|
+
return data;
|
|
1203
|
+
}
|
|
1204
|
+
function readState(context) {
|
|
1205
|
+
const data = readRecord(context.statePath);
|
|
1206
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
1207
|
+
return void 0;
|
|
1208
|
+
return data;
|
|
1209
|
+
}
|
|
1210
|
+
function writeToken(context, record) {
|
|
1211
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1212
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
1213
|
+
rmSync4(context.statePath, { force: true });
|
|
1214
|
+
}
|
|
1215
|
+
function writeState(context, state) {
|
|
1216
|
+
try {
|
|
1217
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1218
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
1219
|
+
} catch {
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
function tokenValid(record, now = Date.now()) {
|
|
1223
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
1224
|
+
}
|
|
1225
|
+
function tokenFresh(record, now = Date.now()) {
|
|
1226
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
1227
|
+
}
|
|
1228
|
+
function toCredential(record) {
|
|
1229
|
+
return {
|
|
1230
|
+
issuer: record.issuer,
|
|
1231
|
+
audience: record.audience,
|
|
1232
|
+
...record.identity,
|
|
1233
|
+
accessToken: record.accessToken,
|
|
1234
|
+
expiresAt: record.expiresAt,
|
|
1235
|
+
apiUrl: record.apiUrl,
|
|
1236
|
+
generation: record.generation,
|
|
1237
|
+
storage: "environment",
|
|
1238
|
+
session: {
|
|
1239
|
+
userId: record.userId,
|
|
1240
|
+
displayName: record.displayName,
|
|
1241
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1242
|
+
refreshAfter: record.refreshAfter
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
function identified(record, reused) {
|
|
1247
|
+
return {
|
|
1248
|
+
status: "ok",
|
|
1249
|
+
credential: toCredential(record),
|
|
1250
|
+
displayName: record.displayName,
|
|
1251
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1252
|
+
reused
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
function cachedSessionCredential(deps = {}) {
|
|
1256
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
1257
|
+
let context;
|
|
1258
|
+
try {
|
|
1259
|
+
context = sessionContext(deps);
|
|
1260
|
+
} catch {
|
|
1261
|
+
return void 0;
|
|
1262
|
+
}
|
|
1263
|
+
if ("status" in context) return void 0;
|
|
1264
|
+
const record = readToken(context);
|
|
1265
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
1266
|
+
}
|
|
1267
|
+
function outcomeFromState(state) {
|
|
1268
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
1269
|
+
return {
|
|
1270
|
+
status: "link_required",
|
|
1271
|
+
githubLogin: state.githubLogin,
|
|
1272
|
+
challengeId: state.challengeId,
|
|
1273
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
1274
|
+
};
|
|
1275
|
+
return failure(
|
|
1276
|
+
state.code,
|
|
1277
|
+
state.cause ?? "the last identity check failed",
|
|
1278
|
+
state.remedy ?? RETRY_REMEDY
|
|
1279
|
+
);
|
|
1280
|
+
}
|
|
1281
|
+
function parseInstant(value) {
|
|
1282
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
1283
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
1284
|
+
const parsed = Date.parse(value);
|
|
1285
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1286
|
+
}
|
|
1287
|
+
return void 0;
|
|
1288
|
+
}
|
|
1289
|
+
async function sendJson(url, init, fetchImpl) {
|
|
1290
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
1291
|
+
let value;
|
|
1292
|
+
try {
|
|
1293
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
1294
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
1295
|
+
} catch {
|
|
1296
|
+
value = void 0;
|
|
1297
|
+
}
|
|
1298
|
+
return { status: response.status, value };
|
|
1299
|
+
}
|
|
1300
|
+
function environmentOnly(deps) {
|
|
1301
|
+
return { ...deps, environmentOnly: true };
|
|
1302
|
+
}
|
|
1303
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
1304
|
+
const send = async (credential2) => {
|
|
1305
|
+
const headers = { "Content-Type": "application/json" };
|
|
1306
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1307
|
+
if (credential2.tokenInjection) {
|
|
1308
|
+
const response = await forwardMachineRequest(
|
|
1309
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
1310
|
+
signal,
|
|
1311
|
+
environmentOnly(deps)
|
|
1312
|
+
);
|
|
1313
|
+
const parsed = await response.json().catch(() => void 0);
|
|
1314
|
+
return {
|
|
1315
|
+
status: response.status,
|
|
1316
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
1317
|
+
};
|
|
1318
|
+
}
|
|
1319
|
+
return sendJson(
|
|
1320
|
+
`${credential2.apiUrl}${path}`,
|
|
1321
|
+
{
|
|
1322
|
+
method,
|
|
1323
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
1324
|
+
...text === void 0 ? {} : { body: text },
|
|
1325
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
1326
|
+
},
|
|
1327
|
+
deps.fetch ?? fetch
|
|
1328
|
+
);
|
|
1329
|
+
};
|
|
1330
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1331
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1332
|
+
let answer = await send(credential);
|
|
1333
|
+
if (answer.status === 401) {
|
|
1334
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
1335
|
+
if (!credential)
|
|
1336
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1337
|
+
answer = await send(credential);
|
|
1338
|
+
}
|
|
1339
|
+
return answer;
|
|
1340
|
+
}
|
|
1341
|
+
function environmentFailure(error, apiUrl) {
|
|
1342
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1343
|
+
return failure(
|
|
1344
|
+
"environment_credential_rejected",
|
|
1345
|
+
"Primitive rejected the cloud environment's credential",
|
|
1346
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
1347
|
+
);
|
|
1348
|
+
const host = (() => {
|
|
1349
|
+
try {
|
|
1350
|
+
return new URL(apiUrl).hostname;
|
|
1351
|
+
} catch {
|
|
1352
|
+
return "Primitive";
|
|
1353
|
+
}
|
|
1354
|
+
})();
|
|
1355
|
+
return failure(
|
|
1356
|
+
"identity_unavailable",
|
|
1357
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
1358
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
1359
|
+
);
|
|
1360
|
+
}
|
|
1361
|
+
function answerError(answer) {
|
|
1362
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
1363
|
+
}
|
|
1364
|
+
async function git(root, args, signal) {
|
|
1365
|
+
try {
|
|
1366
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
1367
|
+
cwd: root,
|
|
1368
|
+
encoding: "utf8",
|
|
1369
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
1370
|
+
signal,
|
|
1371
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
1372
|
+
maxBuffer: 1024 * 1024
|
|
1373
|
+
});
|
|
1374
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
1375
|
+
} catch (error) {
|
|
1376
|
+
const failed = error;
|
|
1377
|
+
return {
|
|
1378
|
+
ok: false,
|
|
1379
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
1380
|
+
stdout: failed.stdout ?? "",
|
|
1381
|
+
stderr: failed.stderr ?? "",
|
|
1382
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
function gitDetail(stderr) {
|
|
1387
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
1388
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1389
|
+
}
|
|
1390
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
1391
|
+
await new Promise((resolve3, reject) => {
|
|
1392
|
+
const timer = setTimeout(resolve3, milliseconds);
|
|
1393
|
+
signal?.addEventListener(
|
|
1394
|
+
"abort",
|
|
1395
|
+
() => {
|
|
1396
|
+
clearTimeout(timer);
|
|
1397
|
+
reject(signal.reason);
|
|
1398
|
+
},
|
|
1399
|
+
{ once: true }
|
|
1400
|
+
);
|
|
1401
|
+
});
|
|
1402
|
+
}
|
|
1403
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
1404
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
1405
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
1406
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
1407
|
+
let unreachable;
|
|
1408
|
+
for (; ; ) {
|
|
1409
|
+
const remaining = deadline - Date.now();
|
|
1410
|
+
if (remaining <= 0) break;
|
|
1411
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
1412
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
1413
|
+
let answer;
|
|
1414
|
+
try {
|
|
1415
|
+
answer = await environmentRequest(
|
|
1416
|
+
"GET",
|
|
1417
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
1418
|
+
void 0,
|
|
1419
|
+
deps,
|
|
1420
|
+
signal
|
|
1421
|
+
);
|
|
1422
|
+
} catch (error) {
|
|
1423
|
+
signal?.throwIfAborted();
|
|
1424
|
+
unreachable = error;
|
|
1425
|
+
continue;
|
|
1426
|
+
}
|
|
1427
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1428
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1429
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
1430
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
1431
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
1432
|
+
continue;
|
|
1433
|
+
}
|
|
1434
|
+
unreachable = void 0;
|
|
1435
|
+
const status = answer.value;
|
|
1436
|
+
if (status?.status === "verified")
|
|
1437
|
+
return {
|
|
1438
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
1439
|
+
};
|
|
1440
|
+
if (status?.status === "expired")
|
|
1441
|
+
return failure(
|
|
1442
|
+
"challenge_expired",
|
|
1443
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
1444
|
+
NEW_SESSION_REMEDY
|
|
1445
|
+
);
|
|
1446
|
+
if (status?.status === "rejected")
|
|
1447
|
+
return rejectionFailure(status.reason, repository);
|
|
1448
|
+
}
|
|
1449
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
1450
|
+
return failure(
|
|
1451
|
+
"webhook_timeout",
|
|
1452
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
1453
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
1456
|
+
function parseTokenAnswer(value) {
|
|
1457
|
+
if (!value) return void 0;
|
|
1458
|
+
const user = value.user;
|
|
1459
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
1460
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
1461
|
+
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))
|
|
1462
|
+
return void 0;
|
|
1463
|
+
return {
|
|
1464
|
+
accessToken: value.accessToken,
|
|
1465
|
+
expiresAt,
|
|
1466
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
1467
|
+
userId: user.id,
|
|
1468
|
+
displayName: user.displayName,
|
|
1469
|
+
organizationId: value.organizationId
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
1473
|
+
"server_contract",
|
|
1474
|
+
"Primitive's answer did not identify the linked member",
|
|
1475
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
1476
|
+
);
|
|
1477
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
1478
|
+
let identity;
|
|
1479
|
+
let environment;
|
|
1480
|
+
try {
|
|
1481
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1482
|
+
identity = await verifyMachineIdentity(
|
|
1483
|
+
context.apiUrl,
|
|
1484
|
+
answer.accessToken,
|
|
1485
|
+
context.clientId,
|
|
1486
|
+
signal,
|
|
1487
|
+
deps.fetch
|
|
1488
|
+
);
|
|
1489
|
+
} catch (error) {
|
|
1490
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
1491
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1492
|
+
return environmentFailure(error, context.apiUrl);
|
|
1493
|
+
}
|
|
1494
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
1495
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1496
|
+
return {
|
|
1497
|
+
version: 1,
|
|
1498
|
+
apiUrl: context.apiUrl,
|
|
1499
|
+
clientId: context.clientId,
|
|
1500
|
+
generation: context.generation,
|
|
1501
|
+
sessionId: context.sessionId,
|
|
1502
|
+
issuer: environment.issuer,
|
|
1503
|
+
audience: environment.audience,
|
|
1504
|
+
accessToken: answer.accessToken,
|
|
1505
|
+
expiresAt: answer.expiresAt,
|
|
1506
|
+
refreshAfter: answer.refreshAfter,
|
|
1507
|
+
userId: answer.userId,
|
|
1508
|
+
displayName: answer.displayName,
|
|
1509
|
+
organizationId: answer.organizationId,
|
|
1510
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
1511
|
+
identity,
|
|
1512
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
async function refreshToken(context, record, deps, signal) {
|
|
1516
|
+
let answer;
|
|
1517
|
+
try {
|
|
1518
|
+
answer = await environmentRequest(
|
|
1519
|
+
"POST",
|
|
1520
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
1521
|
+
{ accessToken: record.accessToken },
|
|
1522
|
+
deps,
|
|
1523
|
+
signal
|
|
1524
|
+
);
|
|
1525
|
+
} catch (error) {
|
|
1526
|
+
signal?.throwIfAborted();
|
|
1527
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
1528
|
+
}
|
|
1529
|
+
const code = answerError(answer);
|
|
1530
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
1531
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
1532
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1533
|
+
return {
|
|
1534
|
+
status: "refused",
|
|
1535
|
+
failure: environmentFailure(
|
|
1536
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
1537
|
+
context.apiUrl
|
|
1538
|
+
)
|
|
1539
|
+
};
|
|
1540
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1541
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
1542
|
+
return { status: "unavailable" };
|
|
1543
|
+
return {
|
|
1544
|
+
status: "ok",
|
|
1545
|
+
record: {
|
|
1546
|
+
...record,
|
|
1547
|
+
accessToken: token.accessToken,
|
|
1548
|
+
expiresAt: token.expiresAt,
|
|
1549
|
+
refreshAfter: token.refreshAfter,
|
|
1550
|
+
displayName: token.displayName
|
|
1551
|
+
}
|
|
1552
|
+
};
|
|
1553
|
+
}
|
|
1554
|
+
function exchangeRefusal(answer, repository) {
|
|
1555
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1556
|
+
if (answer.status !== 409) return void 0;
|
|
1557
|
+
switch (answerError(answer)) {
|
|
1558
|
+
case "identity_mismatch":
|
|
1559
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
1560
|
+
case "challenge_rejected":
|
|
1561
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
1562
|
+
case "challenge_expired":
|
|
1563
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
1564
|
+
case "challenge_already_exchanged":
|
|
1565
|
+
return failure(
|
|
1566
|
+
"challenge_already_exchanged",
|
|
1567
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
1568
|
+
NEW_SESSION_REMEDY
|
|
1569
|
+
);
|
|
1570
|
+
case "challenge_pending":
|
|
1571
|
+
return failure(
|
|
1572
|
+
"webhook_timeout",
|
|
1573
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
1574
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1575
|
+
);
|
|
1576
|
+
default:
|
|
1577
|
+
return void 0;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
1581
|
+
let answer;
|
|
1582
|
+
try {
|
|
1583
|
+
answer = await environmentRequest(
|
|
1584
|
+
"POST",
|
|
1585
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
1586
|
+
{ challengeId: challenge.challengeId },
|
|
1587
|
+
deps,
|
|
1588
|
+
signal
|
|
1589
|
+
);
|
|
1590
|
+
} catch (error) {
|
|
1591
|
+
signal?.throwIfAborted();
|
|
1592
|
+
return environmentFailure(error, context.apiUrl);
|
|
1593
|
+
}
|
|
1594
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
1595
|
+
const login = answer.value?.githubLogin;
|
|
1596
|
+
return {
|
|
1597
|
+
status: "link_required",
|
|
1598
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
1599
|
+
challengeId: challenge.challengeId,
|
|
1600
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
const refused = exchangeRefusal(
|
|
1604
|
+
answer,
|
|
1605
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
1606
|
+
);
|
|
1607
|
+
if (refused) return refused;
|
|
1608
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1609
|
+
if (!token) {
|
|
1610
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1611
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
1612
|
+
return answer.status >= 500 ? environmentFailure(
|
|
1613
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
1614
|
+
context.apiUrl
|
|
1615
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
1616
|
+
}
|
|
1617
|
+
return recordFor(
|
|
1618
|
+
context,
|
|
1619
|
+
token,
|
|
1620
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
1621
|
+
deps,
|
|
1622
|
+
signal
|
|
1623
|
+
);
|
|
1624
|
+
}
|
|
1625
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
1626
|
+
const env = deps.env ?? process.env;
|
|
1627
|
+
const repository = githubRepositoryFullName(root);
|
|
1628
|
+
if (!repository)
|
|
1629
|
+
return failure(
|
|
1630
|
+
"repository_unidentified",
|
|
1631
|
+
"this checkout does not name its GitHub repository",
|
|
1632
|
+
"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"
|
|
1633
|
+
);
|
|
1634
|
+
const branch = currentBranch(root);
|
|
1635
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
1636
|
+
return failure(
|
|
1637
|
+
"not_session_branch",
|
|
1638
|
+
`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`,
|
|
1639
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
1640
|
+
);
|
|
1641
|
+
attempt.branch = branch;
|
|
1642
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
1643
|
+
if (!baseSha) {
|
|
1644
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
1645
|
+
baseSha = head.stdout.trim();
|
|
1646
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
1647
|
+
return failure(
|
|
1648
|
+
"no_commit",
|
|
1649
|
+
"this checkout has no commit to create the session branch at",
|
|
1650
|
+
NEW_SESSION_REMEDY
|
|
1651
|
+
);
|
|
860
1652
|
}
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
1653
|
+
const published = await git(
|
|
1654
|
+
root,
|
|
1655
|
+
[
|
|
1656
|
+
"for-each-ref",
|
|
1657
|
+
"--count=1",
|
|
1658
|
+
"--format=%(refname)",
|
|
1659
|
+
"--contains",
|
|
1660
|
+
baseSha,
|
|
1661
|
+
"refs/remotes/origin/"
|
|
1662
|
+
],
|
|
1663
|
+
signal
|
|
1664
|
+
);
|
|
1665
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
1666
|
+
return failure(
|
|
1667
|
+
"unpublished_commits",
|
|
1668
|
+
`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`,
|
|
1669
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
1670
|
+
);
|
|
1671
|
+
attempt.baseSha = baseSha;
|
|
1672
|
+
const remote = await git(
|
|
1673
|
+
root,
|
|
1674
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
1675
|
+
signal
|
|
1676
|
+
);
|
|
1677
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
1678
|
+
if (remote.ok && recorded) {
|
|
1679
|
+
Object.assign(attempt, recorded);
|
|
1680
|
+
return { ...recorded, repository };
|
|
1681
|
+
}
|
|
1682
|
+
if (remote.ok)
|
|
1683
|
+
return failure(
|
|
1684
|
+
"branch_exists",
|
|
1685
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
1686
|
+
NEW_SESSION_REMEDY
|
|
1687
|
+
);
|
|
1688
|
+
if (remote.code !== 2)
|
|
1689
|
+
return failure(
|
|
1690
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
1691
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
1692
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
1693
|
+
);
|
|
1694
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
1695
|
+
Object.assign(attempt, recorded);
|
|
1696
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
1697
|
+
}
|
|
1698
|
+
let answer;
|
|
1699
|
+
try {
|
|
1700
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
1701
|
+
answer = await environmentRequest(
|
|
1702
|
+
"POST",
|
|
1703
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
1704
|
+
{
|
|
1705
|
+
repositoryFullName: repository,
|
|
1706
|
+
claudeSessionId: context.sessionId,
|
|
1707
|
+
branch,
|
|
1708
|
+
baseSha,
|
|
1709
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
1710
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
1711
|
+
},
|
|
1712
|
+
deps,
|
|
1713
|
+
signal
|
|
1714
|
+
);
|
|
1715
|
+
} catch (error) {
|
|
1716
|
+
signal?.throwIfAborted();
|
|
1717
|
+
return environmentFailure(error, context.apiUrl);
|
|
1718
|
+
}
|
|
1719
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
1720
|
+
return failure(
|
|
1721
|
+
"repository_not_connected",
|
|
1722
|
+
`${repository} is not connected to Primitive`,
|
|
1723
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
1724
|
+
);
|
|
1725
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1726
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
1727
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
1728
|
+
return failure(
|
|
1729
|
+
"challenge_open",
|
|
1730
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
1731
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
1732
|
+
);
|
|
1733
|
+
if (answer.status === 429)
|
|
1734
|
+
return failure(
|
|
1735
|
+
"too_many_challenges",
|
|
1736
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
1737
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
1738
|
+
);
|
|
1739
|
+
const challengeId = answer.value?.challengeId;
|
|
1740
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
1741
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
1742
|
+
return answer.status >= 500 ? environmentFailure(
|
|
1743
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
1744
|
+
context.apiUrl
|
|
1745
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
1746
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
1747
|
+
attempt.challengeId = challengeId;
|
|
1748
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
1749
|
+
return pushSessionBranch(
|
|
1750
|
+
root,
|
|
1751
|
+
repository,
|
|
1752
|
+
branch,
|
|
1753
|
+
baseSha,
|
|
1754
|
+
{ challengeId, challengeExpiresAt },
|
|
1755
|
+
signal
|
|
1756
|
+
);
|
|
864
1757
|
}
|
|
865
|
-
function
|
|
866
|
-
const
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
1758
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
1759
|
+
const push = await git(
|
|
1760
|
+
root,
|
|
1761
|
+
[
|
|
1762
|
+
"-c",
|
|
1763
|
+
"core.hooksPath=/dev/null",
|
|
1764
|
+
"-c",
|
|
1765
|
+
"push.followTags=false",
|
|
1766
|
+
"-c",
|
|
1767
|
+
"push.recurseSubmodules=no",
|
|
1768
|
+
"-c",
|
|
1769
|
+
"push.gpgSign=false",
|
|
1770
|
+
"-c",
|
|
1771
|
+
"push.pushOption=",
|
|
1772
|
+
"push",
|
|
1773
|
+
"--no-verify",
|
|
1774
|
+
"--no-follow-tags",
|
|
1775
|
+
"--no-recurse-submodules",
|
|
1776
|
+
"--no-signed",
|
|
1777
|
+
"--quiet",
|
|
1778
|
+
"origin",
|
|
1779
|
+
`${baseSha}:refs/heads/${branch}`
|
|
1780
|
+
],
|
|
1781
|
+
signal
|
|
1782
|
+
);
|
|
1783
|
+
if (!push.ok)
|
|
1784
|
+
return push.timedOut ? failure(
|
|
1785
|
+
"push_timeout",
|
|
1786
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
1787
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
1788
|
+
) : failure(
|
|
1789
|
+
"push_refused",
|
|
1790
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
1791
|
+
`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}`
|
|
1792
|
+
);
|
|
1793
|
+
return { ...challenge, repository };
|
|
1794
|
+
}
|
|
1795
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
1796
|
+
let context;
|
|
1797
|
+
try {
|
|
1798
|
+
context = sessionContext(deps);
|
|
1799
|
+
} catch (error) {
|
|
1800
|
+
return failure(
|
|
1801
|
+
"environment_credential_invalid",
|
|
1802
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
1803
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
1804
|
+
);
|
|
874
1805
|
}
|
|
875
|
-
|
|
1806
|
+
if ("status" in context) return context;
|
|
1807
|
+
const ctx = context;
|
|
1808
|
+
const startedAt2 = Date.now();
|
|
1809
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
1810
|
+
return withFileLock(
|
|
1811
|
+
ctx.lockPath,
|
|
1812
|
+
async () => {
|
|
1813
|
+
const record = readToken(ctx);
|
|
1814
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
1815
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
1816
|
+
if (record) {
|
|
1817
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
1818
|
+
if (refreshed.status === "ok") {
|
|
1819
|
+
writeToken(ctx, refreshed.record);
|
|
1820
|
+
return identified(refreshed.record, true);
|
|
1821
|
+
}
|
|
1822
|
+
if (refreshed.status === "refused") {
|
|
1823
|
+
rmSync4(ctx.tokenPath, { force: true });
|
|
1824
|
+
writeState(ctx, {
|
|
1825
|
+
sessionId: ctx.sessionId,
|
|
1826
|
+
status: "failed",
|
|
1827
|
+
code: refreshed.failure.code,
|
|
1828
|
+
cause: refreshed.failure.cause,
|
|
1829
|
+
remedy: refreshed.failure.remedy,
|
|
1830
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
1831
|
+
at: Date.now()
|
|
1832
|
+
});
|
|
1833
|
+
return refreshed.failure;
|
|
1834
|
+
}
|
|
1835
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
1836
|
+
}
|
|
1837
|
+
const state = readState(ctx);
|
|
1838
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
1839
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
1840
|
+
if (!options.explicit) {
|
|
1841
|
+
if (!root || !(record || state))
|
|
1842
|
+
return failure(
|
|
1843
|
+
"not_identified",
|
|
1844
|
+
"this session has not identified who started it yet",
|
|
1845
|
+
RETRY_REMEDY
|
|
1846
|
+
);
|
|
1847
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
1848
|
+
} else if (state && state.at >= startedAt2) {
|
|
1849
|
+
return outcomeFromState(state);
|
|
1850
|
+
}
|
|
1851
|
+
if (!root)
|
|
1852
|
+
return failure(
|
|
1853
|
+
"repository_missing",
|
|
1854
|
+
"this is not a git repository",
|
|
1855
|
+
"run it in the repository the session cloned"
|
|
1856
|
+
);
|
|
1857
|
+
const attempt = { root };
|
|
1858
|
+
const remember = (outcome) => {
|
|
1859
|
+
writeState(ctx, {
|
|
1860
|
+
sessionId: ctx.sessionId,
|
|
1861
|
+
status: outcome.status,
|
|
1862
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
1863
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
1864
|
+
githubLogin: outcome.githubLogin
|
|
1865
|
+
},
|
|
1866
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
1867
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
1868
|
+
repositoryRoot: root,
|
|
1869
|
+
branch: attempt.branch ?? state?.branch,
|
|
1870
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
1871
|
+
at: Date.now()
|
|
1872
|
+
});
|
|
1873
|
+
return outcome;
|
|
1874
|
+
};
|
|
1875
|
+
let challenge;
|
|
1876
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
1877
|
+
attempt.challengeId = state.challengeId;
|
|
1878
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
1879
|
+
attempt.branch = state.branch;
|
|
1880
|
+
attempt.baseSha = state.baseSha;
|
|
1881
|
+
challenge = {
|
|
1882
|
+
challengeId: state.challengeId,
|
|
1883
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
1884
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
1885
|
+
};
|
|
1886
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
1887
|
+
attempt.challengeId = state.challengeId;
|
|
1888
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
1889
|
+
const exchanged2 = await exchangeChallenge(
|
|
1890
|
+
ctx,
|
|
1891
|
+
{
|
|
1892
|
+
challengeId: state.challengeId,
|
|
1893
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
1894
|
+
githubLogin: state.githubLogin
|
|
1895
|
+
},
|
|
1896
|
+
root,
|
|
1897
|
+
deps,
|
|
1898
|
+
options.signal
|
|
1899
|
+
);
|
|
1900
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
1901
|
+
writeToken(ctx, exchanged2);
|
|
1902
|
+
return identified(exchanged2, false);
|
|
1903
|
+
} else if (!options.explicit) {
|
|
1904
|
+
return state ? outcomeFromState(state) : failure(
|
|
1905
|
+
"not_identified",
|
|
1906
|
+
"this session has not identified who started it yet",
|
|
1907
|
+
RETRY_REMEDY
|
|
1908
|
+
);
|
|
1909
|
+
} else {
|
|
1910
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
1911
|
+
if ("status" in pushed) return remember(pushed);
|
|
1912
|
+
challenge = pushed;
|
|
1913
|
+
}
|
|
1914
|
+
const verified = await pollChallenge(
|
|
1915
|
+
ctx.apiUrl,
|
|
1916
|
+
challenge.challengeId,
|
|
1917
|
+
challenge.repository,
|
|
1918
|
+
// A hook process waits only briefly for a late notice.
|
|
1919
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
1920
|
+
options.signal
|
|
1921
|
+
);
|
|
1922
|
+
if ("status" in verified) return remember(verified);
|
|
1923
|
+
const exchanged = await exchangeChallenge(
|
|
1924
|
+
ctx,
|
|
1925
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
1926
|
+
root,
|
|
1927
|
+
deps,
|
|
1928
|
+
options.signal
|
|
1929
|
+
);
|
|
1930
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
1931
|
+
writeToken(ctx, exchanged);
|
|
1932
|
+
return identified(exchanged, false);
|
|
1933
|
+
},
|
|
1934
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
1935
|
+
);
|
|
876
1936
|
}
|
|
877
|
-
function
|
|
878
|
-
|
|
1937
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
1938
|
+
const cached2 = cachedSessionCredential(deps);
|
|
1939
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
1940
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
1941
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1942
|
+
let outcome;
|
|
1943
|
+
try {
|
|
1944
|
+
outcome = await ensureSessionIdentity(
|
|
1945
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
1946
|
+
deps
|
|
1947
|
+
);
|
|
1948
|
+
} catch (error) {
|
|
1949
|
+
options.signal?.throwIfAborted();
|
|
1950
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1951
|
+
throw new MachineAuthError(
|
|
1952
|
+
"identity_unavailable",
|
|
1953
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
1954
|
+
);
|
|
1955
|
+
}
|
|
1956
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
1957
|
+
throw new MachineAuthError(
|
|
1958
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
1959
|
+
sessionIdentityMessage(outcome)
|
|
1960
|
+
);
|
|
879
1961
|
}
|
|
880
1962
|
|
|
881
1963
|
// src/lib/machine-credentials.ts
|
|
1964
|
+
function sessionScoped(deps) {
|
|
1965
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
1966
|
+
}
|
|
882
1967
|
var require2 = createRequire(import.meta.url);
|
|
883
1968
|
var SERVICE = "ai.primitive.prim.machine";
|
|
884
|
-
var
|
|
1969
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
885
1970
|
var PROFILE_FILE = "machine_profile.json";
|
|
886
|
-
var
|
|
1971
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
887
1972
|
var cached;
|
|
888
1973
|
function configurationDirectory(deps) {
|
|
889
1974
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
890
1975
|
}
|
|
891
1976
|
function apiUrlFor(deps) {
|
|
892
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
1977
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
893
1978
|
}
|
|
894
|
-
function
|
|
895
|
-
return
|
|
1979
|
+
function hash2(value) {
|
|
1980
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
896
1981
|
}
|
|
897
1982
|
function recordPath(directory, generation) {
|
|
898
|
-
return
|
|
1983
|
+
return join7(directory, `machine_${generation}.json`);
|
|
899
1984
|
}
|
|
900
1985
|
function storageKey(directory, generation) {
|
|
901
|
-
return `${
|
|
1986
|
+
return `${hash2(directory)}:${generation}`;
|
|
902
1987
|
}
|
|
903
1988
|
function environmentContextPath(deps, clientId) {
|
|
904
|
-
return
|
|
1989
|
+
return join7(
|
|
905
1990
|
configurationDirectory(deps),
|
|
906
|
-
`machine_context_${
|
|
1991
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
907
1992
|
);
|
|
908
1993
|
}
|
|
909
1994
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -962,14 +2047,14 @@ function readEnvironmentContext(environment, deps) {
|
|
|
962
2047
|
}
|
|
963
2048
|
}
|
|
964
2049
|
function keyringEntry(key) {
|
|
965
|
-
let directory =
|
|
2050
|
+
let directory = dirname5(fileURLToPath2(import.meta.url));
|
|
966
2051
|
for (let depth = 0; depth < 5; depth++) {
|
|
967
|
-
const loader =
|
|
2052
|
+
const loader = join7(directory, "native", "keyring.cjs");
|
|
968
2053
|
if (existsSync3(loader)) {
|
|
969
2054
|
const module2 = require2(loader);
|
|
970
2055
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
971
2056
|
}
|
|
972
|
-
directory =
|
|
2057
|
+
directory = dirname5(directory);
|
|
973
2058
|
}
|
|
974
2059
|
const module = require2("@napi-rs/keyring");
|
|
975
2060
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
@@ -981,7 +2066,7 @@ function protectPath(path, directory) {
|
|
|
981
2066
|
}
|
|
982
2067
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
983
2068
|
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)`;
|
|
984
|
-
|
|
2069
|
+
execFileSync2(
|
|
985
2070
|
"powershell.exe",
|
|
986
2071
|
[
|
|
987
2072
|
"-NoProfile",
|
|
@@ -994,7 +2079,7 @@ function protectPath(path, directory) {
|
|
|
994
2079
|
}
|
|
995
2080
|
function ensureDirectory(directory) {
|
|
996
2081
|
mkdirSync3(directory, { recursive: true, mode: 448 });
|
|
997
|
-
if (
|
|
2082
|
+
if (lstatSync3(directory).isSymbolicLink())
|
|
998
2083
|
throw new MachineAuthError(
|
|
999
2084
|
"unsafe_storage",
|
|
1000
2085
|
"Credential directory must not be a symbolic link."
|
|
@@ -1006,17 +2091,20 @@ function writePrivate(path, value) {
|
|
|
1006
2091
|
`, { mode: 384 });
|
|
1007
2092
|
protectPath(path, false);
|
|
1008
2093
|
}
|
|
2094
|
+
function readMachineMetadata(path) {
|
|
2095
|
+
return readPrivate(path);
|
|
2096
|
+
}
|
|
1009
2097
|
function readPrivate(path) {
|
|
1010
2098
|
let raw;
|
|
1011
2099
|
try {
|
|
1012
|
-
const stat =
|
|
2100
|
+
const stat = lstatSync3(path);
|
|
1013
2101
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1014
2102
|
throw new MachineAuthError(
|
|
1015
2103
|
"unsafe_storage",
|
|
1016
2104
|
"Machine credential files must be owner-only regular files."
|
|
1017
2105
|
);
|
|
1018
2106
|
}
|
|
1019
|
-
raw =
|
|
2107
|
+
raw = readFileSync5(path, "utf8");
|
|
1020
2108
|
} catch (error) {
|
|
1021
2109
|
if (error.code === "ENOENT") return void 0;
|
|
1022
2110
|
throw error;
|
|
@@ -1061,7 +2149,7 @@ function parseProfile(value) {
|
|
|
1061
2149
|
};
|
|
1062
2150
|
}
|
|
1063
2151
|
function readMachineProfile(deps = {}) {
|
|
1064
|
-
const value = readPrivate(
|
|
2152
|
+
const value = readPrivate(join7(configurationDirectory(deps), PROFILE_FILE));
|
|
1065
2153
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1066
2154
|
}
|
|
1067
2155
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -1070,20 +2158,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
1070
2158
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1071
2159
|
function networkSecretBrokerKey(deps, clientId) {
|
|
1072
2160
|
const directory = configurationDirectory(deps);
|
|
1073
|
-
const path =
|
|
2161
|
+
const path = join7(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1074
2162
|
const known = brokerKeys.get(path);
|
|
1075
2163
|
if (known) return known;
|
|
1076
2164
|
ensureDirectory(directory);
|
|
1077
2165
|
const read = () => {
|
|
1078
2166
|
try {
|
|
1079
|
-
const stat =
|
|
2167
|
+
const stat = lstatSync3(path);
|
|
1080
2168
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1081
2169
|
throw new MachineAuthError(
|
|
1082
2170
|
"unsafe_storage",
|
|
1083
2171
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1084
2172
|
true
|
|
1085
2173
|
);
|
|
1086
|
-
const value =
|
|
2174
|
+
const value = readFileSync5(path, "utf8").trim();
|
|
1087
2175
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1088
2176
|
} catch (error) {
|
|
1089
2177
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -1111,7 +2199,7 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
1111
2199
|
} catch (error) {
|
|
1112
2200
|
if (error.code !== "EEXIST") throw error;
|
|
1113
2201
|
} finally {
|
|
1114
|
-
|
|
2202
|
+
rmSync5(staged, { force: true });
|
|
1115
2203
|
}
|
|
1116
2204
|
}
|
|
1117
2205
|
const key = read()?.key;
|
|
@@ -1144,7 +2232,7 @@ function environmentCredentials(deps) {
|
|
|
1144
2232
|
"conflicting_credentials",
|
|
1145
2233
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1146
2234
|
);
|
|
1147
|
-
const generation =
|
|
2235
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1148
2236
|
const credentials = {
|
|
1149
2237
|
clientId,
|
|
1150
2238
|
generation,
|
|
@@ -1165,12 +2253,12 @@ function environmentCredentials(deps) {
|
|
|
1165
2253
|
return {
|
|
1166
2254
|
clientId,
|
|
1167
2255
|
clientSecret,
|
|
1168
|
-
generation:
|
|
2256
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1169
2257
|
};
|
|
1170
2258
|
}
|
|
1171
2259
|
function hasMachineConfiguration(deps = {}) {
|
|
1172
2260
|
const env = deps.env ?? process.env;
|
|
1173
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(
|
|
2261
|
+
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));
|
|
1174
2262
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1175
2263
|
throw new MachineAuthError(
|
|
1176
2264
|
"conflicting_credentials",
|
|
@@ -1182,6 +2270,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1182
2270
|
}
|
|
1183
2271
|
function machineContext(deps = {}) {
|
|
1184
2272
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2273
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1185
2274
|
const environment = environmentCredentials(deps);
|
|
1186
2275
|
if (environment) {
|
|
1187
2276
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1196,6 +2285,7 @@ function machineContext(deps = {}) {
|
|
|
1196
2285
|
return profile;
|
|
1197
2286
|
}
|
|
1198
2287
|
function cachedMachineCredential(deps = {}) {
|
|
2288
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1199
2289
|
const context = machineContext(deps);
|
|
1200
2290
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1201
2291
|
}
|
|
@@ -1204,7 +2294,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
1204
2294
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1205
2295
|
if (!generation) return false;
|
|
1206
2296
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1207
|
-
return readPrivate(
|
|
2297
|
+
return readPrivate(join7(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1208
2298
|
}
|
|
1209
2299
|
var environmentTerminal;
|
|
1210
2300
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -1268,6 +2358,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
1268
2358
|
}
|
|
1269
2359
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1270
2360
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2361
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1271
2362
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1272
2363
|
const apiUrl = apiUrlFor(deps);
|
|
1273
2364
|
const environment = environmentCredentials(deps);
|
|
@@ -1296,7 +2387,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1296
2387
|
}
|
|
1297
2388
|
}
|
|
1298
2389
|
return withFileLock(
|
|
1299
|
-
|
|
2390
|
+
join7(directory2, "credentials.lock"),
|
|
1300
2391
|
async () => {
|
|
1301
2392
|
if (machineSessionEnded(deps))
|
|
1302
2393
|
throw new MachineAuthError(
|
|
@@ -1304,7 +2395,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1304
2395
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1305
2396
|
true
|
|
1306
2397
|
);
|
|
1307
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
2398
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1308
2399
|
return cached;
|
|
1309
2400
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1310
2401
|
throw networkRejection.error;
|
|
@@ -1378,7 +2469,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1378
2469
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1379
2470
|
try {
|
|
1380
2471
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1381
|
-
|
|
2472
|
+
rmSync5(contextPath, { force: true });
|
|
1382
2473
|
} catch {
|
|
1383
2474
|
}
|
|
1384
2475
|
throw error;
|
|
@@ -1388,7 +2479,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1388
2479
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1389
2480
|
try {
|
|
1390
2481
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1391
|
-
|
|
2482
|
+
rmSync5(contextPath, { force: true });
|
|
1392
2483
|
} catch {
|
|
1393
2484
|
}
|
|
1394
2485
|
}
|
|
@@ -1402,7 +2493,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1402
2493
|
const expected = machineContext(deps);
|
|
1403
2494
|
const directory = configurationDirectory(deps);
|
|
1404
2495
|
return withFileLock(
|
|
1405
|
-
|
|
2496
|
+
join7(directory, "credentials.lock"),
|
|
1406
2497
|
async () => {
|
|
1407
2498
|
const profile = readMachineProfile(deps);
|
|
1408
2499
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1417,7 +2508,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1417
2508
|
true
|
|
1418
2509
|
);
|
|
1419
2510
|
let record = await loadRecord(profile, deps, signal);
|
|
1420
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
2511
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1421
2512
|
try {
|
|
1422
2513
|
const { tokens, identity } = await withMachineCooldown(
|
|
1423
2514
|
directory,
|
|
@@ -1452,7 +2543,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1452
2543
|
await persistRecord(record, deps, signal);
|
|
1453
2544
|
} catch (error) {
|
|
1454
2545
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1455
|
-
writePrivate(
|
|
2546
|
+
writePrivate(join7(directory, "machine_terminal.json"), profile.generation);
|
|
1456
2547
|
throw error;
|
|
1457
2548
|
}
|
|
1458
2549
|
}
|
|
@@ -1482,13 +2573,19 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
1482
2573
|
});
|
|
1483
2574
|
}
|
|
1484
2575
|
function machineJournalBucket(identity) {
|
|
1485
|
-
return `_machine_${
|
|
2576
|
+
return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
1486
2577
|
}
|
|
1487
2578
|
function identityPending(actor) {
|
|
1488
2579
|
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
1489
2580
|
}
|
|
1490
2581
|
function machinePendingBucket(identity) {
|
|
1491
|
-
return `_machine_pending_${
|
|
2582
|
+
return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
2583
|
+
}
|
|
2584
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
2585
|
+
ensureDirectory(directory);
|
|
2586
|
+
}
|
|
2587
|
+
function writeMachineMetadata(path, value) {
|
|
2588
|
+
writePrivate(path, value);
|
|
1492
2589
|
}
|
|
1493
2590
|
|
|
1494
2591
|
// src/lib/machine-broker.ts
|
|
@@ -1503,14 +2600,14 @@ var FORWARD_TIMEOUT_MS = 3e4;
|
|
|
1503
2600
|
var FORWARD_METHODS = ["GET", "POST", "DELETE"];
|
|
1504
2601
|
var IDLE_MS = 5 * 6e4;
|
|
1505
2602
|
function descriptorPath(directory, generation) {
|
|
1506
|
-
return
|
|
2603
|
+
return join8(directory, `machine_broker_${generation}.json`);
|
|
1507
2604
|
}
|
|
1508
2605
|
function readDescriptor(path) {
|
|
1509
2606
|
try {
|
|
1510
|
-
const stat =
|
|
2607
|
+
const stat = lstatSync4(path);
|
|
1511
2608
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1512
2609
|
return void 0;
|
|
1513
|
-
const data = JSON.parse(
|
|
2610
|
+
const data = JSON.parse(readFileSync6(path, "utf8"));
|
|
1514
2611
|
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;
|
|
1515
2612
|
} catch {
|
|
1516
2613
|
return void 0;
|
|
@@ -1523,7 +2620,7 @@ function matches(left, right) {
|
|
|
1523
2620
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
1524
2621
|
}
|
|
1525
2622
|
function tokenHash(token) {
|
|
1526
|
-
return token ?
|
|
2623
|
+
return token ? createHash5("sha256").update(token).digest("hex") : void 0;
|
|
1527
2624
|
}
|
|
1528
2625
|
async function brokerRequest(descriptor, environment, options) {
|
|
1529
2626
|
const body = JSON.stringify({
|
|
@@ -1600,7 +2697,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1600
2697
|
async function ensureBroker(options) {
|
|
1601
2698
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1602
2699
|
return withFileLock(
|
|
1603
|
-
|
|
2700
|
+
join8(options.directory, "machine-broker.lock"),
|
|
1604
2701
|
async () => {
|
|
1605
2702
|
const current = readDescriptor(path);
|
|
1606
2703
|
if (current) {
|
|
@@ -1614,7 +2711,7 @@ async function ensureBroker(options) {
|
|
|
1614
2711
|
}
|
|
1615
2712
|
}
|
|
1616
2713
|
const bundled = fileURLToPath3(import.meta.url);
|
|
1617
|
-
const entry =
|
|
2714
|
+
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
1618
2715
|
if (!entry)
|
|
1619
2716
|
throw new MachineAuthError(
|
|
1620
2717
|
"broker_unavailable",
|
|
@@ -1817,7 +2914,7 @@ async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
|
|
|
1817
2914
|
}
|
|
1818
2915
|
async function credentialResult(apiUrl, data, signal) {
|
|
1819
2916
|
try {
|
|
1820
|
-
const current = cachedMachineCredential();
|
|
2917
|
+
const current = cachedMachineCredential({ localEnvironment: true });
|
|
1821
2918
|
const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
|
|
1822
2919
|
const credential = await acquireMachineCredential(
|
|
1823
2920
|
{ force, signal },
|
|
@@ -1926,7 +3023,7 @@ async function startMachineBroker() {
|
|
|
1926
3023
|
clearTimeout(idle);
|
|
1927
3024
|
server.closeAllConnections();
|
|
1928
3025
|
server.close();
|
|
1929
|
-
if (readDescriptor(path)?.nonce === nonce)
|
|
3026
|
+
if (readDescriptor(path)?.nonce === nonce) rmSync6(path, { force: true });
|
|
1930
3027
|
};
|
|
1931
3028
|
const idle = setTimeout(close, IDLE_MS);
|
|
1932
3029
|
process.once("SIGTERM", close);
|
|
@@ -1944,27 +3041,27 @@ async function startMachineBroker() {
|
|
|
1944
3041
|
}
|
|
1945
3042
|
|
|
1946
3043
|
// src/daemon/principal.ts
|
|
1947
|
-
import { createHash as
|
|
3044
|
+
import { createHash as createHash7 } from "crypto";
|
|
1948
3045
|
|
|
1949
3046
|
// src/lib/credentials.ts
|
|
1950
|
-
import { createHash as
|
|
1951
|
-
import { readFileSync as
|
|
1952
|
-
import { join as
|
|
3047
|
+
import { createHash as createHash6 } from "crypto";
|
|
3048
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
3049
|
+
import { join as join9 } from "path";
|
|
1953
3050
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1954
|
-
var TOKEN_FILE_PATH =
|
|
1955
|
-
var REFRESH_TOKEN_PATH =
|
|
1956
|
-
var TOKEN_EXPIRES_PATH =
|
|
1957
|
-
var TERMINAL_REFRESH_PATH =
|
|
1958
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1959
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1960
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1961
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3051
|
+
var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
|
|
3052
|
+
var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
|
|
3053
|
+
var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
|
|
3054
|
+
var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3055
|
+
var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3056
|
+
var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
|
|
3057
|
+
var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3058
|
+
var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
|
|
1962
3059
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1963
3060
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1964
3061
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1965
3062
|
function readTrimmed(path) {
|
|
1966
3063
|
try {
|
|
1967
|
-
const value =
|
|
3064
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
1968
3065
|
return value || void 0;
|
|
1969
3066
|
} catch {
|
|
1970
3067
|
return void 0;
|
|
@@ -1986,22 +3083,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1986
3083
|
);
|
|
1987
3084
|
if (metadata.state === "legacy_broker") {
|
|
1988
3085
|
if (metadata.metadata) {
|
|
1989
|
-
const
|
|
1990
|
-
if (!
|
|
3086
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3087
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1991
3088
|
return void 0;
|
|
1992
3089
|
}
|
|
1993
3090
|
}
|
|
1994
3091
|
return { token: stored, source: "token_file" };
|
|
1995
3092
|
}
|
|
1996
3093
|
if (metadata.state === "invalid") return void 0;
|
|
1997
|
-
const
|
|
1998
|
-
if (!
|
|
3094
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3095
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1999
3096
|
return void 0;
|
|
2000
3097
|
}
|
|
2001
3098
|
return { token: stored, source: "token_file" };
|
|
2002
3099
|
}
|
|
2003
3100
|
function credentialFingerprint(value) {
|
|
2004
|
-
return
|
|
3101
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
2005
3102
|
}
|
|
2006
3103
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2007
3104
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -2021,7 +3118,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
2021
3118
|
function readBoundedCredentialJson(path) {
|
|
2022
3119
|
let raw;
|
|
2023
3120
|
try {
|
|
2024
|
-
raw =
|
|
3121
|
+
raw = readFileSync7(path, "utf8");
|
|
2025
3122
|
} catch (error) {
|
|
2026
3123
|
return error.code === "ENOENT" ? void 0 : null;
|
|
2027
3124
|
}
|
|
@@ -2099,7 +3196,7 @@ function boundedClaim(value) {
|
|
|
2099
3196
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
2100
3197
|
}
|
|
2101
3198
|
function sha256(value) {
|
|
2102
|
-
return
|
|
3199
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
2103
3200
|
}
|
|
2104
3201
|
function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
|
|
2105
3202
|
if (hasMachineConfiguration()) {
|
|
@@ -2184,7 +3281,7 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
2184
3281
|
// src/daemon/server.ts
|
|
2185
3282
|
import { chmodSync as chmodSync8, existsSync as existsSync12, mkdirSync as mkdirSync10, readFileSync as readFileSync15, unlinkSync as unlinkSync3 } from "fs";
|
|
2186
3283
|
import { createServer as createServer2 } from "net";
|
|
2187
|
-
import { join as
|
|
3284
|
+
import { join as join21 } from "path";
|
|
2188
3285
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2189
3286
|
|
|
2190
3287
|
// src/decisions/identity.ts
|
|
@@ -2265,14 +3362,14 @@ function publicDecisionResponse(value) {
|
|
|
2265
3362
|
}
|
|
2266
3363
|
|
|
2267
3364
|
// src/client.ts
|
|
2268
|
-
import { createHash as
|
|
2269
|
-
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as
|
|
2270
|
-
import { dirname as
|
|
3365
|
+
import { createHash as createHash8 } from "crypto";
|
|
3366
|
+
import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
|
|
3367
|
+
import { dirname as dirname6 } from "path";
|
|
2271
3368
|
|
|
2272
3369
|
// src/daemon/client-instance-id.ts
|
|
2273
3370
|
import { randomBytes as randomBytes4 } from "crypto";
|
|
2274
|
-
import { chmodSync as chmodSync2, lstatSync as
|
|
2275
|
-
import { join as
|
|
3371
|
+
import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
|
|
3372
|
+
import { join as join10 } from "path";
|
|
2276
3373
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
2277
3374
|
var INSTANCE_FILE_MODE = 384;
|
|
2278
3375
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -2285,7 +3382,7 @@ function isClientInstanceId(value) {
|
|
|
2285
3382
|
}
|
|
2286
3383
|
function ensurePrivateConfigDirectory(configDir) {
|
|
2287
3384
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
2288
|
-
const metadata =
|
|
3385
|
+
const metadata = lstatSync5(configDir);
|
|
2289
3386
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
2290
3387
|
throw new Error("prim config path must be a private directory");
|
|
2291
3388
|
}
|
|
@@ -2295,7 +3392,7 @@ function ensurePrivateConfigDirectory(configDir) {
|
|
|
2295
3392
|
function readExisting(path) {
|
|
2296
3393
|
let metadata;
|
|
2297
3394
|
try {
|
|
2298
|
-
metadata =
|
|
3395
|
+
metadata = lstatSync5(path);
|
|
2299
3396
|
} catch (error) {
|
|
2300
3397
|
if (error.code === "ENOENT") {
|
|
2301
3398
|
return;
|
|
@@ -2309,7 +3406,7 @@ function readExisting(path) {
|
|
|
2309
3406
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
2310
3407
|
throw new Error("stored client instance identity is invalid");
|
|
2311
3408
|
}
|
|
2312
|
-
const raw =
|
|
3409
|
+
const raw = readFileSync8(path, "utf8");
|
|
2313
3410
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
2314
3411
|
if (raw !== value && raw !== `${value}
|
|
2315
3412
|
` || !isClientInstanceId(value)) {
|
|
@@ -2323,8 +3420,8 @@ function atomicWrite(path, value) {
|
|
|
2323
3420
|
}
|
|
2324
3421
|
async function getOrCreateClientInstanceId(options) {
|
|
2325
3422
|
const configDir = options.configDir;
|
|
2326
|
-
const path =
|
|
2327
|
-
const lockPath =
|
|
3423
|
+
const path = join10(configDir, "client_instance_id");
|
|
3424
|
+
const lockPath = join10(configDir, "client-instance.lock");
|
|
2328
3425
|
ensurePrivateConfigDirectory(configDir);
|
|
2329
3426
|
return withFileLock(
|
|
2330
3427
|
lockPath,
|
|
@@ -2368,60 +3465,18 @@ async function ingestUploaderHeaders() {
|
|
|
2368
3465
|
return headers;
|
|
2369
3466
|
}
|
|
2370
3467
|
|
|
2371
|
-
// src/lib/terminal-safe.ts
|
|
2372
|
-
function replaceIsolatedSurrogates(value) {
|
|
2373
|
-
let out = "";
|
|
2374
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
2375
|
-
const unit = value.charCodeAt(index);
|
|
2376
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2377
|
-
const next = value.charCodeAt(index + 1);
|
|
2378
|
-
if (next >= 56320 && next <= 57343) {
|
|
2379
|
-
out += value[index] + value[index + 1];
|
|
2380
|
-
index += 1;
|
|
2381
|
-
} else {
|
|
2382
|
-
out += "\uFFFD";
|
|
2383
|
-
}
|
|
2384
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
2385
|
-
out += "\uFFFD";
|
|
2386
|
-
} else {
|
|
2387
|
-
out += value[index];
|
|
2388
|
-
}
|
|
2389
|
-
}
|
|
2390
|
-
return out;
|
|
2391
|
-
}
|
|
2392
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
2393
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2394
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2395
|
-
point === 1564 || // Arabic letter mark
|
|
2396
|
-
point === 6158 || // Mongolian vowel separator
|
|
2397
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2398
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2399
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2400
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2401
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
2402
|
-
point >= 917504 && point <= 917631;
|
|
2403
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
2404
|
-
}
|
|
2405
|
-
function terminalSafeText(value) {
|
|
2406
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2407
|
-
}
|
|
2408
|
-
function terminalSafeLine(value) {
|
|
2409
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2410
|
-
}
|
|
2411
|
-
var stripControlChars = terminalSafeText;
|
|
2412
|
-
|
|
2413
3468
|
// src/client.ts
|
|
2414
3469
|
var CONFIG_DIR_MODE = 448;
|
|
2415
3470
|
var CREDENTIAL_FILE_MODE = 384;
|
|
2416
3471
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2417
|
-
var
|
|
3472
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
2418
3473
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2419
3474
|
function authExpiredMessage() {
|
|
2420
3475
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2421
3476
|
}
|
|
2422
3477
|
function readTrimmed2(path) {
|
|
2423
3478
|
try {
|
|
2424
|
-
const value =
|
|
3479
|
+
const value = readFileSync9(path, "utf8").trim();
|
|
2425
3480
|
return value || void 0;
|
|
2426
3481
|
} catch {
|
|
2427
3482
|
return void 0;
|
|
@@ -2431,13 +3486,13 @@ function getSiteUrl() {
|
|
|
2431
3486
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
2432
3487
|
}
|
|
2433
3488
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
2434
|
-
return primApiUrl?.trim() ||
|
|
3489
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
2435
3490
|
}
|
|
2436
3491
|
function expiresAtFor(token, expiresIn) {
|
|
2437
3492
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
2438
3493
|
}
|
|
2439
3494
|
function ensureConfigDirectory() {
|
|
2440
|
-
const directory =
|
|
3495
|
+
const directory = dirname6(TOKEN_FILE_PATH);
|
|
2441
3496
|
mkdirSync4(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
2442
3497
|
chmodSync3(directory, CONFIG_DIR_MODE);
|
|
2443
3498
|
}
|
|
@@ -2447,7 +3502,7 @@ function atomicWrite2(path, content) {
|
|
|
2447
3502
|
}
|
|
2448
3503
|
function removeCredentialFile(path) {
|
|
2449
3504
|
if (!existsSync4(path)) return false;
|
|
2450
|
-
|
|
3505
|
+
rmSync7(path, { force: true });
|
|
2451
3506
|
return true;
|
|
2452
3507
|
}
|
|
2453
3508
|
function getTokenExpiresAt() {
|
|
@@ -2462,23 +3517,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
2462
3517
|
const expiresAt = getTokenExpiresAt();
|
|
2463
3518
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
2464
3519
|
}
|
|
2465
|
-
function refreshFingerprint(
|
|
2466
|
-
return
|
|
3520
|
+
function refreshFingerprint(refreshToken3) {
|
|
3521
|
+
return createHash8("sha256").update(refreshToken3).digest("hex");
|
|
2467
3522
|
}
|
|
2468
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
3523
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
2469
3524
|
return {
|
|
2470
3525
|
version: 1,
|
|
2471
3526
|
family: "legacy_broker",
|
|
2472
3527
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2473
|
-
refreshTokenHash: refreshFingerprint(
|
|
3528
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2474
3529
|
};
|
|
2475
3530
|
}
|
|
2476
|
-
function credentialFamilyMetadata(accessToken,
|
|
3531
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
2477
3532
|
const hashes = {
|
|
2478
3533
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2479
|
-
refreshTokenHash: refreshFingerprint(
|
|
3534
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2480
3535
|
};
|
|
2481
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
3536
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
2482
3537
|
}
|
|
2483
3538
|
function writeCredentialMigrationSentinel() {
|
|
2484
3539
|
atomicWrite2(
|
|
@@ -2490,11 +3545,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
2490
3545
|
`
|
|
2491
3546
|
);
|
|
2492
3547
|
}
|
|
2493
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
2494
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
3548
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
3549
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
2495
3550
|
return { state: "invalid" };
|
|
2496
3551
|
}
|
|
2497
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3552
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2498
3553
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
2499
3554
|
return { state: "invalid" };
|
|
2500
3555
|
}
|
|
@@ -2511,17 +3566,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
2511
3566
|
const metadata = readStoredCredentialMetadata();
|
|
2512
3567
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
2513
3568
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
2514
|
-
const
|
|
2515
|
-
if (!(accessToken &&
|
|
2516
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3569
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
3570
|
+
if (!(accessToken && refreshToken3)) return;
|
|
3571
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2517
3572
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2518
3573
|
`);
|
|
2519
3574
|
}
|
|
2520
3575
|
function terminalFingerprint() {
|
|
2521
3576
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
2522
3577
|
}
|
|
2523
|
-
function writeTerminalFingerprint(
|
|
2524
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
3578
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
3579
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
2525
3580
|
`);
|
|
2526
3581
|
}
|
|
2527
3582
|
function clearTerminalFingerprint() {
|
|
@@ -2530,20 +3585,20 @@ function clearTerminalFingerprint() {
|
|
|
2530
3585
|
function isSessionEnded() {
|
|
2531
3586
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
2532
3587
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
2533
|
-
const
|
|
3588
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
2534
3589
|
const ended = terminalFingerprint();
|
|
2535
|
-
return Boolean(
|
|
3590
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
2536
3591
|
}
|
|
2537
3592
|
function withCredentialLock(operation, options = {}) {
|
|
2538
3593
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
2539
3594
|
}
|
|
2540
3595
|
function commitCredentialsUnlocked(credentials) {
|
|
2541
3596
|
const accessToken = credentials.accessToken.trim();
|
|
2542
|
-
const
|
|
2543
|
-
if (!accessToken || !
|
|
3597
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
3598
|
+
if (!accessToken || !refreshToken3) {
|
|
2544
3599
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
2545
3600
|
}
|
|
2546
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
3601
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
2547
3602
|
if (credentials.metadata !== void 0) {
|
|
2548
3603
|
preserveMarkerlessLegacyGeneration();
|
|
2549
3604
|
writeCredentialMigrationSentinel();
|
|
@@ -2551,10 +3606,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
2551
3606
|
`);
|
|
2552
3607
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
2553
3608
|
`);
|
|
2554
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3609
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2555
3610
|
`);
|
|
2556
3611
|
} else {
|
|
2557
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3612
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2558
3613
|
`);
|
|
2559
3614
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2560
3615
|
`);
|
|
@@ -2591,15 +3646,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
2591
3646
|
`
|
|
2592
3647
|
);
|
|
2593
3648
|
}
|
|
2594
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
3649
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
2595
3650
|
const current = readStoredCredentialMetadata();
|
|
2596
3651
|
if (expected.state === "legacy_broker") {
|
|
2597
3652
|
if (current.state !== "legacy_broker") return false;
|
|
2598
3653
|
if (!expected.metadata) return current.metadata === void 0;
|
|
2599
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3654
|
+
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;
|
|
2600
3655
|
}
|
|
2601
3656
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
2602
|
-
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(
|
|
3657
|
+
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;
|
|
2603
3658
|
}
|
|
2604
3659
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
2605
3660
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -2768,7 +3823,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
2768
3823
|
);
|
|
2769
3824
|
}
|
|
2770
3825
|
var _refreshInFlight;
|
|
2771
|
-
function
|
|
3826
|
+
function refreshToken2(options = {}) {
|
|
2772
3827
|
if (hasMachineConfiguration())
|
|
2773
3828
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
2774
3829
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -2906,7 +3961,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2906
3961
|
if (response.status === 401)
|
|
2907
3962
|
throw new HttpError(
|
|
2908
3963
|
401,
|
|
2909
|
-
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
|
+
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(
|
|
2910
3965
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2911
3966
|
)
|
|
2912
3967
|
);
|
|
@@ -2927,7 +3982,7 @@ async function request2(method, path, body, options) {
|
|
|
2927
3982
|
let refreshAttempted = false;
|
|
2928
3983
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2929
3984
|
refreshAttempted = true;
|
|
2930
|
-
const token = await
|
|
3985
|
+
const token = await refreshToken2({
|
|
2931
3986
|
signal: options?.signal,
|
|
2932
3987
|
quiet: options?.quietRefresh
|
|
2933
3988
|
});
|
|
@@ -2946,7 +4001,7 @@ async function request2(method, path, body, options) {
|
|
|
2946
4001
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
2947
4002
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
2948
4003
|
refreshAttempted = true;
|
|
2949
|
-
retryToken = await
|
|
4004
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
2950
4005
|
}
|
|
2951
4006
|
if (retryToken) {
|
|
2952
4007
|
_cachedCredential = {
|
|
@@ -2970,7 +4025,7 @@ async function getPinnedClient(options = {}) {
|
|
|
2970
4025
|
const siteUrl = getSiteUrl();
|
|
2971
4026
|
let credential = selectedCredential();
|
|
2972
4027
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2973
|
-
const token2 = await
|
|
4028
|
+
const token2 = await refreshToken2({
|
|
2974
4029
|
signal: options.signal,
|
|
2975
4030
|
quiet: options.quietRefresh
|
|
2976
4031
|
});
|
|
@@ -2989,10 +4044,10 @@ async function getPinnedClient(options = {}) {
|
|
|
2989
4044
|
|
|
2990
4045
|
// src/flusher.ts
|
|
2991
4046
|
import { createReadStream, renameSync as renameSync3, statSync as statSync2, unlinkSync } from "fs";
|
|
2992
|
-
import { dirname as dirname10, join as
|
|
4047
|
+
import { dirname as dirname10, join as join17 } from "path";
|
|
2993
4048
|
|
|
2994
4049
|
// src/dead-letter.ts
|
|
2995
|
-
import { createHash as
|
|
4050
|
+
import { createHash as createHash9, randomBytes as randomBytes5 } from "crypto";
|
|
2996
4051
|
import {
|
|
2997
4052
|
constants as constants2,
|
|
2998
4053
|
chmodSync as chmodSync4,
|
|
@@ -3003,25 +4058,25 @@ import {
|
|
|
3003
4058
|
mkdirSync as mkdirSync5,
|
|
3004
4059
|
openSync as openSync2,
|
|
3005
4060
|
renameSync as renameSync2,
|
|
3006
|
-
rmSync as
|
|
4061
|
+
rmSync as rmSync8,
|
|
3007
4062
|
writeFileSync as writeFileSync4
|
|
3008
4063
|
} from "fs";
|
|
3009
|
-
import { dirname as
|
|
4064
|
+
import { dirname as dirname7, join as join12 } from "path";
|
|
3010
4065
|
var DIRECTORY_MODE2 = 448;
|
|
3011
4066
|
var FILE_MODE2 = 384;
|
|
3012
4067
|
var DEAD_LETTER_DIRNAME = "dead-letter";
|
|
3013
4068
|
function deadLetterDirectoryForRotation(flushingPath) {
|
|
3014
|
-
return
|
|
4069
|
+
return join12(dirname7(flushingPath), DEAD_LETTER_DIRNAME);
|
|
3015
4070
|
}
|
|
3016
4071
|
function deadLetterPathForRawLine(flushingPath, rawLine) {
|
|
3017
|
-
const quarantineId =
|
|
3018
|
-
return
|
|
4072
|
+
const quarantineId = createHash9("sha256").update(rawLine).digest("hex");
|
|
4073
|
+
return join12(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
|
|
3019
4074
|
}
|
|
3020
4075
|
function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
|
|
3021
4076
|
const directory = deadLetterDirectoryForRotation(flushingPath);
|
|
3022
4077
|
mkdirSync5(directory, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
3023
4078
|
chmodSync4(directory, DIRECTORY_MODE2);
|
|
3024
|
-
persistDirectory(
|
|
4079
|
+
persistDirectory(dirname7(directory));
|
|
3025
4080
|
return directory;
|
|
3026
4081
|
}
|
|
3027
4082
|
function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
|
|
@@ -3029,7 +4084,7 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
|
|
|
3029
4084
|
persistDirectory(directory);
|
|
3030
4085
|
return;
|
|
3031
4086
|
}
|
|
3032
|
-
const temporaryPath =
|
|
4087
|
+
const temporaryPath = join12(
|
|
3033
4088
|
directory,
|
|
3034
4089
|
`.${quarantineId}.${String(process.pid)}.${randomBytes5(8).toString("hex")}.tmp`
|
|
3035
4090
|
);
|
|
@@ -3047,7 +4102,7 @@ function persistDeadLetter(directory, path, quarantineId, record, persistDirecto
|
|
|
3047
4102
|
renameSync2(temporaryPath, path);
|
|
3048
4103
|
persistDirectory(directory);
|
|
3049
4104
|
} finally {
|
|
3050
|
-
|
|
4105
|
+
rmSync8(temporaryPath, { force: true });
|
|
3051
4106
|
}
|
|
3052
4107
|
}
|
|
3053
4108
|
function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
|
|
@@ -3056,12 +4111,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
|
|
|
3056
4111
|
const serializedMove = JSON.stringify(move);
|
|
3057
4112
|
const record = {
|
|
3058
4113
|
version: 1,
|
|
3059
|
-
quarantineId:
|
|
4114
|
+
quarantineId: createHash9("sha256").update(serializedMove).digest("hex"),
|
|
3060
4115
|
quarantinedAt: now(),
|
|
3061
4116
|
reason,
|
|
3062
4117
|
move
|
|
3063
4118
|
};
|
|
3064
|
-
const path =
|
|
4119
|
+
const path = join12(directory, `${record.quarantineId}.json`);
|
|
3065
4120
|
persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
|
|
3066
4121
|
return record;
|
|
3067
4122
|
}
|
|
@@ -3072,7 +4127,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
3072
4127
|
const record = {
|
|
3073
4128
|
version: 1,
|
|
3074
4129
|
recordKind: "raw_line_v1",
|
|
3075
|
-
quarantineId:
|
|
4130
|
+
quarantineId: createHash9("sha256").update(bytes).digest("hex"),
|
|
3076
4131
|
quarantinedAt: now(),
|
|
3077
4132
|
reason: "invalid_move",
|
|
3078
4133
|
rawLineEncoding: "base64",
|
|
@@ -3093,12 +4148,12 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
3093
4148
|
import {
|
|
3094
4149
|
chmodSync as chmodSync5,
|
|
3095
4150
|
existsSync as existsSync6,
|
|
3096
|
-
readFileSync as
|
|
4151
|
+
readFileSync as readFileSync10,
|
|
3097
4152
|
readdirSync as readdirSync2,
|
|
3098
|
-
rmSync as
|
|
4153
|
+
rmSync as rmSync9,
|
|
3099
4154
|
rmdirSync
|
|
3100
4155
|
} from "fs";
|
|
3101
|
-
import { basename as
|
|
4156
|
+
import { basename as basename3, dirname as dirname8, join as join13 } from "path";
|
|
3102
4157
|
var DIRECTORY_MODE3 = 448;
|
|
3103
4158
|
var FILE_MODE3 = 384;
|
|
3104
4159
|
var DRAIN_PROGRESS_DIRNAME = "drain-progress";
|
|
@@ -3107,10 +4162,10 @@ function rotationIdentity(stat) {
|
|
|
3107
4162
|
return { size: stat.size, ino: stat.ino, dev: stat.dev };
|
|
3108
4163
|
}
|
|
3109
4164
|
function drainProgressDirectory(flushingPath) {
|
|
3110
|
-
return
|
|
4165
|
+
return join13(dirname8(flushingPath), DRAIN_PROGRESS_DIRNAME);
|
|
3111
4166
|
}
|
|
3112
4167
|
function drainProgressPath(flushingPath) {
|
|
3113
|
-
return
|
|
4168
|
+
return join13(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
|
|
3114
4169
|
}
|
|
3115
4170
|
function isByteCount(value) {
|
|
3116
4171
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
@@ -3118,7 +4173,7 @@ function isByteCount(value) {
|
|
|
3118
4173
|
function drainResumeOffset(flushingPath, rotation) {
|
|
3119
4174
|
let parsed;
|
|
3120
4175
|
try {
|
|
3121
|
-
parsed = JSON.parse(
|
|
4176
|
+
parsed = JSON.parse(readFileSync10(drainProgressPath(flushingPath), "utf8"));
|
|
3122
4177
|
} catch {
|
|
3123
4178
|
return 0;
|
|
3124
4179
|
}
|
|
@@ -3151,11 +4206,11 @@ function removeEmptyDirectory(directory) {
|
|
|
3151
4206
|
}
|
|
3152
4207
|
}
|
|
3153
4208
|
function removeDrainCheckpoint(flushingPath) {
|
|
3154
|
-
|
|
4209
|
+
rmSync9(drainProgressPath(flushingPath), { force: true });
|
|
3155
4210
|
removeEmptyDirectory(drainProgressDirectory(flushingPath));
|
|
3156
4211
|
}
|
|
3157
4212
|
function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
3158
|
-
const directory =
|
|
4213
|
+
const directory = join13(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
|
|
3159
4214
|
let names;
|
|
3160
4215
|
try {
|
|
3161
4216
|
names = readdirSync2(directory);
|
|
@@ -3164,11 +4219,11 @@ function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
|
3164
4219
|
}
|
|
3165
4220
|
for (const name of names) {
|
|
3166
4221
|
const rotation = CHECKPOINT_NAME.exec(name)?.[1];
|
|
3167
|
-
if (rotation === void 0 || existsSync6(
|
|
4222
|
+
if (rotation === void 0 || existsSync6(join13(bucketDirectory, rotation))) {
|
|
3168
4223
|
continue;
|
|
3169
4224
|
}
|
|
3170
4225
|
try {
|
|
3171
|
-
|
|
4226
|
+
rmSync9(join13(directory, name), { force: true });
|
|
3172
4227
|
} catch {
|
|
3173
4228
|
}
|
|
3174
4229
|
}
|
|
@@ -29867,14 +30922,14 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
29867
30922
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
29868
30923
|
import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
|
|
29869
30924
|
import { homedir as homedir2 } from "os";
|
|
29870
|
-
import { join as
|
|
30925
|
+
import { join as join15 } from "path";
|
|
29871
30926
|
|
|
29872
30927
|
// src/lib/cloud-prepared.ts
|
|
29873
|
-
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as
|
|
29874
|
-
import { join as
|
|
30928
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync10, writeFileSync as writeFileSync5 } from "fs";
|
|
30929
|
+
import { join as join14 } from "path";
|
|
29875
30930
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
29876
30931
|
function cloudPreparedPath(env = process.env) {
|
|
29877
|
-
return
|
|
30932
|
+
return join14(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
29878
30933
|
}
|
|
29879
30934
|
function isPreparedCloudSession(env = process.env) {
|
|
29880
30935
|
if (!isClaudeCloudSession(env)) return false;
|
|
@@ -29886,17 +30941,17 @@ function isPreparedCloudSession(env = process.env) {
|
|
|
29886
30941
|
}
|
|
29887
30942
|
|
|
29888
30943
|
// src/lib/demo-pause.ts
|
|
29889
|
-
import { execFileSync as
|
|
30944
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
29890
30945
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
29891
30946
|
var PAUSE_KEY = "prim.demoPause";
|
|
29892
|
-
var
|
|
29893
|
-
function
|
|
30947
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
30948
|
+
function git2(cwd, args) {
|
|
29894
30949
|
try {
|
|
29895
|
-
return
|
|
30950
|
+
return execFileSync3("git", args, {
|
|
29896
30951
|
cwd,
|
|
29897
30952
|
encoding: "utf-8",
|
|
29898
30953
|
stdio: ["ignore", "pipe", "ignore"],
|
|
29899
|
-
timeout:
|
|
30954
|
+
timeout: GIT_TIMEOUT_MS3
|
|
29900
30955
|
});
|
|
29901
30956
|
} catch {
|
|
29902
30957
|
return void 0;
|
|
@@ -29904,10 +30959,10 @@ function git(cwd, args) {
|
|
|
29904
30959
|
}
|
|
29905
30960
|
function setLocal(cwd, key, value) {
|
|
29906
30961
|
try {
|
|
29907
|
-
|
|
30962
|
+
execFileSync3(
|
|
29908
30963
|
"git",
|
|
29909
30964
|
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
29910
|
-
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout:
|
|
30965
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
|
|
29911
30966
|
);
|
|
29912
30967
|
} catch (error) {
|
|
29913
30968
|
if (value !== null || error.status !== 5) throw error;
|
|
@@ -29921,7 +30976,7 @@ function parsePause(value) {
|
|
|
29921
30976
|
function readCaptureConfig(cwd) {
|
|
29922
30977
|
let active;
|
|
29923
30978
|
let pause;
|
|
29924
|
-
const out =
|
|
30979
|
+
const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
29925
30980
|
for (const line of out.split("\n")) {
|
|
29926
30981
|
const space = line.indexOf(" ");
|
|
29927
30982
|
const key = line.slice(0, space).toLowerCase();
|
|
@@ -29946,121 +31001,13 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
29946
31001
|
}
|
|
29947
31002
|
}
|
|
29948
31003
|
|
|
29949
|
-
// src/lib/git.ts
|
|
29950
|
-
import { execFileSync as execFileSync3 } from "child_process";
|
|
29951
|
-
import { createHash as createHash8 } from "crypto";
|
|
29952
|
-
import { lstatSync as lstatSync5, readFileSync as readFileSync11, realpathSync } from "fs";
|
|
29953
|
-
import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, join as join13, relative, resolve as resolve2, sep } from "path";
|
|
29954
|
-
var GIT_TIMEOUT_MS2 = 1e3;
|
|
29955
|
-
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
29956
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
29957
|
-
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
29958
|
-
function gitToplevel(cwd) {
|
|
29959
|
-
try {
|
|
29960
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
29961
|
-
cwd,
|
|
29962
|
-
encoding: "utf-8",
|
|
29963
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29964
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29965
|
-
}).trim();
|
|
29966
|
-
} catch {
|
|
29967
|
-
return null;
|
|
29968
|
-
}
|
|
29969
|
-
}
|
|
29970
|
-
function gitValue(cwd, args) {
|
|
29971
|
-
try {
|
|
29972
|
-
const value = execFileSync3("git", args, {
|
|
29973
|
-
cwd,
|
|
29974
|
-
encoding: "utf-8",
|
|
29975
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29976
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29977
|
-
}).trim();
|
|
29978
|
-
return value || void 0;
|
|
29979
|
-
} catch {
|
|
29980
|
-
return void 0;
|
|
29981
|
-
}
|
|
29982
|
-
}
|
|
29983
|
-
function parseGithubRepositoryName(path) {
|
|
29984
|
-
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
29985
|
-
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
29986
|
-
return null;
|
|
29987
|
-
}
|
|
29988
|
-
return `${parts[0]}/${parts[1]}`;
|
|
29989
|
-
}
|
|
29990
|
-
function githubRepositoryFromRemote(remote) {
|
|
29991
|
-
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
29992
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
29993
|
-
remote
|
|
29994
|
-
);
|
|
29995
|
-
const path = match?.[1] ?? match?.[2];
|
|
29996
|
-
return path ? parseGithubRepositoryName(path) : null;
|
|
29997
|
-
}
|
|
29998
|
-
function checkoutSettingsText(repoRoot) {
|
|
29999
|
-
const path = join13(repoRoot, ".claude", "settings.json");
|
|
30000
|
-
try {
|
|
30001
|
-
if (!lstatSync5(join13(repoRoot, ".claude")).isDirectory()) return null;
|
|
30002
|
-
const stat = lstatSync5(path);
|
|
30003
|
-
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
30004
|
-
return readFileSync11(path, "utf8");
|
|
30005
|
-
} catch {
|
|
30006
|
-
return null;
|
|
30007
|
-
}
|
|
30008
|
-
}
|
|
30009
|
-
function checkoutDeclaration(repoRoot, name) {
|
|
30010
|
-
const text = checkoutSettingsText(repoRoot);
|
|
30011
|
-
if (text === null) return null;
|
|
30012
|
-
let parsed;
|
|
30013
|
-
try {
|
|
30014
|
-
parsed = JSON.parse(text);
|
|
30015
|
-
} catch {
|
|
30016
|
-
return null;
|
|
30017
|
-
}
|
|
30018
|
-
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
30019
|
-
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
30020
|
-
return typeof value === "string" ? value : null;
|
|
30021
|
-
}
|
|
30022
|
-
function declaredGithubRepository(repoRoot) {
|
|
30023
|
-
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
30024
|
-
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
30025
|
-
}
|
|
30026
|
-
function githubRepositoryFullName(cwd) {
|
|
30027
|
-
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
30028
|
-
if (remote) {
|
|
30029
|
-
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
30030
|
-
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
30031
|
-
}
|
|
30032
|
-
const root = gitToplevel(cwd);
|
|
30033
|
-
return root ? declaredGithubRepository(root) : null;
|
|
30034
|
-
}
|
|
30035
|
-
function normalizeOriginRemote(remote) {
|
|
30036
|
-
const value = remote.trim();
|
|
30037
|
-
if (!value) return void 0;
|
|
30038
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
30039
|
-
if (scp?.host && scp.path) {
|
|
30040
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30041
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
30042
|
-
}
|
|
30043
|
-
try {
|
|
30044
|
-
const url = new URL(value);
|
|
30045
|
-
url.username = "";
|
|
30046
|
-
url.password = "";
|
|
30047
|
-
url.search = "";
|
|
30048
|
-
url.hash = "";
|
|
30049
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30050
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
30051
|
-
return void 0;
|
|
30052
|
-
} catch {
|
|
30053
|
-
return void 0;
|
|
30054
|
-
}
|
|
30055
|
-
}
|
|
30056
|
-
|
|
30057
31004
|
// src/lib/activation.ts
|
|
30058
31005
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
30059
31006
|
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
30060
31007
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
30061
31008
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
30062
31009
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
30063
|
-
var
|
|
31010
|
+
var GIT_TIMEOUT_MS4 = 1e3;
|
|
30064
31011
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
30065
31012
|
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
30066
31013
|
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
@@ -30070,7 +31017,7 @@ function repoActiveFlag(cwd, strict = false) {
|
|
|
30070
31017
|
cwd,
|
|
30071
31018
|
encoding: "utf-8",
|
|
30072
31019
|
stdio: ["ignore", "pipe", "ignore"],
|
|
30073
|
-
timeout:
|
|
31020
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30074
31021
|
}).trim();
|
|
30075
31022
|
if (value === "true") return "true";
|
|
30076
31023
|
if (value === "false") return "false";
|
|
@@ -30091,7 +31038,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
30091
31038
|
cwd,
|
|
30092
31039
|
encoding: "utf-8",
|
|
30093
31040
|
stdio: ["ignore", "pipe", "ignore"],
|
|
30094
|
-
timeout:
|
|
31041
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30095
31042
|
}).trim();
|
|
30096
31043
|
return value || void 0;
|
|
30097
31044
|
} catch {
|
|
@@ -30102,7 +31049,7 @@ function setLocalGitConfigValue(cwd, key, value) {
|
|
|
30102
31049
|
execFileSync4("git", ["config", "--local", key, value], {
|
|
30103
31050
|
cwd,
|
|
30104
31051
|
stdio: ["ignore", "ignore", "pipe"],
|
|
30105
|
-
timeout:
|
|
31052
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30106
31053
|
});
|
|
30107
31054
|
}
|
|
30108
31055
|
function repoSyncId(cwd) {
|
|
@@ -30123,7 +31070,7 @@ function repositoryBindingState(cwd) {
|
|
|
30123
31070
|
function projectPrimInstallAt(root) {
|
|
30124
31071
|
if (root === null || root === homedir2()) return false;
|
|
30125
31072
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
30126
|
-
const path =
|
|
31073
|
+
const path = join15(root, rel);
|
|
30127
31074
|
if (existsSync8(path)) {
|
|
30128
31075
|
try {
|
|
30129
31076
|
const content = readFileSync12(path, "utf-8");
|
|
@@ -30544,8 +31491,8 @@ import {
|
|
|
30544
31491
|
readSync,
|
|
30545
31492
|
readdirSync as readdirSync3
|
|
30546
31493
|
} from "fs";
|
|
30547
|
-
import { dirname as dirname9, join as
|
|
30548
|
-
var JOURNAL_DIR =
|
|
31494
|
+
import { dirname as dirname9, join as join16 } from "path";
|
|
31495
|
+
var JOURNAL_DIR = join16(primConfigDirectory(), "moves");
|
|
30549
31496
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
30550
31497
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
30551
31498
|
var PENDING_STATS_MAX_FILES = 128;
|
|
@@ -30557,7 +31504,7 @@ function envSlug(apiUrl) {
|
|
|
30557
31504
|
return slug;
|
|
30558
31505
|
}
|
|
30559
31506
|
function currentEnvDir() {
|
|
30560
|
-
return
|
|
31507
|
+
return join16(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
30561
31508
|
}
|
|
30562
31509
|
function parseMoves(content) {
|
|
30563
31510
|
const moves = [];
|
|
@@ -30582,7 +31529,7 @@ function listBuckets() {
|
|
|
30582
31529
|
if (!entry.isDirectory()) {
|
|
30583
31530
|
continue;
|
|
30584
31531
|
}
|
|
30585
|
-
const path =
|
|
31532
|
+
const path = join16(envDir, entry.name, JOURNAL_BASENAME);
|
|
30586
31533
|
if (existsSync9(path)) {
|
|
30587
31534
|
out.push({ bucket: entry.name, path });
|
|
30588
31535
|
}
|
|
@@ -30659,7 +31606,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
30659
31606
|
entry = entries.readSync();
|
|
30660
31607
|
continue;
|
|
30661
31608
|
}
|
|
30662
|
-
const path =
|
|
31609
|
+
const path = join16(dir, entry.name);
|
|
30663
31610
|
let sample;
|
|
30664
31611
|
try {
|
|
30665
31612
|
sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
|
|
@@ -30697,7 +31644,7 @@ function listFlushing(options = {}) {
|
|
|
30697
31644
|
break;
|
|
30698
31645
|
}
|
|
30699
31646
|
if (entry.isDirectory()) {
|
|
30700
|
-
const found = listFlushingInDir(
|
|
31647
|
+
const found = listFlushingInDir(join16(envDir, entry.name), entry.name, {
|
|
30701
31648
|
sampleBytes: remainingBytes,
|
|
30702
31649
|
maxFiles: maxFiles - out.length
|
|
30703
31650
|
});
|
|
@@ -30717,7 +31664,7 @@ function sweepOrphanedDrainProgress() {
|
|
|
30717
31664
|
}
|
|
30718
31665
|
for (const entry of readdirSync3(envDir, { withFileTypes: true })) {
|
|
30719
31666
|
if (entry.isDirectory()) {
|
|
30720
|
-
sweepOrphanedDrainCheckpoints(
|
|
31667
|
+
sweepOrphanedDrainCheckpoints(join16(envDir, entry.name));
|
|
30721
31668
|
}
|
|
30722
31669
|
}
|
|
30723
31670
|
}
|
|
@@ -31045,12 +31992,12 @@ async function recoverOrphans(candidates, options) {
|
|
|
31045
31992
|
if (summary.failedBuckets.has(file.bucket)) {
|
|
31046
31993
|
continue;
|
|
31047
31994
|
}
|
|
31048
|
-
const { counts, failure } = await settleDrain((onProgress) => drain(file.path, onProgress));
|
|
31995
|
+
const { counts, failure: failure2 } = await settleDrain((onProgress) => drain(file.path, onProgress));
|
|
31049
31996
|
summary.flushed += counts.flushed;
|
|
31050
31997
|
summary.quarantined += counts.quarantined;
|
|
31051
|
-
if (
|
|
31998
|
+
if (failure2) {
|
|
31052
31999
|
summary.failedDrainFlushed += counts.flushed;
|
|
31053
|
-
summary.errors.push(
|
|
32000
|
+
summary.errors.push(failure2.error);
|
|
31054
32001
|
summary.failedBuckets.add(file.bucket);
|
|
31055
32002
|
}
|
|
31056
32003
|
}
|
|
@@ -31109,14 +32056,14 @@ async function flushOnce() {
|
|
|
31109
32056
|
if (recovered.failedBuckets.has(bucket)) {
|
|
31110
32057
|
continue;
|
|
31111
32058
|
}
|
|
31112
|
-
const { counts, failure } = await settleDrain(
|
|
32059
|
+
const { counts, failure: failure2 } = await settleDrain(
|
|
31113
32060
|
(onProgress) => drainPath(path, client2, binding, onProgress)
|
|
31114
32061
|
);
|
|
31115
32062
|
total += counts.flushed;
|
|
31116
32063
|
quarantined += counts.quarantined;
|
|
31117
|
-
if (
|
|
32064
|
+
if (failure2) {
|
|
31118
32065
|
failedDrainFlushed += counts.flushed;
|
|
31119
|
-
errors.push(
|
|
32066
|
+
errors.push(failure2.error);
|
|
31120
32067
|
}
|
|
31121
32068
|
}
|
|
31122
32069
|
if (errors.length > 0) {
|
|
@@ -31131,7 +32078,7 @@ async function flushOnce() {
|
|
|
31131
32078
|
return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
|
|
31132
32079
|
}
|
|
31133
32080
|
var flushInFlight;
|
|
31134
|
-
var FLUSH_LOCK_PATH =
|
|
32081
|
+
var FLUSH_LOCK_PATH = join17(dirname10(JOURNAL_DIR), ".flush.lock");
|
|
31135
32082
|
var FLUSH_LOCK_TIMEOUT_MS = 250;
|
|
31136
32083
|
function isFlushLockContended(error) {
|
|
31137
32084
|
return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
|
|
@@ -31333,8 +32280,8 @@ var StatuslineIngestionCache = class {
|
|
|
31333
32280
|
|
|
31334
32281
|
// src/daemon/client.ts
|
|
31335
32282
|
import { createConnection } from "net";
|
|
31336
|
-
import { join as
|
|
31337
|
-
var SOCK_PATH =
|
|
32283
|
+
import { join as join18 } from "path";
|
|
32284
|
+
var SOCK_PATH = join18(primConfigDirectory(), "sock");
|
|
31338
32285
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
31339
32286
|
var nextRequestId = 1;
|
|
31340
32287
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -31606,7 +32553,7 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
|
|
|
31606
32553
|
|
|
31607
32554
|
// src/daemon/health.ts
|
|
31608
32555
|
import { chmodSync as chmodSync6, existsSync as existsSync10, mkdirSync as mkdirSync8, renameSync as renameSync4, writeFileSync as writeFileSync6 } from "fs";
|
|
31609
|
-
import { dirname as dirname11, join as
|
|
32556
|
+
import { dirname as dirname11, join as join19 } from "path";
|
|
31610
32557
|
var CONFIG_DIR_MODE2 = 448;
|
|
31611
32558
|
var HEALTH_FILE_MODE = 384;
|
|
31612
32559
|
var INGESTION_SLA_MS = 3e4;
|
|
@@ -31614,7 +32561,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
|
|
|
31614
32561
|
var HEARTBEAT_RETRY_CAP_MS = 3e4;
|
|
31615
32562
|
var INGESTION_RETRY_BASE_MS = 5e3;
|
|
31616
32563
|
var INGESTION_RETRY_CAP_MS = 15e3;
|
|
31617
|
-
var DAEMON_HEALTH_PATH =
|
|
32564
|
+
var DAEMON_HEALTH_PATH = join19(primConfigDirectory(), "daemon-health.json");
|
|
31618
32565
|
function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
|
|
31619
32566
|
return {
|
|
31620
32567
|
schemaVersion: 1,
|
|
@@ -31659,7 +32606,7 @@ function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
|
31659
32606
|
if (!existsSync10(dir)) {
|
|
31660
32607
|
mkdirSync8(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
|
|
31661
32608
|
}
|
|
31662
|
-
const tmp =
|
|
32609
|
+
const tmp = join19(dir, `.${process.pid}.daemon-health.tmp`);
|
|
31663
32610
|
writeFileSync6(tmp, `${JSON.stringify(state, null, 2)}
|
|
31664
32611
|
`, { mode: HEALTH_FILE_MODE });
|
|
31665
32612
|
chmodSync6(tmp, HEALTH_FILE_MODE);
|
|
@@ -31674,12 +32621,12 @@ import {
|
|
|
31674
32621
|
mkdirSync as mkdirSync9,
|
|
31675
32622
|
readFileSync as readFileSync14,
|
|
31676
32623
|
renameSync as renameSync5,
|
|
31677
|
-
rmSync as
|
|
32624
|
+
rmSync as rmSync11,
|
|
31678
32625
|
statSync as statSync3,
|
|
31679
32626
|
unlinkSync as unlinkSync2,
|
|
31680
32627
|
writeFileSync as writeFileSync7
|
|
31681
32628
|
} from "fs";
|
|
31682
|
-
import { join as
|
|
32629
|
+
import { join as join20 } from "path";
|
|
31683
32630
|
var DIR_MODE = 448;
|
|
31684
32631
|
var FILE_MODE4 = 384;
|
|
31685
32632
|
var DAEMON_STARTUP_GRACE_MS = 5e3;
|
|
@@ -31702,10 +32649,10 @@ function numericPid(path) {
|
|
|
31702
32649
|
}
|
|
31703
32650
|
}
|
|
31704
32651
|
function readDaemonOwner(configDir) {
|
|
31705
|
-
return readLockRecord(
|
|
32652
|
+
return readLockRecord(join20(configDir, "daemon.lock", "owner.json"));
|
|
31706
32653
|
}
|
|
31707
32654
|
function readDaemonPid(configDir) {
|
|
31708
|
-
const path =
|
|
32655
|
+
const path = join20(configDir, "daemon.pid");
|
|
31709
32656
|
const pid = numericPid(path);
|
|
31710
32657
|
if (pid === void 0) {
|
|
31711
32658
|
return;
|
|
@@ -31720,9 +32667,9 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31720
32667
|
const pid = opts.pid ?? process.pid;
|
|
31721
32668
|
const now = opts.now ?? Date.now();
|
|
31722
32669
|
const isAlive = opts.isAlive ?? processIsAlive;
|
|
31723
|
-
const lockDir =
|
|
31724
|
-
const ownerPath2 =
|
|
31725
|
-
const pidPath =
|
|
32670
|
+
const lockDir = join20(configDir, "daemon.lock");
|
|
32671
|
+
const ownerPath2 = join20(lockDir, "owner.json");
|
|
32672
|
+
const pidPath = join20(configDir, "daemon.pid");
|
|
31726
32673
|
const instanceId2 = randomUUID3();
|
|
31727
32674
|
if (!existsSync11(configDir)) {
|
|
31728
32675
|
mkdirSync9(configDir, { recursive: true, mode: DIR_MODE });
|
|
@@ -31756,7 +32703,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31756
32703
|
const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
|
|
31757
32704
|
try {
|
|
31758
32705
|
renameSync5(lockDir, stale);
|
|
31759
|
-
|
|
32706
|
+
rmSync11(stale, { recursive: true, force: true });
|
|
31760
32707
|
} catch (renameErr) {
|
|
31761
32708
|
if (renameErr.code !== "ENOENT") {
|
|
31762
32709
|
throw renameErr;
|
|
@@ -31778,7 +32725,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31778
32725
|
chmodSync7(ownerPath2, FILE_MODE4);
|
|
31779
32726
|
const legacyPid = numericPid(pidPath);
|
|
31780
32727
|
if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
|
|
31781
|
-
|
|
32728
|
+
rmSync11(lockDir, { recursive: true, force: true });
|
|
31782
32729
|
throw new Error(`daemon already running (pid=${String(legacyPid)})`);
|
|
31783
32730
|
}
|
|
31784
32731
|
writeFileSync7(pidPath, String(pid), { mode: FILE_MODE4 });
|
|
@@ -31812,7 +32759,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
|
|
|
31812
32759
|
}
|
|
31813
32760
|
}
|
|
31814
32761
|
}
|
|
31815
|
-
|
|
32762
|
+
rmSync11(ownership2.lockDir, { recursive: true, force: true });
|
|
31816
32763
|
if (cleanupError) {
|
|
31817
32764
|
throw cleanupError;
|
|
31818
32765
|
}
|
|
@@ -31907,7 +32854,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
31907
32854
|
|
|
31908
32855
|
// src/daemon/server.ts
|
|
31909
32856
|
var CONFIG_DIR = primConfigDirectory();
|
|
31910
|
-
var SOCK_PATH2 =
|
|
32857
|
+
var SOCK_PATH2 = join21(CONFIG_DIR, "sock");
|
|
31911
32858
|
var CONFIG_DIR_MODE3 = 448;
|
|
31912
32859
|
var SOCKET_MODE = 384;
|
|
31913
32860
|
var MAX_SOCKET_CONNECTIONS = 64;
|
|
@@ -31976,7 +32923,7 @@ function resolveRuntimeVersion() {
|
|
|
31976
32923
|
}
|
|
31977
32924
|
try {
|
|
31978
32925
|
const here = fileURLToPath4(new URL(".", import.meta.url));
|
|
31979
|
-
const pkg = JSON.parse(readFileSync15(
|
|
32926
|
+
const pkg = JSON.parse(readFileSync15(join21(here, "..", "..", "package.json"), "utf-8"));
|
|
31980
32927
|
return pkg.version ?? "unknown";
|
|
31981
32928
|
} catch {
|
|
31982
32929
|
return "unknown";
|
|
@@ -32247,7 +33194,7 @@ async function ensureTokenFresh() {
|
|
|
32247
33194
|
}
|
|
32248
33195
|
if (Date.now() >= expiresAt - TOKEN_REFRESH_THRESHOLD_MS) {
|
|
32249
33196
|
try {
|
|
32250
|
-
await
|
|
33197
|
+
await refreshToken2({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
|
|
32251
33198
|
} catch {
|
|
32252
33199
|
}
|
|
32253
33200
|
}
|