@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +211 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
- package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
- package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
- package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
- package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
- package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
- package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
- package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
- package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
- package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
- package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1976 -442
- package/dist/hook-runtime/daemon/server.js +1976 -442
- package/dist/hook-runtime/hooks/post-commit.js +592 -212
- package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
- package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
- package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
- package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
- package/dist/hook-runtime/hooks/session-end.js +549 -180
- package/dist/hook-runtime/hooks/session-start.js +2213 -596
- package/dist/hook-runtime/index.js +5318 -2423
- package/dist/hook-runtime/statusline-main.js +531 -150
- 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 +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +95 -21
- package/dist/index.js +1386 -299
- package/dist/statusline-main.js +531 -150
- package/package.json +1 -1
|
@@ -63,9 +63,9 @@ function parseAgent(argv) {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
// src/commands/cursor-install.ts
|
|
66
|
-
import { existsSync as
|
|
67
|
-
import { homedir as
|
|
68
|
-
import { isAbsolute as isAbsolute5, join as
|
|
66
|
+
import { existsSync as existsSync8, readFileSync as readFileSync8 } from "fs";
|
|
67
|
+
import { homedir as homedir4 } from "os";
|
|
68
|
+
import { isAbsolute as isAbsolute5, join as join10 } from "path";
|
|
69
69
|
|
|
70
70
|
// src/lib/atomic-file.ts
|
|
71
71
|
import { randomUUID } from "crypto";
|
|
@@ -261,6 +261,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
261
261
|
'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
|
|
262
262
|
"fi; fi; "
|
|
263
263
|
].join("");
|
|
264
|
+
var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
|
|
264
265
|
function stableHookCommand(bin, args = "") {
|
|
265
266
|
if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
|
|
266
267
|
throw new Error("invalid stable hook command");
|
|
@@ -272,7 +273,7 @@ function stableHookCommand(bin, args = "") {
|
|
|
272
273
|
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
273
274
|
PRIM_CONFIG_SHELL_RESOLVER,
|
|
274
275
|
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
275
|
-
|
|
276
|
+
LAUNCHER_EXEC
|
|
276
277
|
].join("");
|
|
277
278
|
const suffix = args ? ` ${args}` : "";
|
|
278
279
|
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
@@ -309,10 +310,10 @@ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as rea
|
|
|
309
310
|
import { dirname as dirname3, join as join2 } from "path";
|
|
310
311
|
|
|
311
312
|
// src/lib/process-liveness.ts
|
|
312
|
-
function processIsAlive(pid,
|
|
313
|
+
function processIsAlive(pid, probe2 = process.kill) {
|
|
313
314
|
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
314
315
|
try {
|
|
315
|
-
|
|
316
|
+
probe2(pid, 0);
|
|
316
317
|
return true;
|
|
317
318
|
} catch (error) {
|
|
318
319
|
return error.code === "EPERM";
|
|
@@ -721,25 +722,131 @@ function lstatIfPresent(path) {
|
|
|
721
722
|
import { execFileSync } from "child_process";
|
|
722
723
|
|
|
723
724
|
// src/commands/claude-install.ts
|
|
724
|
-
import { existsSync as
|
|
725
|
+
import { existsSync as existsSync7, lstatSync as lstatSync3, readFileSync as readFileSync7 } from "fs";
|
|
726
|
+
import { homedir as homedir3 } from "os";
|
|
727
|
+
import { join as join9 } from "path";
|
|
728
|
+
|
|
729
|
+
// src/lib/activation.ts
|
|
730
|
+
import { execFileSync as execFileSync4 } from "child_process";
|
|
731
|
+
import { existsSync as existsSync6, readFileSync as readFileSync6 } from "fs";
|
|
725
732
|
import { homedir as homedir2 } from "os";
|
|
733
|
+
import { join as join8 } from "path";
|
|
734
|
+
|
|
735
|
+
// src/lib/cloud-prepared.ts
|
|
736
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "fs";
|
|
726
737
|
import { join as join6 } from "path";
|
|
727
738
|
|
|
728
|
-
// src/lib/
|
|
739
|
+
// src/lib/cloud-env.ts
|
|
740
|
+
function isClaudeCloudSession(env = process.env) {
|
|
741
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
742
|
+
}
|
|
743
|
+
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';
|
|
744
|
+
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';
|
|
745
|
+
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}.`;
|
|
746
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
747
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
748
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
749
|
+
}
|
|
750
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
751
|
+
|
|
752
|
+
// src/lib/cloud-prepared.ts
|
|
753
|
+
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
754
|
+
function cloudPreparedPath(env = process.env) {
|
|
755
|
+
return join6(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
756
|
+
}
|
|
757
|
+
function isPreparedCloudSession(env = process.env) {
|
|
758
|
+
if (!isClaudeCloudSession(env)) return false;
|
|
759
|
+
try {
|
|
760
|
+
return existsSync5(cloudPreparedPath(env));
|
|
761
|
+
} catch {
|
|
762
|
+
return false;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
// src/lib/demo-pause.ts
|
|
729
767
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, relative, resolve as resolve2, sep } from "path";
|
|
768
|
+
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
769
|
+
var PAUSE_KEY = "prim.demoPause";
|
|
733
770
|
var GIT_TIMEOUT_MS = 1e3;
|
|
771
|
+
function git(cwd, args) {
|
|
772
|
+
try {
|
|
773
|
+
return execFileSync2("git", args, {
|
|
774
|
+
cwd,
|
|
775
|
+
encoding: "utf-8",
|
|
776
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
777
|
+
timeout: GIT_TIMEOUT_MS
|
|
778
|
+
});
|
|
779
|
+
} catch {
|
|
780
|
+
return void 0;
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
function setLocal(cwd, key, value) {
|
|
784
|
+
try {
|
|
785
|
+
execFileSync2(
|
|
786
|
+
"git",
|
|
787
|
+
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
788
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
|
|
789
|
+
);
|
|
790
|
+
} catch (error) {
|
|
791
|
+
if (value !== null || error.status !== 5) throw error;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
function parsePause(value) {
|
|
795
|
+
const [runId = "", until, previous, state] = value.trim().split(" ");
|
|
796
|
+
const flag = previous === "true" || previous === "false" ? previous : "unset";
|
|
797
|
+
return { runId, until: Number(until) || 0, previous: flag, ending: state !== "active" };
|
|
798
|
+
}
|
|
799
|
+
function readCaptureConfig(cwd) {
|
|
800
|
+
let active;
|
|
801
|
+
let pause;
|
|
802
|
+
const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
803
|
+
for (const line of out.split("\n")) {
|
|
804
|
+
const space = line.indexOf(" ");
|
|
805
|
+
const key = line.slice(0, space).toLowerCase();
|
|
806
|
+
const value = line.slice(space + 1);
|
|
807
|
+
if (key === "prim.active") active = value === "true" || value === "false" ? value : void 0;
|
|
808
|
+
if (key === "prim.demopause") pause = parsePause(value);
|
|
809
|
+
}
|
|
810
|
+
return { active, pause };
|
|
811
|
+
}
|
|
812
|
+
function resumeCapture(cwd, pause) {
|
|
813
|
+
setLocal(cwd, "prim.active", pause.previous === "unset" ? null : pause.previous);
|
|
814
|
+
setLocal(cwd, PAUSE_KEY, null);
|
|
815
|
+
}
|
|
816
|
+
function healDemoPause(cwd, pause, options = {}) {
|
|
817
|
+
if (pause.until > (options.now ?? Date.now()) && !(pause.ending && options.userPrompt))
|
|
818
|
+
return false;
|
|
819
|
+
try {
|
|
820
|
+
resumeCapture(cwd, pause);
|
|
821
|
+
return true;
|
|
822
|
+
} catch {
|
|
823
|
+
return false;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// src/lib/git.ts
|
|
828
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
829
|
+
import { createHash as createHash2 } from "crypto";
|
|
830
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
831
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve2, sep } from "path";
|
|
832
|
+
var GIT_TIMEOUT_MS2 = 1e3;
|
|
833
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
734
834
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
735
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
835
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
836
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
837
|
+
function gitChildEnvironment(env = process.env) {
|
|
838
|
+
return Object.fromEntries(
|
|
839
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
840
|
+
);
|
|
841
|
+
}
|
|
736
842
|
function gitToplevel(cwd) {
|
|
737
843
|
try {
|
|
738
|
-
return
|
|
844
|
+
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
739
845
|
cwd,
|
|
740
846
|
encoding: "utf-8",
|
|
741
847
|
stdio: ["ignore", "pipe", "ignore"],
|
|
742
|
-
timeout:
|
|
848
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
849
|
+
env: gitChildEnvironment()
|
|
743
850
|
}).trim();
|
|
744
851
|
} catch {
|
|
745
852
|
return null;
|
|
@@ -747,30 +854,76 @@ function gitToplevel(cwd) {
|
|
|
747
854
|
}
|
|
748
855
|
function gitValue(cwd, args) {
|
|
749
856
|
try {
|
|
750
|
-
const value =
|
|
857
|
+
const value = execFileSync3("git", args, {
|
|
751
858
|
cwd,
|
|
752
859
|
encoding: "utf-8",
|
|
753
860
|
stdio: ["ignore", "pipe", "ignore"],
|
|
754
|
-
timeout:
|
|
861
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
862
|
+
env: gitChildEnvironment()
|
|
755
863
|
}).trim();
|
|
756
864
|
return value || void 0;
|
|
757
865
|
} catch {
|
|
758
866
|
return void 0;
|
|
759
867
|
}
|
|
760
868
|
}
|
|
761
|
-
function
|
|
762
|
-
|
|
763
|
-
|
|
869
|
+
function currentBranch(cwd) {
|
|
870
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
871
|
+
}
|
|
872
|
+
function parseGithubRepositoryName(path) {
|
|
873
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
874
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
875
|
+
return null;
|
|
876
|
+
}
|
|
877
|
+
return `${parts[0]}/${parts[1]}`;
|
|
878
|
+
}
|
|
879
|
+
function githubRepositoryFromRemote(remote) {
|
|
880
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
764
881
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
765
882
|
remote
|
|
766
883
|
);
|
|
767
884
|
const path = match?.[1] ?? match?.[2];
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
885
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
886
|
+
}
|
|
887
|
+
function originIdentifiesRepository(cwd) {
|
|
888
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
889
|
+
return remote !== void 0 && Boolean(githubRepositoryFromRemote(remote) || normalizeOriginRemote(remote));
|
|
890
|
+
}
|
|
891
|
+
function checkoutSettingsText(repoRoot) {
|
|
892
|
+
const path = join7(repoRoot, ".claude", "settings.json");
|
|
893
|
+
try {
|
|
894
|
+
if (!lstatSync2(join7(repoRoot, ".claude")).isDirectory()) return null;
|
|
895
|
+
const stat = lstatSync2(path);
|
|
896
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
897
|
+
return readFileSync5(path, "utf8");
|
|
898
|
+
} catch {
|
|
771
899
|
return null;
|
|
772
900
|
}
|
|
773
|
-
|
|
901
|
+
}
|
|
902
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
903
|
+
const text = checkoutSettingsText(repoRoot);
|
|
904
|
+
if (text === null) return null;
|
|
905
|
+
let parsed;
|
|
906
|
+
try {
|
|
907
|
+
parsed = JSON.parse(text);
|
|
908
|
+
} catch {
|
|
909
|
+
return null;
|
|
910
|
+
}
|
|
911
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
912
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
913
|
+
return typeof value === "string" ? value : null;
|
|
914
|
+
}
|
|
915
|
+
function declaredGithubRepository(repoRoot) {
|
|
916
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
917
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
918
|
+
}
|
|
919
|
+
function githubRepositoryFullName(cwd) {
|
|
920
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
921
|
+
if (remote) {
|
|
922
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
923
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
924
|
+
}
|
|
925
|
+
const root = gitToplevel(cwd);
|
|
926
|
+
return root ? declaredGithubRepository(root) : null;
|
|
774
927
|
}
|
|
775
928
|
function normalizeOriginRemote(remote) {
|
|
776
929
|
const value = remote.trim();
|
|
@@ -816,6 +969,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
816
969
|
repoFullName
|
|
817
970
|
};
|
|
818
971
|
}
|
|
972
|
+
if (repoFullName) {
|
|
973
|
+
return {
|
|
974
|
+
repoRoot,
|
|
975
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
976
|
+
identitySource: "declared",
|
|
977
|
+
repoFullName
|
|
978
|
+
};
|
|
979
|
+
}
|
|
819
980
|
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
820
981
|
if (roots && roots.length > 0) {
|
|
821
982
|
return {
|
|
@@ -828,6 +989,179 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
828
989
|
return { repoRoot, repoFullName };
|
|
829
990
|
}
|
|
830
991
|
|
|
992
|
+
// src/lib/activation.ts
|
|
993
|
+
var PRIM_ACTIVE_KEY = "prim.active";
|
|
994
|
+
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
995
|
+
var PRIM_ACTIVE_IMPLICIT_KEY = "prim.activeImplicit";
|
|
996
|
+
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
997
|
+
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
998
|
+
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
999
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
1000
|
+
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
1001
|
+
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
1002
|
+
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
1003
|
+
function repoActiveFlag(cwd, strict = false) {
|
|
1004
|
+
try {
|
|
1005
|
+
const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
|
|
1006
|
+
cwd,
|
|
1007
|
+
encoding: "utf-8",
|
|
1008
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1009
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1010
|
+
}).trim();
|
|
1011
|
+
if (value === "true") return "true";
|
|
1012
|
+
if (value === "false") return "false";
|
|
1013
|
+
if (strict) throw new Error("Repository activation is invalid");
|
|
1014
|
+
return void 0;
|
|
1015
|
+
} catch (error) {
|
|
1016
|
+
if (strict && !(typeof error === "object" && error !== null && "status" in error && error.status === 1))
|
|
1017
|
+
throw error;
|
|
1018
|
+
return void 0;
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
function setRepoActive(cwd, active) {
|
|
1022
|
+
execFileSync4("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
|
|
1023
|
+
cwd,
|
|
1024
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1025
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1026
|
+
});
|
|
1027
|
+
}
|
|
1028
|
+
function isValidRepoSyncId(value) {
|
|
1029
|
+
return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
|
|
1030
|
+
}
|
|
1031
|
+
function localGitConfigValue(cwd, key) {
|
|
1032
|
+
try {
|
|
1033
|
+
const value = execFileSync4("git", ["config", "--local", "--get", key], {
|
|
1034
|
+
cwd,
|
|
1035
|
+
encoding: "utf-8",
|
|
1036
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1037
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1038
|
+
}).trim();
|
|
1039
|
+
return value || void 0;
|
|
1040
|
+
} catch {
|
|
1041
|
+
return void 0;
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
function setLocalGitConfigValue(cwd, key, value) {
|
|
1045
|
+
execFileSync4("git", ["config", "--local", key, value], {
|
|
1046
|
+
cwd,
|
|
1047
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1048
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
function repoSyncId(cwd) {
|
|
1052
|
+
const value = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
1053
|
+
if (!isValidRepoSyncId(value)) return void 0;
|
|
1054
|
+
const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
|
|
1055
|
+
return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
|
|
1056
|
+
}
|
|
1057
|
+
function setRepoSyncId(cwd, value, repositoryFullName) {
|
|
1058
|
+
if (!isValidRepoSyncId(value)) {
|
|
1059
|
+
throw new Error("invalid repository binding returned by server");
|
|
1060
|
+
}
|
|
1061
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
|
|
1062
|
+
cwd,
|
|
1063
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1064
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1065
|
+
});
|
|
1066
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
|
|
1067
|
+
cwd,
|
|
1068
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1069
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
function setRepositoryBindingState(cwd, state) {
|
|
1073
|
+
if (state !== "connected" && state !== "unbound" && state !== "invalid") {
|
|
1074
|
+
throw new Error("invalid repository binding state");
|
|
1075
|
+
}
|
|
1076
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
|
|
1077
|
+
cwd,
|
|
1078
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1079
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
function repositoryBindingState(cwd) {
|
|
1083
|
+
const rawId = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
1084
|
+
const marker = localGitConfigValue(cwd, PRIM_REPO_BINDING_STATE_KEY);
|
|
1085
|
+
if (rawId !== void 0 && !isValidRepoSyncId(rawId)) return "invalid";
|
|
1086
|
+
if (marker === "unbound" || marker === "invalid") return marker;
|
|
1087
|
+
if (marker === "connected") return repoSyncId(cwd) ? "connected" : "invalid";
|
|
1088
|
+
if (marker !== void 0) return "invalid";
|
|
1089
|
+
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
1090
|
+
}
|
|
1091
|
+
function unsetLocalGitConfigValue(cwd, key) {
|
|
1092
|
+
try {
|
|
1093
|
+
execFileSync4("git", ["config", "--local", "--unset-all", key], {
|
|
1094
|
+
cwd,
|
|
1095
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1096
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1097
|
+
});
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
if (typeof error === "object" && error !== null && "status" in error && error.status === 5) {
|
|
1100
|
+
return;
|
|
1101
|
+
}
|
|
1102
|
+
throw error;
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
function projectPrimInstallAt(root) {
|
|
1106
|
+
if (root === null || root === homedir2()) return false;
|
|
1107
|
+
for (const rel of PROJECT_INSTALL_FILES) {
|
|
1108
|
+
const path = join8(root, rel);
|
|
1109
|
+
if (existsSync6(path)) {
|
|
1110
|
+
try {
|
|
1111
|
+
const content = readFileSync6(path, "utf-8");
|
|
1112
|
+
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
1113
|
+
} catch {
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
return false;
|
|
1118
|
+
}
|
|
1119
|
+
var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
|
|
1120
|
+
function declaresInactiveAt(root) {
|
|
1121
|
+
if (root === null || root === homedir2()) return false;
|
|
1122
|
+
if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
|
|
1123
|
+
const text = checkoutSettingsText(root);
|
|
1124
|
+
if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
|
|
1125
|
+
try {
|
|
1126
|
+
JSON.parse(text);
|
|
1127
|
+
return false;
|
|
1128
|
+
} catch {
|
|
1129
|
+
return true;
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
function markActivationImplicit(cwd) {
|
|
1133
|
+
try {
|
|
1134
|
+
setLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY, "true");
|
|
1135
|
+
} catch {
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
function withdrawImplicitActivation(cwd) {
|
|
1139
|
+
try {
|
|
1140
|
+
const root = gitToplevel(cwd);
|
|
1141
|
+
if (root === null) return false;
|
|
1142
|
+
if (localGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY) !== "true") return false;
|
|
1143
|
+
if (localGitConfigValue(root, PRIM_ACTIVE_KEY) !== "true" || !declaresInactiveAt(root))
|
|
1144
|
+
return false;
|
|
1145
|
+
unsetLocalGitConfigValue(root, PRIM_ACTIVE_KEY);
|
|
1146
|
+
unsetLocalGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY);
|
|
1147
|
+
return true;
|
|
1148
|
+
} catch {
|
|
1149
|
+
return false;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
function isRepoActiveForCapture(cwd, options = {}) {
|
|
1153
|
+
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
1154
|
+
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
1155
|
+
if (flag === "true") return true;
|
|
1156
|
+
if (flag === "false") return false;
|
|
1157
|
+
const root = gitToplevel(cwd);
|
|
1158
|
+
if (declaresInactiveAt(root)) return false;
|
|
1159
|
+
return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
|
|
1160
|
+
}
|
|
1161
|
+
function decisionIngestionStatus(cwd) {
|
|
1162
|
+
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
1163
|
+
}
|
|
1164
|
+
|
|
831
1165
|
// src/commands/claude-install.ts
|
|
832
1166
|
var CAPTURE_BIN = "prim-hook";
|
|
833
1167
|
var GATE_BIN = "prim-pre-tool-use";
|
|
@@ -837,7 +1171,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
837
1171
|
var STATUSLINE_BIN = "prim-statusline";
|
|
838
1172
|
var STATUSLINE_ARGS = "";
|
|
839
1173
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
840
|
-
var USER_SCOPE_PATH =
|
|
1174
|
+
var USER_SCOPE_PATH = join9(homedir3(), ".claude", "settings.json");
|
|
841
1175
|
function projectRoot() {
|
|
842
1176
|
return gitToplevel() ?? process.cwd();
|
|
843
1177
|
}
|
|
@@ -913,24 +1247,24 @@ var REGISTRATIONS2 = [
|
|
|
913
1247
|
{ event: "sessionStart", bin: SESSION_START_BIN2 },
|
|
914
1248
|
{ event: "sessionEnd", bin: SESSION_END_BIN2 }
|
|
915
1249
|
];
|
|
916
|
-
function cursorConfigDirectory(env = process.env, home =
|
|
1250
|
+
function cursorConfigDirectory(env = process.env, home = homedir4(), platform = process.platform) {
|
|
917
1251
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
918
1252
|
if (explicit && isAbsolute5(explicit)) return explicit;
|
|
919
1253
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
920
|
-
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return
|
|
921
|
-
return
|
|
1254
|
+
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join10(xdg, "cursor");
|
|
1255
|
+
return join10(home, ".cursor");
|
|
922
1256
|
}
|
|
923
1257
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
924
|
-
return scope === "user" ?
|
|
1258
|
+
return scope === "user" ? join10(cursorConfigDirectory(), "hooks.json") : join10(root, ".cursor", "hooks.json");
|
|
925
1259
|
}
|
|
926
1260
|
function plainObject(value) {
|
|
927
1261
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
928
1262
|
}
|
|
929
1263
|
function readCursorHooks(path) {
|
|
930
|
-
if (!
|
|
1264
|
+
if (!existsSync8(path)) return {};
|
|
931
1265
|
let parsed;
|
|
932
1266
|
try {
|
|
933
|
-
parsed = JSON.parse(
|
|
1267
|
+
parsed = JSON.parse(readFileSync8(path, "utf8"));
|
|
934
1268
|
} catch {
|
|
935
1269
|
throw new Error(`invalid Cursor hooks JSON at ${path}`);
|
|
936
1270
|
}
|
|
@@ -1201,31 +1535,70 @@ function publicDecisionResponse(value) {
|
|
|
1201
1535
|
}
|
|
1202
1536
|
|
|
1203
1537
|
// src/client.ts
|
|
1204
|
-
import { createHash as
|
|
1205
|
-
import { chmodSync as chmodSync4, existsSync as
|
|
1538
|
+
import { createHash as createHash8 } from "crypto";
|
|
1539
|
+
import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
|
|
1206
1540
|
import { dirname as dirname9 } from "path";
|
|
1207
1541
|
|
|
1208
1542
|
// src/lib/credentials.ts
|
|
1209
|
-
import { createHash as
|
|
1210
|
-
import { readFileSync as
|
|
1211
|
-
import { join as
|
|
1543
|
+
import { createHash as createHash7 } from "crypto";
|
|
1544
|
+
import { readFileSync as readFileSync12 } from "fs";
|
|
1545
|
+
import { join as join15 } from "path";
|
|
1212
1546
|
|
|
1213
1547
|
// src/lib/machine-credentials.ts
|
|
1214
|
-
import { execFileSync as
|
|
1215
|
-
import { createHash as
|
|
1216
|
-
import {
|
|
1548
|
+
import { execFileSync as execFileSync5 } from "child_process";
|
|
1549
|
+
import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
1550
|
+
import {
|
|
1551
|
+
chmodSync as chmodSync2,
|
|
1552
|
+
existsSync as existsSync9,
|
|
1553
|
+
linkSync,
|
|
1554
|
+
lstatSync as lstatSync6,
|
|
1555
|
+
mkdirSync as mkdirSync5,
|
|
1556
|
+
readFileSync as readFileSync11,
|
|
1557
|
+
rmSync as rmSync8,
|
|
1558
|
+
writeFileSync as writeFileSync5
|
|
1559
|
+
} from "fs";
|
|
1217
1560
|
import { createRequire as createRequire2 } from "module";
|
|
1218
|
-
import { dirname as dirname8, join as
|
|
1561
|
+
import { dirname as dirname8, join as join14 } from "path";
|
|
1219
1562
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1220
1563
|
|
|
1221
1564
|
// src/lib/machine-broker.ts
|
|
1222
1565
|
import { spawn } from "child_process";
|
|
1223
1566
|
import { createHash as createHash3, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
1224
|
-
import { lstatSync as
|
|
1567
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync9, rmSync as rmSync5 } from "fs";
|
|
1225
1568
|
import { createServer } from "http";
|
|
1226
|
-
import { basename as basename2, join as
|
|
1569
|
+
import { basename as basename2, join as join11 } from "path";
|
|
1227
1570
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1228
1571
|
|
|
1572
|
+
// src/lib/loopback-fetch.ts
|
|
1573
|
+
import { request } from "http";
|
|
1574
|
+
import { Readable } from "stream";
|
|
1575
|
+
function loopbackFetch(url, init = {}) {
|
|
1576
|
+
const target = new URL(url);
|
|
1577
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
1578
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
1579
|
+
return new Promise((resolve10, reject) => {
|
|
1580
|
+
const outgoing = request(
|
|
1581
|
+
target,
|
|
1582
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
1583
|
+
(incoming) => {
|
|
1584
|
+
try {
|
|
1585
|
+
const headers = new Headers();
|
|
1586
|
+
for (const [name, value] of Object.entries(incoming.headers))
|
|
1587
|
+
if (typeof value === "string") headers.set(name, value);
|
|
1588
|
+
const status = incoming.statusCode ?? 502;
|
|
1589
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
1590
|
+
resolve10(new Response(body, { status, headers }));
|
|
1591
|
+
} catch (error) {
|
|
1592
|
+
incoming.destroy();
|
|
1593
|
+
reject(error);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
);
|
|
1597
|
+
outgoing.once("error", reject);
|
|
1598
|
+
outgoing.end(init.body);
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
|
|
1229
1602
|
// src/lib/workos-connect.ts
|
|
1230
1603
|
var TOKEN_PATH = "/oauth2/token";
|
|
1231
1604
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -1362,10 +1735,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
1362
1735
|
"access_token",
|
|
1363
1736
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
1364
1737
|
);
|
|
1365
|
-
const
|
|
1738
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
1366
1739
|
return {
|
|
1367
1740
|
accessToken,
|
|
1368
|
-
refreshToken:
|
|
1741
|
+
refreshToken: refreshToken3,
|
|
1369
1742
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
1370
1743
|
};
|
|
1371
1744
|
}
|
|
@@ -1421,9 +1794,19 @@ function parseMachineConfiguration(value) {
|
|
|
1421
1794
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
1422
1795
|
};
|
|
1423
1796
|
}
|
|
1797
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
1798
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
1799
|
+
}
|
|
1424
1800
|
function machineSignal(signal) {
|
|
1425
1801
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1426
1802
|
}
|
|
1803
|
+
function hostOf(url) {
|
|
1804
|
+
try {
|
|
1805
|
+
return new URL(url).hostname;
|
|
1806
|
+
} catch {
|
|
1807
|
+
return "Primitive";
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1427
1810
|
async function fetchMachine(url, options, fetchImpl) {
|
|
1428
1811
|
try {
|
|
1429
1812
|
return await fetchImpl(url, options);
|
|
@@ -1431,7 +1814,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
1431
1814
|
options.signal?.throwIfAborted();
|
|
1432
1815
|
throw new MachineAuthError(
|
|
1433
1816
|
"authentication_unavailable",
|
|
1434
|
-
|
|
1817
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
1818
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
1819
|
+
isClaudeCloudSession() ? `Machine authentication could not reach ${hostOf(url)}. If this Claude Code cloud environment blocks it, add it to the environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with).` : "Machine authentication is temporarily unavailable. Check the connection and retry."
|
|
1435
1820
|
);
|
|
1436
1821
|
}
|
|
1437
1822
|
}
|
|
@@ -1458,8 +1843,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
1458
1843
|
);
|
|
1459
1844
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
1460
1845
|
}
|
|
1461
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
1462
|
-
|
|
1846
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
1847
|
+
const network = options.secretInjection === "network";
|
|
1848
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
1463
1849
|
throw new MachineAuthError(
|
|
1464
1850
|
"invalid_credentials",
|
|
1465
1851
|
"A machine client ID and secret are required.",
|
|
@@ -1473,11 +1859,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1473
1859
|
redirect: "error",
|
|
1474
1860
|
signal: machineSignal(signal),
|
|
1475
1861
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
client_secret: clientSecret
|
|
1480
|
-
|
|
1862
|
+
// With a network secret the agent proxy authenticates the client with
|
|
1863
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
1864
|
+
body: new URLSearchParams(
|
|
1865
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
1866
|
+
)
|
|
1481
1867
|
},
|
|
1482
1868
|
fetchImpl
|
|
1483
1869
|
);
|
|
@@ -1485,7 +1871,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1485
1871
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
1486
1872
|
throw new MachineAuthError(
|
|
1487
1873
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
1488
|
-
terminal ?
|
|
1874
|
+
terminal ? network ? `The token service rejected the request. Check the cloud environment's network secret for ${new URL(configuration.issuer).hostname}: username = the client ID, password = the client secret.` : rejectedCredentialsMessage(
|
|
1875
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
1876
|
+
) : "The machine token service is temporarily unavailable.",
|
|
1489
1877
|
terminal,
|
|
1490
1878
|
terminal ? void 0 : machineRetryAt(response)
|
|
1491
1879
|
);
|
|
@@ -1505,6 +1893,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1505
1893
|
} catch {
|
|
1506
1894
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
1507
1895
|
}
|
|
1896
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
1897
|
+
throw new MachineAuthError(
|
|
1898
|
+
"token_client_mismatch",
|
|
1899
|
+
"The token service issued a token for another machine client."
|
|
1900
|
+
);
|
|
1508
1901
|
if (claims.iss !== configuration.issuer || claims.aud !== configuration.audience || claims.sub !== clientId || claims.client_id !== clientId || !machineString(claims.org_id, 256) || typeof claims.exp !== "number" || !Number.isFinite(claims.exp) || claims.exp * 1e3 <= Date.now()) {
|
|
1509
1902
|
throw new MachineAuthError(
|
|
1510
1903
|
"token_identity_mismatch",
|
|
@@ -1550,32 +1943,76 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
1550
1943
|
const terminal = response.status === 401 || response.status === 403;
|
|
1551
1944
|
throw new MachineAuthError(
|
|
1552
1945
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
1553
|
-
terminal ?
|
|
1946
|
+
terminal ? rejectedCredentialsMessage(
|
|
1947
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
1948
|
+
) : "Machine verification is temporarily unavailable.",
|
|
1554
1949
|
terminal
|
|
1555
1950
|
);
|
|
1556
1951
|
}
|
|
1557
1952
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
1558
1953
|
}
|
|
1954
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
1955
|
+
const rejected = () => new MachineAuthError(
|
|
1956
|
+
"network_token_rejected",
|
|
1957
|
+
`Primitive did not accept this machine: the cloud environment's proxy attached no token it accepts, or the installation was revoked. Check the environment's OAuth 2.0 client credentials network secret: allowed website ${new URL(apiUrl).hostname}, the client ID (${clientId}), the client secret, and the token URL.`,
|
|
1958
|
+
true
|
|
1959
|
+
);
|
|
1960
|
+
if (status === 401 || status === 403) throw rejected();
|
|
1961
|
+
if (status < 200 || status > 299)
|
|
1962
|
+
throw new MachineAuthError(
|
|
1963
|
+
"verification_unavailable",
|
|
1964
|
+
"Machine verification is temporarily unavailable."
|
|
1965
|
+
);
|
|
1966
|
+
let data;
|
|
1967
|
+
try {
|
|
1968
|
+
data = machineRecord(value);
|
|
1969
|
+
} catch {
|
|
1970
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
1971
|
+
}
|
|
1972
|
+
if (data.authenticated !== true) throw rejected();
|
|
1973
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
1974
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
1975
|
+
throw new MachineAuthError(
|
|
1976
|
+
"network_secret_mismatch",
|
|
1977
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
1978
|
+
true
|
|
1979
|
+
);
|
|
1980
|
+
return parseMachineIdentity(data, clientId);
|
|
1981
|
+
}
|
|
1982
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
1983
|
+
const response = await fetchMachine(
|
|
1984
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
1985
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
1986
|
+
fetchImpl
|
|
1987
|
+
);
|
|
1988
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
1989
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
1990
|
+
}
|
|
1559
1991
|
|
|
1560
1992
|
// src/lib/machine-broker.ts
|
|
1561
1993
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
1994
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
1995
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
1996
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
1997
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
1998
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
1562
1999
|
var IDLE_MS = 5 * 6e4;
|
|
1563
2000
|
function descriptorPath(directory, generation) {
|
|
1564
|
-
return
|
|
2001
|
+
return join11(directory, `machine_broker_${generation}.json`);
|
|
1565
2002
|
}
|
|
1566
2003
|
function readDescriptor(path) {
|
|
1567
2004
|
try {
|
|
1568
|
-
const stat =
|
|
2005
|
+
const stat = lstatSync4(path);
|
|
1569
2006
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1570
2007
|
return void 0;
|
|
1571
|
-
const data = JSON.parse(
|
|
2008
|
+
const data = JSON.parse(readFileSync9(path, "utf8"));
|
|
1572
2009
|
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;
|
|
1573
2010
|
} catch {
|
|
1574
2011
|
return void 0;
|
|
1575
2012
|
}
|
|
1576
2013
|
}
|
|
1577
|
-
function signature(secret, nonce, body) {
|
|
1578
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
2014
|
+
function signature(secret, nonce, body, purpose) {
|
|
2015
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
1579
2016
|
}
|
|
1580
2017
|
function matches(left, right) {
|
|
1581
2018
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -1590,10 +2027,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1590
2027
|
observedTokenHash: tokenHash(options.observedToken),
|
|
1591
2028
|
timestamp: Date.now()
|
|
1592
2029
|
});
|
|
1593
|
-
const response = await
|
|
2030
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
1594
2031
|
method: "POST",
|
|
1595
2032
|
body,
|
|
1596
|
-
redirect: "error",
|
|
1597
2033
|
signal: options.signal,
|
|
1598
2034
|
headers: {
|
|
1599
2035
|
"Content-Type": "application/json",
|
|
@@ -1624,6 +2060,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1624
2060
|
);
|
|
1625
2061
|
return credential;
|
|
1626
2062
|
}
|
|
2063
|
+
function brokerEnvironment(options) {
|
|
2064
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
2065
|
+
return {
|
|
2066
|
+
...options.env,
|
|
2067
|
+
PRIM_API_URL: options.apiUrl,
|
|
2068
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
2069
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
2070
|
+
};
|
|
2071
|
+
}
|
|
1627
2072
|
async function acquireBrokerCredential(options) {
|
|
1628
2073
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1629
2074
|
const existing = readDescriptor(path);
|
|
@@ -1635,15 +2080,28 @@ async function acquireBrokerCredential(options) {
|
|
|
1635
2080
|
if (error instanceof MachineAuthError) throw error;
|
|
1636
2081
|
}
|
|
1637
2082
|
}
|
|
1638
|
-
const descriptor = await
|
|
1639
|
-
|
|
2083
|
+
const descriptor = await ensureBroker(options);
|
|
2084
|
+
try {
|
|
2085
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
2086
|
+
} catch (error) {
|
|
2087
|
+
options.signal.throwIfAborted();
|
|
2088
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2089
|
+
throw new MachineAuthError(
|
|
2090
|
+
"broker_unavailable",
|
|
2091
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
2092
|
+
);
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
async function ensureBroker(options) {
|
|
2096
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2097
|
+
return withFileLock(
|
|
2098
|
+
join11(options.directory, "machine-broker.lock"),
|
|
1640
2099
|
async () => {
|
|
1641
2100
|
const current = readDescriptor(path);
|
|
1642
2101
|
if (current) {
|
|
1643
2102
|
try {
|
|
1644
|
-
const response = await
|
|
1645
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1646
|
-
redirect: "error"
|
|
2103
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
2104
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1647
2105
|
});
|
|
1648
2106
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
1649
2107
|
} catch {
|
|
@@ -1662,7 +2120,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1662
2120
|
detached: true,
|
|
1663
2121
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
1664
2122
|
windowsHide: true,
|
|
1665
|
-
env:
|
|
2123
|
+
env: brokerEnvironment(options)
|
|
1666
2124
|
});
|
|
1667
2125
|
let settled = false;
|
|
1668
2126
|
const finish = (error) => {
|
|
@@ -1714,31 +2172,97 @@ async function acquireBrokerCredential(options) {
|
|
|
1714
2172
|
},
|
|
1715
2173
|
{ signal: options.signal }
|
|
1716
2174
|
);
|
|
2175
|
+
}
|
|
2176
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
2177
|
+
const body = JSON.stringify({
|
|
2178
|
+
generation: environment.generation,
|
|
2179
|
+
timestamp: Date.now(),
|
|
2180
|
+
method: request3.method,
|
|
2181
|
+
path: request3.path,
|
|
2182
|
+
headers: request3.headers ?? {},
|
|
2183
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
2184
|
+
});
|
|
2185
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
2186
|
+
method: "POST",
|
|
2187
|
+
body,
|
|
2188
|
+
signal,
|
|
2189
|
+
headers: {
|
|
2190
|
+
"Content-Type": "application/json",
|
|
2191
|
+
"X-Prim-Proof": signature(
|
|
2192
|
+
environment.clientSecret,
|
|
2193
|
+
descriptor.nonce,
|
|
2194
|
+
body,
|
|
2195
|
+
FORWARD_REQUEST_PROOF
|
|
2196
|
+
)
|
|
2197
|
+
}
|
|
2198
|
+
});
|
|
2199
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
2200
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
2201
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
2202
|
+
envelope.proof
|
|
2203
|
+
))
|
|
2204
|
+
throw new MachineAuthError(
|
|
2205
|
+
"broker_unavailable",
|
|
2206
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
2207
|
+
);
|
|
2208
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
2209
|
+
if (data.error) {
|
|
2210
|
+
const error = machineRecord(data.error);
|
|
2211
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
2212
|
+
}
|
|
2213
|
+
const status = data.status;
|
|
2214
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
2215
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
2216
|
+
const headers = new Headers();
|
|
2217
|
+
for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
2218
|
+
if (typeof value === "string") headers.set(name, value);
|
|
2219
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
2220
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
2221
|
+
}
|
|
2222
|
+
async function forwardBrokerRequest(options) {
|
|
2223
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2224
|
+
const unavailable = () => new MachineAuthError(
|
|
2225
|
+
"broker_unavailable",
|
|
2226
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
2227
|
+
);
|
|
2228
|
+
const existing = readDescriptor(path);
|
|
2229
|
+
if (existing) {
|
|
2230
|
+
try {
|
|
2231
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
2232
|
+
} catch (error) {
|
|
2233
|
+
options.signal.throwIfAborted();
|
|
2234
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2235
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
const descriptor = await ensureBroker(options);
|
|
1717
2239
|
try {
|
|
1718
|
-
return await
|
|
2240
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
1719
2241
|
} catch (error) {
|
|
1720
2242
|
options.signal.throwIfAborted();
|
|
1721
2243
|
if (error instanceof MachineAuthError) throw error;
|
|
1722
|
-
throw
|
|
1723
|
-
"broker_unavailable",
|
|
1724
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
1725
|
-
);
|
|
2244
|
+
throw unavailable();
|
|
1726
2245
|
}
|
|
1727
2246
|
}
|
|
1728
2247
|
|
|
1729
2248
|
// src/lib/machine-retry.ts
|
|
1730
2249
|
import { createHash as createHash4 } from "crypto";
|
|
1731
|
-
import { lstatSync as
|
|
1732
|
-
import { join as
|
|
1733
|
-
|
|
2250
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync6 } from "fs";
|
|
2251
|
+
import { join as join12 } from "path";
|
|
2252
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
2253
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
2254
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
1734
2255
|
signal?.throwIfAborted();
|
|
1735
2256
|
const key = createHash4("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1736
|
-
const path =
|
|
1737
|
-
let state = {
|
|
2257
|
+
const path = join12(directory, `machine_retry_${key}.json`);
|
|
2258
|
+
let state = {
|
|
2259
|
+
failures: 0,
|
|
2260
|
+
retryAt: 0
|
|
2261
|
+
};
|
|
1738
2262
|
try {
|
|
1739
|
-
const stat =
|
|
2263
|
+
const stat = lstatSync5(path);
|
|
1740
2264
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
1741
|
-
const data = JSON.parse(
|
|
2265
|
+
const data = JSON.parse(readFileSync10(path, "utf8"));
|
|
1742
2266
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
1743
2267
|
throw new Error("Invalid retry state");
|
|
1744
2268
|
state = data;
|
|
@@ -1749,13 +2273,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
1749
2273
|
if (state.retryAt > Date.now())
|
|
1750
2274
|
throw new MachineAuthError(
|
|
1751
2275
|
"token_service_unavailable",
|
|
1752
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
2276
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
2277
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
2278
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
2279
|
+
) : (
|
|
2280
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
2281
|
+
// retries at once and names the cause.
|
|
2282
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
2283
|
+
),
|
|
1753
2284
|
false,
|
|
1754
2285
|
state.retryAt
|
|
1755
2286
|
);
|
|
1756
2287
|
try {
|
|
1757
|
-
const result = await
|
|
1758
|
-
|
|
2288
|
+
const result = await request3();
|
|
2289
|
+
rmSync6(path, { force: true });
|
|
1759
2290
|
return result;
|
|
1760
2291
|
} catch (error) {
|
|
1761
2292
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -1766,40 +2297,1015 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
1766
2297
|
].includes(error.code)) {
|
|
1767
2298
|
const failures = Math.min(16, state.failures + 1);
|
|
1768
2299
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
1769
|
-
const retryAt = error.retryAt
|
|
1770
|
-
atomicWriteFile(
|
|
2300
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
2301
|
+
atomicWriteFile(
|
|
2302
|
+
path,
|
|
2303
|
+
JSON.stringify({
|
|
2304
|
+
failures,
|
|
2305
|
+
retryAt,
|
|
2306
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
2307
|
+
}),
|
|
2308
|
+
{ mode: 384 }
|
|
2309
|
+
);
|
|
1771
2310
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
1772
2311
|
}
|
|
1773
2312
|
throw error;
|
|
1774
2313
|
}
|
|
1775
2314
|
}
|
|
1776
2315
|
|
|
2316
|
+
// src/lib/session-identity.ts
|
|
2317
|
+
import { execFile } from "child_process";
|
|
2318
|
+
import { createHash as createHash5 } from "crypto";
|
|
2319
|
+
import { rmSync as rmSync7 } from "fs";
|
|
2320
|
+
import { join as join13 } from "path";
|
|
2321
|
+
import { promisify } from "util";
|
|
2322
|
+
|
|
2323
|
+
// src/lib/terminal-safe.ts
|
|
2324
|
+
function replaceIsolatedSurrogates(value) {
|
|
2325
|
+
let out = "";
|
|
2326
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
2327
|
+
const unit = value.charCodeAt(index);
|
|
2328
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
2329
|
+
const next = value.charCodeAt(index + 1);
|
|
2330
|
+
if (next >= 56320 && next <= 57343) {
|
|
2331
|
+
out += value[index] + value[index + 1];
|
|
2332
|
+
index += 1;
|
|
2333
|
+
} else {
|
|
2334
|
+
out += "\uFFFD";
|
|
2335
|
+
}
|
|
2336
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
2337
|
+
out += "\uFFFD";
|
|
2338
|
+
} else {
|
|
2339
|
+
out += value[index];
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
return out;
|
|
2343
|
+
}
|
|
2344
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
2345
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2346
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2347
|
+
point === 1564 || // Arabic letter mark
|
|
2348
|
+
point === 6158 || // Mongolian vowel separator
|
|
2349
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2350
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2351
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2352
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2353
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
2354
|
+
point >= 917504 && point <= 917631;
|
|
2355
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
2356
|
+
}
|
|
2357
|
+
function terminalSafeText(value) {
|
|
2358
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2359
|
+
}
|
|
2360
|
+
function terminalSafeLine(value) {
|
|
2361
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2362
|
+
}
|
|
2363
|
+
function isTerminalSafeText(value) {
|
|
2364
|
+
return terminalSafeText(value) === value;
|
|
2365
|
+
}
|
|
2366
|
+
var stripControlChars = terminalSafeText;
|
|
2367
|
+
|
|
2368
|
+
// src/lib/session-identity.ts
|
|
2369
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
2370
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
2371
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
2372
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
2373
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
2374
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
2375
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
2376
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
2377
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
2378
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
2379
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
2380
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
2381
|
+
token: "/api/cli/session-identity/token",
|
|
2382
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
2383
|
+
link: "/api/cli/session-identity/link"
|
|
2384
|
+
};
|
|
2385
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
2386
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
2387
|
+
var GIT_TIMEOUT_MS4 = 1e4;
|
|
2388
|
+
var POLL_BUDGET_MS = 15e3;
|
|
2389
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
2390
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
2391
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
2392
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
2393
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
2394
|
+
function sessionIdentityRequested(env = process.env) {
|
|
2395
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
2396
|
+
}
|
|
2397
|
+
function sessionIdentityMode(deps = {}) {
|
|
2398
|
+
const env = deps.env ?? process.env;
|
|
2399
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
2400
|
+
}
|
|
2401
|
+
function failure(code, cause, remedy) {
|
|
2402
|
+
return { status: "failed", code, cause, remedy };
|
|
2403
|
+
}
|
|
2404
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
2405
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
2406
|
+
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';
|
|
2407
|
+
var SESSION_REVOKED = failure(
|
|
2408
|
+
"session_revoked",
|
|
2409
|
+
"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",
|
|
2410
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
2411
|
+
);
|
|
2412
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
2413
|
+
"challenge_expired",
|
|
2414
|
+
"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)",
|
|
2415
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
2416
|
+
);
|
|
2417
|
+
var CHALLENGE_GONE = failure(
|
|
2418
|
+
"challenge_not_found",
|
|
2419
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
2420
|
+
NEW_SESSION_REMEDY
|
|
2421
|
+
);
|
|
2422
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
2423
|
+
function rejectionFailure(reason, repository) {
|
|
2424
|
+
switch (reason) {
|
|
2425
|
+
case "identity_mismatch":
|
|
2426
|
+
return failure(
|
|
2427
|
+
"identity_mismatch",
|
|
2428
|
+
"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",
|
|
2429
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
2430
|
+
);
|
|
2431
|
+
case "push_after_expiry":
|
|
2432
|
+
return failure(
|
|
2433
|
+
"push_after_expiry",
|
|
2434
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
2435
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
2436
|
+
);
|
|
2437
|
+
case "repository_mismatch":
|
|
2438
|
+
return failure(
|
|
2439
|
+
"repository_mismatch",
|
|
2440
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
2441
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
2442
|
+
);
|
|
2443
|
+
case "conflicting_push":
|
|
2444
|
+
return failure(
|
|
2445
|
+
"conflicting_push",
|
|
2446
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
2447
|
+
NEW_SESSION_REMEDY
|
|
2448
|
+
);
|
|
2449
|
+
case "unsupported_sender":
|
|
2450
|
+
return failure(
|
|
2451
|
+
"unsupported_sender",
|
|
2452
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
2453
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
2454
|
+
);
|
|
2455
|
+
default:
|
|
2456
|
+
return failure(
|
|
2457
|
+
"challenge_rejected",
|
|
2458
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
2459
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
2460
|
+
);
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
function sessionIdentityMessage(outcome) {
|
|
2464
|
+
if (outcome.status === "link_required")
|
|
2465
|
+
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.`;
|
|
2466
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
2467
|
+
}
|
|
2468
|
+
function hash(value) {
|
|
2469
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
2470
|
+
}
|
|
2471
|
+
function sessionContext(deps) {
|
|
2472
|
+
const env = deps.env ?? process.env;
|
|
2473
|
+
const environment = environmentCredentials(deps);
|
|
2474
|
+
if (!environment)
|
|
2475
|
+
return failure(
|
|
2476
|
+
"environment_credential_missing",
|
|
2477
|
+
"the cloud environment has no environment credential",
|
|
2478
|
+
'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'
|
|
2479
|
+
);
|
|
2480
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
2481
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
2482
|
+
return failure(
|
|
2483
|
+
"session_id_missing",
|
|
2484
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
2485
|
+
NEW_SESSION_REMEDY
|
|
2486
|
+
);
|
|
2487
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
2488
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
2489
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
2490
|
+
return {
|
|
2491
|
+
directory,
|
|
2492
|
+
apiUrl,
|
|
2493
|
+
clientId: environment.clientId,
|
|
2494
|
+
generation: environment.generation,
|
|
2495
|
+
sessionId,
|
|
2496
|
+
tokenPath: join13(directory, `session_identity_${key}.json`),
|
|
2497
|
+
statePath: join13(directory, `session_identity_${key}.state.json`),
|
|
2498
|
+
lockPath: join13(directory, "session-identity.lock")
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
function readRecord(path) {
|
|
2502
|
+
try {
|
|
2503
|
+
const value = readMachineMetadata(path);
|
|
2504
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
2505
|
+
} catch {
|
|
2506
|
+
return void 0;
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
function finiteNumber(value) {
|
|
2510
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
2511
|
+
}
|
|
2512
|
+
function readToken(context) {
|
|
2513
|
+
const data = readRecord(context.tokenPath);
|
|
2514
|
+
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))
|
|
2515
|
+
return void 0;
|
|
2516
|
+
const identity = data.identity;
|
|
2517
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
2518
|
+
return void 0;
|
|
2519
|
+
return data;
|
|
2520
|
+
}
|
|
2521
|
+
function readState(context) {
|
|
2522
|
+
const data = readRecord(context.statePath);
|
|
2523
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
2524
|
+
return void 0;
|
|
2525
|
+
return data;
|
|
2526
|
+
}
|
|
2527
|
+
function writeToken(context, record) {
|
|
2528
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2529
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
2530
|
+
rmSync7(context.statePath, { force: true });
|
|
2531
|
+
}
|
|
2532
|
+
function writeState(context, state) {
|
|
2533
|
+
try {
|
|
2534
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2535
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
2536
|
+
} catch {
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
function tokenValid(record, now = Date.now()) {
|
|
2540
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
2541
|
+
}
|
|
2542
|
+
function tokenFresh(record, now = Date.now()) {
|
|
2543
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
2544
|
+
}
|
|
2545
|
+
function toCredential(record) {
|
|
2546
|
+
return {
|
|
2547
|
+
issuer: record.issuer,
|
|
2548
|
+
audience: record.audience,
|
|
2549
|
+
...record.identity,
|
|
2550
|
+
accessToken: record.accessToken,
|
|
2551
|
+
expiresAt: record.expiresAt,
|
|
2552
|
+
apiUrl: record.apiUrl,
|
|
2553
|
+
generation: record.generation,
|
|
2554
|
+
storage: "environment",
|
|
2555
|
+
session: {
|
|
2556
|
+
userId: record.userId,
|
|
2557
|
+
displayName: record.displayName,
|
|
2558
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2559
|
+
refreshAfter: record.refreshAfter
|
|
2560
|
+
}
|
|
2561
|
+
};
|
|
2562
|
+
}
|
|
2563
|
+
function identified(record, reused) {
|
|
2564
|
+
return {
|
|
2565
|
+
status: "ok",
|
|
2566
|
+
credential: toCredential(record),
|
|
2567
|
+
displayName: record.displayName,
|
|
2568
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2569
|
+
reused
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
function cachedSessionCredential(deps = {}) {
|
|
2573
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
2574
|
+
let context;
|
|
2575
|
+
try {
|
|
2576
|
+
context = sessionContext(deps);
|
|
2577
|
+
} catch {
|
|
2578
|
+
return void 0;
|
|
2579
|
+
}
|
|
2580
|
+
if ("status" in context) return void 0;
|
|
2581
|
+
const record = readToken(context);
|
|
2582
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
2583
|
+
}
|
|
2584
|
+
function outcomeFromState(state) {
|
|
2585
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
2586
|
+
return {
|
|
2587
|
+
status: "link_required",
|
|
2588
|
+
githubLogin: state.githubLogin,
|
|
2589
|
+
challengeId: state.challengeId,
|
|
2590
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
2591
|
+
};
|
|
2592
|
+
return failure(
|
|
2593
|
+
state.code,
|
|
2594
|
+
state.cause ?? "the last identity check failed",
|
|
2595
|
+
state.remedy ?? RETRY_REMEDY
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
function parseInstant(value) {
|
|
2599
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
2600
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
2601
|
+
const parsed = Date.parse(value);
|
|
2602
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2603
|
+
}
|
|
2604
|
+
return void 0;
|
|
2605
|
+
}
|
|
2606
|
+
async function sendJson(url, init, fetchImpl) {
|
|
2607
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
2608
|
+
let value;
|
|
2609
|
+
try {
|
|
2610
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
2611
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2612
|
+
} catch {
|
|
2613
|
+
value = void 0;
|
|
2614
|
+
}
|
|
2615
|
+
return { status: response.status, value };
|
|
2616
|
+
}
|
|
2617
|
+
function environmentOnly(deps) {
|
|
2618
|
+
return { ...deps, environmentOnly: true };
|
|
2619
|
+
}
|
|
2620
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
2621
|
+
const send = async (credential2) => {
|
|
2622
|
+
const headers = { "Content-Type": "application/json" };
|
|
2623
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
2624
|
+
if (credential2.tokenInjection) {
|
|
2625
|
+
const response = await forwardMachineRequest(
|
|
2626
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
2627
|
+
signal,
|
|
2628
|
+
environmentOnly(deps)
|
|
2629
|
+
);
|
|
2630
|
+
const parsed = await response.json().catch(() => void 0);
|
|
2631
|
+
return {
|
|
2632
|
+
status: response.status,
|
|
2633
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
return sendJson(
|
|
2637
|
+
`${credential2.apiUrl}${path}`,
|
|
2638
|
+
{
|
|
2639
|
+
method,
|
|
2640
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
2641
|
+
...text === void 0 ? {} : { body: text },
|
|
2642
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS4)
|
|
2643
|
+
},
|
|
2644
|
+
deps.fetch ?? fetch
|
|
2645
|
+
);
|
|
2646
|
+
};
|
|
2647
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2648
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2649
|
+
let answer = await send(credential);
|
|
2650
|
+
if (answer.status === 401) {
|
|
2651
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
2652
|
+
if (!credential)
|
|
2653
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2654
|
+
answer = await send(credential);
|
|
2655
|
+
}
|
|
2656
|
+
return answer;
|
|
2657
|
+
}
|
|
2658
|
+
function environmentFailure(error, apiUrl) {
|
|
2659
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2660
|
+
return failure(
|
|
2661
|
+
"environment_credential_rejected",
|
|
2662
|
+
"Primitive rejected the cloud environment's credential",
|
|
2663
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
2664
|
+
);
|
|
2665
|
+
const host = (() => {
|
|
2666
|
+
try {
|
|
2667
|
+
return new URL(apiUrl).hostname;
|
|
2668
|
+
} catch {
|
|
2669
|
+
return "Primitive";
|
|
2670
|
+
}
|
|
2671
|
+
})();
|
|
2672
|
+
return failure(
|
|
2673
|
+
"identity_unavailable",
|
|
2674
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
2675
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
2676
|
+
);
|
|
2677
|
+
}
|
|
2678
|
+
function answerError(answer) {
|
|
2679
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
2680
|
+
}
|
|
2681
|
+
async function git2(root, args, signal) {
|
|
2682
|
+
try {
|
|
2683
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
2684
|
+
cwd: root,
|
|
2685
|
+
encoding: "utf8",
|
|
2686
|
+
timeout: GIT_TIMEOUT_MS4,
|
|
2687
|
+
signal,
|
|
2688
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
2689
|
+
maxBuffer: 1024 * 1024
|
|
2690
|
+
});
|
|
2691
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
2692
|
+
} catch (error) {
|
|
2693
|
+
const failed = error;
|
|
2694
|
+
return {
|
|
2695
|
+
ok: false,
|
|
2696
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
2697
|
+
stdout: failed.stdout ?? "",
|
|
2698
|
+
stderr: failed.stderr ?? "",
|
|
2699
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
function gitDetail(stderr) {
|
|
2704
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
2705
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
2706
|
+
}
|
|
2707
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
2708
|
+
await new Promise((resolve10, reject) => {
|
|
2709
|
+
const timer = setTimeout(resolve10, milliseconds);
|
|
2710
|
+
signal?.addEventListener(
|
|
2711
|
+
"abort",
|
|
2712
|
+
() => {
|
|
2713
|
+
clearTimeout(timer);
|
|
2714
|
+
reject(signal.reason);
|
|
2715
|
+
},
|
|
2716
|
+
{ once: true }
|
|
2717
|
+
);
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
2721
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
2722
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
2723
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
2724
|
+
let unreachable2;
|
|
2725
|
+
for (; ; ) {
|
|
2726
|
+
const remaining = deadline - Date.now();
|
|
2727
|
+
if (remaining <= 0) break;
|
|
2728
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
2729
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
2730
|
+
let answer;
|
|
2731
|
+
try {
|
|
2732
|
+
answer = await environmentRequest(
|
|
2733
|
+
"GET",
|
|
2734
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
2735
|
+
void 0,
|
|
2736
|
+
deps,
|
|
2737
|
+
signal
|
|
2738
|
+
);
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
signal?.throwIfAborted();
|
|
2741
|
+
unreachable2 = error;
|
|
2742
|
+
continue;
|
|
2743
|
+
}
|
|
2744
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2745
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2746
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
2747
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
2748
|
+
unreachable2 = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
2749
|
+
continue;
|
|
2750
|
+
}
|
|
2751
|
+
unreachable2 = void 0;
|
|
2752
|
+
const status = answer.value;
|
|
2753
|
+
if (status?.status === "verified")
|
|
2754
|
+
return {
|
|
2755
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
2756
|
+
};
|
|
2757
|
+
if (status?.status === "expired")
|
|
2758
|
+
return failure(
|
|
2759
|
+
"challenge_expired",
|
|
2760
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
2761
|
+
NEW_SESSION_REMEDY
|
|
2762
|
+
);
|
|
2763
|
+
if (status?.status === "rejected")
|
|
2764
|
+
return rejectionFailure(status.reason, repository);
|
|
2765
|
+
}
|
|
2766
|
+
if (unreachable2) return environmentFailure(unreachable2, apiUrl);
|
|
2767
|
+
return failure(
|
|
2768
|
+
"webhook_timeout",
|
|
2769
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
2770
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2771
|
+
);
|
|
2772
|
+
}
|
|
2773
|
+
function parseTokenAnswer(value) {
|
|
2774
|
+
if (!value) return void 0;
|
|
2775
|
+
const user = value.user;
|
|
2776
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
2777
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
2778
|
+
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))
|
|
2779
|
+
return void 0;
|
|
2780
|
+
return {
|
|
2781
|
+
accessToken: value.accessToken,
|
|
2782
|
+
expiresAt,
|
|
2783
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
2784
|
+
userId: user.id,
|
|
2785
|
+
displayName: user.displayName,
|
|
2786
|
+
organizationId: value.organizationId
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
2790
|
+
"server_contract",
|
|
2791
|
+
"Primitive's answer did not identify the linked member",
|
|
2792
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
2793
|
+
);
|
|
2794
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
2795
|
+
let identity;
|
|
2796
|
+
let environment;
|
|
2797
|
+
try {
|
|
2798
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2799
|
+
identity = await verifyMachineIdentity(
|
|
2800
|
+
context.apiUrl,
|
|
2801
|
+
answer.accessToken,
|
|
2802
|
+
context.clientId,
|
|
2803
|
+
signal,
|
|
2804
|
+
deps.fetch
|
|
2805
|
+
);
|
|
2806
|
+
} catch (error) {
|
|
2807
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
2808
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2809
|
+
return environmentFailure(error, context.apiUrl);
|
|
2810
|
+
}
|
|
2811
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
2812
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2813
|
+
return {
|
|
2814
|
+
version: 1,
|
|
2815
|
+
apiUrl: context.apiUrl,
|
|
2816
|
+
clientId: context.clientId,
|
|
2817
|
+
generation: context.generation,
|
|
2818
|
+
sessionId: context.sessionId,
|
|
2819
|
+
issuer: environment.issuer,
|
|
2820
|
+
audience: environment.audience,
|
|
2821
|
+
accessToken: answer.accessToken,
|
|
2822
|
+
expiresAt: answer.expiresAt,
|
|
2823
|
+
refreshAfter: answer.refreshAfter,
|
|
2824
|
+
userId: answer.userId,
|
|
2825
|
+
displayName: answer.displayName,
|
|
2826
|
+
organizationId: answer.organizationId,
|
|
2827
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
2828
|
+
identity,
|
|
2829
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
async function refreshToken(context, record, deps, signal) {
|
|
2833
|
+
let answer;
|
|
2834
|
+
try {
|
|
2835
|
+
answer = await environmentRequest(
|
|
2836
|
+
"POST",
|
|
2837
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
2838
|
+
{ accessToken: record.accessToken },
|
|
2839
|
+
deps,
|
|
2840
|
+
signal
|
|
2841
|
+
);
|
|
2842
|
+
} catch (error) {
|
|
2843
|
+
signal?.throwIfAborted();
|
|
2844
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
2845
|
+
}
|
|
2846
|
+
const code = answerError(answer);
|
|
2847
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
2848
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
2849
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2850
|
+
return {
|
|
2851
|
+
status: "refused",
|
|
2852
|
+
failure: environmentFailure(
|
|
2853
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
2854
|
+
context.apiUrl
|
|
2855
|
+
)
|
|
2856
|
+
};
|
|
2857
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2858
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
2859
|
+
return { status: "unavailable" };
|
|
2860
|
+
return {
|
|
2861
|
+
status: "ok",
|
|
2862
|
+
record: {
|
|
2863
|
+
...record,
|
|
2864
|
+
accessToken: token.accessToken,
|
|
2865
|
+
expiresAt: token.expiresAt,
|
|
2866
|
+
refreshAfter: token.refreshAfter,
|
|
2867
|
+
displayName: token.displayName
|
|
2868
|
+
}
|
|
2869
|
+
};
|
|
2870
|
+
}
|
|
2871
|
+
function exchangeRefusal(answer, repository) {
|
|
2872
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2873
|
+
if (answer.status !== 409) return void 0;
|
|
2874
|
+
switch (answerError(answer)) {
|
|
2875
|
+
case "identity_mismatch":
|
|
2876
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
2877
|
+
case "challenge_rejected":
|
|
2878
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
2879
|
+
case "challenge_expired":
|
|
2880
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
2881
|
+
case "challenge_already_exchanged":
|
|
2882
|
+
return failure(
|
|
2883
|
+
"challenge_already_exchanged",
|
|
2884
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
2885
|
+
NEW_SESSION_REMEDY
|
|
2886
|
+
);
|
|
2887
|
+
case "challenge_pending":
|
|
2888
|
+
return failure(
|
|
2889
|
+
"webhook_timeout",
|
|
2890
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
2891
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2892
|
+
);
|
|
2893
|
+
default:
|
|
2894
|
+
return void 0;
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
2898
|
+
let answer;
|
|
2899
|
+
try {
|
|
2900
|
+
answer = await environmentRequest(
|
|
2901
|
+
"POST",
|
|
2902
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
2903
|
+
{ challengeId: challenge.challengeId },
|
|
2904
|
+
deps,
|
|
2905
|
+
signal
|
|
2906
|
+
);
|
|
2907
|
+
} catch (error) {
|
|
2908
|
+
signal?.throwIfAborted();
|
|
2909
|
+
return environmentFailure(error, context.apiUrl);
|
|
2910
|
+
}
|
|
2911
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
2912
|
+
const login = answer.value?.githubLogin;
|
|
2913
|
+
return {
|
|
2914
|
+
status: "link_required",
|
|
2915
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
2916
|
+
challengeId: challenge.challengeId,
|
|
2917
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
const refused = exchangeRefusal(
|
|
2921
|
+
answer,
|
|
2922
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
2923
|
+
);
|
|
2924
|
+
if (refused) return refused;
|
|
2925
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2926
|
+
if (!token) {
|
|
2927
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2928
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2929
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2930
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2931
|
+
context.apiUrl
|
|
2932
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2933
|
+
}
|
|
2934
|
+
return recordFor(
|
|
2935
|
+
context,
|
|
2936
|
+
token,
|
|
2937
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
2938
|
+
deps,
|
|
2939
|
+
signal
|
|
2940
|
+
);
|
|
2941
|
+
}
|
|
2942
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2943
|
+
const env = deps.env ?? process.env;
|
|
2944
|
+
const repository = githubRepositoryFullName(root);
|
|
2945
|
+
if (!repository)
|
|
2946
|
+
return failure(
|
|
2947
|
+
"repository_unidentified",
|
|
2948
|
+
"this checkout does not name its GitHub repository",
|
|
2949
|
+
"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"
|
|
2950
|
+
);
|
|
2951
|
+
const branch = currentBranch(root);
|
|
2952
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2953
|
+
return failure(
|
|
2954
|
+
"not_session_branch",
|
|
2955
|
+
`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`,
|
|
2956
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2957
|
+
);
|
|
2958
|
+
attempt.branch = branch;
|
|
2959
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2960
|
+
if (!baseSha) {
|
|
2961
|
+
const head = await git2(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2962
|
+
baseSha = head.stdout.trim();
|
|
2963
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2964
|
+
return failure(
|
|
2965
|
+
"no_commit",
|
|
2966
|
+
"this checkout has no commit to create the session branch at",
|
|
2967
|
+
NEW_SESSION_REMEDY
|
|
2968
|
+
);
|
|
2969
|
+
}
|
|
2970
|
+
const published = await git2(
|
|
2971
|
+
root,
|
|
2972
|
+
[
|
|
2973
|
+
"for-each-ref",
|
|
2974
|
+
"--count=1",
|
|
2975
|
+
"--format=%(refname)",
|
|
2976
|
+
"--contains",
|
|
2977
|
+
baseSha,
|
|
2978
|
+
"refs/remotes/origin/"
|
|
2979
|
+
],
|
|
2980
|
+
signal
|
|
2981
|
+
);
|
|
2982
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2983
|
+
return failure(
|
|
2984
|
+
"unpublished_commits",
|
|
2985
|
+
`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`,
|
|
2986
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2987
|
+
);
|
|
2988
|
+
attempt.baseSha = baseSha;
|
|
2989
|
+
const remote = await git2(
|
|
2990
|
+
root,
|
|
2991
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2992
|
+
signal
|
|
2993
|
+
);
|
|
2994
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2995
|
+
if (remote.ok && recorded) {
|
|
2996
|
+
Object.assign(attempt, recorded);
|
|
2997
|
+
return { ...recorded, repository };
|
|
2998
|
+
}
|
|
2999
|
+
if (remote.ok)
|
|
3000
|
+
return failure(
|
|
3001
|
+
"branch_exists",
|
|
3002
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
3003
|
+
NEW_SESSION_REMEDY
|
|
3004
|
+
);
|
|
3005
|
+
if (remote.code !== 2)
|
|
3006
|
+
return failure(
|
|
3007
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
3008
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
3009
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
3010
|
+
);
|
|
3011
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
3012
|
+
Object.assign(attempt, recorded);
|
|
3013
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
3014
|
+
}
|
|
3015
|
+
let answer;
|
|
3016
|
+
try {
|
|
3017
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
3018
|
+
answer = await environmentRequest(
|
|
3019
|
+
"POST",
|
|
3020
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
3021
|
+
{
|
|
3022
|
+
repositoryFullName: repository,
|
|
3023
|
+
claudeSessionId: context.sessionId,
|
|
3024
|
+
branch,
|
|
3025
|
+
baseSha,
|
|
3026
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
3027
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
3028
|
+
},
|
|
3029
|
+
deps,
|
|
3030
|
+
signal
|
|
3031
|
+
);
|
|
3032
|
+
} catch (error) {
|
|
3033
|
+
signal?.throwIfAborted();
|
|
3034
|
+
return environmentFailure(error, context.apiUrl);
|
|
3035
|
+
}
|
|
3036
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
3037
|
+
return failure(
|
|
3038
|
+
"repository_not_connected",
|
|
3039
|
+
`${repository} is not connected to Primitive`,
|
|
3040
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
3041
|
+
);
|
|
3042
|
+
if (answer.status === 401 || answer.status === 403)
|
|
3043
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
3044
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
3045
|
+
return failure(
|
|
3046
|
+
"challenge_open",
|
|
3047
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
3048
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
3049
|
+
);
|
|
3050
|
+
if (answer.status === 429)
|
|
3051
|
+
return failure(
|
|
3052
|
+
"too_many_challenges",
|
|
3053
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
3054
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
3055
|
+
);
|
|
3056
|
+
const challengeId = answer.value?.challengeId;
|
|
3057
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
3058
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
3059
|
+
return answer.status >= 500 ? environmentFailure(
|
|
3060
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
3061
|
+
context.apiUrl
|
|
3062
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
3063
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
3064
|
+
attempt.challengeId = challengeId;
|
|
3065
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
3066
|
+
return pushSessionBranch(
|
|
3067
|
+
root,
|
|
3068
|
+
repository,
|
|
3069
|
+
branch,
|
|
3070
|
+
baseSha,
|
|
3071
|
+
{ challengeId, challengeExpiresAt },
|
|
3072
|
+
signal
|
|
3073
|
+
);
|
|
3074
|
+
}
|
|
3075
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
3076
|
+
const push = await git2(
|
|
3077
|
+
root,
|
|
3078
|
+
[
|
|
3079
|
+
"-c",
|
|
3080
|
+
"core.hooksPath=/dev/null",
|
|
3081
|
+
"-c",
|
|
3082
|
+
"push.followTags=false",
|
|
3083
|
+
"-c",
|
|
3084
|
+
"push.recurseSubmodules=no",
|
|
3085
|
+
"-c",
|
|
3086
|
+
"push.gpgSign=false",
|
|
3087
|
+
"-c",
|
|
3088
|
+
"push.pushOption=",
|
|
3089
|
+
"push",
|
|
3090
|
+
"--no-verify",
|
|
3091
|
+
"--no-follow-tags",
|
|
3092
|
+
"--no-recurse-submodules",
|
|
3093
|
+
"--no-signed",
|
|
3094
|
+
"--quiet",
|
|
3095
|
+
"origin",
|
|
3096
|
+
`${baseSha}:refs/heads/${branch}`
|
|
3097
|
+
],
|
|
3098
|
+
signal
|
|
3099
|
+
);
|
|
3100
|
+
if (!push.ok)
|
|
3101
|
+
return push.timedOut ? failure(
|
|
3102
|
+
"push_timeout",
|
|
3103
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS4 / 1e3} s`,
|
|
3104
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
3105
|
+
) : failure(
|
|
3106
|
+
"push_refused",
|
|
3107
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
3108
|
+
`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}`
|
|
3109
|
+
);
|
|
3110
|
+
return { ...challenge, repository };
|
|
3111
|
+
}
|
|
3112
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
3113
|
+
let context;
|
|
3114
|
+
try {
|
|
3115
|
+
context = sessionContext(deps);
|
|
3116
|
+
} catch (error) {
|
|
3117
|
+
return failure(
|
|
3118
|
+
"environment_credential_invalid",
|
|
3119
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
3120
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
3121
|
+
);
|
|
3122
|
+
}
|
|
3123
|
+
if ("status" in context) return context;
|
|
3124
|
+
const ctx = context;
|
|
3125
|
+
const startedAt = Date.now();
|
|
3126
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
3127
|
+
return withFileLock(
|
|
3128
|
+
ctx.lockPath,
|
|
3129
|
+
async () => {
|
|
3130
|
+
const record = readToken(ctx);
|
|
3131
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
3132
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
3133
|
+
if (record) {
|
|
3134
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
3135
|
+
if (refreshed.status === "ok") {
|
|
3136
|
+
writeToken(ctx, refreshed.record);
|
|
3137
|
+
return identified(refreshed.record, true);
|
|
3138
|
+
}
|
|
3139
|
+
if (refreshed.status === "refused") {
|
|
3140
|
+
rmSync7(ctx.tokenPath, { force: true });
|
|
3141
|
+
writeState(ctx, {
|
|
3142
|
+
sessionId: ctx.sessionId,
|
|
3143
|
+
status: "failed",
|
|
3144
|
+
code: refreshed.failure.code,
|
|
3145
|
+
cause: refreshed.failure.cause,
|
|
3146
|
+
remedy: refreshed.failure.remedy,
|
|
3147
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
3148
|
+
at: Date.now()
|
|
3149
|
+
});
|
|
3150
|
+
return refreshed.failure;
|
|
3151
|
+
}
|
|
3152
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
3153
|
+
}
|
|
3154
|
+
const state = readState(ctx);
|
|
3155
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
3156
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
3157
|
+
if (!options.explicit) {
|
|
3158
|
+
if (!root || !(record || state))
|
|
3159
|
+
return failure(
|
|
3160
|
+
"not_identified",
|
|
3161
|
+
"this session has not identified who started it yet",
|
|
3162
|
+
RETRY_REMEDY
|
|
3163
|
+
);
|
|
3164
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
3165
|
+
} else if (state && state.at >= startedAt) {
|
|
3166
|
+
return outcomeFromState(state);
|
|
3167
|
+
}
|
|
3168
|
+
if (!root)
|
|
3169
|
+
return failure(
|
|
3170
|
+
"repository_missing",
|
|
3171
|
+
"this is not a git repository",
|
|
3172
|
+
"run it in the repository the session cloned"
|
|
3173
|
+
);
|
|
3174
|
+
const attempt = { root };
|
|
3175
|
+
const remember = (outcome) => {
|
|
3176
|
+
writeState(ctx, {
|
|
3177
|
+
sessionId: ctx.sessionId,
|
|
3178
|
+
status: outcome.status,
|
|
3179
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
3180
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
3181
|
+
githubLogin: outcome.githubLogin
|
|
3182
|
+
},
|
|
3183
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
3184
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
3185
|
+
repositoryRoot: root,
|
|
3186
|
+
branch: attempt.branch ?? state?.branch,
|
|
3187
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
3188
|
+
at: Date.now()
|
|
3189
|
+
});
|
|
3190
|
+
return outcome;
|
|
3191
|
+
};
|
|
3192
|
+
let challenge;
|
|
3193
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
3194
|
+
attempt.challengeId = state.challengeId;
|
|
3195
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
3196
|
+
attempt.branch = state.branch;
|
|
3197
|
+
attempt.baseSha = state.baseSha;
|
|
3198
|
+
challenge = {
|
|
3199
|
+
challengeId: state.challengeId,
|
|
3200
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
3201
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
3202
|
+
};
|
|
3203
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
3204
|
+
attempt.challengeId = state.challengeId;
|
|
3205
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
3206
|
+
const exchanged2 = await exchangeChallenge(
|
|
3207
|
+
ctx,
|
|
3208
|
+
{
|
|
3209
|
+
challengeId: state.challengeId,
|
|
3210
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
3211
|
+
githubLogin: state.githubLogin
|
|
3212
|
+
},
|
|
3213
|
+
root,
|
|
3214
|
+
deps,
|
|
3215
|
+
options.signal
|
|
3216
|
+
);
|
|
3217
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
3218
|
+
writeToken(ctx, exchanged2);
|
|
3219
|
+
return identified(exchanged2, false);
|
|
3220
|
+
} else if (!options.explicit) {
|
|
3221
|
+
return state ? outcomeFromState(state) : failure(
|
|
3222
|
+
"not_identified",
|
|
3223
|
+
"this session has not identified who started it yet",
|
|
3224
|
+
RETRY_REMEDY
|
|
3225
|
+
);
|
|
3226
|
+
} else {
|
|
3227
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
3228
|
+
if ("status" in pushed) return remember(pushed);
|
|
3229
|
+
challenge = pushed;
|
|
3230
|
+
}
|
|
3231
|
+
const verified = await pollChallenge(
|
|
3232
|
+
ctx.apiUrl,
|
|
3233
|
+
challenge.challengeId,
|
|
3234
|
+
challenge.repository,
|
|
3235
|
+
// A hook process waits only briefly for a late notice.
|
|
3236
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
3237
|
+
options.signal
|
|
3238
|
+
);
|
|
3239
|
+
if ("status" in verified) return remember(verified);
|
|
3240
|
+
const exchanged = await exchangeChallenge(
|
|
3241
|
+
ctx,
|
|
3242
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
3243
|
+
root,
|
|
3244
|
+
deps,
|
|
3245
|
+
options.signal
|
|
3246
|
+
);
|
|
3247
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
3248
|
+
writeToken(ctx, exchanged);
|
|
3249
|
+
return identified(exchanged, false);
|
|
3250
|
+
},
|
|
3251
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
3252
|
+
);
|
|
3253
|
+
}
|
|
3254
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
3255
|
+
const cached2 = cachedSessionCredential(deps);
|
|
3256
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
3257
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
3258
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
3259
|
+
let outcome;
|
|
3260
|
+
try {
|
|
3261
|
+
outcome = await ensureSessionIdentity(
|
|
3262
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
3263
|
+
deps
|
|
3264
|
+
);
|
|
3265
|
+
} catch (error) {
|
|
3266
|
+
options.signal?.throwIfAborted();
|
|
3267
|
+
if (error instanceof MachineAuthError) throw error;
|
|
3268
|
+
throw new MachineAuthError(
|
|
3269
|
+
"identity_unavailable",
|
|
3270
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
3271
|
+
);
|
|
3272
|
+
}
|
|
3273
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
3274
|
+
throw new MachineAuthError(
|
|
3275
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
3276
|
+
sessionIdentityMessage(outcome)
|
|
3277
|
+
);
|
|
3278
|
+
}
|
|
3279
|
+
|
|
1777
3280
|
// src/lib/machine-credentials.ts
|
|
3281
|
+
function sessionScoped(deps) {
|
|
3282
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
3283
|
+
}
|
|
1778
3284
|
var require3 = createRequire2(import.meta.url);
|
|
1779
3285
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1780
|
-
var
|
|
3286
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1781
3287
|
var PROFILE_FILE = "machine_profile.json";
|
|
1782
|
-
var
|
|
3288
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
1783
3289
|
var cached;
|
|
1784
3290
|
function configurationDirectory(deps) {
|
|
1785
3291
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
1786
3292
|
}
|
|
1787
3293
|
function apiUrlFor(deps) {
|
|
1788
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
3294
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1789
3295
|
}
|
|
1790
|
-
function
|
|
1791
|
-
return
|
|
3296
|
+
function hash2(value) {
|
|
3297
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1792
3298
|
}
|
|
1793
3299
|
function recordPath(directory, generation) {
|
|
1794
|
-
return
|
|
3300
|
+
return join14(directory, `machine_${generation}.json`);
|
|
1795
3301
|
}
|
|
1796
3302
|
function storageKey(directory, generation) {
|
|
1797
|
-
return `${
|
|
3303
|
+
return `${hash2(directory)}:${generation}`;
|
|
1798
3304
|
}
|
|
1799
3305
|
function environmentContextPath(deps, clientId) {
|
|
1800
|
-
return
|
|
3306
|
+
return join14(
|
|
1801
3307
|
configurationDirectory(deps),
|
|
1802
|
-
`machine_context_${
|
|
3308
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1803
3309
|
);
|
|
1804
3310
|
}
|
|
1805
3311
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -1860,8 +3366,8 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1860
3366
|
function keyringEntry(key) {
|
|
1861
3367
|
let directory = dirname8(fileURLToPath4(import.meta.url));
|
|
1862
3368
|
for (let depth = 0; depth < 5; depth++) {
|
|
1863
|
-
const loader =
|
|
1864
|
-
if (
|
|
3369
|
+
const loader = join14(directory, "native", "keyring.cjs");
|
|
3370
|
+
if (existsSync9(loader)) {
|
|
1865
3371
|
const module2 = require3(loader);
|
|
1866
3372
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1867
3373
|
}
|
|
@@ -1877,7 +3383,7 @@ function protectPath(path, directory) {
|
|
|
1877
3383
|
}
|
|
1878
3384
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1879
3385
|
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)`;
|
|
1880
|
-
|
|
3386
|
+
execFileSync5(
|
|
1881
3387
|
"powershell.exe",
|
|
1882
3388
|
[
|
|
1883
3389
|
"-NoProfile",
|
|
@@ -1889,8 +3395,8 @@ function protectPath(path, directory) {
|
|
|
1889
3395
|
);
|
|
1890
3396
|
}
|
|
1891
3397
|
function ensureDirectory(directory) {
|
|
1892
|
-
|
|
1893
|
-
if (
|
|
3398
|
+
mkdirSync5(directory, { recursive: true, mode: 448 });
|
|
3399
|
+
if (lstatSync6(directory).isSymbolicLink())
|
|
1894
3400
|
throw new MachineAuthError(
|
|
1895
3401
|
"unsafe_storage",
|
|
1896
3402
|
"Credential directory must not be a symbolic link."
|
|
@@ -1902,17 +3408,20 @@ function writePrivate(path, value) {
|
|
|
1902
3408
|
`, { mode: 384 });
|
|
1903
3409
|
protectPath(path, false);
|
|
1904
3410
|
}
|
|
3411
|
+
function readMachineMetadata(path) {
|
|
3412
|
+
return readPrivate(path);
|
|
3413
|
+
}
|
|
1905
3414
|
function readPrivate(path) {
|
|
1906
3415
|
let raw;
|
|
1907
3416
|
try {
|
|
1908
|
-
const stat =
|
|
3417
|
+
const stat = lstatSync6(path);
|
|
1909
3418
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1910
3419
|
throw new MachineAuthError(
|
|
1911
3420
|
"unsafe_storage",
|
|
1912
3421
|
"Machine credential files must be owner-only regular files."
|
|
1913
3422
|
);
|
|
1914
3423
|
}
|
|
1915
|
-
raw =
|
|
3424
|
+
raw = readFileSync11(path, "utf8");
|
|
1916
3425
|
} catch (error) {
|
|
1917
3426
|
if (error.code === "ENOENT") return void 0;
|
|
1918
3427
|
throw error;
|
|
@@ -1957,13 +3466,101 @@ function parseProfile(value) {
|
|
|
1957
3466
|
};
|
|
1958
3467
|
}
|
|
1959
3468
|
function readMachineProfile(deps = {}) {
|
|
1960
|
-
const value = readPrivate(
|
|
3469
|
+
const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
1961
3470
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1962
3471
|
}
|
|
3472
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
3473
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
3474
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
3475
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
3476
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
3477
|
+
const directory = configurationDirectory(deps);
|
|
3478
|
+
const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
3479
|
+
const known = brokerKeys.get(path);
|
|
3480
|
+
if (known) return known;
|
|
3481
|
+
ensureDirectory(directory);
|
|
3482
|
+
const read = () => {
|
|
3483
|
+
try {
|
|
3484
|
+
const stat = lstatSync6(path);
|
|
3485
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
3486
|
+
throw new MachineAuthError(
|
|
3487
|
+
"unsafe_storage",
|
|
3488
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
3489
|
+
true
|
|
3490
|
+
);
|
|
3491
|
+
const value = readFileSync11(path, "utf8").trim();
|
|
3492
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
3493
|
+
} catch (error) {
|
|
3494
|
+
if (error.code === "ENOENT") return void 0;
|
|
3495
|
+
throw error;
|
|
3496
|
+
}
|
|
3497
|
+
};
|
|
3498
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
3499
|
+
const existing = read();
|
|
3500
|
+
if (existing?.key) {
|
|
3501
|
+
brokerKeys.set(path, existing.key);
|
|
3502
|
+
return existing.key;
|
|
3503
|
+
}
|
|
3504
|
+
if (existing)
|
|
3505
|
+
throw new MachineAuthError(
|
|
3506
|
+
"unsafe_storage",
|
|
3507
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
3508
|
+
true
|
|
3509
|
+
);
|
|
3510
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
3511
|
+
try {
|
|
3512
|
+
writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
|
|
3513
|
+
`, { mode: 384, flag: "wx" });
|
|
3514
|
+
protectPath(staged, false);
|
|
3515
|
+
linkSync(staged, path);
|
|
3516
|
+
} catch (error) {
|
|
3517
|
+
if (error.code !== "EEXIST") throw error;
|
|
3518
|
+
} finally {
|
|
3519
|
+
rmSync8(staged, { force: true });
|
|
3520
|
+
}
|
|
3521
|
+
}
|
|
3522
|
+
const key = read()?.key;
|
|
3523
|
+
if (!key)
|
|
3524
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
3525
|
+
brokerKeys.set(path, key);
|
|
3526
|
+
return key;
|
|
3527
|
+
}
|
|
1963
3528
|
function environmentCredentials(deps) {
|
|
1964
3529
|
const env = deps.env ?? process.env;
|
|
1965
|
-
const {
|
|
1966
|
-
|
|
3530
|
+
const {
|
|
3531
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
3532
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
3533
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
3534
|
+
} = env;
|
|
3535
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
3536
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
3537
|
+
throw new MachineAuthError(
|
|
3538
|
+
"incomplete_machine_credentials",
|
|
3539
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
3540
|
+
);
|
|
3541
|
+
if (auth !== void 0) {
|
|
3542
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
3543
|
+
throw new MachineAuthError(
|
|
3544
|
+
"incomplete_machine_credentials",
|
|
3545
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
3546
|
+
);
|
|
3547
|
+
if (clientSecret !== void 0)
|
|
3548
|
+
throw new MachineAuthError(
|
|
3549
|
+
"conflicting_credentials",
|
|
3550
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
3551
|
+
);
|
|
3552
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
3553
|
+
const credentials = {
|
|
3554
|
+
clientId,
|
|
3555
|
+
generation,
|
|
3556
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
3557
|
+
};
|
|
3558
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
3559
|
+
enumerable: true,
|
|
3560
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
3561
|
+
});
|
|
3562
|
+
return credentials;
|
|
3563
|
+
}
|
|
1967
3564
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1968
3565
|
throw new MachineAuthError(
|
|
1969
3566
|
"incomplete_machine_credentials",
|
|
@@ -1973,12 +3570,12 @@ function environmentCredentials(deps) {
|
|
|
1973
3570
|
return {
|
|
1974
3571
|
clientId,
|
|
1975
3572
|
clientSecret,
|
|
1976
|
-
generation:
|
|
3573
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1977
3574
|
};
|
|
1978
3575
|
}
|
|
1979
3576
|
function hasMachineConfiguration(deps = {}) {
|
|
1980
3577
|
const env = deps.env ?? process.env;
|
|
1981
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 ||
|
|
3578
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
1982
3579
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1983
3580
|
throw new MachineAuthError(
|
|
1984
3581
|
"conflicting_credentials",
|
|
@@ -1990,6 +3587,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1990
3587
|
}
|
|
1991
3588
|
function machineContext(deps = {}) {
|
|
1992
3589
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3590
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1993
3591
|
const environment = environmentCredentials(deps);
|
|
1994
3592
|
if (environment) {
|
|
1995
3593
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -2004,6 +3602,7 @@ function machineContext(deps = {}) {
|
|
|
2004
3602
|
return profile;
|
|
2005
3603
|
}
|
|
2006
3604
|
function cachedMachineCredential(deps = {}) {
|
|
3605
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
2007
3606
|
const context = machineContext(deps);
|
|
2008
3607
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
2009
3608
|
}
|
|
@@ -2012,9 +3611,11 @@ function machineSessionEnded(deps = {}) {
|
|
|
2012
3611
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2013
3612
|
if (!generation) return false;
|
|
2014
3613
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2015
|
-
return readPrivate(
|
|
3614
|
+
return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2016
3615
|
}
|
|
2017
3616
|
var environmentTerminal;
|
|
3617
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
3618
|
+
var networkRejection;
|
|
2018
3619
|
async function loadRecord(profile, deps, signal) {
|
|
2019
3620
|
const directory = configurationDirectory(deps);
|
|
2020
3621
|
let value;
|
|
@@ -2074,10 +3675,12 @@ async function persistRecord(record, deps, signal) {
|
|
|
2074
3675
|
}
|
|
2075
3676
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
2076
3677
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3678
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
2077
3679
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2078
3680
|
const apiUrl = apiUrlFor(deps);
|
|
2079
3681
|
const environment = environmentCredentials(deps);
|
|
2080
3682
|
if (environment) {
|
|
3683
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
2081
3684
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
2082
3685
|
const directory2 = configurationDirectory(deps);
|
|
2083
3686
|
ensureDirectory(directory2);
|
|
@@ -2095,22 +3698,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2095
3698
|
writeEnvironmentContext(cached, deps);
|
|
2096
3699
|
return cached;
|
|
2097
3700
|
} catch (error) {
|
|
2098
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
3701
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
2099
3702
|
environmentTerminal = environment.generation;
|
|
2100
3703
|
throw error;
|
|
2101
3704
|
}
|
|
2102
3705
|
}
|
|
2103
3706
|
return withFileLock(
|
|
2104
|
-
|
|
3707
|
+
join14(directory2, "credentials.lock"),
|
|
2105
3708
|
async () => {
|
|
2106
3709
|
if (machineSessionEnded(deps))
|
|
2107
3710
|
throw new MachineAuthError(
|
|
2108
3711
|
"machine_credentials_rejected",
|
|
2109
|
-
"Rotate the injected machine credentials.",
|
|
3712
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
2110
3713
|
true
|
|
2111
3714
|
);
|
|
2112
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
3715
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
2113
3716
|
return cached;
|
|
3717
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
3718
|
+
throw networkRejection.error;
|
|
2114
3719
|
try {
|
|
2115
3720
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
2116
3721
|
directory2,
|
|
@@ -2119,13 +3724,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2119
3724
|
signal,
|
|
2120
3725
|
async () => {
|
|
2121
3726
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
3727
|
+
if (environment.tokenInjection) {
|
|
3728
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
3729
|
+
apiUrl,
|
|
3730
|
+
environment.clientId,
|
|
3731
|
+
signal,
|
|
3732
|
+
deps.fetch
|
|
3733
|
+
);
|
|
3734
|
+
const tokens3 = {
|
|
3735
|
+
accessToken: "",
|
|
3736
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
3737
|
+
};
|
|
3738
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
3739
|
+
}
|
|
2122
3740
|
const tokens2 = await exchangeMachineCredentials(
|
|
2123
3741
|
configuration2,
|
|
2124
3742
|
environment.clientId,
|
|
2125
|
-
|
|
3743
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
3744
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
2126
3745
|
signal,
|
|
2127
|
-
deps.fetch
|
|
2128
|
-
|
|
3746
|
+
deps.fetch,
|
|
3747
|
+
{ secretInjection: environment.secretInjection }
|
|
3748
|
+
).catch((error) => {
|
|
3749
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
3750
|
+
throw new MachineAuthError(
|
|
3751
|
+
"network_secret_mismatch",
|
|
3752
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
3753
|
+
true
|
|
3754
|
+
);
|
|
3755
|
+
throw error;
|
|
3756
|
+
});
|
|
2129
3757
|
const identity2 = await verifyMachineIdentity(
|
|
2130
3758
|
apiUrl,
|
|
2131
3759
|
tokens2.accessToken,
|
|
@@ -2142,17 +3770,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2142
3770
|
...identity,
|
|
2143
3771
|
apiUrl,
|
|
2144
3772
|
generation: environment.generation,
|
|
2145
|
-
storage: "environment"
|
|
3773
|
+
storage: "environment",
|
|
3774
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
2146
3775
|
};
|
|
2147
3776
|
writeEnvironmentContext(cached, deps);
|
|
2148
3777
|
return cached;
|
|
2149
3778
|
} catch (error) {
|
|
3779
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
3780
|
+
networkRejection = {
|
|
3781
|
+
generation: environment.generation,
|
|
3782
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
3783
|
+
error
|
|
3784
|
+
};
|
|
3785
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
3786
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
3787
|
+
try {
|
|
3788
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
3789
|
+
rmSync8(contextPath, { force: true });
|
|
3790
|
+
} catch {
|
|
3791
|
+
}
|
|
3792
|
+
throw error;
|
|
3793
|
+
}
|
|
2150
3794
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
2151
3795
|
environmentTerminal = environment.generation;
|
|
2152
3796
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2153
3797
|
try {
|
|
2154
3798
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2155
|
-
|
|
3799
|
+
rmSync8(contextPath, { force: true });
|
|
2156
3800
|
} catch {
|
|
2157
3801
|
}
|
|
2158
3802
|
}
|
|
@@ -2166,7 +3810,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2166
3810
|
const expected = machineContext(deps);
|
|
2167
3811
|
const directory = configurationDirectory(deps);
|
|
2168
3812
|
return withFileLock(
|
|
2169
|
-
|
|
3813
|
+
join14(directory, "credentials.lock"),
|
|
2170
3814
|
async () => {
|
|
2171
3815
|
const profile = readMachineProfile(deps);
|
|
2172
3816
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2181,7 +3825,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2181
3825
|
true
|
|
2182
3826
|
);
|
|
2183
3827
|
let record = await loadRecord(profile, deps, signal);
|
|
2184
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
3828
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
2185
3829
|
try {
|
|
2186
3830
|
const { tokens, identity } = await withMachineCooldown(
|
|
2187
3831
|
directory,
|
|
@@ -2216,7 +3860,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2216
3860
|
await persistRecord(record, deps, signal);
|
|
2217
3861
|
} catch (error) {
|
|
2218
3862
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2219
|
-
writePrivate(
|
|
3863
|
+
writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
|
|
2220
3864
|
throw error;
|
|
2221
3865
|
}
|
|
2222
3866
|
}
|
|
@@ -2227,23 +3871,47 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2227
3871
|
{ signal }
|
|
2228
3872
|
);
|
|
2229
3873
|
}
|
|
3874
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
3875
|
+
const environment = environmentCredentials(deps);
|
|
3876
|
+
if (!environment?.tokenInjection)
|
|
3877
|
+
throw new MachineAuthError(
|
|
3878
|
+
"identity_changed",
|
|
3879
|
+
"Machine identity changed; restart the operation."
|
|
3880
|
+
);
|
|
3881
|
+
const directory = configurationDirectory(deps);
|
|
3882
|
+
ensureDirectory(directory);
|
|
3883
|
+
return forwardBrokerRequest({
|
|
3884
|
+
directory,
|
|
3885
|
+
apiUrl: apiUrlFor(deps),
|
|
3886
|
+
environment,
|
|
3887
|
+
env: deps.env ?? process.env,
|
|
3888
|
+
request: request3,
|
|
3889
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
3890
|
+
});
|
|
3891
|
+
}
|
|
3892
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
3893
|
+
ensureDirectory(directory);
|
|
3894
|
+
}
|
|
3895
|
+
function writeMachineMetadata(path, value) {
|
|
3896
|
+
writePrivate(path, value);
|
|
3897
|
+
}
|
|
2230
3898
|
|
|
2231
3899
|
// src/lib/credentials.ts
|
|
2232
3900
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
2233
|
-
var TOKEN_FILE_PATH =
|
|
2234
|
-
var REFRESH_TOKEN_PATH =
|
|
2235
|
-
var TOKEN_EXPIRES_PATH =
|
|
2236
|
-
var TERMINAL_REFRESH_PATH =
|
|
2237
|
-
var CREDENTIAL_METADATA_PATH =
|
|
2238
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
2239
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
2240
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3901
|
+
var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
|
|
3902
|
+
var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
|
|
3903
|
+
var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
|
|
3904
|
+
var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3905
|
+
var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3906
|
+
var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
|
|
3907
|
+
var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3908
|
+
var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
|
|
2241
3909
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
2242
3910
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
2243
3911
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
2244
3912
|
function readTrimmed(path) {
|
|
2245
3913
|
try {
|
|
2246
|
-
const value =
|
|
3914
|
+
const value = readFileSync12(path, "utf8").trim();
|
|
2247
3915
|
return value || void 0;
|
|
2248
3916
|
} catch {
|
|
2249
3917
|
return void 0;
|
|
@@ -2252,7 +3920,7 @@ function readTrimmed(path) {
|
|
|
2252
3920
|
function resolveAuthCredential(options = {}) {
|
|
2253
3921
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
2254
3922
|
const machine = cachedMachineCredential({ env: options.env });
|
|
2255
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
3923
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
2256
3924
|
}
|
|
2257
3925
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
2258
3926
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -2265,22 +3933,33 @@ function resolveAuthCredential(options = {}) {
|
|
|
2265
3933
|
);
|
|
2266
3934
|
if (metadata.state === "legacy_broker") {
|
|
2267
3935
|
if (metadata.metadata) {
|
|
2268
|
-
const
|
|
2269
|
-
if (!
|
|
3936
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3937
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
2270
3938
|
return void 0;
|
|
2271
3939
|
}
|
|
2272
3940
|
}
|
|
2273
3941
|
return { token: stored, source: "token_file" };
|
|
2274
3942
|
}
|
|
2275
3943
|
if (metadata.state === "invalid") return void 0;
|
|
2276
|
-
const
|
|
2277
|
-
if (!
|
|
3944
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3945
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
2278
3946
|
return void 0;
|
|
2279
3947
|
}
|
|
2280
3948
|
return { token: stored, source: "token_file" };
|
|
2281
3949
|
}
|
|
3950
|
+
function resolveStoredCredential(env = process.env) {
|
|
3951
|
+
const directory = primConfigDirectory({ env });
|
|
3952
|
+
return resolveAuthCredential({
|
|
3953
|
+
env,
|
|
3954
|
+
tokenFilePath: join15(directory, "token"),
|
|
3955
|
+
refreshTokenPath: join15(directory, "refresh_token"),
|
|
3956
|
+
metadataPath: join15(directory, "credential_metadata.json"),
|
|
3957
|
+
familyPath: join15(directory, "credential_family.json"),
|
|
3958
|
+
migrationPath: join15(directory, "credential_migration.json")
|
|
3959
|
+
});
|
|
3960
|
+
}
|
|
2282
3961
|
function credentialFingerprint(value) {
|
|
2283
|
-
return
|
|
3962
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
2284
3963
|
}
|
|
2285
3964
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2286
3965
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -2300,7 +3979,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
2300
3979
|
function readBoundedCredentialJson(path) {
|
|
2301
3980
|
let raw;
|
|
2302
3981
|
try {
|
|
2303
|
-
raw =
|
|
3982
|
+
raw = readFileSync12(path, "utf8");
|
|
2304
3983
|
} catch (error) {
|
|
2305
3984
|
return error.code === "ENOENT" ? void 0 : null;
|
|
2306
3985
|
}
|
|
@@ -2372,9 +4051,9 @@ function jwtExpiresAt(token) {
|
|
|
2372
4051
|
}
|
|
2373
4052
|
|
|
2374
4053
|
// src/daemon/client-instance-id.ts
|
|
2375
|
-
import { randomBytes as
|
|
2376
|
-
import { chmodSync as chmodSync3, lstatSync as
|
|
2377
|
-
import { join as
|
|
4054
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
4055
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
4056
|
+
import { join as join16 } from "path";
|
|
2378
4057
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
2379
4058
|
var INSTANCE_FILE_MODE = 384;
|
|
2380
4059
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -2387,7 +4066,7 @@ function isClientInstanceId(value) {
|
|
|
2387
4066
|
}
|
|
2388
4067
|
function ensurePrivateConfigDirectory(configDir) {
|
|
2389
4068
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
2390
|
-
const metadata =
|
|
4069
|
+
const metadata = lstatSync7(configDir);
|
|
2391
4070
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
2392
4071
|
throw new Error("prim config path must be a private directory");
|
|
2393
4072
|
}
|
|
@@ -2397,7 +4076,7 @@ function ensurePrivateConfigDirectory(configDir) {
|
|
|
2397
4076
|
function readExisting(path) {
|
|
2398
4077
|
let metadata;
|
|
2399
4078
|
try {
|
|
2400
|
-
metadata =
|
|
4079
|
+
metadata = lstatSync7(path);
|
|
2401
4080
|
} catch (error) {
|
|
2402
4081
|
if (error.code === "ENOENT") {
|
|
2403
4082
|
return;
|
|
@@ -2411,7 +4090,7 @@ function readExisting(path) {
|
|
|
2411
4090
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
2412
4091
|
throw new Error("stored client instance identity is invalid");
|
|
2413
4092
|
}
|
|
2414
|
-
const raw =
|
|
4093
|
+
const raw = readFileSync13(path, "utf8");
|
|
2415
4094
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
2416
4095
|
if (raw !== value && raw !== `${value}
|
|
2417
4096
|
` || !isClientInstanceId(value)) {
|
|
@@ -2425,8 +4104,8 @@ function atomicWrite(path, value) {
|
|
|
2425
4104
|
}
|
|
2426
4105
|
async function getOrCreateClientInstanceId(options) {
|
|
2427
4106
|
const configDir = options.configDir;
|
|
2428
|
-
const path =
|
|
2429
|
-
const lockPath =
|
|
4107
|
+
const path = join16(configDir, "client_instance_id");
|
|
4108
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
2430
4109
|
ensurePrivateConfigDirectory(configDir);
|
|
2431
4110
|
return withFileLock(
|
|
2432
4111
|
lockPath,
|
|
@@ -2435,7 +4114,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
2435
4114
|
if (existing !== void 0) {
|
|
2436
4115
|
return existing;
|
|
2437
4116
|
}
|
|
2438
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
4117
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
2439
4118
|
"base64url"
|
|
2440
4119
|
)}`;
|
|
2441
4120
|
if (!isClientInstanceId(generated)) {
|
|
@@ -2470,60 +4149,18 @@ async function ingestUploaderHeaders() {
|
|
|
2470
4149
|
return headers;
|
|
2471
4150
|
}
|
|
2472
4151
|
|
|
2473
|
-
// src/lib/terminal-safe.ts
|
|
2474
|
-
function replaceIsolatedSurrogates(value) {
|
|
2475
|
-
let out = "";
|
|
2476
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
2477
|
-
const unit = value.charCodeAt(index);
|
|
2478
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2479
|
-
const next = value.charCodeAt(index + 1);
|
|
2480
|
-
if (next >= 56320 && next <= 57343) {
|
|
2481
|
-
out += value[index] + value[index + 1];
|
|
2482
|
-
index += 1;
|
|
2483
|
-
} else {
|
|
2484
|
-
out += "\uFFFD";
|
|
2485
|
-
}
|
|
2486
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
2487
|
-
out += "\uFFFD";
|
|
2488
|
-
} else {
|
|
2489
|
-
out += value[index];
|
|
2490
|
-
}
|
|
2491
|
-
}
|
|
2492
|
-
return out;
|
|
2493
|
-
}
|
|
2494
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
2495
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2496
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2497
|
-
point === 1564 || // Arabic letter mark
|
|
2498
|
-
point === 6158 || // Mongolian vowel separator
|
|
2499
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2500
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2501
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2502
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2503
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
2504
|
-
point >= 917504 && point <= 917631;
|
|
2505
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
2506
|
-
}
|
|
2507
|
-
function terminalSafeText(value) {
|
|
2508
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2509
|
-
}
|
|
2510
|
-
function terminalSafeLine(value) {
|
|
2511
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2512
|
-
}
|
|
2513
|
-
function isTerminalSafeText(value) {
|
|
2514
|
-
return terminalSafeText(value) === value;
|
|
2515
|
-
}
|
|
2516
|
-
var stripControlChars = terminalSafeText;
|
|
2517
|
-
|
|
2518
4152
|
// src/client.ts
|
|
2519
4153
|
var CONFIG_DIR_MODE = 448;
|
|
2520
4154
|
var CREDENTIAL_FILE_MODE = 384;
|
|
2521
4155
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2522
|
-
var
|
|
4156
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
2523
4157
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
4158
|
+
function authExpiredMessage() {
|
|
4159
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
4160
|
+
}
|
|
2524
4161
|
function readTrimmed2(path) {
|
|
2525
4162
|
try {
|
|
2526
|
-
const value =
|
|
4163
|
+
const value = readFileSync14(path, "utf8").trim();
|
|
2527
4164
|
return value || void 0;
|
|
2528
4165
|
} catch {
|
|
2529
4166
|
return void 0;
|
|
@@ -2533,14 +4170,14 @@ function getSiteUrl() {
|
|
|
2533
4170
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
2534
4171
|
}
|
|
2535
4172
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
2536
|
-
return primApiUrl?.trim() ||
|
|
4173
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
2537
4174
|
}
|
|
2538
4175
|
function expiresAtFor(token, expiresIn) {
|
|
2539
4176
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
2540
4177
|
}
|
|
2541
4178
|
function ensureConfigDirectory() {
|
|
2542
4179
|
const directory = dirname9(TOKEN_FILE_PATH);
|
|
2543
|
-
|
|
4180
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
2544
4181
|
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
2545
4182
|
}
|
|
2546
4183
|
function atomicWrite2(path, content) {
|
|
@@ -2548,8 +4185,8 @@ function atomicWrite2(path, content) {
|
|
|
2548
4185
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
2549
4186
|
}
|
|
2550
4187
|
function removeCredentialFile(path) {
|
|
2551
|
-
if (!
|
|
2552
|
-
|
|
4188
|
+
if (!existsSync10(path)) return false;
|
|
4189
|
+
rmSync9(path, { force: true });
|
|
2553
4190
|
return true;
|
|
2554
4191
|
}
|
|
2555
4192
|
function getTokenExpiresAt() {
|
|
@@ -2564,23 +4201,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
2564
4201
|
const expiresAt = getTokenExpiresAt();
|
|
2565
4202
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
2566
4203
|
}
|
|
2567
|
-
function refreshFingerprint(
|
|
2568
|
-
return
|
|
4204
|
+
function refreshFingerprint(refreshToken3) {
|
|
4205
|
+
return createHash8("sha256").update(refreshToken3).digest("hex");
|
|
2569
4206
|
}
|
|
2570
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
4207
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
2571
4208
|
return {
|
|
2572
4209
|
version: 1,
|
|
2573
4210
|
family: "legacy_broker",
|
|
2574
4211
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2575
|
-
refreshTokenHash: refreshFingerprint(
|
|
4212
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2576
4213
|
};
|
|
2577
4214
|
}
|
|
2578
|
-
function credentialFamilyMetadata(accessToken,
|
|
4215
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
2579
4216
|
const hashes = {
|
|
2580
4217
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2581
|
-
refreshTokenHash: refreshFingerprint(
|
|
4218
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2582
4219
|
};
|
|
2583
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
4220
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
2584
4221
|
}
|
|
2585
4222
|
function writeCredentialMigrationSentinel() {
|
|
2586
4223
|
atomicWrite2(
|
|
@@ -2592,11 +4229,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
2592
4229
|
`
|
|
2593
4230
|
);
|
|
2594
4231
|
}
|
|
2595
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
2596
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
4232
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
4233
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
2597
4234
|
return { state: "invalid" };
|
|
2598
4235
|
}
|
|
2599
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
4236
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2600
4237
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
2601
4238
|
return { state: "invalid" };
|
|
2602
4239
|
}
|
|
@@ -2613,17 +4250,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
2613
4250
|
const metadata = readStoredCredentialMetadata();
|
|
2614
4251
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
2615
4252
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
2616
|
-
const
|
|
2617
|
-
if (!(accessToken &&
|
|
2618
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
4253
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
4254
|
+
if (!(accessToken && refreshToken3)) return;
|
|
4255
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2619
4256
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2620
4257
|
`);
|
|
2621
4258
|
}
|
|
2622
4259
|
function terminalFingerprint() {
|
|
2623
4260
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
2624
4261
|
}
|
|
2625
|
-
function writeTerminalFingerprint(
|
|
2626
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
4262
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
4263
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
2627
4264
|
`);
|
|
2628
4265
|
}
|
|
2629
4266
|
function clearTerminalFingerprint() {
|
|
@@ -2632,20 +4269,20 @@ function clearTerminalFingerprint() {
|
|
|
2632
4269
|
function isSessionEnded() {
|
|
2633
4270
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
2634
4271
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
2635
|
-
const
|
|
4272
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
2636
4273
|
const ended = terminalFingerprint();
|
|
2637
|
-
return Boolean(
|
|
4274
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
2638
4275
|
}
|
|
2639
4276
|
function withCredentialLock(operation, options = {}) {
|
|
2640
4277
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
2641
4278
|
}
|
|
2642
4279
|
function commitCredentialsUnlocked(credentials) {
|
|
2643
4280
|
const accessToken = credentials.accessToken.trim();
|
|
2644
|
-
const
|
|
2645
|
-
if (!accessToken || !
|
|
4281
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
4282
|
+
if (!accessToken || !refreshToken3) {
|
|
2646
4283
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
2647
4284
|
}
|
|
2648
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
4285
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
2649
4286
|
if (credentials.metadata !== void 0) {
|
|
2650
4287
|
preserveMarkerlessLegacyGeneration();
|
|
2651
4288
|
writeCredentialMigrationSentinel();
|
|
@@ -2653,10 +4290,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
2653
4290
|
`);
|
|
2654
4291
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
2655
4292
|
`);
|
|
2656
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
4293
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2657
4294
|
`);
|
|
2658
4295
|
} else {
|
|
2659
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
4296
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2660
4297
|
`);
|
|
2661
4298
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2662
4299
|
`);
|
|
@@ -2693,15 +4330,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
2693
4330
|
`
|
|
2694
4331
|
);
|
|
2695
4332
|
}
|
|
2696
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
4333
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
2697
4334
|
const current = readStoredCredentialMetadata();
|
|
2698
4335
|
if (expected.state === "legacy_broker") {
|
|
2699
4336
|
if (current.state !== "legacy_broker") return false;
|
|
2700
4337
|
if (!expected.metadata) return current.metadata === void 0;
|
|
2701
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
4338
|
+
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;
|
|
2702
4339
|
}
|
|
2703
4340
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
2704
|
-
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(
|
|
4341
|
+
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;
|
|
2705
4342
|
}
|
|
2706
4343
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
2707
4344
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -2870,7 +4507,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
2870
4507
|
);
|
|
2871
4508
|
}
|
|
2872
4509
|
var _refreshInFlight;
|
|
2873
|
-
function
|
|
4510
|
+
function refreshToken2(options = {}) {
|
|
2874
4511
|
if (hasMachineConfiguration())
|
|
2875
4512
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
2876
4513
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -2902,7 +4539,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
2902
4539
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2903
4540
|
async function managementResponseValue(response) {
|
|
2904
4541
|
if (response.status === 401) {
|
|
2905
|
-
throw new HttpError(401,
|
|
4542
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2906
4543
|
}
|
|
2907
4544
|
let value;
|
|
2908
4545
|
try {
|
|
@@ -2924,23 +4561,50 @@ function selectedCredential() {
|
|
|
2924
4561
|
}
|
|
2925
4562
|
return _cachedCredential;
|
|
2926
4563
|
}
|
|
4564
|
+
async function requestHeaders(method, path) {
|
|
4565
|
+
return {
|
|
4566
|
+
"Content-Type": "application/json",
|
|
4567
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
4568
|
+
};
|
|
4569
|
+
}
|
|
2927
4570
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
2928
4571
|
return fetch(`${siteUrl}${path}`, {
|
|
2929
4572
|
method,
|
|
2930
|
-
headers: {
|
|
2931
|
-
Authorization: `Bearer ${token}`,
|
|
2932
|
-
"Content-Type": "application/json",
|
|
2933
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2934
|
-
},
|
|
4573
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
2935
4574
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
2936
4575
|
signal: options?.signal,
|
|
2937
4576
|
redirect: options?.redirect
|
|
2938
4577
|
});
|
|
2939
4578
|
}
|
|
4579
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
4580
|
+
if (!credential.tokenInjection)
|
|
4581
|
+
return fetchWithToken(
|
|
4582
|
+
method,
|
|
4583
|
+
path,
|
|
4584
|
+
body,
|
|
4585
|
+
{ ...options, redirect: "error" },
|
|
4586
|
+
credential.accessToken,
|
|
4587
|
+
credential.apiUrl
|
|
4588
|
+
);
|
|
4589
|
+
try {
|
|
4590
|
+
return await forwardMachineRequest(
|
|
4591
|
+
{
|
|
4592
|
+
method,
|
|
4593
|
+
path,
|
|
4594
|
+
headers: await requestHeaders(method, path),
|
|
4595
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
4596
|
+
},
|
|
4597
|
+
options.signal
|
|
4598
|
+
);
|
|
4599
|
+
} catch (error) {
|
|
4600
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
4601
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
4602
|
+
}
|
|
4603
|
+
}
|
|
2940
4604
|
async function responseValue(response) {
|
|
2941
4605
|
if (!response.ok) {
|
|
2942
4606
|
if (response.status === 401) {
|
|
2943
|
-
throw new HttpError(401,
|
|
4607
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2944
4608
|
}
|
|
2945
4609
|
const errorBody = await response.json().catch(() => null);
|
|
2946
4610
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -2967,14 +4631,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2967
4631
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2968
4632
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
2969
4633
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2970
|
-
let response = await
|
|
2971
|
-
method,
|
|
2972
|
-
path,
|
|
2973
|
-
body,
|
|
2974
|
-
{ ...requestOptions, redirect: "error" },
|
|
2975
|
-
current.accessToken,
|
|
2976
|
-
selected.apiUrl
|
|
2977
|
-
);
|
|
4634
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
2978
4635
|
if (response.status === 401) {
|
|
2979
4636
|
const renewed = await acquireMachineCredential({
|
|
2980
4637
|
force: true,
|
|
@@ -2983,19 +4640,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
2983
4640
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
2984
4641
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2985
4642
|
}
|
|
2986
|
-
response = await
|
|
2987
|
-
method,
|
|
2988
|
-
path,
|
|
2989
|
-
body,
|
|
2990
|
-
{ ...requestOptions, redirect: "error" },
|
|
2991
|
-
renewed.accessToken,
|
|
2992
|
-
renewed.apiUrl
|
|
2993
|
-
);
|
|
4643
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
2994
4644
|
}
|
|
2995
4645
|
if (response.status === 401)
|
|
2996
4646
|
throw new HttpError(
|
|
2997
4647
|
401,
|
|
2998
|
-
"Machine access was rejected.
|
|
4648
|
+
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(
|
|
4649
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
4650
|
+
)
|
|
2999
4651
|
);
|
|
3000
4652
|
return parse2(response);
|
|
3001
4653
|
};
|
|
@@ -3005,7 +4657,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
3005
4657
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
3006
4658
|
};
|
|
3007
4659
|
}
|
|
3008
|
-
async function
|
|
4660
|
+
async function request2(method, path, body, options) {
|
|
3009
4661
|
const machine = await machineClient(options);
|
|
3010
4662
|
if (machine)
|
|
3011
4663
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -3014,17 +4666,17 @@ async function request(method, path, body, options) {
|
|
|
3014
4666
|
let refreshAttempted = false;
|
|
3015
4667
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
3016
4668
|
refreshAttempted = true;
|
|
3017
|
-
const token = await
|
|
4669
|
+
const token = await refreshToken2({
|
|
3018
4670
|
signal: options?.signal,
|
|
3019
4671
|
quiet: options?.quietRefresh
|
|
3020
4672
|
});
|
|
3021
4673
|
if (token) credential = { token, source: "token_file" };
|
|
3022
4674
|
}
|
|
3023
4675
|
if (!credential) {
|
|
3024
|
-
throw new HttpError(401,
|
|
4676
|
+
throw new HttpError(401, authExpiredMessage());
|
|
3025
4677
|
}
|
|
3026
4678
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
3027
|
-
throw new HttpError(401,
|
|
4679
|
+
throw new HttpError(401, authExpiredMessage());
|
|
3028
4680
|
}
|
|
3029
4681
|
const tokenUsed = credential.token;
|
|
3030
4682
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -3033,7 +4685,7 @@ async function request(method, path, body, options) {
|
|
|
3033
4685
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
3034
4686
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
3035
4687
|
refreshAttempted = true;
|
|
3036
|
-
retryToken = await
|
|
4688
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
3037
4689
|
}
|
|
3038
4690
|
if (retryToken) {
|
|
3039
4691
|
_cachedCredential = {
|
|
@@ -3047,30 +4699,30 @@ async function request(method, path, body, options) {
|
|
|
3047
4699
|
}
|
|
3048
4700
|
function getClient() {
|
|
3049
4701
|
return {
|
|
3050
|
-
get: (path, options) =>
|
|
3051
|
-
post: (path, body, options) =>
|
|
4702
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
4703
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
3052
4704
|
};
|
|
3053
4705
|
}
|
|
3054
4706
|
|
|
3055
4707
|
// src/commands/claude-plugin.ts
|
|
3056
|
-
import { createHash as
|
|
4708
|
+
import { createHash as createHash11 } from "crypto";
|
|
3057
4709
|
import {
|
|
3058
4710
|
constants as constants4,
|
|
3059
4711
|
closeSync as closeSync3,
|
|
3060
|
-
existsSync as
|
|
4712
|
+
existsSync as existsSync13,
|
|
3061
4713
|
fstatSync as fstatSync2,
|
|
3062
|
-
lstatSync as
|
|
3063
|
-
mkdirSync as
|
|
4714
|
+
lstatSync as lstatSync10,
|
|
4715
|
+
mkdirSync as mkdirSync7,
|
|
3064
4716
|
openSync as openSync3,
|
|
3065
|
-
readFileSync as
|
|
4717
|
+
readFileSync as readFileSync17,
|
|
3066
4718
|
readSync as readSync2,
|
|
3067
|
-
readdirSync as
|
|
4719
|
+
readdirSync as readdirSync5,
|
|
3068
4720
|
realpathSync as realpathSync3,
|
|
3069
|
-
rmSync as
|
|
4721
|
+
rmSync as rmSync10,
|
|
3070
4722
|
rmdirSync as rmdirSync3
|
|
3071
4723
|
} from "fs";
|
|
3072
|
-
import { homedir as
|
|
3073
|
-
import { dirname as dirname12, isAbsolute as isAbsolute6, join as
|
|
4724
|
+
import { homedir as homedir7 } from "os";
|
|
4725
|
+
import { dirname as dirname12, isAbsolute as isAbsolute6, join as join21, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
|
|
3074
4726
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
3075
4727
|
|
|
3076
4728
|
// node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
|
|
@@ -9341,22 +10993,22 @@ function parse(src, reviver, options) {
|
|
|
9341
10993
|
}
|
|
9342
10994
|
|
|
9343
10995
|
// src/commands/skill.ts
|
|
9344
|
-
import { createHash as
|
|
10996
|
+
import { createHash as createHash10 } from "crypto";
|
|
9345
10997
|
import {
|
|
9346
10998
|
constants as constants3,
|
|
9347
10999
|
closeSync as closeSync2,
|
|
9348
|
-
existsSync as
|
|
11000
|
+
existsSync as existsSync12,
|
|
9349
11001
|
fstatSync,
|
|
9350
|
-
lstatSync as
|
|
11002
|
+
lstatSync as lstatSync9,
|
|
9351
11003
|
openSync as openSync2,
|
|
9352
|
-
readFileSync as
|
|
11004
|
+
readFileSync as readFileSync16,
|
|
9353
11005
|
readSync,
|
|
9354
|
-
readdirSync as
|
|
11006
|
+
readdirSync as readdirSync4,
|
|
9355
11007
|
rmdirSync as rmdirSync2,
|
|
9356
11008
|
unlinkSync as unlinkSync2
|
|
9357
11009
|
} from "fs";
|
|
9358
|
-
import { homedir as
|
|
9359
|
-
import { dirname as dirname11, join as
|
|
11010
|
+
import { homedir as homedir6 } from "os";
|
|
11011
|
+
import { dirname as dirname11, join as join20, resolve as resolve4 } from "path";
|
|
9360
11012
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
9361
11013
|
|
|
9362
11014
|
// node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
|
|
@@ -9526,7 +11178,7 @@ Diff.prototype = {
|
|
|
9526
11178
|
tokenize: function tokenize(value) {
|
|
9527
11179
|
return value.split("");
|
|
9528
11180
|
},
|
|
9529
|
-
join: function
|
|
11181
|
+
join: function join18(chars) {
|
|
9530
11182
|
return chars.join("");
|
|
9531
11183
|
}
|
|
9532
11184
|
};
|
|
@@ -9711,11 +11363,11 @@ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
|
|
|
9711
11363
|
};
|
|
9712
11364
|
|
|
9713
11365
|
// src/commands/welcome-skill.ts
|
|
9714
|
-
import { createHash as
|
|
9715
|
-
import { existsSync as
|
|
9716
|
-
import { homedir as
|
|
9717
|
-
import { dirname as dirname10, join as
|
|
9718
|
-
var WELCOME_SKILL_SOURCE =
|
|
11366
|
+
import { createHash as createHash9 } from "crypto";
|
|
11367
|
+
import { existsSync as existsSync11, lstatSync as lstatSync8, readFileSync as readFileSync15, readdirSync as readdirSync3, rmdirSync, unlinkSync } from "fs";
|
|
11368
|
+
import { homedir as homedir5 } from "os";
|
|
11369
|
+
import { dirname as dirname10, join as join19 } from "path";
|
|
11370
|
+
var WELCOME_SKILL_SOURCE = join19("skills", "prim-welcome", "SKILL.md");
|
|
9719
11371
|
|
|
9720
11372
|
// src/commands/skill.ts
|
|
9721
11373
|
var __dirname = dirname11(fileURLToPath5(import.meta.url));
|
|
@@ -9727,7 +11379,7 @@ var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
|
|
|
9727
11379
|
var SKILL_END_BUFFER = Buffer.from(SKILL_END);
|
|
9728
11380
|
function readCodexGuidance(path) {
|
|
9729
11381
|
try {
|
|
9730
|
-
const entry =
|
|
11382
|
+
const entry = lstatSync9(path);
|
|
9731
11383
|
if (entry.isSymbolicLink() || !entry.isFile()) return null;
|
|
9732
11384
|
const fd = openSync2(path, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
9733
11385
|
try {
|
|
@@ -9750,10 +11402,10 @@ function readCodexGuidance(path) {
|
|
|
9750
11402
|
}
|
|
9751
11403
|
}
|
|
9752
11404
|
function effectiveCodexGuidance(scope) {
|
|
9753
|
-
const override = readCodexGuidance(
|
|
11405
|
+
const override = readCodexGuidance(join20(scope, "AGENTS.override.md"));
|
|
9754
11406
|
if (override === null) return null;
|
|
9755
11407
|
if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
|
|
9756
|
-
const base = readCodexGuidance(
|
|
11408
|
+
const base = readCodexGuidance(join20(scope, "AGENTS.md"));
|
|
9757
11409
|
return base ?? null;
|
|
9758
11410
|
}
|
|
9759
11411
|
function hasUsablePrimBlock(content, visibleBytes) {
|
|
@@ -9776,7 +11428,7 @@ function hasUsablePrimBlock(content, visibleBytes) {
|
|
|
9776
11428
|
}
|
|
9777
11429
|
function hasUsableCodexGuidance(projectRoot2) {
|
|
9778
11430
|
try {
|
|
9779
|
-
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) :
|
|
11431
|
+
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join20(homedir6(), ".codex");
|
|
9780
11432
|
const scopes = [
|
|
9781
11433
|
{ path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
|
|
9782
11434
|
{ path: projectRoot2, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
|
|
@@ -9792,23 +11444,23 @@ function hasUsableCodexGuidance(projectRoot2) {
|
|
|
9792
11444
|
var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
|
|
9793
11445
|
var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
|
|
9794
11446
|
function sha256(content) {
|
|
9795
|
-
return
|
|
11447
|
+
return createHash10("sha256").update(content).digest("hex");
|
|
9796
11448
|
}
|
|
9797
11449
|
function cursorSkillDirectory(cwd, scope) {
|
|
9798
11450
|
const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
|
|
9799
|
-
return
|
|
11451
|
+
return join20(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
|
|
9800
11452
|
}
|
|
9801
11453
|
function cursorSkillPaths(cwd, scope) {
|
|
9802
11454
|
const directory = cursorSkillDirectory(cwd, scope);
|
|
9803
11455
|
return {
|
|
9804
11456
|
directory,
|
|
9805
|
-
skill:
|
|
9806
|
-
manifest:
|
|
11457
|
+
skill: join20(directory, "SKILL.md"),
|
|
11458
|
+
manifest: join20(directory, CURSOR_SKILL_MANIFEST)
|
|
9807
11459
|
};
|
|
9808
11460
|
}
|
|
9809
11461
|
function readCursorSkillManifest(path) {
|
|
9810
11462
|
try {
|
|
9811
|
-
const value = JSON.parse(
|
|
11463
|
+
const value = JSON.parse(readFileSync16(path, "utf8"));
|
|
9812
11464
|
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
9813
11465
|
const record = value;
|
|
9814
11466
|
if (record.version !== 1 || record.owner !== CURSOR_SKILL_OWNER || typeof record.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record.contentSha256)) {
|
|
@@ -9822,7 +11474,7 @@ function readCursorSkillManifest(path) {
|
|
|
9822
11474
|
function cursorSkillStatus(cwd, scope) {
|
|
9823
11475
|
const paths = cursorSkillPaths(cwd, scope);
|
|
9824
11476
|
const manifest = readCursorSkillManifest(paths.manifest);
|
|
9825
|
-
const content =
|
|
11477
|
+
const content = existsSync12(paths.skill) ? readFileSync16(paths.skill, "utf8") : void 0;
|
|
9826
11478
|
const owned = manifest !== void 0;
|
|
9827
11479
|
const installed = owned && content !== void 0 && sha256(content) === manifest.contentSha256;
|
|
9828
11480
|
return {
|
|
@@ -9839,7 +11491,7 @@ function loadSkill(file = "SKILL.md") {
|
|
|
9839
11491
|
let dir = __dirname;
|
|
9840
11492
|
while (dir !== dirname11(dir)) {
|
|
9841
11493
|
const p = resolve4(dir, file);
|
|
9842
|
-
if (
|
|
11494
|
+
if (existsSync12(p)) return readFileSync16(p, "utf-8");
|
|
9843
11495
|
dir = dirname11(dir);
|
|
9844
11496
|
}
|
|
9845
11497
|
throw new Error(`${file} not found in package`);
|
|
@@ -9856,14 +11508,14 @@ var MAX_SKILL_BYTES = 1024 * 1024;
|
|
|
9856
11508
|
var REFRESH_LOCK_TIMEOUT_MS = 150;
|
|
9857
11509
|
var REFRESH_LOCK_POLL_MS = 10;
|
|
9858
11510
|
function pluginDirFor(cwd, scope) {
|
|
9859
|
-
const base = scope === "user" ?
|
|
9860
|
-
return
|
|
11511
|
+
const base = scope === "user" ? join21(homedir7(), ".claude") : join21(gitToplevel(cwd) ?? cwd, ".claude");
|
|
11512
|
+
return join21(base, "skills", "prim");
|
|
9861
11513
|
}
|
|
9862
11514
|
function packageVersion2() {
|
|
9863
11515
|
let dir = __dirname2;
|
|
9864
11516
|
while (dir !== dirname12(dir)) {
|
|
9865
11517
|
const p = resolve5(dir, "package.json");
|
|
9866
|
-
if (
|
|
11518
|
+
if (existsSync13(p)) return JSON.parse(readFileSync17(p, "utf-8")).version;
|
|
9867
11519
|
dir = dirname12(dir);
|
|
9868
11520
|
}
|
|
9869
11521
|
return "0.0.0";
|
|
@@ -9879,8 +11531,8 @@ function renderClaudePlugin() {
|
|
|
9879
11531
|
}
|
|
9880
11532
|
function pluginPaths(dir) {
|
|
9881
11533
|
return {
|
|
9882
|
-
manifestPath:
|
|
9883
|
-
skillPath:
|
|
11534
|
+
manifestPath: join21(dir, ".claude-plugin", "plugin.json"),
|
|
11535
|
+
skillPath: join21(dir, "SKILL.md")
|
|
9884
11536
|
};
|
|
9885
11537
|
}
|
|
9886
11538
|
function pathIsInside(root, path) {
|
|
@@ -9890,7 +11542,7 @@ function pathIsInside(root, path) {
|
|
|
9890
11542
|
function managedPathsAreSafe(paths, projectRoot2) {
|
|
9891
11543
|
try {
|
|
9892
11544
|
const managed = [paths.manifestPath, paths.skillPath];
|
|
9893
|
-
if (managed.some((path) => !
|
|
11545
|
+
if (managed.some((path) => !lstatSync10(path).isFile())) return false;
|
|
9894
11546
|
if (projectRoot2 === void 0) return true;
|
|
9895
11547
|
const realRoot = realpathSync3(projectRoot2);
|
|
9896
11548
|
return managed.every((path) => pathIsInside(realRoot, realpathSync3(path)));
|
|
@@ -9931,7 +11583,7 @@ function hasUsablePrimFrontmatter(skill) {
|
|
|
9931
11583
|
}
|
|
9932
11584
|
}
|
|
9933
11585
|
function inspectRecognizedInstallation(paths, projectRoot2) {
|
|
9934
|
-
if (!
|
|
11586
|
+
if (!existsSync13(paths.manifestPath) || !existsSync13(paths.skillPath)) return;
|
|
9935
11587
|
if (!managedPathsAreSafe(paths, projectRoot2)) return;
|
|
9936
11588
|
const manifest = readBoundedRegularFile(paths.manifestPath, MAX_MANIFEST_BYTES2);
|
|
9937
11589
|
const parsed = JSON.parse(manifest);
|
|
@@ -9945,9 +11597,9 @@ function inspectRecognizedInstallation(paths, projectRoot2) {
|
|
|
9945
11597
|
};
|
|
9946
11598
|
}
|
|
9947
11599
|
function refreshLockDir(physicalPluginDir) {
|
|
9948
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ||
|
|
9949
|
-
const identity =
|
|
9950
|
-
return
|
|
11600
|
+
const cacheRoot = process.env.XDG_CACHE_HOME || join21(homedir7(), ".cache");
|
|
11601
|
+
const identity = createHash11("sha256").update(physicalPluginDir).digest("hex");
|
|
11602
|
+
return join21(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
|
|
9951
11603
|
}
|
|
9952
11604
|
async function refreshClaudePlugins(cwd, options = {}) {
|
|
9953
11605
|
const result = { installed: 0, refreshed: 0 };
|
|
@@ -9955,7 +11607,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
9955
11607
|
if (options.includeProject !== false) {
|
|
9956
11608
|
const projectRoot2 = options.projectRoot ?? gitToplevel(cwd);
|
|
9957
11609
|
if (projectRoot2 !== null && isAbsolute6(projectRoot2)) {
|
|
9958
|
-
candidates.push({ dir:
|
|
11610
|
+
candidates.push({ dir: join21(projectRoot2, ".claude", "skills", "prim"), projectRoot: projectRoot2 });
|
|
9959
11611
|
}
|
|
9960
11612
|
}
|
|
9961
11613
|
candidates.push({ dir: pluginDirFor(cwd, "user") });
|
|
@@ -10003,7 +11655,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
10003
11655
|
};
|
|
10004
11656
|
try {
|
|
10005
11657
|
const paths = pluginPaths(dir);
|
|
10006
|
-
if (!
|
|
11658
|
+
if (!existsSync13(paths.manifestPath) || !existsSync13(paths.skillPath)) continue;
|
|
10007
11659
|
const physicalPluginDir = realpathSync3(dir);
|
|
10008
11660
|
if (seen.has(physicalPluginDir)) continue;
|
|
10009
11661
|
seen.add(physicalPluginDir);
|
|
@@ -10018,13 +11670,13 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
10018
11670
|
}
|
|
10019
11671
|
|
|
10020
11672
|
// src/daemon/principal.ts
|
|
10021
|
-
import { createHash as
|
|
11673
|
+
import { createHash as createHash12 } from "crypto";
|
|
10022
11674
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
10023
11675
|
function boundedClaim(value) {
|
|
10024
11676
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
10025
11677
|
}
|
|
10026
11678
|
function sha2562(value) {
|
|
10027
|
-
return
|
|
11679
|
+
return createHash12("sha256").update(value).digest("hex");
|
|
10028
11680
|
}
|
|
10029
11681
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
10030
11682
|
if (hasMachineConfiguration()) {
|
|
@@ -10078,14 +11730,14 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
10078
11730
|
|
|
10079
11731
|
// src/daemon/client.ts
|
|
10080
11732
|
import { createConnection } from "net";
|
|
10081
|
-
import { join as
|
|
10082
|
-
var SOCK_PATH =
|
|
11733
|
+
import { join as join22 } from "path";
|
|
11734
|
+
var SOCK_PATH = join22(primConfigDirectory(), "sock");
|
|
10083
11735
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
10084
11736
|
var nextRequestId = 1;
|
|
10085
11737
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
10086
11738
|
const id = nextRequestId++;
|
|
10087
11739
|
const caller = resolveDaemonPrincipal();
|
|
10088
|
-
const
|
|
11740
|
+
const request3 = {
|
|
10089
11741
|
id,
|
|
10090
11742
|
method,
|
|
10091
11743
|
params,
|
|
@@ -10124,7 +11776,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
10124
11776
|
});
|
|
10125
11777
|
socket.on("connect", () => {
|
|
10126
11778
|
try {
|
|
10127
|
-
socket?.write(`${JSON.stringify(
|
|
11779
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
10128
11780
|
`);
|
|
10129
11781
|
} catch {
|
|
10130
11782
|
clearTimeout(timer);
|
|
@@ -10385,206 +12037,16 @@ async function acknowledgeDecisionFeedback(input, dependencies = {}) {
|
|
|
10385
12037
|
}
|
|
10386
12038
|
}
|
|
10387
12039
|
|
|
10388
|
-
// src/lib/activation.ts
|
|
10389
|
-
import { execFileSync as execFileSync5 } from "child_process";
|
|
10390
|
-
import { existsSync as existsSync12, readFileSync as readFileSync15 } from "fs";
|
|
10391
|
-
import { homedir as homedir7 } from "os";
|
|
10392
|
-
import { join as join19 } from "path";
|
|
10393
|
-
|
|
10394
|
-
// src/lib/demo-pause.ts
|
|
10395
|
-
import { execFileSync as execFileSync4 } from "child_process";
|
|
10396
|
-
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
10397
|
-
var PAUSE_KEY = "prim.demoPause";
|
|
10398
|
-
var GIT_TIMEOUT_MS2 = 1e3;
|
|
10399
|
-
function git(cwd, args) {
|
|
10400
|
-
try {
|
|
10401
|
-
return execFileSync4("git", args, {
|
|
10402
|
-
cwd,
|
|
10403
|
-
encoding: "utf-8",
|
|
10404
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
10405
|
-
timeout: GIT_TIMEOUT_MS2
|
|
10406
|
-
});
|
|
10407
|
-
} catch {
|
|
10408
|
-
return void 0;
|
|
10409
|
-
}
|
|
10410
|
-
}
|
|
10411
|
-
function setLocal(cwd, key, value) {
|
|
10412
|
-
try {
|
|
10413
|
-
execFileSync4(
|
|
10414
|
-
"git",
|
|
10415
|
-
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
10416
|
-
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
|
|
10417
|
-
);
|
|
10418
|
-
} catch (error) {
|
|
10419
|
-
if (value !== null || error.status !== 5) throw error;
|
|
10420
|
-
}
|
|
10421
|
-
}
|
|
10422
|
-
function parsePause(value) {
|
|
10423
|
-
const [runId = "", until, previous, state] = value.trim().split(" ");
|
|
10424
|
-
const flag = previous === "true" || previous === "false" ? previous : "unset";
|
|
10425
|
-
return { runId, until: Number(until) || 0, previous: flag, ending: state !== "active" };
|
|
10426
|
-
}
|
|
10427
|
-
function readCaptureConfig(cwd) {
|
|
10428
|
-
let active;
|
|
10429
|
-
let pause;
|
|
10430
|
-
const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
10431
|
-
for (const line of out.split("\n")) {
|
|
10432
|
-
const space = line.indexOf(" ");
|
|
10433
|
-
const key = line.slice(0, space).toLowerCase();
|
|
10434
|
-
const value = line.slice(space + 1);
|
|
10435
|
-
if (key === "prim.active") active = value === "true" || value === "false" ? value : void 0;
|
|
10436
|
-
if (key === "prim.demopause") pause = parsePause(value);
|
|
10437
|
-
}
|
|
10438
|
-
return { active, pause };
|
|
10439
|
-
}
|
|
10440
|
-
function resumeCapture(cwd, pause) {
|
|
10441
|
-
setLocal(cwd, "prim.active", pause.previous === "unset" ? null : pause.previous);
|
|
10442
|
-
setLocal(cwd, PAUSE_KEY, null);
|
|
10443
|
-
}
|
|
10444
|
-
function healDemoPause(cwd, pause, options = {}) {
|
|
10445
|
-
if (pause.until > (options.now ?? Date.now()) && !(pause.ending && options.userPrompt))
|
|
10446
|
-
return false;
|
|
10447
|
-
try {
|
|
10448
|
-
resumeCapture(cwd, pause);
|
|
10449
|
-
return true;
|
|
10450
|
-
} catch {
|
|
10451
|
-
return false;
|
|
10452
|
-
}
|
|
10453
|
-
}
|
|
10454
|
-
|
|
10455
|
-
// src/lib/activation.ts
|
|
10456
|
-
var PRIM_ACTIVE_KEY = "prim.active";
|
|
10457
|
-
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
10458
|
-
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
10459
|
-
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
10460
|
-
var GIT_TIMEOUT_MS3 = 1e3;
|
|
10461
|
-
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
10462
|
-
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
10463
|
-
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
10464
|
-
function repoActiveFlag(cwd, strict = false) {
|
|
10465
|
-
try {
|
|
10466
|
-
const value = execFileSync5("git", ["config", "--get", PRIM_ACTIVE_KEY], {
|
|
10467
|
-
cwd,
|
|
10468
|
-
encoding: "utf-8",
|
|
10469
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
10470
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10471
|
-
}).trim();
|
|
10472
|
-
if (value === "true") return "true";
|
|
10473
|
-
if (value === "false") return "false";
|
|
10474
|
-
if (strict) throw new Error("Repository activation is invalid");
|
|
10475
|
-
return void 0;
|
|
10476
|
-
} catch (error) {
|
|
10477
|
-
if (strict && !(typeof error === "object" && error !== null && "status" in error && error.status === 1))
|
|
10478
|
-
throw error;
|
|
10479
|
-
return void 0;
|
|
10480
|
-
}
|
|
10481
|
-
}
|
|
10482
|
-
function setRepoActive(cwd, active) {
|
|
10483
|
-
execFileSync5("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
|
|
10484
|
-
cwd,
|
|
10485
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
10486
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10487
|
-
});
|
|
10488
|
-
}
|
|
10489
|
-
function isValidRepoSyncId(value) {
|
|
10490
|
-
return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
|
|
10491
|
-
}
|
|
10492
|
-
function localGitConfigValue(cwd, key) {
|
|
10493
|
-
try {
|
|
10494
|
-
const value = execFileSync5("git", ["config", "--local", "--get", key], {
|
|
10495
|
-
cwd,
|
|
10496
|
-
encoding: "utf-8",
|
|
10497
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
10498
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10499
|
-
}).trim();
|
|
10500
|
-
return value || void 0;
|
|
10501
|
-
} catch {
|
|
10502
|
-
return void 0;
|
|
10503
|
-
}
|
|
10504
|
-
}
|
|
10505
|
-
function setLocalGitConfigValue(cwd, key, value) {
|
|
10506
|
-
execFileSync5("git", ["config", "--local", key, value], {
|
|
10507
|
-
cwd,
|
|
10508
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
10509
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10510
|
-
});
|
|
10511
|
-
}
|
|
10512
|
-
function repoSyncId(cwd) {
|
|
10513
|
-
const value = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
10514
|
-
if (!isValidRepoSyncId(value)) return void 0;
|
|
10515
|
-
const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
|
|
10516
|
-
return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
|
|
10517
|
-
}
|
|
10518
|
-
function setRepoSyncId(cwd, value, repositoryFullName) {
|
|
10519
|
-
if (!isValidRepoSyncId(value)) {
|
|
10520
|
-
throw new Error("invalid repository binding returned by server");
|
|
10521
|
-
}
|
|
10522
|
-
execFileSync5("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
|
|
10523
|
-
cwd,
|
|
10524
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
10525
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10526
|
-
});
|
|
10527
|
-
execFileSync5("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
|
|
10528
|
-
cwd,
|
|
10529
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
10530
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10531
|
-
});
|
|
10532
|
-
}
|
|
10533
|
-
function setRepositoryBindingState(cwd, state) {
|
|
10534
|
-
if (state !== "connected" && state !== "unbound" && state !== "invalid") {
|
|
10535
|
-
throw new Error("invalid repository binding state");
|
|
10536
|
-
}
|
|
10537
|
-
execFileSync5("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
|
|
10538
|
-
cwd,
|
|
10539
|
-
stdio: ["ignore", "ignore", "pipe"],
|
|
10540
|
-
timeout: GIT_TIMEOUT_MS3
|
|
10541
|
-
});
|
|
10542
|
-
}
|
|
10543
|
-
function repositoryBindingState(cwd) {
|
|
10544
|
-
const rawId = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
10545
|
-
const marker = localGitConfigValue(cwd, PRIM_REPO_BINDING_STATE_KEY);
|
|
10546
|
-
if (rawId !== void 0 && !isValidRepoSyncId(rawId)) return "invalid";
|
|
10547
|
-
if (marker === "unbound" || marker === "invalid") return marker;
|
|
10548
|
-
if (marker === "connected") return repoSyncId(cwd) ? "connected" : "invalid";
|
|
10549
|
-
if (marker !== void 0) return "invalid";
|
|
10550
|
-
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
10551
|
-
}
|
|
10552
|
-
function hasProjectPrimInstall(cwd) {
|
|
10553
|
-
const root = gitToplevel(cwd);
|
|
10554
|
-
if (root === null || root === homedir7()) return false;
|
|
10555
|
-
for (const rel of PROJECT_INSTALL_FILES) {
|
|
10556
|
-
const path = join19(root, rel);
|
|
10557
|
-
if (existsSync12(path)) {
|
|
10558
|
-
try {
|
|
10559
|
-
const content = readFileSync15(path, "utf-8");
|
|
10560
|
-
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
10561
|
-
} catch {
|
|
10562
|
-
}
|
|
10563
|
-
}
|
|
10564
|
-
}
|
|
10565
|
-
return false;
|
|
10566
|
-
}
|
|
10567
|
-
function isRepoActiveForCapture(cwd, options = {}) {
|
|
10568
|
-
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
10569
|
-
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
10570
|
-
if (flag === "true") return true;
|
|
10571
|
-
if (flag === "false") return false;
|
|
10572
|
-
return hasProjectPrimInstall(cwd);
|
|
10573
|
-
}
|
|
10574
|
-
function decisionIngestionStatus(cwd) {
|
|
10575
|
-
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
10576
|
-
}
|
|
10577
|
-
|
|
10578
12040
|
// src/lib/bin-cache.ts
|
|
10579
|
-
import { chmodSync as chmodSync5, mkdirSync as
|
|
12041
|
+
import { chmodSync as chmodSync5, mkdirSync as mkdirSync8 } from "fs";
|
|
10580
12042
|
import { homedir as homedir8 } from "os";
|
|
10581
|
-
import { join as
|
|
12043
|
+
import { join as join23 } from "path";
|
|
10582
12044
|
var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
|
|
10583
12045
|
var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
|
|
10584
12046
|
var GIT_HOOK_CACHED_BINS = ["prim-post-commit", "prim-post-rewrite"];
|
|
10585
12047
|
function binCacheDir() {
|
|
10586
|
-
const base = process.env.XDG_CACHE_HOME ||
|
|
10587
|
-
return
|
|
12048
|
+
const base = process.env.XDG_CACHE_HOME || join23(homedir8(), ".cache");
|
|
12049
|
+
return join23(base, "prim", "bin");
|
|
10588
12050
|
}
|
|
10589
12051
|
function writeAtomic(path, content) {
|
|
10590
12052
|
atomicWriteFile(path, content, { mode: 384 });
|
|
@@ -10595,19 +12057,108 @@ function warmBinCache() {
|
|
|
10595
12057
|
return;
|
|
10596
12058
|
}
|
|
10597
12059
|
const dir = binCacheDir();
|
|
10598
|
-
|
|
12060
|
+
mkdirSync8(dir, { recursive: true, mode: 448 });
|
|
10599
12061
|
chmodSync5(dir, 448);
|
|
10600
|
-
writeAtomic(
|
|
12062
|
+
writeAtomic(join23(dir, "node"), process.execPath);
|
|
10601
12063
|
for (const bin of GIT_HOOK_CACHED_BINS) {
|
|
10602
12064
|
const file = binFile(bin);
|
|
10603
12065
|
if (file) {
|
|
10604
|
-
writeAtomic(
|
|
12066
|
+
writeAtomic(join23(dir, bin), file);
|
|
10605
12067
|
}
|
|
10606
12068
|
}
|
|
10607
12069
|
} catch {
|
|
10608
12070
|
}
|
|
10609
12071
|
}
|
|
10610
12072
|
|
|
12073
|
+
// src/lib/cloud-session.ts
|
|
12074
|
+
var PRODUCTION_SIGN_IN_HOST = "signin.getprimitive.ai";
|
|
12075
|
+
var PROBE_TIMEOUT_MS = 3e3;
|
|
12076
|
+
function repositoryIdentityRemedy(root) {
|
|
12077
|
+
return originIdentifiesRepository(root) ? "this checkout's origin is not a GitHub repository in owner/name form; Primitive connects GitHub repositories only" : "this checkout does not identify its GitHub repository. Commit the repository declaration: run `prim claude install --scope project` in a clone whose origin is on GitHub, which records PRIM_REPOSITORY in .claude/settings.json";
|
|
12078
|
+
}
|
|
12079
|
+
function hostOf2(url, fallback) {
|
|
12080
|
+
try {
|
|
12081
|
+
return new URL(url).hostname || fallback;
|
|
12082
|
+
} catch {
|
|
12083
|
+
return fallback;
|
|
12084
|
+
}
|
|
12085
|
+
}
|
|
12086
|
+
function cloudAllowedDomains(siteUrl = getSiteUrl(), signInHost = PRODUCTION_SIGN_IN_HOST, env = process.env) {
|
|
12087
|
+
const api = hostOf2(siteUrl, "api.getprimitive.ai");
|
|
12088
|
+
return env.PRIM_M2M_CLIENT_AUTH === NETWORK_TOKEN_AUTH ? [api] : [.../* @__PURE__ */ new Set([api, signInHost])];
|
|
12089
|
+
}
|
|
12090
|
+
function cloudEgressRemedy(siteUrl, signInHost, env) {
|
|
12091
|
+
return `add ${cloudAllowedDomains(siteUrl, signInHost, env).join(" and ")} to the cloud environment's Allowed domains (Network access: Limited), then start a new cloud session (a running session keeps the network rules it started with)`;
|
|
12092
|
+
}
|
|
12093
|
+
function probeFailure(error) {
|
|
12094
|
+
const name = error instanceof Error ? error.name : "";
|
|
12095
|
+
if (name === "TimeoutError" || name === "AbortError") return "timeout";
|
|
12096
|
+
const cause = error?.cause;
|
|
12097
|
+
const code = typeof cause?.code === "string" ? cause.code : "";
|
|
12098
|
+
const message = typeof cause?.message === "string" ? cause.message : "";
|
|
12099
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "blocked";
|
|
12100
|
+
if (/cancel|tunnel|\(403\)/iu.test(message) && !/\(5\d\d\)/u.test(message)) return "blocked";
|
|
12101
|
+
return code || "network error";
|
|
12102
|
+
}
|
|
12103
|
+
async function probe(url, fetchImpl) {
|
|
12104
|
+
try {
|
|
12105
|
+
const response = await fetchImpl(url, {
|
|
12106
|
+
redirect: "manual",
|
|
12107
|
+
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
|
|
12108
|
+
});
|
|
12109
|
+
return { ok: true, response };
|
|
12110
|
+
} catch (error) {
|
|
12111
|
+
return { ok: false, failure: probeFailure(error) };
|
|
12112
|
+
}
|
|
12113
|
+
}
|
|
12114
|
+
function unreachable(what, failure2, remedy) {
|
|
12115
|
+
if (failure2 === "blocked") return `this environment cannot reach ${what}. To fix it, ${remedy}.`;
|
|
12116
|
+
if (failure2 === "timeout")
|
|
12117
|
+
return `${what} did not answer in time. If this persists, check that you ${remedy.replace(/^add /u, "added ")}.`;
|
|
12118
|
+
return `${what} could not be reached (${failure2}). Check the environment's network access: ${remedy}.`;
|
|
12119
|
+
}
|
|
12120
|
+
function credentialRejected(error) {
|
|
12121
|
+
return error instanceof HttpError && error.status === 401;
|
|
12122
|
+
}
|
|
12123
|
+
async function diagnoseCloudSession(options = {}) {
|
|
12124
|
+
const env = options.env ?? process.env;
|
|
12125
|
+
if (!isClaudeCloudSession(env)) return void 0;
|
|
12126
|
+
const prefix = "Primitive is not connected in this Claude Code cloud session";
|
|
12127
|
+
let machine;
|
|
12128
|
+
try {
|
|
12129
|
+
machine = hasMachineConfiguration({ env });
|
|
12130
|
+
} catch (error) {
|
|
12131
|
+
if (error instanceof MachineAuthError && (error.code === "conflicting_credentials" || env.PRIM_M2M_CLIENT_AUTH !== void 0))
|
|
12132
|
+
return `${prefix}: ${error.message}`;
|
|
12133
|
+
return `${prefix}: ${error instanceof MachineAuthError ? error.message : "its machine credentials are incomplete."} To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
|
|
12134
|
+
}
|
|
12135
|
+
if (!machine && !resolveStoredCredential(env))
|
|
12136
|
+
return `${prefix}: it has no credentials. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
|
|
12137
|
+
if (machine && credentialRejected(options.bindFailure)) return CLOUD_REJECTED_CREDENTIALS_NOTICE;
|
|
12138
|
+
if (options.cwd !== void 0 && !githubRepositoryFullName(options.cwd))
|
|
12139
|
+
return `${prefix}: ${repositoryIdentityRemedy(options.cwd)}.`;
|
|
12140
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
12141
|
+
const siteUrl = options.siteUrl ?? getSiteUrl();
|
|
12142
|
+
const config = await probe(`${siteUrl.replace(/\/+$/u, "")}/api/cli/auth/m2m/config`, fetchImpl);
|
|
12143
|
+
if (!config.ok)
|
|
12144
|
+
return `${prefix}: ${unreachable("Primitive", config.failure, cloudEgressRemedy(siteUrl, void 0, env))}`;
|
|
12145
|
+
if (machine && env.PRIM_M2M_CLIENT_AUTH !== NETWORK_TOKEN_AUTH) {
|
|
12146
|
+
let issuer;
|
|
12147
|
+
try {
|
|
12148
|
+
const body = await config.response.json();
|
|
12149
|
+
issuer = typeof body.issuer === "string" ? machineApiUrl(body.issuer) : void 0;
|
|
12150
|
+
} catch {
|
|
12151
|
+
issuer = void 0;
|
|
12152
|
+
}
|
|
12153
|
+
if (issuer) {
|
|
12154
|
+
const signIn = await probe(issuer, fetchImpl);
|
|
12155
|
+
if (!signIn.ok)
|
|
12156
|
+
return `${prefix}: ${unreachable("Primitive's sign-in service", signIn.failure, cloudEgressRemedy(siteUrl, hostOf2(issuer, PRODUCTION_SIGN_IN_HOST)))}`;
|
|
12157
|
+
}
|
|
12158
|
+
}
|
|
12159
|
+
return `${prefix}: the repository could not be connected. Run \`prim setup --cloud\` for details.`;
|
|
12160
|
+
}
|
|
12161
|
+
|
|
10611
12162
|
// src/generated/cli-http-v1.validators.js
|
|
10612
12163
|
var import_ucs2length = __toESM(require_ucs2length(), 1);
|
|
10613
12164
|
var schema33 = { "anyOf": [{ "type": "object", "properties": { "authenticated": { "type": "boolean", "const": true }, "organizationBindingVersion": { "type": "number", "const": 1 }, "captureAuthorityKind": { "type": "string", "enum": ["workos", "service_token"] }, "organizationId": { "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }] }, "workosOrganizationId": { "anyOf": [{ "type": "string", "minLength": 1 }, { "type": "null" }] } }, "required": ["authenticated", "organizationBindingVersion", "captureAuthorityKind", "organizationId", "workosOrganizationId"], "additionalProperties": false }, { "type": "object", "properties": { "authenticated": { "type": "boolean", "const": true }, "organizationBindingVersion": { "type": "number", "const": 2 }, "captureAuthorityKind": { "type": "string", "const": "workos_m2m" }, "organizationId": { "type": "string", "minLength": 1 }, "workosOrganizationId": { "type": "string", "minLength": 1 }, "principal": { "type": "object", "properties": { "kind": { "type": "string", "const": "machine" }, "machineId": { "type": "string", "minLength": 1 }, "clientId": { "type": "string", "minLength": 1 }, "displayName": { "type": "string", "minLength": 1 }, "scopes": { "type": "array", "items": { "type": "string" } } }, "required": ["kind", "machineId", "clientId", "displayName", "scopes"], "additionalProperties": false } }, "required": ["authenticated", "organizationBindingVersion", "captureAuthorityKind", "organizationId", "workosOrganizationId", "principal"], "additionalProperties": false }, { "type": "object", "properties": { "authenticated": { "type": "boolean", "const": true }, "organizationBindingVersion": { "type": "number", "const": 3 }, "captureAuthorityKind": { "type": "string", "const": "workos_m2m" }, "organizationId": { "type": "string", "minLength": 1 }, "workosOrganizationId": { "type": "string", "minLength": 1 }, "principal": { "type": "object", "properties": { "kind": { "type": "string", "const": "machine" }, "machineId": { "type": "string", "minLength": 1 }, "clientId": { "type": "string", "minLength": 1 }, "displayName": { "type": "string", "minLength": 1 }, "scopes": { "type": "array", "items": { "type": "string" } }, "authorizedUserId": { "type": "string", "minLength": 1 } }, "required": ["kind", "machineId", "clientId", "displayName", "scopes", "authorizedUserId"], "additionalProperties": false } }, "required": ["authenticated", "organizationBindingVersion", "captureAuthorityKind", "organizationId", "workosOrganizationId", "principal"], "additionalProperties": false }] };
|
|
@@ -37421,24 +38972,24 @@ async function fetchAndCacheCollectScope(cwd, dependencies = defaultDependencies
|
|
|
37421
38972
|
|
|
37422
38973
|
// src/lib/commit-heartbeat.ts
|
|
37423
38974
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
37424
|
-
import { mkdirSync as
|
|
37425
|
-
import { dirname as dirname13, join as
|
|
38975
|
+
import { mkdirSync as mkdirSync9, readFileSync as readFileSync18, readdirSync as readdirSync6, unlinkSync as unlinkSync3 } from "fs";
|
|
38976
|
+
import { dirname as dirname13, join as join24, resolve as resolve6 } from "path";
|
|
37426
38977
|
var WIRED_PATH = "prim/git-hooks-wired";
|
|
37427
|
-
var
|
|
38978
|
+
var GIT_TIMEOUT_MS5 = 1e3;
|
|
37428
38979
|
var MAX_STAMP_BYTES = 1024;
|
|
37429
38980
|
function commonPath(cwd, relative4) {
|
|
37430
38981
|
const value = execFileSync6("git", ["rev-parse", "--git-common-dir"], {
|
|
37431
38982
|
cwd,
|
|
37432
38983
|
encoding: "utf8",
|
|
37433
38984
|
stdio: ["ignore", "pipe", "ignore"],
|
|
37434
|
-
timeout:
|
|
38985
|
+
timeout: GIT_TIMEOUT_MS5
|
|
37435
38986
|
}).replace(/\r?\n$/u, "");
|
|
37436
38987
|
if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
|
|
37437
|
-
return
|
|
38988
|
+
return join24(resolve6(cwd, value), relative4);
|
|
37438
38989
|
}
|
|
37439
38990
|
function ensurePrivateParent(path) {
|
|
37440
|
-
|
|
37441
|
-
|
|
38991
|
+
mkdirSync9(dirname13(dirname13(path)), { recursive: true, mode: 448 });
|
|
38992
|
+
mkdirSync9(dirname13(path), { recursive: true, mode: 448 });
|
|
37442
38993
|
}
|
|
37443
38994
|
function writeStamp(path, at) {
|
|
37444
38995
|
ensurePrivateParent(path);
|
|
@@ -37447,7 +38998,7 @@ function writeStamp(path, at) {
|
|
|
37447
38998
|
}
|
|
37448
38999
|
function readStampAt(path) {
|
|
37449
39000
|
try {
|
|
37450
|
-
const raw =
|
|
39001
|
+
const raw = readFileSync18(path, "utf8");
|
|
37451
39002
|
if (raw.length > MAX_STAMP_BYTES) return void 0;
|
|
37452
39003
|
const parsed = JSON.parse(raw);
|
|
37453
39004
|
return typeof parsed.at === "number" && Number.isSafeInteger(parsed.at) && parsed.at > 0 ? parsed.at : void 0;
|
|
@@ -37472,23 +39023,23 @@ function clearHooksWired(cwd) {
|
|
|
37472
39023
|
|
|
37473
39024
|
// src/lib/git-hooks.ts
|
|
37474
39025
|
import { execFileSync as execFileSync7 } from "child_process";
|
|
37475
|
-
import { createHash as
|
|
39026
|
+
import { createHash as createHash13, randomUUID as randomUUID3 } from "crypto";
|
|
37476
39027
|
import {
|
|
37477
39028
|
constants as constants5,
|
|
37478
39029
|
closeSync as closeSync4,
|
|
37479
|
-
existsSync as
|
|
39030
|
+
existsSync as existsSync14,
|
|
37480
39031
|
fchmodSync as fchmodSync2,
|
|
37481
39032
|
fsyncSync as fsyncSync2,
|
|
37482
|
-
lstatSync as
|
|
37483
|
-
mkdirSync as
|
|
39033
|
+
lstatSync as lstatSync11,
|
|
39034
|
+
mkdirSync as mkdirSync10,
|
|
37484
39035
|
openSync as openSync4,
|
|
37485
|
-
readFileSync as
|
|
39036
|
+
readFileSync as readFileSync19,
|
|
37486
39037
|
realpathSync as realpathSync4,
|
|
37487
39038
|
renameSync as renameSync3,
|
|
37488
39039
|
unlinkSync as unlinkSync4,
|
|
37489
|
-
writeFileSync as
|
|
39040
|
+
writeFileSync as writeFileSync6
|
|
37490
39041
|
} from "fs";
|
|
37491
|
-
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as
|
|
39042
|
+
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as join25, relative as relative3, resolve as resolve7, sep as sep3 } from "path";
|
|
37492
39043
|
|
|
37493
39044
|
// src/lib/git-hook-legacy.ts
|
|
37494
39045
|
import { isAbsolute as isAbsolute7 } from "path";
|
|
@@ -37667,7 +39218,7 @@ var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
|
|
|
37667
39218
|
var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
|
|
37668
39219
|
var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
|
|
37669
39220
|
var MAX_HOOK_BYTES = 1048576;
|
|
37670
|
-
var
|
|
39221
|
+
var GIT_TIMEOUT_MS6 = 1e3;
|
|
37671
39222
|
var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
|
|
37672
39223
|
"#!/bin/sh",
|
|
37673
39224
|
"#!/usr/bin/env sh",
|
|
@@ -37717,7 +39268,7 @@ function gitHooksMode(options = {}) {
|
|
|
37717
39268
|
cwd: options.cwd,
|
|
37718
39269
|
encoding: "utf8",
|
|
37719
39270
|
stdio: ["ignore", "pipe", "ignore"],
|
|
37720
|
-
timeout:
|
|
39271
|
+
timeout: GIT_TIMEOUT_MS6
|
|
37721
39272
|
}
|
|
37722
39273
|
).trim();
|
|
37723
39274
|
return value === "manual" ? "manual" : "auto";
|
|
@@ -37797,7 +39348,7 @@ function realpathLoose(path) {
|
|
|
37797
39348
|
let current = resolve7(path);
|
|
37798
39349
|
for (; ; ) {
|
|
37799
39350
|
try {
|
|
37800
|
-
return
|
|
39351
|
+
return join25(realpathSync4.native(current), ...missing);
|
|
37801
39352
|
} catch {
|
|
37802
39353
|
const parent = dirname14(current);
|
|
37803
39354
|
if (parent === current) return resolve7(path);
|
|
@@ -37812,7 +39363,7 @@ function isWithin(path, directory) {
|
|
|
37812
39363
|
}
|
|
37813
39364
|
function primGitHooksDirectory() {
|
|
37814
39365
|
try {
|
|
37815
|
-
return
|
|
39366
|
+
return join25(primConfigDirectory(), "git-hooks");
|
|
37816
39367
|
} catch {
|
|
37817
39368
|
return void 0;
|
|
37818
39369
|
}
|
|
@@ -37824,7 +39375,7 @@ function otherWorktreeRoots(gitRoot) {
|
|
|
37824
39375
|
cwd: gitRoot,
|
|
37825
39376
|
encoding: "utf8",
|
|
37826
39377
|
stdio: ["ignore", "pipe", "ignore"],
|
|
37827
|
-
timeout:
|
|
39378
|
+
timeout: GIT_TIMEOUT_MS6
|
|
37828
39379
|
}).split("\n").flatMap((line) => line.startsWith("worktree ") ? [realpathLoose(line.slice(9))] : []).filter((root) => root !== self);
|
|
37829
39380
|
} catch {
|
|
37830
39381
|
return [];
|
|
@@ -37858,7 +39409,7 @@ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
|
|
|
37858
39409
|
cwd: gitRoot,
|
|
37859
39410
|
encoding: "utf8",
|
|
37860
39411
|
stdio: ["ignore", "pipe", "ignore"],
|
|
37861
|
-
timeout:
|
|
39412
|
+
timeout: GIT_TIMEOUT_MS6
|
|
37862
39413
|
}
|
|
37863
39414
|
).replace(/\r?\n$/u, "").split(/\r?\n/u);
|
|
37864
39415
|
if (lines.length !== 3) throw new Error("Git returned unexpected repository paths");
|
|
@@ -37890,8 +39441,8 @@ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
|
|
|
37890
39441
|
};
|
|
37891
39442
|
}
|
|
37892
39443
|
function assertSafeFile(path, spec) {
|
|
37893
|
-
if (!
|
|
37894
|
-
const stat =
|
|
39444
|
+
if (!existsSync14(path)) return void 0;
|
|
39445
|
+
const stat = lstatSync11(path);
|
|
37895
39446
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_HOOK_BYTES) {
|
|
37896
39447
|
throw new Error(`unsafe ${spec.hookName} hook target: ${path}`);
|
|
37897
39448
|
}
|
|
@@ -37915,13 +39466,13 @@ function assertUsableHuskyDispatcher(target, spec) {
|
|
|
37915
39466
|
const huskyRuntime = resolve7(dirname14(target.dispatcherPath), "h");
|
|
37916
39467
|
const runtimeStat = assertSafeFile(huskyRuntime, spec);
|
|
37917
39468
|
const runtime = runtimeStat ? readHookFile(huskyRuntime) : void 0;
|
|
37918
|
-
const runtimeHash = runtime ?
|
|
39469
|
+
const runtimeHash = runtime ? createHash13("sha256").update(runtime).digest("hex") : void 0;
|
|
37919
39470
|
if (!runtimeHash || !HUSKY_V9_RUNTIME_HASHES.has(runtimeHash)) {
|
|
37920
39471
|
throw new Error(`unrecognized Husky v9 hook runtime: ${huskyRuntime}`);
|
|
37921
39472
|
}
|
|
37922
39473
|
}
|
|
37923
39474
|
function readHookFile(path) {
|
|
37924
|
-
const value =
|
|
39475
|
+
const value = readFileSync19(path);
|
|
37925
39476
|
return Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
37926
39477
|
}
|
|
37927
39478
|
function decodeHookText(content, spec) {
|
|
@@ -37993,11 +39544,11 @@ function blockInsertionPoint(content, spec, huskyV8) {
|
|
|
37993
39544
|
var HUSKY_SPEC_MAJOR_RE = /^\s*[~^]?=?\s*v?([0-9]+)(?:\.(?:[0-9]+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?\s*$/u;
|
|
37994
39545
|
function declaredHuskyMajor(dir) {
|
|
37995
39546
|
for (let current = resolve7(dir); ; ) {
|
|
37996
|
-
const manifest =
|
|
37997
|
-
if (
|
|
39547
|
+
const manifest = join25(current, "package.json");
|
|
39548
|
+
if (existsSync14(manifest)) {
|
|
37998
39549
|
try {
|
|
37999
|
-
if (
|
|
38000
|
-
const parsed = JSON.parse(
|
|
39550
|
+
if (lstatSync11(manifest).size > MAX_HOOK_BYTES) return void 0;
|
|
39551
|
+
const parsed = JSON.parse(readFileSync19(manifest, "utf8"));
|
|
38001
39552
|
const range = parsed.devDependencies?.husky ?? parsed.dependencies?.husky;
|
|
38002
39553
|
const major = typeof range === "string" ? HUSKY_SPEC_MAJOR_RE.exec(range)?.[1] : void 0;
|
|
38003
39554
|
return major === void 0 ? void 0 : Number(major);
|
|
@@ -38006,15 +39557,15 @@ function declaredHuskyMajor(dir) {
|
|
|
38006
39557
|
}
|
|
38007
39558
|
}
|
|
38008
39559
|
const parent = dirname14(current);
|
|
38009
|
-
if (parent === current ||
|
|
39560
|
+
if (parent === current || existsSync14(join25(current, ".git"))) return void 0;
|
|
38010
39561
|
current = parent;
|
|
38011
39562
|
}
|
|
38012
39563
|
}
|
|
38013
39564
|
function isHuskyV8Hook(hookPath) {
|
|
38014
|
-
const runtime =
|
|
39565
|
+
const runtime = join25(dirname14(hookPath), "_", "husky.sh");
|
|
38015
39566
|
try {
|
|
38016
|
-
const stat =
|
|
38017
|
-
return stat.isFile() && stat.size <= MAX_HOOK_BYTES &&
|
|
39567
|
+
const stat = lstatSync11(runtime);
|
|
39568
|
+
return stat.isFile() && stat.size <= MAX_HOOK_BYTES && readFileSync19(runtime, "utf8").includes("husky_skip_init");
|
|
38018
39569
|
} catch (error) {
|
|
38019
39570
|
if (errorCode(error) !== "ENOENT") return false;
|
|
38020
39571
|
}
|
|
@@ -38155,7 +39706,7 @@ function errorCode(error) {
|
|
|
38155
39706
|
function assertTargetUnchanged(path, expected, spec, stat) {
|
|
38156
39707
|
let current;
|
|
38157
39708
|
try {
|
|
38158
|
-
current =
|
|
39709
|
+
current = lstatSync11(path);
|
|
38159
39710
|
} catch (error) {
|
|
38160
39711
|
if (expected === void 0 && errorCode(error) === "ENOENT") return;
|
|
38161
39712
|
throw new Error(`${spec.hookName} hook changed concurrently: ${path}`);
|
|
@@ -38169,7 +39720,7 @@ function assertTargetUnchanged(path, expected, spec, stat) {
|
|
|
38169
39720
|
}
|
|
38170
39721
|
function rewriteHookAtomically(path, next, expected, spec, stat) {
|
|
38171
39722
|
const parent = dirname14(path);
|
|
38172
|
-
|
|
39723
|
+
mkdirSync10(parent, { recursive: true });
|
|
38173
39724
|
const temporary = resolve7(
|
|
38174
39725
|
parent,
|
|
38175
39726
|
`.${basename3(path)}.prim-${String(process.pid)}-${randomUUID3()}.tmp`
|
|
@@ -38181,7 +39732,7 @@ function rewriteHookAtomically(path, next, expected, spec, stat) {
|
|
|
38181
39732
|
constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW,
|
|
38182
39733
|
stat?.mode ?? 493
|
|
38183
39734
|
);
|
|
38184
|
-
|
|
39735
|
+
writeFileSync6(fd, next);
|
|
38185
39736
|
fchmodSync2(fd, (stat?.mode ?? 493) & 4095);
|
|
38186
39737
|
fsyncSync2(fd);
|
|
38187
39738
|
closeSync4(fd);
|
|
@@ -38269,7 +39820,9 @@ var InvalidRepositoryBindingResponseError = class extends Error {
|
|
|
38269
39820
|
async function resolveRepositoryBindingWithClient(root, client, options) {
|
|
38270
39821
|
const repositoryFullName = githubRepositoryFullName(root);
|
|
38271
39822
|
if (!repositoryFullName) {
|
|
38272
|
-
throw new Error(
|
|
39823
|
+
throw new Error(
|
|
39824
|
+
originIdentifiesRepository(root) ? "origin must be a GitHub HTTPS/SSH remote in owner/name form" : "origin does not identify this checkout's repository; commit its repository declaration (`prim claude install --scope project`, run in a clone whose origin is on GitHub, records PRIM_REPOSITORY in .claude/settings.json)"
|
|
39825
|
+
);
|
|
38273
39826
|
}
|
|
38274
39827
|
let response;
|
|
38275
39828
|
try {
|
|
@@ -38328,17 +39881,17 @@ import {
|
|
|
38328
39881
|
closeSync as closeSync5,
|
|
38329
39882
|
fchmodSync as fchmodSync3,
|
|
38330
39883
|
fsyncSync as fsyncSync3,
|
|
38331
|
-
linkSync,
|
|
38332
|
-
lstatSync as
|
|
38333
|
-
mkdirSync as
|
|
39884
|
+
linkSync as linkSync2,
|
|
39885
|
+
lstatSync as lstatSync12,
|
|
39886
|
+
mkdirSync as mkdirSync11,
|
|
38334
39887
|
openSync as openSync5,
|
|
38335
|
-
readFileSync as
|
|
39888
|
+
readFileSync as readFileSync20,
|
|
38336
39889
|
statSync as statSync3,
|
|
38337
39890
|
unlinkSync as unlinkSync5,
|
|
38338
|
-
writeFileSync as
|
|
39891
|
+
writeFileSync as writeFileSync7
|
|
38339
39892
|
} from "fs";
|
|
38340
|
-
import { dirname as dirname15, isAbsolute as isAbsolute9, join as
|
|
38341
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
39893
|
+
import { dirname as dirname15, isAbsolute as isAbsolute9, join as join26, resolve as resolve8 } from "path";
|
|
39894
|
+
var WORKSPACE_ID_RELATIVE_PATH = join26("prim", "workspace-id");
|
|
38342
39895
|
var MAX_ANCESTORS = 64;
|
|
38343
39896
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
38344
39897
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -38397,19 +39950,19 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
38397
39950
|
function resolveFromFilesystem(cwd) {
|
|
38398
39951
|
let current = resolve8(cwd);
|
|
38399
39952
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
38400
|
-
const dotGit =
|
|
39953
|
+
const dotGit = join26(current, ".git");
|
|
38401
39954
|
try {
|
|
38402
|
-
const stat =
|
|
39955
|
+
const stat = lstatSync12(dotGit);
|
|
38403
39956
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
38404
|
-
return
|
|
39957
|
+
return join26(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
38405
39958
|
}
|
|
38406
39959
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
38407
|
-
const contents =
|
|
39960
|
+
const contents = readFileSync20(dotGit, "utf8");
|
|
38408
39961
|
const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
|
|
38409
39962
|
if (match?.[1]) {
|
|
38410
39963
|
const gitDirectory = isAbsolute9(match[1]) ? resolve8(match[1]) : resolve8(current, match[1]);
|
|
38411
39964
|
if (isGitDirectory(gitDirectory)) {
|
|
38412
|
-
return
|
|
39965
|
+
return join26(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
38413
39966
|
}
|
|
38414
39967
|
}
|
|
38415
39968
|
}
|
|
@@ -38428,7 +39981,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
38428
39981
|
}
|
|
38429
39982
|
function isGitDirectory(path) {
|
|
38430
39983
|
try {
|
|
38431
|
-
return statSync3(
|
|
39984
|
+
return statSync3(join26(path, "HEAD")).isFile();
|
|
38432
39985
|
} catch {
|
|
38433
39986
|
return false;
|
|
38434
39987
|
}
|
|
@@ -38436,7 +39989,7 @@ function isGitDirectory(path) {
|
|
|
38436
39989
|
function inspectPath(path) {
|
|
38437
39990
|
let stat;
|
|
38438
39991
|
try {
|
|
38439
|
-
stat =
|
|
39992
|
+
stat = lstatSync12(path);
|
|
38440
39993
|
} catch (error) {
|
|
38441
39994
|
const code = errorCode2(error);
|
|
38442
39995
|
if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing", path };
|
|
@@ -38447,7 +40000,7 @@ function inspectPath(path) {
|
|
|
38447
40000
|
return { status: "corrupt", path, reason: "invalid_content" };
|
|
38448
40001
|
}
|
|
38449
40002
|
try {
|
|
38450
|
-
const contents =
|
|
40003
|
+
const contents = readFileSync20(path, "utf8");
|
|
38451
40004
|
const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
|
|
38452
40005
|
if ((contents === workspaceId || contents === `${workspaceId}
|
|
38453
40006
|
`) && isCanonicalWorkspaceId(workspaceId)) {
|
|
@@ -38466,11 +40019,11 @@ function inspectPath(path) {
|
|
|
38466
40019
|
function createWorkspaceId(path) {
|
|
38467
40020
|
const parent = dirname15(path);
|
|
38468
40021
|
const workspaceId = randomUUID4();
|
|
38469
|
-
const temporaryPath =
|
|
40022
|
+
const temporaryPath = join26(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
38470
40023
|
let temporaryCreated = false;
|
|
38471
40024
|
let publishing = false;
|
|
38472
40025
|
try {
|
|
38473
|
-
|
|
40026
|
+
mkdirSync11(parent, { recursive: true, mode: 448 });
|
|
38474
40027
|
chmodSync6(parent, 448);
|
|
38475
40028
|
const fd = openSync5(
|
|
38476
40029
|
temporaryPath,
|
|
@@ -38479,7 +40032,7 @@ function createWorkspaceId(path) {
|
|
|
38479
40032
|
);
|
|
38480
40033
|
temporaryCreated = true;
|
|
38481
40034
|
try {
|
|
38482
|
-
|
|
40035
|
+
writeFileSync7(fd, `${workspaceId}
|
|
38483
40036
|
`, "utf8");
|
|
38484
40037
|
fchmodSync3(fd, 384);
|
|
38485
40038
|
fsyncSync3(fd);
|
|
@@ -38487,7 +40040,7 @@ function createWorkspaceId(path) {
|
|
|
38487
40040
|
closeSync5(fd);
|
|
38488
40041
|
}
|
|
38489
40042
|
publishing = true;
|
|
38490
|
-
|
|
40043
|
+
linkSync2(temporaryPath, path);
|
|
38491
40044
|
return { status: "ready", workspaceId, path, created: true };
|
|
38492
40045
|
} catch (error) {
|
|
38493
40046
|
if (publishing && errorCode2(error) === "EEXIST") return inspectAfterRace(path);
|
|
@@ -38526,23 +40079,23 @@ function errorCode2(error) {
|
|
|
38526
40079
|
}
|
|
38527
40080
|
|
|
38528
40081
|
// src/hooks/codex-context.ts
|
|
38529
|
-
import { createHash as
|
|
40082
|
+
import { createHash as createHash14, randomBytes as randomBytes7 } from "crypto";
|
|
38530
40083
|
import {
|
|
38531
40084
|
chmodSync as chmodSync7,
|
|
38532
|
-
existsSync as
|
|
38533
|
-
mkdirSync as
|
|
38534
|
-
readFileSync as
|
|
38535
|
-
readdirSync as
|
|
40085
|
+
existsSync as existsSync15,
|
|
40086
|
+
mkdirSync as mkdirSync12,
|
|
40087
|
+
readFileSync as readFileSync21,
|
|
40088
|
+
readdirSync as readdirSync7,
|
|
38536
40089
|
renameSync as renameSync4,
|
|
38537
|
-
rmSync as
|
|
40090
|
+
rmSync as rmSync11,
|
|
38538
40091
|
statSync as statSync4,
|
|
38539
40092
|
unlinkSync as unlinkSync6,
|
|
38540
|
-
writeFileSync as
|
|
40093
|
+
writeFileSync as writeFileSync8
|
|
38541
40094
|
} from "fs";
|
|
38542
|
-
import { join as
|
|
40095
|
+
import { join as join27 } from "path";
|
|
38543
40096
|
|
|
38544
40097
|
// src/daemon/decision-digest-cache.ts
|
|
38545
|
-
import { randomBytes as
|
|
40098
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
38546
40099
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
38547
40100
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
38548
40101
|
var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
|
|
@@ -38692,10 +40245,10 @@ var STATE_VERSION = 1;
|
|
|
38692
40245
|
var DRAFT_STATE_VERSION = 2;
|
|
38693
40246
|
var NO_CURSOR = -1;
|
|
38694
40247
|
function stateRoot(namespace) {
|
|
38695
|
-
return
|
|
40248
|
+
return join27(primConfigDirectory(), namespace, "decision-digests");
|
|
38696
40249
|
}
|
|
38697
40250
|
function draftStateRoot(namespace) {
|
|
38698
|
-
return
|
|
40251
|
+
return join27(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
38699
40252
|
}
|
|
38700
40253
|
function workspaceFor(cwd) {
|
|
38701
40254
|
try {
|
|
@@ -38706,13 +40259,13 @@ function workspaceFor(cwd) {
|
|
|
38706
40259
|
}
|
|
38707
40260
|
function statePath(args) {
|
|
38708
40261
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
38709
|
-
const key =
|
|
38710
|
-
return
|
|
40262
|
+
const key = createHash14("sha256").update(identity).digest("hex");
|
|
40263
|
+
return join27(stateRoot(args.namespace), `${key}.json`);
|
|
38711
40264
|
}
|
|
38712
40265
|
function draftStatePath(args) {
|
|
38713
40266
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
38714
|
-
const key =
|
|
38715
|
-
return
|
|
40267
|
+
const key = createHash14("sha256").update(identity).digest("hex");
|
|
40268
|
+
return join27(draftStateRoot(args.namespace), `${key}.json`);
|
|
38716
40269
|
}
|
|
38717
40270
|
function parseState(value) {
|
|
38718
40271
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -38750,31 +40303,31 @@ function parseDraftState(value) {
|
|
|
38750
40303
|
updatedAt: record.updatedAt
|
|
38751
40304
|
};
|
|
38752
40305
|
}
|
|
38753
|
-
function
|
|
38754
|
-
if (!
|
|
40306
|
+
function readState2(path) {
|
|
40307
|
+
if (!existsSync15(path)) return void 0;
|
|
38755
40308
|
try {
|
|
38756
|
-
return parseState(JSON.parse(
|
|
40309
|
+
return parseState(JSON.parse(readFileSync21(path, "utf8")));
|
|
38757
40310
|
} catch {
|
|
38758
40311
|
return void 0;
|
|
38759
40312
|
}
|
|
38760
40313
|
}
|
|
38761
40314
|
function readDraftState(path) {
|
|
38762
|
-
if (!
|
|
40315
|
+
if (!existsSync15(path)) return void 0;
|
|
38763
40316
|
try {
|
|
38764
|
-
return parseDraftState(JSON.parse(
|
|
40317
|
+
return parseDraftState(JSON.parse(readFileSync21(path, "utf8")));
|
|
38765
40318
|
} catch {
|
|
38766
40319
|
return void 0;
|
|
38767
40320
|
}
|
|
38768
40321
|
}
|
|
38769
40322
|
function writeStateFile(path, directory, state) {
|
|
38770
|
-
|
|
40323
|
+
mkdirSync12(directory, { recursive: true, mode: 448 });
|
|
38771
40324
|
chmodSync7(directory, 448);
|
|
38772
|
-
const temporary =
|
|
40325
|
+
const temporary = join27(
|
|
38773
40326
|
directory,
|
|
38774
|
-
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${
|
|
40327
|
+
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
38775
40328
|
);
|
|
38776
40329
|
try {
|
|
38777
|
-
|
|
40330
|
+
writeFileSync8(temporary, `${JSON.stringify(state)}
|
|
38778
40331
|
`, {
|
|
38779
40332
|
encoding: "utf8",
|
|
38780
40333
|
mode: 384,
|
|
@@ -38790,17 +40343,17 @@ function writeStateFile(path, directory, state) {
|
|
|
38790
40343
|
}
|
|
38791
40344
|
}
|
|
38792
40345
|
function cleanupStateFiles(directory, now) {
|
|
38793
|
-
if (!
|
|
40346
|
+
if (!existsSync15(directory)) return;
|
|
38794
40347
|
let names;
|
|
38795
40348
|
try {
|
|
38796
|
-
names =
|
|
40349
|
+
names = readdirSync7(directory);
|
|
38797
40350
|
} catch {
|
|
38798
40351
|
return;
|
|
38799
40352
|
}
|
|
38800
40353
|
const files = [];
|
|
38801
40354
|
const residue = [];
|
|
38802
40355
|
for (const name of names) {
|
|
38803
|
-
const path =
|
|
40356
|
+
const path = join27(directory, name);
|
|
38804
40357
|
try {
|
|
38805
40358
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
38806
40359
|
if (name.endsWith(".json")) {
|
|
@@ -38822,7 +40375,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
38822
40375
|
for (const path of residue) {
|
|
38823
40376
|
try {
|
|
38824
40377
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
38825
|
-
|
|
40378
|
+
rmSync11(path, { recursive: true, force: true });
|
|
38826
40379
|
}
|
|
38827
40380
|
} catch {
|
|
38828
40381
|
}
|
|
@@ -38908,7 +40461,7 @@ async function commitState(path, args, namespace) {
|
|
|
38908
40461
|
await withFileLock(
|
|
38909
40462
|
`${path}.lock`,
|
|
38910
40463
|
() => {
|
|
38911
|
-
const latest =
|
|
40464
|
+
const latest = readState2(path);
|
|
38912
40465
|
writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
|
|
38913
40466
|
cleanupStateFiles(stateRoot(namespace), args.now);
|
|
38914
40467
|
},
|
|
@@ -38955,7 +40508,7 @@ async function prepareCodexContext(options) {
|
|
|
38955
40508
|
const siteUrl = getSiteUrl();
|
|
38956
40509
|
const workspace = workspaceFor(options.cwd);
|
|
38957
40510
|
const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
|
|
38958
|
-
const previous =
|
|
40511
|
+
const previous = readState2(path);
|
|
38959
40512
|
const principal = resolveDaemonPrincipal();
|
|
38960
40513
|
const privatePath = principal ? draftStatePath({
|
|
38961
40514
|
cwd: options.cwd,
|
|
@@ -39105,7 +40658,7 @@ async function prepareCodexContext(options) {
|
|
|
39105
40658
|
}
|
|
39106
40659
|
|
|
39107
40660
|
// src/hooks/normalize.ts
|
|
39108
|
-
import { createHash as
|
|
40661
|
+
import { createHash as createHash15 } from "crypto";
|
|
39109
40662
|
import { realpathSync as realpathSync5 } from "fs";
|
|
39110
40663
|
import { isAbsolute as isAbsolute10, resolve as resolve9 } from "path";
|
|
39111
40664
|
var HERMES_EVENT_MAP = {
|
|
@@ -39150,7 +40703,7 @@ function requiredId(value, field) {
|
|
|
39150
40703
|
}
|
|
39151
40704
|
function cursorToolUseId(value) {
|
|
39152
40705
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
39153
|
-
return `cursor:tool:v1:${
|
|
40706
|
+
return `cursor:tool:v1:${createHash15("sha256").update(value).digest("hex")}`;
|
|
39154
40707
|
}
|
|
39155
40708
|
function workspaceCandidates(value) {
|
|
39156
40709
|
if (!Array.isArray(value)) return [];
|
|
@@ -39247,7 +40800,7 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
39247
40800
|
]);
|
|
39248
40801
|
return {
|
|
39249
40802
|
...parsed,
|
|
39250
|
-
tool_use_id: `codex:fallback:v1:${
|
|
40803
|
+
tool_use_id: `codex:fallback:v1:${createHash15("sha256").update(stableToolIdentity).digest("hex")}`
|
|
39251
40804
|
};
|
|
39252
40805
|
}
|
|
39253
40806
|
return parsed;
|
|
@@ -39263,18 +40816,46 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
39263
40816
|
}
|
|
39264
40817
|
|
|
39265
40818
|
// src/hooks/reauth-notice.ts
|
|
40819
|
+
function sharedEnvironment() {
|
|
40820
|
+
try {
|
|
40821
|
+
return sessionIdentityMode();
|
|
40822
|
+
} catch {
|
|
40823
|
+
return false;
|
|
40824
|
+
}
|
|
40825
|
+
}
|
|
39266
40826
|
var REAUTH_NOTICE = "[prim] authentication ended \u2014 run `prim auth login` to resume decision capture";
|
|
39267
40827
|
function reauthNoticeFields(agent) {
|
|
39268
|
-
if (agent === "claude_code")
|
|
40828
|
+
if (agent === "claude_code") {
|
|
40829
|
+
if (isClaudeCloudSession()) {
|
|
40830
|
+
const notice = !hasMachineConfiguration() ? `Primitive is not connected in this Claude Code cloud session: its sign-in ended. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.` : sharedEnvironment() ? `Primitive is not connected in this Claude Code cloud session: its environment credential was rejected. To fix it, ${ENVIRONMENT_CREDENTIAL_REMEDY}.` : CLOUD_REJECTED_CREDENTIALS_NOTICE;
|
|
40831
|
+
return {
|
|
40832
|
+
systemMessage: notice,
|
|
40833
|
+
additionalContext: `${notice} Tell the user this in one sentence before starting their task.`
|
|
40834
|
+
};
|
|
40835
|
+
}
|
|
39269
40836
|
return {
|
|
39270
40837
|
systemMessage: hasMachineConfiguration() ? "[prim] machine delivery paused; local capture remains saved. Run `prim auth status` and ask your administrator to enable or rotate machine credentials." : REAUTH_NOTICE
|
|
39271
40838
|
};
|
|
40839
|
+
}
|
|
39272
40840
|
return;
|
|
39273
40841
|
}
|
|
39274
40842
|
|
|
39275
40843
|
// src/hooks/session-start-core.ts
|
|
39276
40844
|
var DAEMON_TIMEOUT_MS = 250;
|
|
39277
40845
|
var REPOSITORY_BIND_TIMEOUT_MS = 1e3;
|
|
40846
|
+
var CLOUD_REPOSITORY_BIND_TIMEOUT_MS = 1e4;
|
|
40847
|
+
var SESSION_IDENTITY_TIMEOUT_MS = 35e3;
|
|
40848
|
+
function sessionIdentityNotice(outcome) {
|
|
40849
|
+
if (!outcome || outcome.status === "ok") return void 0;
|
|
40850
|
+
const notice = `${sessionIdentityMessage(outcome)} Until then, nothing this session captures is sent to Primitive.`;
|
|
40851
|
+
return outcome.status === "link_required" ? {
|
|
40852
|
+
notice,
|
|
40853
|
+
instruction: `${notice} Before starting their task, tell the user this in one sentence. When they agree, run \`prim auth link\` as a background command (it waits until they finish signing in), and give them the sign-in URL and code it prints as soon as they appear.`
|
|
40854
|
+
} : {
|
|
40855
|
+
notice,
|
|
40856
|
+
instruction: `${notice} Tell the user this in one sentence before starting their task.`
|
|
40857
|
+
};
|
|
40858
|
+
}
|
|
39278
40859
|
var PRIM_TRIGGER = "When this task chooses between plausible approaches or establishes or changes a lasting goal, priority, constraint, invariant, default, commitment, tradeoff, exception, or shared instruction";
|
|
39279
40860
|
var PRIM_EXCLUSIONS = "Never invoke `prim` for routine implementation that merely follows an existing decision made before this task or for temporary tactics; they never qualify, including for evaluation.";
|
|
39280
40861
|
function primReminder(action, rationaleAction) {
|
|
@@ -39295,6 +40876,7 @@ async function activeProjectRoot(cwd) {
|
|
|
39295
40876
|
if (!shellGateActive) {
|
|
39296
40877
|
try {
|
|
39297
40878
|
setRepoActive(root, true);
|
|
40879
|
+
markActivationImplicit(root);
|
|
39298
40880
|
shellGateActive = true;
|
|
39299
40881
|
} catch {
|
|
39300
40882
|
}
|
|
@@ -39316,7 +40898,9 @@ async function activeProjectRoot(cwd) {
|
|
|
39316
40898
|
}
|
|
39317
40899
|
try {
|
|
39318
40900
|
const binding = await bindRepository(root, {
|
|
39319
|
-
signal: AbortSignal.timeout(
|
|
40901
|
+
signal: AbortSignal.timeout(
|
|
40902
|
+
isClaudeCloudSession() ? CLOUD_REPOSITORY_BIND_TIMEOUT_MS : REPOSITORY_BIND_TIMEOUT_MS
|
|
40903
|
+
),
|
|
39320
40904
|
quietRefresh: true
|
|
39321
40905
|
});
|
|
39322
40906
|
try {
|
|
@@ -39324,14 +40908,16 @@ async function activeProjectRoot(cwd) {
|
|
|
39324
40908
|
} catch {
|
|
39325
40909
|
}
|
|
39326
40910
|
return { root, binding };
|
|
39327
|
-
} catch {
|
|
40911
|
+
} catch (error) {
|
|
40912
|
+
return { root, bindFailure: error };
|
|
39328
40913
|
}
|
|
39329
|
-
return { root };
|
|
39330
40914
|
} catch {
|
|
39331
40915
|
return null;
|
|
39332
40916
|
}
|
|
39333
40917
|
}
|
|
39334
|
-
function claudeBindingReminder(binding) {
|
|
40918
|
+
function claudeBindingReminder(binding, cloud = false) {
|
|
40919
|
+
if (cloud && binding.status !== "connected")
|
|
40920
|
+
return `GitHub repo connection is required before Primitive can attribute work in ${binding.repositoryFullName}, and it cannot be completed from this Claude Code cloud session. Before doing task work, tell the user exactly: "Primitive needs a one-time GitHub connection for ${binding.repositoryFullName}. Run \`prim github connect\` in a clone of it on your own machine, then start a new cloud session." Then continue the user's request.`;
|
|
39335
40921
|
if (binding.status === "connected") {
|
|
39336
40922
|
return `The GitHub repo connection is complete for ${binding.repositoryFullName}. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation. In your first response, begin with exactly: "GitHub repo connection is complete for ${binding.repositoryFullName}. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation." Then continue the user's request.`;
|
|
39337
40923
|
}
|
|
@@ -39355,6 +40941,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39355
40941
|
return { output: buildHookOutput({}) };
|
|
39356
40942
|
}
|
|
39357
40943
|
const cwd = envelope.cwd ?? process.cwd();
|
|
40944
|
+
withdrawImplicitActivation(cwd);
|
|
39358
40945
|
if (!gitToplevel(cwd) || !isRepoActiveForCapture(cwd)) {
|
|
39359
40946
|
if (repoActiveFlag(cwd) === "false") clearHooksWired(cwd);
|
|
39360
40947
|
return { output: agent === "cursor" ? {} : buildHookOutput({}) };
|
|
@@ -39370,11 +40957,31 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39370
40957
|
let active = false;
|
|
39371
40958
|
let skillState = { installed: 0, refreshed: 0 };
|
|
39372
40959
|
let claudeBinding;
|
|
40960
|
+
let bindFailure;
|
|
40961
|
+
let identityNotice;
|
|
39373
40962
|
if (agent === "claude_code") {
|
|
40963
|
+
let identityMode = false;
|
|
40964
|
+
try {
|
|
40965
|
+
identityMode = sessionIdentityMode();
|
|
40966
|
+
} catch {
|
|
40967
|
+
}
|
|
40968
|
+
if (identityMode) {
|
|
40969
|
+
try {
|
|
40970
|
+
identityNotice = sessionIdentityNotice(
|
|
40971
|
+
await ensureSessionIdentity({
|
|
40972
|
+
cwd,
|
|
40973
|
+
explicit: true,
|
|
40974
|
+
signal: AbortSignal.timeout(SESSION_IDENTITY_TIMEOUT_MS)
|
|
40975
|
+
})
|
|
40976
|
+
);
|
|
40977
|
+
} catch {
|
|
40978
|
+
}
|
|
40979
|
+
}
|
|
39374
40980
|
const activeProject = await activeProjectRoot(cwd);
|
|
39375
40981
|
projectRoot2 = activeProject?.root ?? null;
|
|
39376
40982
|
active = projectRoot2 !== null;
|
|
39377
40983
|
claudeBinding = activeProject?.binding;
|
|
40984
|
+
bindFailure = activeProject?.bindFailure;
|
|
39378
40985
|
try {
|
|
39379
40986
|
skillState = await refreshClaudePlugins(
|
|
39380
40987
|
cwd,
|
|
@@ -39383,7 +40990,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39383
40990
|
} catch {
|
|
39384
40991
|
}
|
|
39385
40992
|
}
|
|
39386
|
-
if (isSessionEnded() && agent !== "codex" && agent !== "cursor") {
|
|
40993
|
+
if (isSessionEnded() && agent !== "codex" && agent !== "cursor" && !identityNotice) {
|
|
39387
40994
|
const notice = reauthNoticeFields(agent);
|
|
39388
40995
|
if (notice) {
|
|
39389
40996
|
return {
|
|
@@ -39446,8 +41053,16 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39446
41053
|
};
|
|
39447
41054
|
}
|
|
39448
41055
|
if (agent === "claude_code") {
|
|
41056
|
+
let cloudNotice = identityNotice?.notice;
|
|
41057
|
+
if (active && !claudeBinding && isClaudeCloudSession() && !identityNotice) {
|
|
41058
|
+
try {
|
|
41059
|
+
cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd, bindFailure });
|
|
41060
|
+
} catch {
|
|
41061
|
+
}
|
|
41062
|
+
}
|
|
39449
41063
|
const additionalContext = [
|
|
39450
|
-
|
|
41064
|
+
identityNotice ? identityNotice.instruction : cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
|
|
41065
|
+
claudeBinding ? claudeBindingReminder(claudeBinding, isClaudeCloudSession()) : void 0,
|
|
39451
41066
|
active && skillState.installed > 0 ? PRIM_SKILL_REMINDER : void 0
|
|
39452
41067
|
].filter((value) => value !== void 0).join("\n\n");
|
|
39453
41068
|
const reloadSkills = skillState.refreshed > 0;
|
|
@@ -39463,7 +41078,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39463
41078
|
const rendered = lease ? renderFeedback(lease) : void 0;
|
|
39464
41079
|
return {
|
|
39465
41080
|
output: buildHookOutput({
|
|
39466
|
-
systemMessage: rendered?.systemMessage,
|
|
41081
|
+
systemMessage: [cloudNotice, rendered?.systemMessage].filter(Boolean).join("\n\n") || void 0,
|
|
39467
41082
|
additionalContext,
|
|
39468
41083
|
reloadSkills
|
|
39469
41084
|
}),
|
|
@@ -39478,7 +41093,9 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39478
41093
|
};
|
|
39479
41094
|
}
|
|
39480
41095
|
}
|
|
39481
|
-
return {
|
|
41096
|
+
return {
|
|
41097
|
+
output: buildHookOutput({ systemMessage: cloudNotice, additionalContext, reloadSkills })
|
|
41098
|
+
};
|
|
39482
41099
|
}
|
|
39483
41100
|
await activeProjectRoot(cwd);
|
|
39484
41101
|
return { output: buildHookOutput({}) };
|