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