@primitive.ai/prim 0.1.0-alpha.125 → 0.1.0-alpha.127
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 +140 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-JFWJN2ME.js → chunk-72NIZMZN.js} +114 -5
- package/dist/{chunk-2BEUR3DU.js → chunk-A5VTE43F.js} +2 -2
- package/dist/{chunk-6OPSSJHO.js → chunk-C4QNBSWB.js} +24 -9
- package/dist/{chunk-BFYJLI7V.js → chunk-F3FDVHR7.js} +1 -1
- package/dist/{chunk-YP4OXKNX.js → chunk-H6X52UVF.js} +1 -1
- package/dist/{chunk-ND6TYHNI.js → chunk-H74RDXKP.js} +2 -2
- package/dist/{chunk-NJBN3WXF.js → chunk-HZI5PBN4.js} +785 -154
- package/dist/{chunk-FYYHBOOM.js → chunk-JCKOW45X.js} +2 -2
- package/dist/{chunk-DT7E3SD5.js → chunk-KFRGVHGB.js} +4 -4
- package/dist/{chunk-TI37ME2D.js → chunk-L6IL4N6Y.js} +16 -7
- package/dist/{chunk-HPA7RGSZ.js → chunk-MGKSZSTV.js} +7 -8
- package/dist/{chunk-ZKXNJB6U.js → chunk-NVDPKW7Z.js} +69 -29
- package/dist/{chunk-NBNQI3YJ.js → chunk-O65UVJZH.js} +6 -3
- package/dist/{chunk-74DQDWLW.js → chunk-R4EYLEIK.js} +7 -2
- package/dist/{chunk-R35M4RCY.js → chunk-RV3JFSMX.js} +4 -4
- package/dist/{chunk-PPZ56EVJ.js → chunk-TNWI3JWK.js} +1 -1
- package/dist/{chunk-6KXQQ7CQ.js → chunk-URYZDQFH.js} +3 -3
- package/dist/{chunk-L32WYFJT.js → chunk-UUQT5GMO.js} +135 -12
- package/dist/{chunk-EZXIKEMA.js → chunk-VVFVENU4.js} +6 -4
- package/dist/{chunk-O73J3KQQ.js → chunk-WGTUNUIS.js} +5 -2
- package/dist/daemon/server.js +805 -218
- package/dist/hook-runtime/daemon/server.js +805 -218
- package/dist/hook-runtime/hooks/post-commit.js +286 -59
- package/dist/hook-runtime/hooks/post-rewrite.js +278 -51
- package/dist/hook-runtime/hooks/post-tool-use.js +672 -194
- package/dist/hook-runtime/hooks/pre-commit.js +536 -88
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +616 -165
- package/dist/hook-runtime/hooks/prim-hook.js +642 -167
- package/dist/hook-runtime/hooks/session-end.js +263 -47
- package/dist/hook-runtime/hooks/session-start.js +1103 -476
- package/dist/hook-runtime/index.js +3645 -2120
- package/dist/hook-runtime/statusline-main.js +257 -29
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +15 -15
- 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 +49 -18
- package/dist/index.js +1014 -271
- package/dist/statusline-main.js +257 -29
- 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,122 @@ 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
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
746
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
747
|
+
}
|
|
748
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
749
|
+
|
|
750
|
+
// src/lib/cloud-prepared.ts
|
|
751
|
+
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
752
|
+
function cloudPreparedPath(env = process.env) {
|
|
753
|
+
return join6(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
754
|
+
}
|
|
755
|
+
function isPreparedCloudSession(env = process.env) {
|
|
756
|
+
if (!isClaudeCloudSession(env)) return false;
|
|
757
|
+
try {
|
|
758
|
+
return existsSync5(cloudPreparedPath(env));
|
|
759
|
+
} catch {
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
// src/lib/demo-pause.ts
|
|
729
765
|
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";
|
|
766
|
+
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
767
|
+
var PAUSE_KEY = "prim.demoPause";
|
|
733
768
|
var GIT_TIMEOUT_MS = 1e3;
|
|
769
|
+
function git(cwd, args) {
|
|
770
|
+
try {
|
|
771
|
+
return execFileSync2("git", args, {
|
|
772
|
+
cwd,
|
|
773
|
+
encoding: "utf-8",
|
|
774
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
775
|
+
timeout: GIT_TIMEOUT_MS
|
|
776
|
+
});
|
|
777
|
+
} catch {
|
|
778
|
+
return void 0;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
function setLocal(cwd, key, value) {
|
|
782
|
+
try {
|
|
783
|
+
execFileSync2(
|
|
784
|
+
"git",
|
|
785
|
+
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
786
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
|
|
787
|
+
);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
if (value !== null || error.status !== 5) throw error;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
function parsePause(value) {
|
|
793
|
+
const [runId = "", until, previous, state] = value.trim().split(" ");
|
|
794
|
+
const flag = previous === "true" || previous === "false" ? previous : "unset";
|
|
795
|
+
return { runId, until: Number(until) || 0, previous: flag, ending: state !== "active" };
|
|
796
|
+
}
|
|
797
|
+
function readCaptureConfig(cwd) {
|
|
798
|
+
let active;
|
|
799
|
+
let pause;
|
|
800
|
+
const out = git(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
801
|
+
for (const line of out.split("\n")) {
|
|
802
|
+
const space = line.indexOf(" ");
|
|
803
|
+
const key = line.slice(0, space).toLowerCase();
|
|
804
|
+
const value = line.slice(space + 1);
|
|
805
|
+
if (key === "prim.active") active = value === "true" || value === "false" ? value : void 0;
|
|
806
|
+
if (key === "prim.demopause") pause = parsePause(value);
|
|
807
|
+
}
|
|
808
|
+
return { active, pause };
|
|
809
|
+
}
|
|
810
|
+
function resumeCapture(cwd, pause) {
|
|
811
|
+
setLocal(cwd, "prim.active", pause.previous === "unset" ? null : pause.previous);
|
|
812
|
+
setLocal(cwd, PAUSE_KEY, null);
|
|
813
|
+
}
|
|
814
|
+
function healDemoPause(cwd, pause, options = {}) {
|
|
815
|
+
if (pause.until > (options.now ?? Date.now()) && !(pause.ending && options.userPrompt))
|
|
816
|
+
return false;
|
|
817
|
+
try {
|
|
818
|
+
resumeCapture(cwd, pause);
|
|
819
|
+
return true;
|
|
820
|
+
} catch {
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
// src/lib/git.ts
|
|
826
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
827
|
+
import { createHash as createHash2 } from "crypto";
|
|
828
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
829
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve2, sep } from "path";
|
|
830
|
+
var GIT_TIMEOUT_MS2 = 1e3;
|
|
831
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
734
832
|
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;
|
|
833
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
736
834
|
function gitToplevel(cwd) {
|
|
737
835
|
try {
|
|
738
|
-
return
|
|
836
|
+
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
739
837
|
cwd,
|
|
740
838
|
encoding: "utf-8",
|
|
741
839
|
stdio: ["ignore", "pipe", "ignore"],
|
|
742
|
-
timeout:
|
|
840
|
+
timeout: GIT_TIMEOUT_MS2
|
|
743
841
|
}).trim();
|
|
744
842
|
} catch {
|
|
745
843
|
return null;
|
|
@@ -747,30 +845,72 @@ function gitToplevel(cwd) {
|
|
|
747
845
|
}
|
|
748
846
|
function gitValue(cwd, args) {
|
|
749
847
|
try {
|
|
750
|
-
const value =
|
|
848
|
+
const value = execFileSync3("git", args, {
|
|
751
849
|
cwd,
|
|
752
850
|
encoding: "utf-8",
|
|
753
851
|
stdio: ["ignore", "pipe", "ignore"],
|
|
754
|
-
timeout:
|
|
852
|
+
timeout: GIT_TIMEOUT_MS2
|
|
755
853
|
}).trim();
|
|
756
854
|
return value || void 0;
|
|
757
855
|
} catch {
|
|
758
856
|
return void 0;
|
|
759
857
|
}
|
|
760
858
|
}
|
|
761
|
-
function
|
|
762
|
-
const
|
|
763
|
-
if (
|
|
859
|
+
function parseGithubRepositoryName(path) {
|
|
860
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
861
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
862
|
+
return null;
|
|
863
|
+
}
|
|
864
|
+
return `${parts[0]}/${parts[1]}`;
|
|
865
|
+
}
|
|
866
|
+
function githubRepositoryFromRemote(remote) {
|
|
867
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
764
868
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
765
869
|
remote
|
|
766
870
|
);
|
|
767
871
|
const path = match?.[1] ?? match?.[2];
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
872
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
873
|
+
}
|
|
874
|
+
function originIdentifiesRepository(cwd) {
|
|
875
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
876
|
+
return remote !== void 0 && Boolean(githubRepositoryFromRemote(remote) || normalizeOriginRemote(remote));
|
|
877
|
+
}
|
|
878
|
+
function checkoutSettingsText(repoRoot) {
|
|
879
|
+
const path = join7(repoRoot, ".claude", "settings.json");
|
|
880
|
+
try {
|
|
881
|
+
if (!lstatSync2(join7(repoRoot, ".claude")).isDirectory()) return null;
|
|
882
|
+
const stat = lstatSync2(path);
|
|
883
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
884
|
+
return readFileSync5(path, "utf8");
|
|
885
|
+
} catch {
|
|
771
886
|
return null;
|
|
772
887
|
}
|
|
773
|
-
|
|
888
|
+
}
|
|
889
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
890
|
+
const text = checkoutSettingsText(repoRoot);
|
|
891
|
+
if (text === null) return null;
|
|
892
|
+
let parsed;
|
|
893
|
+
try {
|
|
894
|
+
parsed = JSON.parse(text);
|
|
895
|
+
} catch {
|
|
896
|
+
return null;
|
|
897
|
+
}
|
|
898
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
899
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
900
|
+
return typeof value === "string" ? value : null;
|
|
901
|
+
}
|
|
902
|
+
function declaredGithubRepository(repoRoot) {
|
|
903
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
904
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
905
|
+
}
|
|
906
|
+
function githubRepositoryFullName(cwd) {
|
|
907
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
908
|
+
if (remote) {
|
|
909
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
910
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
911
|
+
}
|
|
912
|
+
const root = gitToplevel(cwd);
|
|
913
|
+
return root ? declaredGithubRepository(root) : null;
|
|
774
914
|
}
|
|
775
915
|
function normalizeOriginRemote(remote) {
|
|
776
916
|
const value = remote.trim();
|
|
@@ -816,6 +956,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
816
956
|
repoFullName
|
|
817
957
|
};
|
|
818
958
|
}
|
|
959
|
+
if (repoFullName) {
|
|
960
|
+
return {
|
|
961
|
+
repoRoot,
|
|
962
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
963
|
+
identitySource: "declared",
|
|
964
|
+
repoFullName
|
|
965
|
+
};
|
|
966
|
+
}
|
|
819
967
|
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
820
968
|
if (roots && roots.length > 0) {
|
|
821
969
|
return {
|
|
@@ -828,6 +976,179 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
828
976
|
return { repoRoot, repoFullName };
|
|
829
977
|
}
|
|
830
978
|
|
|
979
|
+
// src/lib/activation.ts
|
|
980
|
+
var PRIM_ACTIVE_KEY = "prim.active";
|
|
981
|
+
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
982
|
+
var PRIM_ACTIVE_IMPLICIT_KEY = "prim.activeImplicit";
|
|
983
|
+
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
984
|
+
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
985
|
+
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
986
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
987
|
+
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
988
|
+
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
989
|
+
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
990
|
+
function repoActiveFlag(cwd, strict = false) {
|
|
991
|
+
try {
|
|
992
|
+
const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
|
|
993
|
+
cwd,
|
|
994
|
+
encoding: "utf-8",
|
|
995
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
996
|
+
timeout: GIT_TIMEOUT_MS3
|
|
997
|
+
}).trim();
|
|
998
|
+
if (value === "true") return "true";
|
|
999
|
+
if (value === "false") return "false";
|
|
1000
|
+
if (strict) throw new Error("Repository activation is invalid");
|
|
1001
|
+
return void 0;
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
if (strict && !(typeof error === "object" && error !== null && "status" in error && error.status === 1))
|
|
1004
|
+
throw error;
|
|
1005
|
+
return void 0;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
function setRepoActive(cwd, active) {
|
|
1009
|
+
execFileSync4("git", ["config", "--local", PRIM_ACTIVE_KEY, active ? "true" : "false"], {
|
|
1010
|
+
cwd,
|
|
1011
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1012
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
function isValidRepoSyncId(value) {
|
|
1016
|
+
return typeof value === "string" && REPO_SYNC_ID_RE.test(value);
|
|
1017
|
+
}
|
|
1018
|
+
function localGitConfigValue(cwd, key) {
|
|
1019
|
+
try {
|
|
1020
|
+
const value = execFileSync4("git", ["config", "--local", "--get", key], {
|
|
1021
|
+
cwd,
|
|
1022
|
+
encoding: "utf-8",
|
|
1023
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1024
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1025
|
+
}).trim();
|
|
1026
|
+
return value || void 0;
|
|
1027
|
+
} catch {
|
|
1028
|
+
return void 0;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
function setLocalGitConfigValue(cwd, key, value) {
|
|
1032
|
+
execFileSync4("git", ["config", "--local", key, value], {
|
|
1033
|
+
cwd,
|
|
1034
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1035
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
function repoSyncId(cwd) {
|
|
1039
|
+
const value = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
1040
|
+
if (!isValidRepoSyncId(value)) return void 0;
|
|
1041
|
+
const repositoryFullName = localGitConfigValue(cwd, PRIM_REPO_SYNC_REPOSITORY_KEY);
|
|
1042
|
+
return repositoryFullName === githubRepositoryFullName(cwd) ? value : void 0;
|
|
1043
|
+
}
|
|
1044
|
+
function setRepoSyncId(cwd, value, repositoryFullName) {
|
|
1045
|
+
if (!isValidRepoSyncId(value)) {
|
|
1046
|
+
throw new Error("invalid repository binding returned by server");
|
|
1047
|
+
}
|
|
1048
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_SYNC_ID_KEY, value], {
|
|
1049
|
+
cwd,
|
|
1050
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1051
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1052
|
+
});
|
|
1053
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_SYNC_REPOSITORY_KEY, repositoryFullName], {
|
|
1054
|
+
cwd,
|
|
1055
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1056
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
function setRepositoryBindingState(cwd, state) {
|
|
1060
|
+
if (state !== "connected" && state !== "unbound" && state !== "invalid") {
|
|
1061
|
+
throw new Error("invalid repository binding state");
|
|
1062
|
+
}
|
|
1063
|
+
execFileSync4("git", ["config", "--local", PRIM_REPO_BINDING_STATE_KEY, state], {
|
|
1064
|
+
cwd,
|
|
1065
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1066
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1067
|
+
});
|
|
1068
|
+
}
|
|
1069
|
+
function repositoryBindingState(cwd) {
|
|
1070
|
+
const rawId = localGitConfigValue(cwd, PRIM_REPO_SYNC_ID_KEY);
|
|
1071
|
+
const marker = localGitConfigValue(cwd, PRIM_REPO_BINDING_STATE_KEY);
|
|
1072
|
+
if (rawId !== void 0 && !isValidRepoSyncId(rawId)) return "invalid";
|
|
1073
|
+
if (marker === "unbound" || marker === "invalid") return marker;
|
|
1074
|
+
if (marker === "connected") return repoSyncId(cwd) ? "connected" : "invalid";
|
|
1075
|
+
if (marker !== void 0) return "invalid";
|
|
1076
|
+
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
1077
|
+
}
|
|
1078
|
+
function unsetLocalGitConfigValue(cwd, key) {
|
|
1079
|
+
try {
|
|
1080
|
+
execFileSync4("git", ["config", "--local", "--unset-all", key], {
|
|
1081
|
+
cwd,
|
|
1082
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
1083
|
+
timeout: GIT_TIMEOUT_MS3
|
|
1084
|
+
});
|
|
1085
|
+
} catch (error) {
|
|
1086
|
+
if (typeof error === "object" && error !== null && "status" in error && error.status === 5) {
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
throw error;
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
function projectPrimInstallAt(root) {
|
|
1093
|
+
if (root === null || root === homedir2()) return false;
|
|
1094
|
+
for (const rel of PROJECT_INSTALL_FILES) {
|
|
1095
|
+
const path = join8(root, rel);
|
|
1096
|
+
if (existsSync6(path)) {
|
|
1097
|
+
try {
|
|
1098
|
+
const content = readFileSync6(path, "utf-8");
|
|
1099
|
+
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
1100
|
+
} catch {
|
|
1101
|
+
}
|
|
1102
|
+
}
|
|
1103
|
+
}
|
|
1104
|
+
return false;
|
|
1105
|
+
}
|
|
1106
|
+
var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
|
|
1107
|
+
function declaresInactiveAt(root) {
|
|
1108
|
+
if (root === null || root === homedir2()) return false;
|
|
1109
|
+
if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
|
|
1110
|
+
const text = checkoutSettingsText(root);
|
|
1111
|
+
if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
|
|
1112
|
+
try {
|
|
1113
|
+
JSON.parse(text);
|
|
1114
|
+
return false;
|
|
1115
|
+
} catch {
|
|
1116
|
+
return true;
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
function markActivationImplicit(cwd) {
|
|
1120
|
+
try {
|
|
1121
|
+
setLocalGitConfigValue(cwd, PRIM_ACTIVE_IMPLICIT_KEY, "true");
|
|
1122
|
+
} catch {
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
function withdrawImplicitActivation(cwd) {
|
|
1126
|
+
try {
|
|
1127
|
+
const root = gitToplevel(cwd);
|
|
1128
|
+
if (root === null) return false;
|
|
1129
|
+
if (localGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY) !== "true") return false;
|
|
1130
|
+
if (localGitConfigValue(root, PRIM_ACTIVE_KEY) !== "true" || !declaresInactiveAt(root))
|
|
1131
|
+
return false;
|
|
1132
|
+
unsetLocalGitConfigValue(root, PRIM_ACTIVE_KEY);
|
|
1133
|
+
unsetLocalGitConfigValue(root, PRIM_ACTIVE_IMPLICIT_KEY);
|
|
1134
|
+
return true;
|
|
1135
|
+
} catch {
|
|
1136
|
+
return false;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
function isRepoActiveForCapture(cwd, options = {}) {
|
|
1140
|
+
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
1141
|
+
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
1142
|
+
if (flag === "true") return true;
|
|
1143
|
+
if (flag === "false") return false;
|
|
1144
|
+
const root = gitToplevel(cwd);
|
|
1145
|
+
if (declaresInactiveAt(root)) return false;
|
|
1146
|
+
return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
|
|
1147
|
+
}
|
|
1148
|
+
function decisionIngestionStatus(cwd) {
|
|
1149
|
+
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
1150
|
+
}
|
|
1151
|
+
|
|
831
1152
|
// src/commands/claude-install.ts
|
|
832
1153
|
var CAPTURE_BIN = "prim-hook";
|
|
833
1154
|
var GATE_BIN = "prim-pre-tool-use";
|
|
@@ -837,7 +1158,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
837
1158
|
var STATUSLINE_BIN = "prim-statusline";
|
|
838
1159
|
var STATUSLINE_ARGS = "";
|
|
839
1160
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
840
|
-
var USER_SCOPE_PATH =
|
|
1161
|
+
var USER_SCOPE_PATH = join9(homedir3(), ".claude", "settings.json");
|
|
841
1162
|
function projectRoot() {
|
|
842
1163
|
return gitToplevel() ?? process.cwd();
|
|
843
1164
|
}
|
|
@@ -913,24 +1234,24 @@ var REGISTRATIONS2 = [
|
|
|
913
1234
|
{ event: "sessionStart", bin: SESSION_START_BIN2 },
|
|
914
1235
|
{ event: "sessionEnd", bin: SESSION_END_BIN2 }
|
|
915
1236
|
];
|
|
916
|
-
function cursorConfigDirectory(env = process.env, home =
|
|
1237
|
+
function cursorConfigDirectory(env = process.env, home = homedir4(), platform = process.platform) {
|
|
917
1238
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
918
1239
|
if (explicit && isAbsolute5(explicit)) return explicit;
|
|
919
1240
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
920
|
-
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return
|
|
921
|
-
return
|
|
1241
|
+
if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join10(xdg, "cursor");
|
|
1242
|
+
return join10(home, ".cursor");
|
|
922
1243
|
}
|
|
923
1244
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
924
|
-
return scope === "user" ?
|
|
1245
|
+
return scope === "user" ? join10(cursorConfigDirectory(), "hooks.json") : join10(root, ".cursor", "hooks.json");
|
|
925
1246
|
}
|
|
926
1247
|
function plainObject(value) {
|
|
927
1248
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
928
1249
|
}
|
|
929
1250
|
function readCursorHooks(path) {
|
|
930
|
-
if (!
|
|
1251
|
+
if (!existsSync8(path)) return {};
|
|
931
1252
|
let parsed;
|
|
932
1253
|
try {
|
|
933
|
-
parsed = JSON.parse(
|
|
1254
|
+
parsed = JSON.parse(readFileSync8(path, "utf8"));
|
|
934
1255
|
} catch {
|
|
935
1256
|
throw new Error(`invalid Cursor hooks JSON at ${path}`);
|
|
936
1257
|
}
|
|
@@ -1202,30 +1523,69 @@ function publicDecisionResponse(value) {
|
|
|
1202
1523
|
|
|
1203
1524
|
// src/client.ts
|
|
1204
1525
|
import { createHash as createHash7 } from "crypto";
|
|
1205
|
-
import { chmodSync as chmodSync4, existsSync as
|
|
1526
|
+
import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync8 } from "fs";
|
|
1206
1527
|
import { dirname as dirname9 } from "path";
|
|
1207
1528
|
|
|
1208
1529
|
// src/lib/credentials.ts
|
|
1209
1530
|
import { createHash as createHash6 } from "crypto";
|
|
1210
|
-
import { readFileSync as
|
|
1211
|
-
import { join as
|
|
1531
|
+
import { readFileSync as readFileSync12 } from "fs";
|
|
1532
|
+
import { join as join14 } from "path";
|
|
1212
1533
|
|
|
1213
1534
|
// src/lib/machine-credentials.ts
|
|
1214
|
-
import { execFileSync as
|
|
1215
|
-
import { createHash as createHash5, randomUUID as randomUUID2 } from "crypto";
|
|
1216
|
-
import {
|
|
1535
|
+
import { execFileSync as execFileSync5 } from "child_process";
|
|
1536
|
+
import { createHash as createHash5, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
1537
|
+
import {
|
|
1538
|
+
chmodSync as chmodSync2,
|
|
1539
|
+
existsSync as existsSync9,
|
|
1540
|
+
linkSync,
|
|
1541
|
+
lstatSync as lstatSync6,
|
|
1542
|
+
mkdirSync as mkdirSync5,
|
|
1543
|
+
readFileSync as readFileSync11,
|
|
1544
|
+
rmSync as rmSync7,
|
|
1545
|
+
writeFileSync as writeFileSync5
|
|
1546
|
+
} from "fs";
|
|
1217
1547
|
import { createRequire as createRequire2 } from "module";
|
|
1218
|
-
import { dirname as dirname8, join as
|
|
1548
|
+
import { dirname as dirname8, join as join13 } from "path";
|
|
1219
1549
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1220
1550
|
|
|
1221
1551
|
// src/lib/machine-broker.ts
|
|
1222
1552
|
import { spawn } from "child_process";
|
|
1223
1553
|
import { createHash as createHash3, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
1224
|
-
import { lstatSync as
|
|
1554
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync9, rmSync as rmSync5 } from "fs";
|
|
1225
1555
|
import { createServer } from "http";
|
|
1226
|
-
import { basename as basename2, join as
|
|
1556
|
+
import { basename as basename2, join as join11 } from "path";
|
|
1227
1557
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
1228
1558
|
|
|
1559
|
+
// src/lib/loopback-fetch.ts
|
|
1560
|
+
import { request } from "http";
|
|
1561
|
+
import { Readable } from "stream";
|
|
1562
|
+
function loopbackFetch(url, init = {}) {
|
|
1563
|
+
const target = new URL(url);
|
|
1564
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
1565
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
1566
|
+
return new Promise((resolve10, reject) => {
|
|
1567
|
+
const outgoing = request(
|
|
1568
|
+
target,
|
|
1569
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
1570
|
+
(incoming) => {
|
|
1571
|
+
try {
|
|
1572
|
+
const headers = new Headers();
|
|
1573
|
+
for (const [name, value] of Object.entries(incoming.headers))
|
|
1574
|
+
if (typeof value === "string") headers.set(name, value);
|
|
1575
|
+
const status = incoming.statusCode ?? 502;
|
|
1576
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
1577
|
+
resolve10(new Response(body, { status, headers }));
|
|
1578
|
+
} catch (error) {
|
|
1579
|
+
incoming.destroy();
|
|
1580
|
+
reject(error);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
);
|
|
1584
|
+
outgoing.once("error", reject);
|
|
1585
|
+
outgoing.end(init.body);
|
|
1586
|
+
});
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1229
1589
|
// src/lib/workos-connect.ts
|
|
1230
1590
|
var TOKEN_PATH = "/oauth2/token";
|
|
1231
1591
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -1421,9 +1781,19 @@ function parseMachineConfiguration(value) {
|
|
|
1421
1781
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
1422
1782
|
};
|
|
1423
1783
|
}
|
|
1784
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
1785
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
1786
|
+
}
|
|
1424
1787
|
function machineSignal(signal) {
|
|
1425
1788
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1426
1789
|
}
|
|
1790
|
+
function hostOf(url) {
|
|
1791
|
+
try {
|
|
1792
|
+
return new URL(url).hostname;
|
|
1793
|
+
} catch {
|
|
1794
|
+
return "Primitive";
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1427
1797
|
async function fetchMachine(url, options, fetchImpl) {
|
|
1428
1798
|
try {
|
|
1429
1799
|
return await fetchImpl(url, options);
|
|
@@ -1431,7 +1801,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
1431
1801
|
options.signal?.throwIfAborted();
|
|
1432
1802
|
throw new MachineAuthError(
|
|
1433
1803
|
"authentication_unavailable",
|
|
1434
|
-
|
|
1804
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
1805
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
1806
|
+
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
1807
|
);
|
|
1436
1808
|
}
|
|
1437
1809
|
}
|
|
@@ -1458,8 +1830,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
1458
1830
|
);
|
|
1459
1831
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
1460
1832
|
}
|
|
1461
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
1462
|
-
|
|
1833
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
1834
|
+
const network = options.secretInjection === "network";
|
|
1835
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
1463
1836
|
throw new MachineAuthError(
|
|
1464
1837
|
"invalid_credentials",
|
|
1465
1838
|
"A machine client ID and secret are required.",
|
|
@@ -1473,11 +1846,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1473
1846
|
redirect: "error",
|
|
1474
1847
|
signal: machineSignal(signal),
|
|
1475
1848
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
client_secret: clientSecret
|
|
1480
|
-
|
|
1849
|
+
// With a network secret the agent proxy authenticates the client with
|
|
1850
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
1851
|
+
body: new URLSearchParams(
|
|
1852
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
1853
|
+
)
|
|
1481
1854
|
},
|
|
1482
1855
|
fetchImpl
|
|
1483
1856
|
);
|
|
@@ -1485,7 +1858,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1485
1858
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
1486
1859
|
throw new MachineAuthError(
|
|
1487
1860
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
1488
|
-
terminal ?
|
|
1861
|
+
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(
|
|
1862
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
1863
|
+
) : "The machine token service is temporarily unavailable.",
|
|
1489
1864
|
terminal,
|
|
1490
1865
|
terminal ? void 0 : machineRetryAt(response)
|
|
1491
1866
|
);
|
|
@@ -1505,6 +1880,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
1505
1880
|
} catch {
|
|
1506
1881
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
1507
1882
|
}
|
|
1883
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
1884
|
+
throw new MachineAuthError(
|
|
1885
|
+
"token_client_mismatch",
|
|
1886
|
+
"The token service issued a token for another machine client."
|
|
1887
|
+
);
|
|
1508
1888
|
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
1889
|
throw new MachineAuthError(
|
|
1510
1890
|
"token_identity_mismatch",
|
|
@@ -1550,32 +1930,76 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
1550
1930
|
const terminal = response.status === 401 || response.status === 403;
|
|
1551
1931
|
throw new MachineAuthError(
|
|
1552
1932
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
1553
|
-
terminal ?
|
|
1933
|
+
terminal ? rejectedCredentialsMessage(
|
|
1934
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
1935
|
+
) : "Machine verification is temporarily unavailable.",
|
|
1554
1936
|
terminal
|
|
1555
1937
|
);
|
|
1556
1938
|
}
|
|
1557
1939
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
1558
1940
|
}
|
|
1941
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
1942
|
+
const rejected = () => new MachineAuthError(
|
|
1943
|
+
"network_token_rejected",
|
|
1944
|
+
`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.`,
|
|
1945
|
+
true
|
|
1946
|
+
);
|
|
1947
|
+
if (status === 401 || status === 403) throw rejected();
|
|
1948
|
+
if (status < 200 || status > 299)
|
|
1949
|
+
throw new MachineAuthError(
|
|
1950
|
+
"verification_unavailable",
|
|
1951
|
+
"Machine verification is temporarily unavailable."
|
|
1952
|
+
);
|
|
1953
|
+
let data;
|
|
1954
|
+
try {
|
|
1955
|
+
data = machineRecord(value);
|
|
1956
|
+
} catch {
|
|
1957
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
1958
|
+
}
|
|
1959
|
+
if (data.authenticated !== true) throw rejected();
|
|
1960
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
1961
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
1962
|
+
throw new MachineAuthError(
|
|
1963
|
+
"network_secret_mismatch",
|
|
1964
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
1965
|
+
true
|
|
1966
|
+
);
|
|
1967
|
+
return parseMachineIdentity(data, clientId);
|
|
1968
|
+
}
|
|
1969
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
1970
|
+
const response = await fetchMachine(
|
|
1971
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
1972
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
1973
|
+
fetchImpl
|
|
1974
|
+
);
|
|
1975
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
1976
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
1977
|
+
}
|
|
1559
1978
|
|
|
1560
1979
|
// src/lib/machine-broker.ts
|
|
1561
1980
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
1981
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
1982
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
1983
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
1984
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
1985
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
1562
1986
|
var IDLE_MS = 5 * 6e4;
|
|
1563
1987
|
function descriptorPath(directory, generation) {
|
|
1564
|
-
return
|
|
1988
|
+
return join11(directory, `machine_broker_${generation}.json`);
|
|
1565
1989
|
}
|
|
1566
1990
|
function readDescriptor(path) {
|
|
1567
1991
|
try {
|
|
1568
|
-
const stat =
|
|
1992
|
+
const stat = lstatSync4(path);
|
|
1569
1993
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1570
1994
|
return void 0;
|
|
1571
|
-
const data = JSON.parse(
|
|
1995
|
+
const data = JSON.parse(readFileSync9(path, "utf8"));
|
|
1572
1996
|
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
1997
|
} catch {
|
|
1574
1998
|
return void 0;
|
|
1575
1999
|
}
|
|
1576
2000
|
}
|
|
1577
|
-
function signature(secret, nonce, body) {
|
|
1578
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
2001
|
+
function signature(secret, nonce, body, purpose) {
|
|
2002
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
1579
2003
|
}
|
|
1580
2004
|
function matches(left, right) {
|
|
1581
2005
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -1590,10 +2014,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1590
2014
|
observedTokenHash: tokenHash(options.observedToken),
|
|
1591
2015
|
timestamp: Date.now()
|
|
1592
2016
|
});
|
|
1593
|
-
const response = await
|
|
2017
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
1594
2018
|
method: "POST",
|
|
1595
2019
|
body,
|
|
1596
|
-
redirect: "error",
|
|
1597
2020
|
signal: options.signal,
|
|
1598
2021
|
headers: {
|
|
1599
2022
|
"Content-Type": "application/json",
|
|
@@ -1624,6 +2047,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
1624
2047
|
);
|
|
1625
2048
|
return credential;
|
|
1626
2049
|
}
|
|
2050
|
+
function brokerEnvironment(options) {
|
|
2051
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
2052
|
+
return {
|
|
2053
|
+
...options.env,
|
|
2054
|
+
PRIM_API_URL: options.apiUrl,
|
|
2055
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
2056
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
2057
|
+
};
|
|
2058
|
+
}
|
|
1627
2059
|
async function acquireBrokerCredential(options) {
|
|
1628
2060
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1629
2061
|
const existing = readDescriptor(path);
|
|
@@ -1635,15 +2067,28 @@ async function acquireBrokerCredential(options) {
|
|
|
1635
2067
|
if (error instanceof MachineAuthError) throw error;
|
|
1636
2068
|
}
|
|
1637
2069
|
}
|
|
1638
|
-
const descriptor = await
|
|
1639
|
-
|
|
2070
|
+
const descriptor = await ensureBroker(options);
|
|
2071
|
+
try {
|
|
2072
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
2073
|
+
} catch (error) {
|
|
2074
|
+
options.signal.throwIfAborted();
|
|
2075
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2076
|
+
throw new MachineAuthError(
|
|
2077
|
+
"broker_unavailable",
|
|
2078
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
2079
|
+
);
|
|
2080
|
+
}
|
|
2081
|
+
}
|
|
2082
|
+
async function ensureBroker(options) {
|
|
2083
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2084
|
+
return withFileLock(
|
|
2085
|
+
join11(options.directory, "machine-broker.lock"),
|
|
1640
2086
|
async () => {
|
|
1641
2087
|
const current = readDescriptor(path);
|
|
1642
2088
|
if (current) {
|
|
1643
2089
|
try {
|
|
1644
|
-
const response = await
|
|
1645
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1646
|
-
redirect: "error"
|
|
2090
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
2091
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
1647
2092
|
});
|
|
1648
2093
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
1649
2094
|
} catch {
|
|
@@ -1662,7 +2107,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1662
2107
|
detached: true,
|
|
1663
2108
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
1664
2109
|
windowsHide: true,
|
|
1665
|
-
env:
|
|
2110
|
+
env: brokerEnvironment(options)
|
|
1666
2111
|
});
|
|
1667
2112
|
let settled = false;
|
|
1668
2113
|
const finish = (error) => {
|
|
@@ -1714,31 +2159,97 @@ async function acquireBrokerCredential(options) {
|
|
|
1714
2159
|
},
|
|
1715
2160
|
{ signal: options.signal }
|
|
1716
2161
|
);
|
|
2162
|
+
}
|
|
2163
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
2164
|
+
const body = JSON.stringify({
|
|
2165
|
+
generation: environment.generation,
|
|
2166
|
+
timestamp: Date.now(),
|
|
2167
|
+
method: request3.method,
|
|
2168
|
+
path: request3.path,
|
|
2169
|
+
headers: request3.headers ?? {},
|
|
2170
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
2171
|
+
});
|
|
2172
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
2173
|
+
method: "POST",
|
|
2174
|
+
body,
|
|
2175
|
+
signal,
|
|
2176
|
+
headers: {
|
|
2177
|
+
"Content-Type": "application/json",
|
|
2178
|
+
"X-Prim-Proof": signature(
|
|
2179
|
+
environment.clientSecret,
|
|
2180
|
+
descriptor.nonce,
|
|
2181
|
+
body,
|
|
2182
|
+
FORWARD_REQUEST_PROOF
|
|
2183
|
+
)
|
|
2184
|
+
}
|
|
2185
|
+
});
|
|
2186
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
2187
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
2188
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
2189
|
+
envelope.proof
|
|
2190
|
+
))
|
|
2191
|
+
throw new MachineAuthError(
|
|
2192
|
+
"broker_unavailable",
|
|
2193
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
2194
|
+
);
|
|
2195
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
2196
|
+
if (data.error) {
|
|
2197
|
+
const error = machineRecord(data.error);
|
|
2198
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
2199
|
+
}
|
|
2200
|
+
const status = data.status;
|
|
2201
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
2202
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
2203
|
+
const headers = new Headers();
|
|
2204
|
+
for (const [name, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
2205
|
+
if (typeof value === "string") headers.set(name, value);
|
|
2206
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
2207
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
2208
|
+
}
|
|
2209
|
+
async function forwardBrokerRequest(options) {
|
|
2210
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2211
|
+
const unavailable = () => new MachineAuthError(
|
|
2212
|
+
"broker_unavailable",
|
|
2213
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
2214
|
+
);
|
|
2215
|
+
const existing = readDescriptor(path);
|
|
2216
|
+
if (existing) {
|
|
2217
|
+
try {
|
|
2218
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
2219
|
+
} catch (error) {
|
|
2220
|
+
options.signal.throwIfAborted();
|
|
2221
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2222
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
const descriptor = await ensureBroker(options);
|
|
1717
2226
|
try {
|
|
1718
|
-
return await
|
|
2227
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
1719
2228
|
} catch (error) {
|
|
1720
2229
|
options.signal.throwIfAborted();
|
|
1721
2230
|
if (error instanceof MachineAuthError) throw error;
|
|
1722
|
-
throw
|
|
1723
|
-
"broker_unavailable",
|
|
1724
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
1725
|
-
);
|
|
2231
|
+
throw unavailable();
|
|
1726
2232
|
}
|
|
1727
2233
|
}
|
|
1728
2234
|
|
|
1729
2235
|
// src/lib/machine-retry.ts
|
|
1730
2236
|
import { createHash as createHash4 } from "crypto";
|
|
1731
|
-
import { lstatSync as
|
|
1732
|
-
import { join as
|
|
1733
|
-
|
|
2237
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync10, readdirSync as readdirSync2, rmSync as rmSync6 } from "fs";
|
|
2238
|
+
import { join as join12 } from "path";
|
|
2239
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
2240
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
2241
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
1734
2242
|
signal?.throwIfAborted();
|
|
1735
2243
|
const key = createHash4("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1736
|
-
const path =
|
|
1737
|
-
let state = {
|
|
2244
|
+
const path = join12(directory, `machine_retry_${key}.json`);
|
|
2245
|
+
let state = {
|
|
2246
|
+
failures: 0,
|
|
2247
|
+
retryAt: 0
|
|
2248
|
+
};
|
|
1738
2249
|
try {
|
|
1739
|
-
const stat =
|
|
2250
|
+
const stat = lstatSync5(path);
|
|
1740
2251
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
1741
|
-
const data = JSON.parse(
|
|
2252
|
+
const data = JSON.parse(readFileSync10(path, "utf8"));
|
|
1742
2253
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
1743
2254
|
throw new Error("Invalid retry state");
|
|
1744
2255
|
state = data;
|
|
@@ -1749,13 +2260,20 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
1749
2260
|
if (state.retryAt > Date.now())
|
|
1750
2261
|
throw new MachineAuthError(
|
|
1751
2262
|
"token_service_unavailable",
|
|
1752
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
2263
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
2264
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
2265
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
2266
|
+
) : (
|
|
2267
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
2268
|
+
// retries at once and names the cause.
|
|
2269
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
2270
|
+
),
|
|
1753
2271
|
false,
|
|
1754
2272
|
state.retryAt
|
|
1755
2273
|
);
|
|
1756
2274
|
try {
|
|
1757
|
-
const result = await
|
|
1758
|
-
|
|
2275
|
+
const result = await request3();
|
|
2276
|
+
rmSync6(path, { force: true });
|
|
1759
2277
|
return result;
|
|
1760
2278
|
} catch (error) {
|
|
1761
2279
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -1766,8 +2284,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
1766
2284
|
].includes(error.code)) {
|
|
1767
2285
|
const failures = Math.min(16, state.failures + 1);
|
|
1768
2286
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
1769
|
-
const retryAt = error.retryAt
|
|
1770
|
-
atomicWriteFile(
|
|
2287
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
2288
|
+
atomicWriteFile(
|
|
2289
|
+
path,
|
|
2290
|
+
JSON.stringify({
|
|
2291
|
+
failures,
|
|
2292
|
+
retryAt,
|
|
2293
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
2294
|
+
}),
|
|
2295
|
+
{ mode: 384 }
|
|
2296
|
+
);
|
|
1771
2297
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
1772
2298
|
}
|
|
1773
2299
|
throw error;
|
|
@@ -1791,13 +2317,13 @@ function hash(value) {
|
|
|
1791
2317
|
return createHash5("sha256").update(value).digest("hex");
|
|
1792
2318
|
}
|
|
1793
2319
|
function recordPath(directory, generation) {
|
|
1794
|
-
return
|
|
2320
|
+
return join13(directory, `machine_${generation}.json`);
|
|
1795
2321
|
}
|
|
1796
2322
|
function storageKey(directory, generation) {
|
|
1797
2323
|
return `${hash(directory)}:${generation}`;
|
|
1798
2324
|
}
|
|
1799
2325
|
function environmentContextPath(deps, clientId) {
|
|
1800
|
-
return
|
|
2326
|
+
return join13(
|
|
1801
2327
|
configurationDirectory(deps),
|
|
1802
2328
|
`machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1803
2329
|
);
|
|
@@ -1860,8 +2386,8 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1860
2386
|
function keyringEntry(key) {
|
|
1861
2387
|
let directory = dirname8(fileURLToPath4(import.meta.url));
|
|
1862
2388
|
for (let depth = 0; depth < 5; depth++) {
|
|
1863
|
-
const loader =
|
|
1864
|
-
if (
|
|
2389
|
+
const loader = join13(directory, "native", "keyring.cjs");
|
|
2390
|
+
if (existsSync9(loader)) {
|
|
1865
2391
|
const module2 = require3(loader);
|
|
1866
2392
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1867
2393
|
}
|
|
@@ -1877,7 +2403,7 @@ function protectPath(path, directory) {
|
|
|
1877
2403
|
}
|
|
1878
2404
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1879
2405
|
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
|
-
|
|
2406
|
+
execFileSync5(
|
|
1881
2407
|
"powershell.exe",
|
|
1882
2408
|
[
|
|
1883
2409
|
"-NoProfile",
|
|
@@ -1889,8 +2415,8 @@ function protectPath(path, directory) {
|
|
|
1889
2415
|
);
|
|
1890
2416
|
}
|
|
1891
2417
|
function ensureDirectory(directory) {
|
|
1892
|
-
|
|
1893
|
-
if (
|
|
2418
|
+
mkdirSync5(directory, { recursive: true, mode: 448 });
|
|
2419
|
+
if (lstatSync6(directory).isSymbolicLink())
|
|
1894
2420
|
throw new MachineAuthError(
|
|
1895
2421
|
"unsafe_storage",
|
|
1896
2422
|
"Credential directory must not be a symbolic link."
|
|
@@ -1905,14 +2431,14 @@ function writePrivate(path, value) {
|
|
|
1905
2431
|
function readPrivate(path) {
|
|
1906
2432
|
let raw;
|
|
1907
2433
|
try {
|
|
1908
|
-
const stat =
|
|
2434
|
+
const stat = lstatSync6(path);
|
|
1909
2435
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1910
2436
|
throw new MachineAuthError(
|
|
1911
2437
|
"unsafe_storage",
|
|
1912
2438
|
"Machine credential files must be owner-only regular files."
|
|
1913
2439
|
);
|
|
1914
2440
|
}
|
|
1915
|
-
raw =
|
|
2441
|
+
raw = readFileSync11(path, "utf8");
|
|
1916
2442
|
} catch (error) {
|
|
1917
2443
|
if (error.code === "ENOENT") return void 0;
|
|
1918
2444
|
throw error;
|
|
@@ -1957,13 +2483,101 @@ function parseProfile(value) {
|
|
|
1957
2483
|
};
|
|
1958
2484
|
}
|
|
1959
2485
|
function readMachineProfile(deps = {}) {
|
|
1960
|
-
const value = readPrivate(
|
|
2486
|
+
const value = readPrivate(join13(configurationDirectory(deps), PROFILE_FILE));
|
|
1961
2487
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1962
2488
|
}
|
|
2489
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
2490
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
2491
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
2492
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2493
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
2494
|
+
const directory = configurationDirectory(deps);
|
|
2495
|
+
const path = join13(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2496
|
+
const known = brokerKeys.get(path);
|
|
2497
|
+
if (known) return known;
|
|
2498
|
+
ensureDirectory(directory);
|
|
2499
|
+
const read = () => {
|
|
2500
|
+
try {
|
|
2501
|
+
const stat = lstatSync6(path);
|
|
2502
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
2503
|
+
throw new MachineAuthError(
|
|
2504
|
+
"unsafe_storage",
|
|
2505
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
2506
|
+
true
|
|
2507
|
+
);
|
|
2508
|
+
const value = readFileSync11(path, "utf8").trim();
|
|
2509
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
2510
|
+
} catch (error) {
|
|
2511
|
+
if (error.code === "ENOENT") return void 0;
|
|
2512
|
+
throw error;
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
2516
|
+
const existing = read();
|
|
2517
|
+
if (existing?.key) {
|
|
2518
|
+
brokerKeys.set(path, existing.key);
|
|
2519
|
+
return existing.key;
|
|
2520
|
+
}
|
|
2521
|
+
if (existing)
|
|
2522
|
+
throw new MachineAuthError(
|
|
2523
|
+
"unsafe_storage",
|
|
2524
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
2525
|
+
true
|
|
2526
|
+
);
|
|
2527
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
2528
|
+
try {
|
|
2529
|
+
writeFileSync5(staged, `${randomBytes4(32).toString("hex")}
|
|
2530
|
+
`, { mode: 384, flag: "wx" });
|
|
2531
|
+
protectPath(staged, false);
|
|
2532
|
+
linkSync(staged, path);
|
|
2533
|
+
} catch (error) {
|
|
2534
|
+
if (error.code !== "EEXIST") throw error;
|
|
2535
|
+
} finally {
|
|
2536
|
+
rmSync7(staged, { force: true });
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
const key = read()?.key;
|
|
2540
|
+
if (!key)
|
|
2541
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
2542
|
+
brokerKeys.set(path, key);
|
|
2543
|
+
return key;
|
|
2544
|
+
}
|
|
1963
2545
|
function environmentCredentials(deps) {
|
|
1964
2546
|
const env = deps.env ?? process.env;
|
|
1965
|
-
const {
|
|
1966
|
-
|
|
2547
|
+
const {
|
|
2548
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
2549
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
2550
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
2551
|
+
} = env;
|
|
2552
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
2553
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
2554
|
+
throw new MachineAuthError(
|
|
2555
|
+
"incomplete_machine_credentials",
|
|
2556
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
2557
|
+
);
|
|
2558
|
+
if (auth !== void 0) {
|
|
2559
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
2560
|
+
throw new MachineAuthError(
|
|
2561
|
+
"incomplete_machine_credentials",
|
|
2562
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
2563
|
+
);
|
|
2564
|
+
if (clientSecret !== void 0)
|
|
2565
|
+
throw new MachineAuthError(
|
|
2566
|
+
"conflicting_credentials",
|
|
2567
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
2568
|
+
);
|
|
2569
|
+
const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
2570
|
+
const credentials = {
|
|
2571
|
+
clientId,
|
|
2572
|
+
generation,
|
|
2573
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
2574
|
+
};
|
|
2575
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
2576
|
+
enumerable: true,
|
|
2577
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
2578
|
+
});
|
|
2579
|
+
return credentials;
|
|
2580
|
+
}
|
|
1967
2581
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1968
2582
|
throw new MachineAuthError(
|
|
1969
2583
|
"incomplete_machine_credentials",
|
|
@@ -1978,7 +2592,7 @@ function environmentCredentials(deps) {
|
|
|
1978
2592
|
}
|
|
1979
2593
|
function hasMachineConfiguration(deps = {}) {
|
|
1980
2594
|
const env = deps.env ?? process.env;
|
|
1981
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 ||
|
|
2595
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(join13(configurationDirectory(deps), PROFILE_FILE));
|
|
1982
2596
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1983
2597
|
throw new MachineAuthError(
|
|
1984
2598
|
"conflicting_credentials",
|
|
@@ -2012,9 +2626,11 @@ function machineSessionEnded(deps = {}) {
|
|
|
2012
2626
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2013
2627
|
if (!generation) return false;
|
|
2014
2628
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2015
|
-
return readPrivate(
|
|
2629
|
+
return readPrivate(join13(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2016
2630
|
}
|
|
2017
2631
|
var environmentTerminal;
|
|
2632
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
2633
|
+
var networkRejection;
|
|
2018
2634
|
async function loadRecord(profile, deps, signal) {
|
|
2019
2635
|
const directory = configurationDirectory(deps);
|
|
2020
2636
|
let value;
|
|
@@ -2078,6 +2694,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2078
2694
|
const apiUrl = apiUrlFor(deps);
|
|
2079
2695
|
const environment = environmentCredentials(deps);
|
|
2080
2696
|
if (environment) {
|
|
2697
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
2081
2698
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
2082
2699
|
const directory2 = configurationDirectory(deps);
|
|
2083
2700
|
ensureDirectory(directory2);
|
|
@@ -2095,22 +2712,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2095
2712
|
writeEnvironmentContext(cached, deps);
|
|
2096
2713
|
return cached;
|
|
2097
2714
|
} catch (error) {
|
|
2098
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
2715
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
2099
2716
|
environmentTerminal = environment.generation;
|
|
2100
2717
|
throw error;
|
|
2101
2718
|
}
|
|
2102
2719
|
}
|
|
2103
2720
|
return withFileLock(
|
|
2104
|
-
|
|
2721
|
+
join13(directory2, "credentials.lock"),
|
|
2105
2722
|
async () => {
|
|
2106
2723
|
if (machineSessionEnded(deps))
|
|
2107
2724
|
throw new MachineAuthError(
|
|
2108
2725
|
"machine_credentials_rejected",
|
|
2109
|
-
"Rotate the injected machine credentials.",
|
|
2726
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
2110
2727
|
true
|
|
2111
2728
|
);
|
|
2112
2729
|
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
2113
2730
|
return cached;
|
|
2731
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
2732
|
+
throw networkRejection.error;
|
|
2114
2733
|
try {
|
|
2115
2734
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
2116
2735
|
directory2,
|
|
@@ -2119,13 +2738,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2119
2738
|
signal,
|
|
2120
2739
|
async () => {
|
|
2121
2740
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
2741
|
+
if (environment.tokenInjection) {
|
|
2742
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
2743
|
+
apiUrl,
|
|
2744
|
+
environment.clientId,
|
|
2745
|
+
signal,
|
|
2746
|
+
deps.fetch
|
|
2747
|
+
);
|
|
2748
|
+
const tokens3 = {
|
|
2749
|
+
accessToken: "",
|
|
2750
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
2751
|
+
};
|
|
2752
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
2753
|
+
}
|
|
2122
2754
|
const tokens2 = await exchangeMachineCredentials(
|
|
2123
2755
|
configuration2,
|
|
2124
2756
|
environment.clientId,
|
|
2125
|
-
|
|
2757
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
2758
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
2126
2759
|
signal,
|
|
2127
|
-
deps.fetch
|
|
2128
|
-
|
|
2760
|
+
deps.fetch,
|
|
2761
|
+
{ secretInjection: environment.secretInjection }
|
|
2762
|
+
).catch((error) => {
|
|
2763
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
2764
|
+
throw new MachineAuthError(
|
|
2765
|
+
"network_secret_mismatch",
|
|
2766
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
2767
|
+
true
|
|
2768
|
+
);
|
|
2769
|
+
throw error;
|
|
2770
|
+
});
|
|
2129
2771
|
const identity2 = await verifyMachineIdentity(
|
|
2130
2772
|
apiUrl,
|
|
2131
2773
|
tokens2.accessToken,
|
|
@@ -2142,17 +2784,33 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2142
2784
|
...identity,
|
|
2143
2785
|
apiUrl,
|
|
2144
2786
|
generation: environment.generation,
|
|
2145
|
-
storage: "environment"
|
|
2787
|
+
storage: "environment",
|
|
2788
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
2146
2789
|
};
|
|
2147
2790
|
writeEnvironmentContext(cached, deps);
|
|
2148
2791
|
return cached;
|
|
2149
2792
|
} catch (error) {
|
|
2793
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
2794
|
+
networkRejection = {
|
|
2795
|
+
generation: environment.generation,
|
|
2796
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
2797
|
+
error
|
|
2798
|
+
};
|
|
2799
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
2800
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2801
|
+
try {
|
|
2802
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2803
|
+
rmSync7(contextPath, { force: true });
|
|
2804
|
+
} catch {
|
|
2805
|
+
}
|
|
2806
|
+
throw error;
|
|
2807
|
+
}
|
|
2150
2808
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
2151
2809
|
environmentTerminal = environment.generation;
|
|
2152
2810
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2153
2811
|
try {
|
|
2154
2812
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2155
|
-
|
|
2813
|
+
rmSync7(contextPath, { force: true });
|
|
2156
2814
|
} catch {
|
|
2157
2815
|
}
|
|
2158
2816
|
}
|
|
@@ -2166,7 +2824,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2166
2824
|
const expected = machineContext(deps);
|
|
2167
2825
|
const directory = configurationDirectory(deps);
|
|
2168
2826
|
return withFileLock(
|
|
2169
|
-
|
|
2827
|
+
join13(directory, "credentials.lock"),
|
|
2170
2828
|
async () => {
|
|
2171
2829
|
const profile = readMachineProfile(deps);
|
|
2172
2830
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2216,7 +2874,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2216
2874
|
await persistRecord(record, deps, signal);
|
|
2217
2875
|
} catch (error) {
|
|
2218
2876
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2219
|
-
writePrivate(
|
|
2877
|
+
writePrivate(join13(directory, "machine_terminal.json"), profile.generation);
|
|
2220
2878
|
throw error;
|
|
2221
2879
|
}
|
|
2222
2880
|
}
|
|
@@ -2227,23 +2885,41 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2227
2885
|
{ signal }
|
|
2228
2886
|
);
|
|
2229
2887
|
}
|
|
2888
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
2889
|
+
const environment = environmentCredentials(deps);
|
|
2890
|
+
if (!environment?.tokenInjection)
|
|
2891
|
+
throw new MachineAuthError(
|
|
2892
|
+
"identity_changed",
|
|
2893
|
+
"Machine identity changed; restart the operation."
|
|
2894
|
+
);
|
|
2895
|
+
const directory = configurationDirectory(deps);
|
|
2896
|
+
ensureDirectory(directory);
|
|
2897
|
+
return forwardBrokerRequest({
|
|
2898
|
+
directory,
|
|
2899
|
+
apiUrl: apiUrlFor(deps),
|
|
2900
|
+
environment,
|
|
2901
|
+
env: deps.env ?? process.env,
|
|
2902
|
+
request: request3,
|
|
2903
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
2904
|
+
});
|
|
2905
|
+
}
|
|
2230
2906
|
|
|
2231
2907
|
// src/lib/credentials.ts
|
|
2232
2908
|
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 =
|
|
2909
|
+
var TOKEN_FILE_PATH = join14(CONFIG_DIRECTORY, "token");
|
|
2910
|
+
var REFRESH_TOKEN_PATH = join14(CONFIG_DIRECTORY, "refresh_token");
|
|
2911
|
+
var TOKEN_EXPIRES_PATH = join14(CONFIG_DIRECTORY, "token_expires_at");
|
|
2912
|
+
var TERMINAL_REFRESH_PATH = join14(CONFIG_DIRECTORY, "refresh_terminal");
|
|
2913
|
+
var CREDENTIAL_METADATA_PATH = join14(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
2914
|
+
var CREDENTIAL_FAMILY_PATH = join14(CONFIG_DIRECTORY, "credential_family.json");
|
|
2915
|
+
var CREDENTIAL_MIGRATION_PATH = join14(CONFIG_DIRECTORY, "credential_migration.json");
|
|
2916
|
+
var CREDENTIAL_LOCK_PATH = join14(CONFIG_DIRECTORY, "credentials.lock");
|
|
2241
2917
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
2242
2918
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
2243
2919
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
2244
2920
|
function readTrimmed(path) {
|
|
2245
2921
|
try {
|
|
2246
|
-
const value =
|
|
2922
|
+
const value = readFileSync12(path, "utf8").trim();
|
|
2247
2923
|
return value || void 0;
|
|
2248
2924
|
} catch {
|
|
2249
2925
|
return void 0;
|
|
@@ -2252,7 +2928,7 @@ function readTrimmed(path) {
|
|
|
2252
2928
|
function resolveAuthCredential(options = {}) {
|
|
2253
2929
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
2254
2930
|
const machine = cachedMachineCredential({ env: options.env });
|
|
2255
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
2931
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
2256
2932
|
}
|
|
2257
2933
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
2258
2934
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -2279,6 +2955,17 @@ function resolveAuthCredential(options = {}) {
|
|
|
2279
2955
|
}
|
|
2280
2956
|
return { token: stored, source: "token_file" };
|
|
2281
2957
|
}
|
|
2958
|
+
function resolveStoredCredential(env = process.env) {
|
|
2959
|
+
const directory = primConfigDirectory({ env });
|
|
2960
|
+
return resolveAuthCredential({
|
|
2961
|
+
env,
|
|
2962
|
+
tokenFilePath: join14(directory, "token"),
|
|
2963
|
+
refreshTokenPath: join14(directory, "refresh_token"),
|
|
2964
|
+
metadataPath: join14(directory, "credential_metadata.json"),
|
|
2965
|
+
familyPath: join14(directory, "credential_family.json"),
|
|
2966
|
+
migrationPath: join14(directory, "credential_migration.json")
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
2282
2969
|
function credentialFingerprint(value) {
|
|
2283
2970
|
return createHash6("sha256").update(value).digest("hex");
|
|
2284
2971
|
}
|
|
@@ -2300,7 +2987,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
2300
2987
|
function readBoundedCredentialJson(path) {
|
|
2301
2988
|
let raw;
|
|
2302
2989
|
try {
|
|
2303
|
-
raw =
|
|
2990
|
+
raw = readFileSync12(path, "utf8");
|
|
2304
2991
|
} catch (error) {
|
|
2305
2992
|
return error.code === "ENOENT" ? void 0 : null;
|
|
2306
2993
|
}
|
|
@@ -2372,9 +3059,9 @@ function jwtExpiresAt(token) {
|
|
|
2372
3059
|
}
|
|
2373
3060
|
|
|
2374
3061
|
// src/daemon/client-instance-id.ts
|
|
2375
|
-
import { randomBytes as
|
|
2376
|
-
import { chmodSync as chmodSync3, lstatSync as
|
|
2377
|
-
import { join as
|
|
3062
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
3063
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
3064
|
+
import { join as join15 } from "path";
|
|
2378
3065
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
2379
3066
|
var INSTANCE_FILE_MODE = 384;
|
|
2380
3067
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -2387,7 +3074,7 @@ function isClientInstanceId(value) {
|
|
|
2387
3074
|
}
|
|
2388
3075
|
function ensurePrivateConfigDirectory(configDir) {
|
|
2389
3076
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
2390
|
-
const metadata =
|
|
3077
|
+
const metadata = lstatSync7(configDir);
|
|
2391
3078
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
2392
3079
|
throw new Error("prim config path must be a private directory");
|
|
2393
3080
|
}
|
|
@@ -2397,7 +3084,7 @@ function ensurePrivateConfigDirectory(configDir) {
|
|
|
2397
3084
|
function readExisting(path) {
|
|
2398
3085
|
let metadata;
|
|
2399
3086
|
try {
|
|
2400
|
-
metadata =
|
|
3087
|
+
metadata = lstatSync7(path);
|
|
2401
3088
|
} catch (error) {
|
|
2402
3089
|
if (error.code === "ENOENT") {
|
|
2403
3090
|
return;
|
|
@@ -2411,7 +3098,7 @@ function readExisting(path) {
|
|
|
2411
3098
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
2412
3099
|
throw new Error("stored client instance identity is invalid");
|
|
2413
3100
|
}
|
|
2414
|
-
const raw =
|
|
3101
|
+
const raw = readFileSync13(path, "utf8");
|
|
2415
3102
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
2416
3103
|
if (raw !== value && raw !== `${value}
|
|
2417
3104
|
` || !isClientInstanceId(value)) {
|
|
@@ -2425,8 +3112,8 @@ function atomicWrite(path, value) {
|
|
|
2425
3112
|
}
|
|
2426
3113
|
async function getOrCreateClientInstanceId(options) {
|
|
2427
3114
|
const configDir = options.configDir;
|
|
2428
|
-
const path =
|
|
2429
|
-
const lockPath =
|
|
3115
|
+
const path = join15(configDir, "client_instance_id");
|
|
3116
|
+
const lockPath = join15(configDir, "client-instance.lock");
|
|
2430
3117
|
ensurePrivateConfigDirectory(configDir);
|
|
2431
3118
|
return withFileLock(
|
|
2432
3119
|
lockPath,
|
|
@@ -2435,7 +3122,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
2435
3122
|
if (existing !== void 0) {
|
|
2436
3123
|
return existing;
|
|
2437
3124
|
}
|
|
2438
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
3125
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
2439
3126
|
"base64url"
|
|
2440
3127
|
)}`;
|
|
2441
3128
|
if (!isClientInstanceId(generated)) {
|
|
@@ -2521,9 +3208,12 @@ var CREDENTIAL_FILE_MODE = 384;
|
|
|
2521
3208
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2522
3209
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
2523
3210
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
3211
|
+
function authExpiredMessage() {
|
|
3212
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
3213
|
+
}
|
|
2524
3214
|
function readTrimmed2(path) {
|
|
2525
3215
|
try {
|
|
2526
|
-
const value =
|
|
3216
|
+
const value = readFileSync14(path, "utf8").trim();
|
|
2527
3217
|
return value || void 0;
|
|
2528
3218
|
} catch {
|
|
2529
3219
|
return void 0;
|
|
@@ -2540,7 +3230,7 @@ function expiresAtFor(token, expiresIn) {
|
|
|
2540
3230
|
}
|
|
2541
3231
|
function ensureConfigDirectory() {
|
|
2542
3232
|
const directory = dirname9(TOKEN_FILE_PATH);
|
|
2543
|
-
|
|
3233
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
2544
3234
|
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
2545
3235
|
}
|
|
2546
3236
|
function atomicWrite2(path, content) {
|
|
@@ -2548,8 +3238,8 @@ function atomicWrite2(path, content) {
|
|
|
2548
3238
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
2549
3239
|
}
|
|
2550
3240
|
function removeCredentialFile(path) {
|
|
2551
|
-
if (!
|
|
2552
|
-
|
|
3241
|
+
if (!existsSync10(path)) return false;
|
|
3242
|
+
rmSync8(path, { force: true });
|
|
2553
3243
|
return true;
|
|
2554
3244
|
}
|
|
2555
3245
|
function getTokenExpiresAt() {
|
|
@@ -2902,7 +3592,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
2902
3592
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
2903
3593
|
async function managementResponseValue(response) {
|
|
2904
3594
|
if (response.status === 401) {
|
|
2905
|
-
throw new HttpError(401,
|
|
3595
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2906
3596
|
}
|
|
2907
3597
|
let value;
|
|
2908
3598
|
try {
|
|
@@ -2924,23 +3614,50 @@ function selectedCredential() {
|
|
|
2924
3614
|
}
|
|
2925
3615
|
return _cachedCredential;
|
|
2926
3616
|
}
|
|
3617
|
+
async function requestHeaders(method, path) {
|
|
3618
|
+
return {
|
|
3619
|
+
"Content-Type": "application/json",
|
|
3620
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
3621
|
+
};
|
|
3622
|
+
}
|
|
2927
3623
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
2928
3624
|
return fetch(`${siteUrl}${path}`, {
|
|
2929
3625
|
method,
|
|
2930
|
-
headers: {
|
|
2931
|
-
Authorization: `Bearer ${token}`,
|
|
2932
|
-
"Content-Type": "application/json",
|
|
2933
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
2934
|
-
},
|
|
3626
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
2935
3627
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
2936
3628
|
signal: options?.signal,
|
|
2937
3629
|
redirect: options?.redirect
|
|
2938
3630
|
});
|
|
2939
3631
|
}
|
|
3632
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
3633
|
+
if (!credential.tokenInjection)
|
|
3634
|
+
return fetchWithToken(
|
|
3635
|
+
method,
|
|
3636
|
+
path,
|
|
3637
|
+
body,
|
|
3638
|
+
{ ...options, redirect: "error" },
|
|
3639
|
+
credential.accessToken,
|
|
3640
|
+
credential.apiUrl
|
|
3641
|
+
);
|
|
3642
|
+
try {
|
|
3643
|
+
return await forwardMachineRequest(
|
|
3644
|
+
{
|
|
3645
|
+
method,
|
|
3646
|
+
path,
|
|
3647
|
+
headers: await requestHeaders(method, path),
|
|
3648
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
3649
|
+
},
|
|
3650
|
+
options.signal
|
|
3651
|
+
);
|
|
3652
|
+
} catch (error) {
|
|
3653
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
3654
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
3655
|
+
}
|
|
3656
|
+
}
|
|
2940
3657
|
async function responseValue(response) {
|
|
2941
3658
|
if (!response.ok) {
|
|
2942
3659
|
if (response.status === 401) {
|
|
2943
|
-
throw new HttpError(401,
|
|
3660
|
+
throw new HttpError(401, authExpiredMessage());
|
|
2944
3661
|
}
|
|
2945
3662
|
const errorBody = await response.json().catch(() => null);
|
|
2946
3663
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -2967,14 +3684,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2967
3684
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
2968
3685
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
2969
3686
|
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
|
-
);
|
|
3687
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
2978
3688
|
if (response.status === 401) {
|
|
2979
3689
|
const renewed = await acquireMachineCredential({
|
|
2980
3690
|
force: true,
|
|
@@ -2983,19 +3693,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
2983
3693
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
2984
3694
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
2985
3695
|
}
|
|
2986
|
-
response = await
|
|
2987
|
-
method,
|
|
2988
|
-
path,
|
|
2989
|
-
body,
|
|
2990
|
-
{ ...requestOptions, redirect: "error" },
|
|
2991
|
-
renewed.accessToken,
|
|
2992
|
-
renewed.apiUrl
|
|
2993
|
-
);
|
|
3696
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
2994
3697
|
}
|
|
2995
3698
|
if (response.status === 401)
|
|
2996
3699
|
throw new HttpError(
|
|
2997
3700
|
401,
|
|
2998
|
-
"Machine access was rejected.
|
|
3701
|
+
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(
|
|
3702
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
3703
|
+
)
|
|
2999
3704
|
);
|
|
3000
3705
|
return parse2(response);
|
|
3001
3706
|
};
|
|
@@ -3005,7 +3710,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
3005
3710
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
3006
3711
|
};
|
|
3007
3712
|
}
|
|
3008
|
-
async function
|
|
3713
|
+
async function request2(method, path, body, options) {
|
|
3009
3714
|
const machine = await machineClient(options);
|
|
3010
3715
|
if (machine)
|
|
3011
3716
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -3021,10 +3726,10 @@ async function request(method, path, body, options) {
|
|
|
3021
3726
|
if (token) credential = { token, source: "token_file" };
|
|
3022
3727
|
}
|
|
3023
3728
|
if (!credential) {
|
|
3024
|
-
throw new HttpError(401,
|
|
3729
|
+
throw new HttpError(401, authExpiredMessage());
|
|
3025
3730
|
}
|
|
3026
3731
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
3027
|
-
throw new HttpError(401,
|
|
3732
|
+
throw new HttpError(401, authExpiredMessage());
|
|
3028
3733
|
}
|
|
3029
3734
|
const tokenUsed = credential.token;
|
|
3030
3735
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -3047,8 +3752,8 @@ async function request(method, path, body, options) {
|
|
|
3047
3752
|
}
|
|
3048
3753
|
function getClient() {
|
|
3049
3754
|
return {
|
|
3050
|
-
get: (path, options) =>
|
|
3051
|
-
post: (path, body, options) =>
|
|
3755
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
3756
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
3052
3757
|
};
|
|
3053
3758
|
}
|
|
3054
3759
|
|
|
@@ -3057,20 +3762,20 @@ import { createHash as createHash10 } from "crypto";
|
|
|
3057
3762
|
import {
|
|
3058
3763
|
constants as constants4,
|
|
3059
3764
|
closeSync as closeSync3,
|
|
3060
|
-
existsSync as
|
|
3765
|
+
existsSync as existsSync13,
|
|
3061
3766
|
fstatSync as fstatSync2,
|
|
3062
|
-
lstatSync as
|
|
3063
|
-
mkdirSync as
|
|
3767
|
+
lstatSync as lstatSync10,
|
|
3768
|
+
mkdirSync as mkdirSync7,
|
|
3064
3769
|
openSync as openSync3,
|
|
3065
|
-
readFileSync as
|
|
3770
|
+
readFileSync as readFileSync17,
|
|
3066
3771
|
readSync as readSync2,
|
|
3067
|
-
readdirSync as
|
|
3772
|
+
readdirSync as readdirSync5,
|
|
3068
3773
|
realpathSync as realpathSync3,
|
|
3069
|
-
rmSync as
|
|
3774
|
+
rmSync as rmSync9,
|
|
3070
3775
|
rmdirSync as rmdirSync3
|
|
3071
3776
|
} from "fs";
|
|
3072
|
-
import { homedir as
|
|
3073
|
-
import { dirname as dirname12, isAbsolute as isAbsolute6, join as
|
|
3777
|
+
import { homedir as homedir7 } from "os";
|
|
3778
|
+
import { dirname as dirname12, isAbsolute as isAbsolute6, join as join20, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
|
|
3074
3779
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
3075
3780
|
|
|
3076
3781
|
// node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
|
|
@@ -9345,18 +10050,18 @@ import { createHash as createHash9 } from "crypto";
|
|
|
9345
10050
|
import {
|
|
9346
10051
|
constants as constants3,
|
|
9347
10052
|
closeSync as closeSync2,
|
|
9348
|
-
existsSync as
|
|
10053
|
+
existsSync as existsSync12,
|
|
9349
10054
|
fstatSync,
|
|
9350
|
-
lstatSync as
|
|
10055
|
+
lstatSync as lstatSync9,
|
|
9351
10056
|
openSync as openSync2,
|
|
9352
|
-
readFileSync as
|
|
10057
|
+
readFileSync as readFileSync16,
|
|
9353
10058
|
readSync,
|
|
9354
|
-
readdirSync as
|
|
10059
|
+
readdirSync as readdirSync4,
|
|
9355
10060
|
rmdirSync as rmdirSync2,
|
|
9356
10061
|
unlinkSync as unlinkSync2
|
|
9357
10062
|
} from "fs";
|
|
9358
|
-
import { homedir as
|
|
9359
|
-
import { dirname as dirname11, join as
|
|
10063
|
+
import { homedir as homedir6 } from "os";
|
|
10064
|
+
import { dirname as dirname11, join as join19, resolve as resolve4 } from "path";
|
|
9360
10065
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
9361
10066
|
|
|
9362
10067
|
// node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
|
|
@@ -9526,7 +10231,7 @@ Diff.prototype = {
|
|
|
9526
10231
|
tokenize: function tokenize(value) {
|
|
9527
10232
|
return value.split("");
|
|
9528
10233
|
},
|
|
9529
|
-
join: function
|
|
10234
|
+
join: function join17(chars) {
|
|
9530
10235
|
return chars.join("");
|
|
9531
10236
|
}
|
|
9532
10237
|
};
|
|
@@ -9712,10 +10417,10 @@ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
|
|
|
9712
10417
|
|
|
9713
10418
|
// src/commands/welcome-skill.ts
|
|
9714
10419
|
import { createHash as createHash8 } from "crypto";
|
|
9715
|
-
import { existsSync as
|
|
9716
|
-
import { homedir as
|
|
9717
|
-
import { dirname as dirname10, join as
|
|
9718
|
-
var WELCOME_SKILL_SOURCE =
|
|
10420
|
+
import { existsSync as existsSync11, lstatSync as lstatSync8, readFileSync as readFileSync15, readdirSync as readdirSync3, rmdirSync, unlinkSync } from "fs";
|
|
10421
|
+
import { homedir as homedir5 } from "os";
|
|
10422
|
+
import { dirname as dirname10, join as join18 } from "path";
|
|
10423
|
+
var WELCOME_SKILL_SOURCE = join18("skills", "prim-welcome", "SKILL.md");
|
|
9719
10424
|
|
|
9720
10425
|
// src/commands/skill.ts
|
|
9721
10426
|
var __dirname = dirname11(fileURLToPath5(import.meta.url));
|
|
@@ -9727,7 +10432,7 @@ var SKILL_BEGIN_BUFFER = Buffer.from(SKILL_BEGIN);
|
|
|
9727
10432
|
var SKILL_END_BUFFER = Buffer.from(SKILL_END);
|
|
9728
10433
|
function readCodexGuidance(path) {
|
|
9729
10434
|
try {
|
|
9730
|
-
const entry =
|
|
10435
|
+
const entry = lstatSync9(path);
|
|
9731
10436
|
if (entry.isSymbolicLink() || !entry.isFile()) return null;
|
|
9732
10437
|
const fd = openSync2(path, constants3.O_RDONLY | constants3.O_NOFOLLOW);
|
|
9733
10438
|
try {
|
|
@@ -9750,10 +10455,10 @@ function readCodexGuidance(path) {
|
|
|
9750
10455
|
}
|
|
9751
10456
|
}
|
|
9752
10457
|
function effectiveCodexGuidance(scope) {
|
|
9753
|
-
const override = readCodexGuidance(
|
|
10458
|
+
const override = readCodexGuidance(join19(scope, "AGENTS.override.md"));
|
|
9754
10459
|
if (override === null) return null;
|
|
9755
10460
|
if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
|
|
9756
|
-
const base = readCodexGuidance(
|
|
10461
|
+
const base = readCodexGuidance(join19(scope, "AGENTS.md"));
|
|
9757
10462
|
return base ?? null;
|
|
9758
10463
|
}
|
|
9759
10464
|
function hasUsablePrimBlock(content, visibleBytes) {
|
|
@@ -9776,7 +10481,7 @@ function hasUsablePrimBlock(content, visibleBytes) {
|
|
|
9776
10481
|
}
|
|
9777
10482
|
function hasUsableCodexGuidance(projectRoot2) {
|
|
9778
10483
|
try {
|
|
9779
|
-
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) :
|
|
10484
|
+
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join19(homedir6(), ".codex");
|
|
9780
10485
|
const scopes = [
|
|
9781
10486
|
{ path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
|
|
9782
10487
|
{ path: projectRoot2, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
|
|
@@ -9796,19 +10501,19 @@ function sha256(content) {
|
|
|
9796
10501
|
}
|
|
9797
10502
|
function cursorSkillDirectory(cwd, scope) {
|
|
9798
10503
|
const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
|
|
9799
|
-
return
|
|
10504
|
+
return join19(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
|
|
9800
10505
|
}
|
|
9801
10506
|
function cursorSkillPaths(cwd, scope) {
|
|
9802
10507
|
const directory = cursorSkillDirectory(cwd, scope);
|
|
9803
10508
|
return {
|
|
9804
10509
|
directory,
|
|
9805
|
-
skill:
|
|
9806
|
-
manifest:
|
|
10510
|
+
skill: join19(directory, "SKILL.md"),
|
|
10511
|
+
manifest: join19(directory, CURSOR_SKILL_MANIFEST)
|
|
9807
10512
|
};
|
|
9808
10513
|
}
|
|
9809
10514
|
function readCursorSkillManifest(path) {
|
|
9810
10515
|
try {
|
|
9811
|
-
const value = JSON.parse(
|
|
10516
|
+
const value = JSON.parse(readFileSync16(path, "utf8"));
|
|
9812
10517
|
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
9813
10518
|
const record = value;
|
|
9814
10519
|
if (record.version !== 1 || record.owner !== CURSOR_SKILL_OWNER || typeof record.contentSha256 !== "string" || !/^[0-9a-f]{64}$/u.test(record.contentSha256)) {
|
|
@@ -9822,7 +10527,7 @@ function readCursorSkillManifest(path) {
|
|
|
9822
10527
|
function cursorSkillStatus(cwd, scope) {
|
|
9823
10528
|
const paths = cursorSkillPaths(cwd, scope);
|
|
9824
10529
|
const manifest = readCursorSkillManifest(paths.manifest);
|
|
9825
|
-
const content =
|
|
10530
|
+
const content = existsSync12(paths.skill) ? readFileSync16(paths.skill, "utf8") : void 0;
|
|
9826
10531
|
const owned = manifest !== void 0;
|
|
9827
10532
|
const installed = owned && content !== void 0 && sha256(content) === manifest.contentSha256;
|
|
9828
10533
|
return {
|
|
@@ -9839,7 +10544,7 @@ function loadSkill(file = "SKILL.md") {
|
|
|
9839
10544
|
let dir = __dirname;
|
|
9840
10545
|
while (dir !== dirname11(dir)) {
|
|
9841
10546
|
const p = resolve4(dir, file);
|
|
9842
|
-
if (
|
|
10547
|
+
if (existsSync12(p)) return readFileSync16(p, "utf-8");
|
|
9843
10548
|
dir = dirname11(dir);
|
|
9844
10549
|
}
|
|
9845
10550
|
throw new Error(`${file} not found in package`);
|
|
@@ -9856,14 +10561,14 @@ var MAX_SKILL_BYTES = 1024 * 1024;
|
|
|
9856
10561
|
var REFRESH_LOCK_TIMEOUT_MS = 150;
|
|
9857
10562
|
var REFRESH_LOCK_POLL_MS = 10;
|
|
9858
10563
|
function pluginDirFor(cwd, scope) {
|
|
9859
|
-
const base = scope === "user" ?
|
|
9860
|
-
return
|
|
10564
|
+
const base = scope === "user" ? join20(homedir7(), ".claude") : join20(gitToplevel(cwd) ?? cwd, ".claude");
|
|
10565
|
+
return join20(base, "skills", "prim");
|
|
9861
10566
|
}
|
|
9862
10567
|
function packageVersion2() {
|
|
9863
10568
|
let dir = __dirname2;
|
|
9864
10569
|
while (dir !== dirname12(dir)) {
|
|
9865
10570
|
const p = resolve5(dir, "package.json");
|
|
9866
|
-
if (
|
|
10571
|
+
if (existsSync13(p)) return JSON.parse(readFileSync17(p, "utf-8")).version;
|
|
9867
10572
|
dir = dirname12(dir);
|
|
9868
10573
|
}
|
|
9869
10574
|
return "0.0.0";
|
|
@@ -9879,8 +10584,8 @@ function renderClaudePlugin() {
|
|
|
9879
10584
|
}
|
|
9880
10585
|
function pluginPaths(dir) {
|
|
9881
10586
|
return {
|
|
9882
|
-
manifestPath:
|
|
9883
|
-
skillPath:
|
|
10587
|
+
manifestPath: join20(dir, ".claude-plugin", "plugin.json"),
|
|
10588
|
+
skillPath: join20(dir, "SKILL.md")
|
|
9884
10589
|
};
|
|
9885
10590
|
}
|
|
9886
10591
|
function pathIsInside(root, path) {
|
|
@@ -9890,7 +10595,7 @@ function pathIsInside(root, path) {
|
|
|
9890
10595
|
function managedPathsAreSafe(paths, projectRoot2) {
|
|
9891
10596
|
try {
|
|
9892
10597
|
const managed = [paths.manifestPath, paths.skillPath];
|
|
9893
|
-
if (managed.some((path) => !
|
|
10598
|
+
if (managed.some((path) => !lstatSync10(path).isFile())) return false;
|
|
9894
10599
|
if (projectRoot2 === void 0) return true;
|
|
9895
10600
|
const realRoot = realpathSync3(projectRoot2);
|
|
9896
10601
|
return managed.every((path) => pathIsInside(realRoot, realpathSync3(path)));
|
|
@@ -9931,7 +10636,7 @@ function hasUsablePrimFrontmatter(skill) {
|
|
|
9931
10636
|
}
|
|
9932
10637
|
}
|
|
9933
10638
|
function inspectRecognizedInstallation(paths, projectRoot2) {
|
|
9934
|
-
if (!
|
|
10639
|
+
if (!existsSync13(paths.manifestPath) || !existsSync13(paths.skillPath)) return;
|
|
9935
10640
|
if (!managedPathsAreSafe(paths, projectRoot2)) return;
|
|
9936
10641
|
const manifest = readBoundedRegularFile(paths.manifestPath, MAX_MANIFEST_BYTES2);
|
|
9937
10642
|
const parsed = JSON.parse(manifest);
|
|
@@ -9945,9 +10650,9 @@ function inspectRecognizedInstallation(paths, projectRoot2) {
|
|
|
9945
10650
|
};
|
|
9946
10651
|
}
|
|
9947
10652
|
function refreshLockDir(physicalPluginDir) {
|
|
9948
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ||
|
|
10653
|
+
const cacheRoot = process.env.XDG_CACHE_HOME || join20(homedir7(), ".cache");
|
|
9949
10654
|
const identity = createHash10("sha256").update(physicalPluginDir).digest("hex");
|
|
9950
|
-
return
|
|
10655
|
+
return join20(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
|
|
9951
10656
|
}
|
|
9952
10657
|
async function refreshClaudePlugins(cwd, options = {}) {
|
|
9953
10658
|
const result = { installed: 0, refreshed: 0 };
|
|
@@ -9955,7 +10660,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
9955
10660
|
if (options.includeProject !== false) {
|
|
9956
10661
|
const projectRoot2 = options.projectRoot ?? gitToplevel(cwd);
|
|
9957
10662
|
if (projectRoot2 !== null && isAbsolute6(projectRoot2)) {
|
|
9958
|
-
candidates.push({ dir:
|
|
10663
|
+
candidates.push({ dir: join20(projectRoot2, ".claude", "skills", "prim"), projectRoot: projectRoot2 });
|
|
9959
10664
|
}
|
|
9960
10665
|
}
|
|
9961
10666
|
candidates.push({ dir: pluginDirFor(cwd, "user") });
|
|
@@ -10003,7 +10708,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
10003
10708
|
};
|
|
10004
10709
|
try {
|
|
10005
10710
|
const paths = pluginPaths(dir);
|
|
10006
|
-
if (!
|
|
10711
|
+
if (!existsSync13(paths.manifestPath) || !existsSync13(paths.skillPath)) continue;
|
|
10007
10712
|
const physicalPluginDir = realpathSync3(dir);
|
|
10008
10713
|
if (seen.has(physicalPluginDir)) continue;
|
|
10009
10714
|
seen.add(physicalPluginDir);
|
|
@@ -10078,14 +10783,14 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
10078
10783
|
|
|
10079
10784
|
// src/daemon/client.ts
|
|
10080
10785
|
import { createConnection } from "net";
|
|
10081
|
-
import { join as
|
|
10082
|
-
var SOCK_PATH =
|
|
10786
|
+
import { join as join21 } from "path";
|
|
10787
|
+
var SOCK_PATH = join21(primConfigDirectory(), "sock");
|
|
10083
10788
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
10084
10789
|
var nextRequestId = 1;
|
|
10085
10790
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
10086
10791
|
const id = nextRequestId++;
|
|
10087
10792
|
const caller = resolveDaemonPrincipal();
|
|
10088
|
-
const
|
|
10793
|
+
const request3 = {
|
|
10089
10794
|
id,
|
|
10090
10795
|
method,
|
|
10091
10796
|
params,
|
|
@@ -10124,7 +10829,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
10124
10829
|
});
|
|
10125
10830
|
socket.on("connect", () => {
|
|
10126
10831
|
try {
|
|
10127
|
-
socket?.write(`${JSON.stringify(
|
|
10832
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
10128
10833
|
`);
|
|
10129
10834
|
} catch {
|
|
10130
10835
|
clearTimeout(timer);
|
|
@@ -10385,206 +11090,16 @@ async function acknowledgeDecisionFeedback(input, dependencies = {}) {
|
|
|
10385
11090
|
}
|
|
10386
11091
|
}
|
|
10387
11092
|
|
|
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
11093
|
// src/lib/bin-cache.ts
|
|
10579
|
-
import { chmodSync as chmodSync5, mkdirSync as
|
|
11094
|
+
import { chmodSync as chmodSync5, mkdirSync as mkdirSync8 } from "fs";
|
|
10580
11095
|
import { homedir as homedir8 } from "os";
|
|
10581
|
-
import { join as
|
|
11096
|
+
import { join as join22 } from "path";
|
|
10582
11097
|
var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
|
|
10583
11098
|
var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
|
|
10584
11099
|
var GIT_HOOK_CACHED_BINS = ["prim-post-commit", "prim-post-rewrite"];
|
|
10585
11100
|
function binCacheDir() {
|
|
10586
|
-
const base = process.env.XDG_CACHE_HOME ||
|
|
10587
|
-
return
|
|
11101
|
+
const base = process.env.XDG_CACHE_HOME || join22(homedir8(), ".cache");
|
|
11102
|
+
return join22(base, "prim", "bin");
|
|
10588
11103
|
}
|
|
10589
11104
|
function writeAtomic(path, content) {
|
|
10590
11105
|
atomicWriteFile(path, content, { mode: 384 });
|
|
@@ -10595,19 +11110,104 @@ function warmBinCache() {
|
|
|
10595
11110
|
return;
|
|
10596
11111
|
}
|
|
10597
11112
|
const dir = binCacheDir();
|
|
10598
|
-
|
|
11113
|
+
mkdirSync8(dir, { recursive: true, mode: 448 });
|
|
10599
11114
|
chmodSync5(dir, 448);
|
|
10600
|
-
writeAtomic(
|
|
11115
|
+
writeAtomic(join22(dir, "node"), process.execPath);
|
|
10601
11116
|
for (const bin of GIT_HOOK_CACHED_BINS) {
|
|
10602
11117
|
const file = binFile(bin);
|
|
10603
11118
|
if (file) {
|
|
10604
|
-
writeAtomic(
|
|
11119
|
+
writeAtomic(join22(dir, bin), file);
|
|
10605
11120
|
}
|
|
10606
11121
|
}
|
|
10607
11122
|
} catch {
|
|
10608
11123
|
}
|
|
10609
11124
|
}
|
|
10610
11125
|
|
|
11126
|
+
// src/lib/cloud-session.ts
|
|
11127
|
+
var PRODUCTION_SIGN_IN_HOST = "signin.getprimitive.ai";
|
|
11128
|
+
var PROBE_TIMEOUT_MS = 3e3;
|
|
11129
|
+
function repositoryIdentityRemedy(root) {
|
|
11130
|
+
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";
|
|
11131
|
+
}
|
|
11132
|
+
function hostOf2(url, fallback) {
|
|
11133
|
+
try {
|
|
11134
|
+
return new URL(url).hostname || fallback;
|
|
11135
|
+
} catch {
|
|
11136
|
+
return fallback;
|
|
11137
|
+
}
|
|
11138
|
+
}
|
|
11139
|
+
function cloudAllowedDomains(siteUrl = getSiteUrl(), signInHost = PRODUCTION_SIGN_IN_HOST, env = process.env) {
|
|
11140
|
+
const api = hostOf2(siteUrl, "api.getprimitive.ai");
|
|
11141
|
+
return env.PRIM_M2M_CLIENT_AUTH === NETWORK_TOKEN_AUTH ? [api] : [.../* @__PURE__ */ new Set([api, signInHost])];
|
|
11142
|
+
}
|
|
11143
|
+
function cloudEgressRemedy(siteUrl, signInHost, env) {
|
|
11144
|
+
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)`;
|
|
11145
|
+
}
|
|
11146
|
+
function probeFailure(error) {
|
|
11147
|
+
const name = error instanceof Error ? error.name : "";
|
|
11148
|
+
if (name === "TimeoutError" || name === "AbortError") return "timeout";
|
|
11149
|
+
const cause = error?.cause;
|
|
11150
|
+
const code = typeof cause?.code === "string" ? cause.code : "";
|
|
11151
|
+
const message = typeof cause?.message === "string" ? cause.message : "";
|
|
11152
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return "blocked";
|
|
11153
|
+
if (/cancel|tunnel|\(403\)/iu.test(message) && !/\(5\d\d\)/u.test(message)) return "blocked";
|
|
11154
|
+
return code || "network error";
|
|
11155
|
+
}
|
|
11156
|
+
async function probe(url, fetchImpl) {
|
|
11157
|
+
try {
|
|
11158
|
+
const response = await fetchImpl(url, {
|
|
11159
|
+
redirect: "manual",
|
|
11160
|
+
signal: AbortSignal.timeout(PROBE_TIMEOUT_MS)
|
|
11161
|
+
});
|
|
11162
|
+
return { ok: true, response };
|
|
11163
|
+
} catch (error) {
|
|
11164
|
+
return { ok: false, failure: probeFailure(error) };
|
|
11165
|
+
}
|
|
11166
|
+
}
|
|
11167
|
+
function unreachable(what, failure, remedy) {
|
|
11168
|
+
if (failure === "blocked") return `this environment cannot reach ${what}. To fix it, ${remedy}.`;
|
|
11169
|
+
if (failure === "timeout")
|
|
11170
|
+
return `${what} did not answer in time. If this persists, check that you ${remedy.replace(/^add /u, "added ")}.`;
|
|
11171
|
+
return `${what} could not be reached (${failure}). Check the environment's network access: ${remedy}.`;
|
|
11172
|
+
}
|
|
11173
|
+
async function diagnoseCloudSession(options = {}) {
|
|
11174
|
+
const env = options.env ?? process.env;
|
|
11175
|
+
if (!isClaudeCloudSession(env)) return void 0;
|
|
11176
|
+
const prefix = "Primitive is not connected in this Claude Code cloud session";
|
|
11177
|
+
let machine;
|
|
11178
|
+
try {
|
|
11179
|
+
machine = hasMachineConfiguration({ env });
|
|
11180
|
+
} catch (error) {
|
|
11181
|
+
if (error instanceof MachineAuthError && (error.code === "conflicting_credentials" || env.PRIM_M2M_CLIENT_AUTH !== void 0))
|
|
11182
|
+
return `${prefix}: ${error.message}`;
|
|
11183
|
+
return `${prefix}: ${error instanceof MachineAuthError ? error.message : "its machine credentials are incomplete."} To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
|
|
11184
|
+
}
|
|
11185
|
+
if (!machine && !resolveStoredCredential(env))
|
|
11186
|
+
return `${prefix}: it has no credentials. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
|
|
11187
|
+
if (options.cwd !== void 0 && !githubRepositoryFullName(options.cwd))
|
|
11188
|
+
return `${prefix}: ${repositoryIdentityRemedy(options.cwd)}.`;
|
|
11189
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
11190
|
+
const siteUrl = options.siteUrl ?? getSiteUrl();
|
|
11191
|
+
const config = await probe(`${siteUrl.replace(/\/+$/u, "")}/api/cli/auth/m2m/config`, fetchImpl);
|
|
11192
|
+
if (!config.ok)
|
|
11193
|
+
return `${prefix}: ${unreachable("Primitive", config.failure, cloudEgressRemedy(siteUrl, void 0, env))}`;
|
|
11194
|
+
if (machine && env.PRIM_M2M_CLIENT_AUTH !== NETWORK_TOKEN_AUTH) {
|
|
11195
|
+
let issuer;
|
|
11196
|
+
try {
|
|
11197
|
+
const body = await config.response.json();
|
|
11198
|
+
issuer = typeof body.issuer === "string" ? machineApiUrl(body.issuer) : void 0;
|
|
11199
|
+
} catch {
|
|
11200
|
+
issuer = void 0;
|
|
11201
|
+
}
|
|
11202
|
+
if (issuer) {
|
|
11203
|
+
const signIn = await probe(issuer, fetchImpl);
|
|
11204
|
+
if (!signIn.ok)
|
|
11205
|
+
return `${prefix}: ${unreachable("Primitive's sign-in service", signIn.failure, cloudEgressRemedy(siteUrl, hostOf2(issuer, PRODUCTION_SIGN_IN_HOST)))}`;
|
|
11206
|
+
}
|
|
11207
|
+
}
|
|
11208
|
+
return `${prefix}: the repository could not be connected. Run \`prim setup --cloud\` for details.`;
|
|
11209
|
+
}
|
|
11210
|
+
|
|
10611
11211
|
// src/generated/cli-http-v1.validators.js
|
|
10612
11212
|
var import_ucs2length = __toESM(require_ucs2length(), 1);
|
|
10613
11213
|
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,8 +38021,8 @@ async function fetchAndCacheCollectScope(cwd, dependencies = defaultDependencies
|
|
|
37421
38021
|
|
|
37422
38022
|
// src/lib/commit-heartbeat.ts
|
|
37423
38023
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
37424
|
-
import { mkdirSync as
|
|
37425
|
-
import { dirname as dirname13, join as
|
|
38024
|
+
import { mkdirSync as mkdirSync9, readFileSync as readFileSync18, readdirSync as readdirSync6, unlinkSync as unlinkSync3 } from "fs";
|
|
38025
|
+
import { dirname as dirname13, join as join23, resolve as resolve6 } from "path";
|
|
37426
38026
|
var WIRED_PATH = "prim/git-hooks-wired";
|
|
37427
38027
|
var GIT_TIMEOUT_MS4 = 1e3;
|
|
37428
38028
|
var MAX_STAMP_BYTES = 1024;
|
|
@@ -37434,11 +38034,11 @@ function commonPath(cwd, relative4) {
|
|
|
37434
38034
|
timeout: GIT_TIMEOUT_MS4
|
|
37435
38035
|
}).replace(/\r?\n$/u, "");
|
|
37436
38036
|
if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
|
|
37437
|
-
return
|
|
38037
|
+
return join23(resolve6(cwd, value), relative4);
|
|
37438
38038
|
}
|
|
37439
38039
|
function ensurePrivateParent(path) {
|
|
37440
|
-
|
|
37441
|
-
|
|
38040
|
+
mkdirSync9(dirname13(dirname13(path)), { recursive: true, mode: 448 });
|
|
38041
|
+
mkdirSync9(dirname13(path), { recursive: true, mode: 448 });
|
|
37442
38042
|
}
|
|
37443
38043
|
function writeStamp(path, at) {
|
|
37444
38044
|
ensurePrivateParent(path);
|
|
@@ -37447,7 +38047,7 @@ function writeStamp(path, at) {
|
|
|
37447
38047
|
}
|
|
37448
38048
|
function readStampAt(path) {
|
|
37449
38049
|
try {
|
|
37450
|
-
const raw =
|
|
38050
|
+
const raw = readFileSync18(path, "utf8");
|
|
37451
38051
|
if (raw.length > MAX_STAMP_BYTES) return void 0;
|
|
37452
38052
|
const parsed = JSON.parse(raw);
|
|
37453
38053
|
return typeof parsed.at === "number" && Number.isSafeInteger(parsed.at) && parsed.at > 0 ? parsed.at : void 0;
|
|
@@ -37476,19 +38076,19 @@ import { createHash as createHash12, randomUUID as randomUUID3 } from "crypto";
|
|
|
37476
38076
|
import {
|
|
37477
38077
|
constants as constants5,
|
|
37478
38078
|
closeSync as closeSync4,
|
|
37479
|
-
existsSync as
|
|
38079
|
+
existsSync as existsSync14,
|
|
37480
38080
|
fchmodSync as fchmodSync2,
|
|
37481
38081
|
fsyncSync as fsyncSync2,
|
|
37482
|
-
lstatSync as
|
|
37483
|
-
mkdirSync as
|
|
38082
|
+
lstatSync as lstatSync11,
|
|
38083
|
+
mkdirSync as mkdirSync10,
|
|
37484
38084
|
openSync as openSync4,
|
|
37485
|
-
readFileSync as
|
|
38085
|
+
readFileSync as readFileSync19,
|
|
37486
38086
|
realpathSync as realpathSync4,
|
|
37487
38087
|
renameSync as renameSync3,
|
|
37488
38088
|
unlinkSync as unlinkSync4,
|
|
37489
|
-
writeFileSync as
|
|
38089
|
+
writeFileSync as writeFileSync6
|
|
37490
38090
|
} from "fs";
|
|
37491
|
-
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as
|
|
38091
|
+
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as join24, relative as relative3, resolve as resolve7, sep as sep3 } from "path";
|
|
37492
38092
|
|
|
37493
38093
|
// src/lib/git-hook-legacy.ts
|
|
37494
38094
|
import { isAbsolute as isAbsolute7 } from "path";
|
|
@@ -37797,7 +38397,7 @@ function realpathLoose(path) {
|
|
|
37797
38397
|
let current = resolve7(path);
|
|
37798
38398
|
for (; ; ) {
|
|
37799
38399
|
try {
|
|
37800
|
-
return
|
|
38400
|
+
return join24(realpathSync4.native(current), ...missing);
|
|
37801
38401
|
} catch {
|
|
37802
38402
|
const parent = dirname14(current);
|
|
37803
38403
|
if (parent === current) return resolve7(path);
|
|
@@ -37812,7 +38412,7 @@ function isWithin(path, directory) {
|
|
|
37812
38412
|
}
|
|
37813
38413
|
function primGitHooksDirectory() {
|
|
37814
38414
|
try {
|
|
37815
|
-
return
|
|
38415
|
+
return join24(primConfigDirectory(), "git-hooks");
|
|
37816
38416
|
} catch {
|
|
37817
38417
|
return void 0;
|
|
37818
38418
|
}
|
|
@@ -37890,8 +38490,8 @@ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
|
|
|
37890
38490
|
};
|
|
37891
38491
|
}
|
|
37892
38492
|
function assertSafeFile(path, spec) {
|
|
37893
|
-
if (!
|
|
37894
|
-
const stat =
|
|
38493
|
+
if (!existsSync14(path)) return void 0;
|
|
38494
|
+
const stat = lstatSync11(path);
|
|
37895
38495
|
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_HOOK_BYTES) {
|
|
37896
38496
|
throw new Error(`unsafe ${spec.hookName} hook target: ${path}`);
|
|
37897
38497
|
}
|
|
@@ -37921,7 +38521,7 @@ function assertUsableHuskyDispatcher(target, spec) {
|
|
|
37921
38521
|
}
|
|
37922
38522
|
}
|
|
37923
38523
|
function readHookFile(path) {
|
|
37924
|
-
const value =
|
|
38524
|
+
const value = readFileSync19(path);
|
|
37925
38525
|
return Buffer.isBuffer(value) ? value : Buffer.from(value);
|
|
37926
38526
|
}
|
|
37927
38527
|
function decodeHookText(content, spec) {
|
|
@@ -37993,11 +38593,11 @@ function blockInsertionPoint(content, spec, huskyV8) {
|
|
|
37993
38593
|
var HUSKY_SPEC_MAJOR_RE = /^\s*[~^]?=?\s*v?([0-9]+)(?:\.(?:[0-9]+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?\s*$/u;
|
|
37994
38594
|
function declaredHuskyMajor(dir) {
|
|
37995
38595
|
for (let current = resolve7(dir); ; ) {
|
|
37996
|
-
const manifest =
|
|
37997
|
-
if (
|
|
38596
|
+
const manifest = join24(current, "package.json");
|
|
38597
|
+
if (existsSync14(manifest)) {
|
|
37998
38598
|
try {
|
|
37999
|
-
if (
|
|
38000
|
-
const parsed = JSON.parse(
|
|
38599
|
+
if (lstatSync11(manifest).size > MAX_HOOK_BYTES) return void 0;
|
|
38600
|
+
const parsed = JSON.parse(readFileSync19(manifest, "utf8"));
|
|
38001
38601
|
const range = parsed.devDependencies?.husky ?? parsed.dependencies?.husky;
|
|
38002
38602
|
const major = typeof range === "string" ? HUSKY_SPEC_MAJOR_RE.exec(range)?.[1] : void 0;
|
|
38003
38603
|
return major === void 0 ? void 0 : Number(major);
|
|
@@ -38006,15 +38606,15 @@ function declaredHuskyMajor(dir) {
|
|
|
38006
38606
|
}
|
|
38007
38607
|
}
|
|
38008
38608
|
const parent = dirname14(current);
|
|
38009
|
-
if (parent === current ||
|
|
38609
|
+
if (parent === current || existsSync14(join24(current, ".git"))) return void 0;
|
|
38010
38610
|
current = parent;
|
|
38011
38611
|
}
|
|
38012
38612
|
}
|
|
38013
38613
|
function isHuskyV8Hook(hookPath) {
|
|
38014
|
-
const runtime =
|
|
38614
|
+
const runtime = join24(dirname14(hookPath), "_", "husky.sh");
|
|
38015
38615
|
try {
|
|
38016
|
-
const stat =
|
|
38017
|
-
return stat.isFile() && stat.size <= MAX_HOOK_BYTES &&
|
|
38616
|
+
const stat = lstatSync11(runtime);
|
|
38617
|
+
return stat.isFile() && stat.size <= MAX_HOOK_BYTES && readFileSync19(runtime, "utf8").includes("husky_skip_init");
|
|
38018
38618
|
} catch (error) {
|
|
38019
38619
|
if (errorCode(error) !== "ENOENT") return false;
|
|
38020
38620
|
}
|
|
@@ -38155,7 +38755,7 @@ function errorCode(error) {
|
|
|
38155
38755
|
function assertTargetUnchanged(path, expected, spec, stat) {
|
|
38156
38756
|
let current;
|
|
38157
38757
|
try {
|
|
38158
|
-
current =
|
|
38758
|
+
current = lstatSync11(path);
|
|
38159
38759
|
} catch (error) {
|
|
38160
38760
|
if (expected === void 0 && errorCode(error) === "ENOENT") return;
|
|
38161
38761
|
throw new Error(`${spec.hookName} hook changed concurrently: ${path}`);
|
|
@@ -38169,7 +38769,7 @@ function assertTargetUnchanged(path, expected, spec, stat) {
|
|
|
38169
38769
|
}
|
|
38170
38770
|
function rewriteHookAtomically(path, next, expected, spec, stat) {
|
|
38171
38771
|
const parent = dirname14(path);
|
|
38172
|
-
|
|
38772
|
+
mkdirSync10(parent, { recursive: true });
|
|
38173
38773
|
const temporary = resolve7(
|
|
38174
38774
|
parent,
|
|
38175
38775
|
`.${basename3(path)}.prim-${String(process.pid)}-${randomUUID3()}.tmp`
|
|
@@ -38181,7 +38781,7 @@ function rewriteHookAtomically(path, next, expected, spec, stat) {
|
|
|
38181
38781
|
constants5.O_CREAT | constants5.O_EXCL | constants5.O_WRONLY | constants5.O_NOFOLLOW,
|
|
38182
38782
|
stat?.mode ?? 493
|
|
38183
38783
|
);
|
|
38184
|
-
|
|
38784
|
+
writeFileSync6(fd, next);
|
|
38185
38785
|
fchmodSync2(fd, (stat?.mode ?? 493) & 4095);
|
|
38186
38786
|
fsyncSync2(fd);
|
|
38187
38787
|
closeSync4(fd);
|
|
@@ -38269,7 +38869,9 @@ var InvalidRepositoryBindingResponseError = class extends Error {
|
|
|
38269
38869
|
async function resolveRepositoryBindingWithClient(root, client, options) {
|
|
38270
38870
|
const repositoryFullName = githubRepositoryFullName(root);
|
|
38271
38871
|
if (!repositoryFullName) {
|
|
38272
|
-
throw new Error(
|
|
38872
|
+
throw new Error(
|
|
38873
|
+
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)"
|
|
38874
|
+
);
|
|
38273
38875
|
}
|
|
38274
38876
|
let response;
|
|
38275
38877
|
try {
|
|
@@ -38328,17 +38930,17 @@ import {
|
|
|
38328
38930
|
closeSync as closeSync5,
|
|
38329
38931
|
fchmodSync as fchmodSync3,
|
|
38330
38932
|
fsyncSync as fsyncSync3,
|
|
38331
|
-
linkSync,
|
|
38332
|
-
lstatSync as
|
|
38333
|
-
mkdirSync as
|
|
38933
|
+
linkSync as linkSync2,
|
|
38934
|
+
lstatSync as lstatSync12,
|
|
38935
|
+
mkdirSync as mkdirSync11,
|
|
38334
38936
|
openSync as openSync5,
|
|
38335
|
-
readFileSync as
|
|
38937
|
+
readFileSync as readFileSync20,
|
|
38336
38938
|
statSync as statSync3,
|
|
38337
38939
|
unlinkSync as unlinkSync5,
|
|
38338
|
-
writeFileSync as
|
|
38940
|
+
writeFileSync as writeFileSync7
|
|
38339
38941
|
} from "fs";
|
|
38340
|
-
import { dirname as dirname15, isAbsolute as isAbsolute9, join as
|
|
38341
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
38942
|
+
import { dirname as dirname15, isAbsolute as isAbsolute9, join as join25, resolve as resolve8 } from "path";
|
|
38943
|
+
var WORKSPACE_ID_RELATIVE_PATH = join25("prim", "workspace-id");
|
|
38342
38944
|
var MAX_ANCESTORS = 64;
|
|
38343
38945
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
38344
38946
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -38397,19 +38999,19 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
38397
38999
|
function resolveFromFilesystem(cwd) {
|
|
38398
39000
|
let current = resolve8(cwd);
|
|
38399
39001
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
38400
|
-
const dotGit =
|
|
39002
|
+
const dotGit = join25(current, ".git");
|
|
38401
39003
|
try {
|
|
38402
|
-
const stat =
|
|
39004
|
+
const stat = lstatSync12(dotGit);
|
|
38403
39005
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
38404
|
-
return
|
|
39006
|
+
return join25(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
38405
39007
|
}
|
|
38406
39008
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
38407
|
-
const contents =
|
|
39009
|
+
const contents = readFileSync20(dotGit, "utf8");
|
|
38408
39010
|
const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
|
|
38409
39011
|
if (match?.[1]) {
|
|
38410
39012
|
const gitDirectory = isAbsolute9(match[1]) ? resolve8(match[1]) : resolve8(current, match[1]);
|
|
38411
39013
|
if (isGitDirectory(gitDirectory)) {
|
|
38412
|
-
return
|
|
39014
|
+
return join25(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
38413
39015
|
}
|
|
38414
39016
|
}
|
|
38415
39017
|
}
|
|
@@ -38428,7 +39030,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
38428
39030
|
}
|
|
38429
39031
|
function isGitDirectory(path) {
|
|
38430
39032
|
try {
|
|
38431
|
-
return statSync3(
|
|
39033
|
+
return statSync3(join25(path, "HEAD")).isFile();
|
|
38432
39034
|
} catch {
|
|
38433
39035
|
return false;
|
|
38434
39036
|
}
|
|
@@ -38436,7 +39038,7 @@ function isGitDirectory(path) {
|
|
|
38436
39038
|
function inspectPath(path) {
|
|
38437
39039
|
let stat;
|
|
38438
39040
|
try {
|
|
38439
|
-
stat =
|
|
39041
|
+
stat = lstatSync12(path);
|
|
38440
39042
|
} catch (error) {
|
|
38441
39043
|
const code = errorCode2(error);
|
|
38442
39044
|
if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing", path };
|
|
@@ -38447,7 +39049,7 @@ function inspectPath(path) {
|
|
|
38447
39049
|
return { status: "corrupt", path, reason: "invalid_content" };
|
|
38448
39050
|
}
|
|
38449
39051
|
try {
|
|
38450
|
-
const contents =
|
|
39052
|
+
const contents = readFileSync20(path, "utf8");
|
|
38451
39053
|
const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
|
|
38452
39054
|
if ((contents === workspaceId || contents === `${workspaceId}
|
|
38453
39055
|
`) && isCanonicalWorkspaceId(workspaceId)) {
|
|
@@ -38466,11 +39068,11 @@ function inspectPath(path) {
|
|
|
38466
39068
|
function createWorkspaceId(path) {
|
|
38467
39069
|
const parent = dirname15(path);
|
|
38468
39070
|
const workspaceId = randomUUID4();
|
|
38469
|
-
const temporaryPath =
|
|
39071
|
+
const temporaryPath = join25(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
38470
39072
|
let temporaryCreated = false;
|
|
38471
39073
|
let publishing = false;
|
|
38472
39074
|
try {
|
|
38473
|
-
|
|
39075
|
+
mkdirSync11(parent, { recursive: true, mode: 448 });
|
|
38474
39076
|
chmodSync6(parent, 448);
|
|
38475
39077
|
const fd = openSync5(
|
|
38476
39078
|
temporaryPath,
|
|
@@ -38479,7 +39081,7 @@ function createWorkspaceId(path) {
|
|
|
38479
39081
|
);
|
|
38480
39082
|
temporaryCreated = true;
|
|
38481
39083
|
try {
|
|
38482
|
-
|
|
39084
|
+
writeFileSync7(fd, `${workspaceId}
|
|
38483
39085
|
`, "utf8");
|
|
38484
39086
|
fchmodSync3(fd, 384);
|
|
38485
39087
|
fsyncSync3(fd);
|
|
@@ -38487,7 +39089,7 @@ function createWorkspaceId(path) {
|
|
|
38487
39089
|
closeSync5(fd);
|
|
38488
39090
|
}
|
|
38489
39091
|
publishing = true;
|
|
38490
|
-
|
|
39092
|
+
linkSync2(temporaryPath, path);
|
|
38491
39093
|
return { status: "ready", workspaceId, path, created: true };
|
|
38492
39094
|
} catch (error) {
|
|
38493
39095
|
if (publishing && errorCode2(error) === "EEXIST") return inspectAfterRace(path);
|
|
@@ -38526,23 +39128,23 @@ function errorCode2(error) {
|
|
|
38526
39128
|
}
|
|
38527
39129
|
|
|
38528
39130
|
// src/hooks/codex-context.ts
|
|
38529
|
-
import { createHash as createHash13, randomBytes as
|
|
39131
|
+
import { createHash as createHash13, randomBytes as randomBytes7 } from "crypto";
|
|
38530
39132
|
import {
|
|
38531
39133
|
chmodSync as chmodSync7,
|
|
38532
|
-
existsSync as
|
|
38533
|
-
mkdirSync as
|
|
38534
|
-
readFileSync as
|
|
38535
|
-
readdirSync as
|
|
39134
|
+
existsSync as existsSync15,
|
|
39135
|
+
mkdirSync as mkdirSync12,
|
|
39136
|
+
readFileSync as readFileSync21,
|
|
39137
|
+
readdirSync as readdirSync7,
|
|
38536
39138
|
renameSync as renameSync4,
|
|
38537
|
-
rmSync as
|
|
39139
|
+
rmSync as rmSync10,
|
|
38538
39140
|
statSync as statSync4,
|
|
38539
39141
|
unlinkSync as unlinkSync6,
|
|
38540
|
-
writeFileSync as
|
|
39142
|
+
writeFileSync as writeFileSync8
|
|
38541
39143
|
} from "fs";
|
|
38542
|
-
import { join as
|
|
39144
|
+
import { join as join26 } from "path";
|
|
38543
39145
|
|
|
38544
39146
|
// src/daemon/decision-digest-cache.ts
|
|
38545
|
-
import { randomBytes as
|
|
39147
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
38546
39148
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
38547
39149
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
38548
39150
|
var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
|
|
@@ -38692,10 +39294,10 @@ var STATE_VERSION = 1;
|
|
|
38692
39294
|
var DRAFT_STATE_VERSION = 2;
|
|
38693
39295
|
var NO_CURSOR = -1;
|
|
38694
39296
|
function stateRoot(namespace) {
|
|
38695
|
-
return
|
|
39297
|
+
return join26(primConfigDirectory(), namespace, "decision-digests");
|
|
38696
39298
|
}
|
|
38697
39299
|
function draftStateRoot(namespace) {
|
|
38698
|
-
return
|
|
39300
|
+
return join26(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
38699
39301
|
}
|
|
38700
39302
|
function workspaceFor(cwd) {
|
|
38701
39303
|
try {
|
|
@@ -38707,12 +39309,12 @@ function workspaceFor(cwd) {
|
|
|
38707
39309
|
function statePath(args) {
|
|
38708
39310
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
38709
39311
|
const key = createHash13("sha256").update(identity).digest("hex");
|
|
38710
|
-
return
|
|
39312
|
+
return join26(stateRoot(args.namespace), `${key}.json`);
|
|
38711
39313
|
}
|
|
38712
39314
|
function draftStatePath(args) {
|
|
38713
39315
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
38714
39316
|
const key = createHash13("sha256").update(identity).digest("hex");
|
|
38715
|
-
return
|
|
39317
|
+
return join26(draftStateRoot(args.namespace), `${key}.json`);
|
|
38716
39318
|
}
|
|
38717
39319
|
function parseState(value) {
|
|
38718
39320
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -38751,30 +39353,30 @@ function parseDraftState(value) {
|
|
|
38751
39353
|
};
|
|
38752
39354
|
}
|
|
38753
39355
|
function readState(path) {
|
|
38754
|
-
if (!
|
|
39356
|
+
if (!existsSync15(path)) return void 0;
|
|
38755
39357
|
try {
|
|
38756
|
-
return parseState(JSON.parse(
|
|
39358
|
+
return parseState(JSON.parse(readFileSync21(path, "utf8")));
|
|
38757
39359
|
} catch {
|
|
38758
39360
|
return void 0;
|
|
38759
39361
|
}
|
|
38760
39362
|
}
|
|
38761
39363
|
function readDraftState(path) {
|
|
38762
|
-
if (!
|
|
39364
|
+
if (!existsSync15(path)) return void 0;
|
|
38763
39365
|
try {
|
|
38764
|
-
return parseDraftState(JSON.parse(
|
|
39366
|
+
return parseDraftState(JSON.parse(readFileSync21(path, "utf8")));
|
|
38765
39367
|
} catch {
|
|
38766
39368
|
return void 0;
|
|
38767
39369
|
}
|
|
38768
39370
|
}
|
|
38769
39371
|
function writeStateFile(path, directory, state) {
|
|
38770
|
-
|
|
39372
|
+
mkdirSync12(directory, { recursive: true, mode: 448 });
|
|
38771
39373
|
chmodSync7(directory, 448);
|
|
38772
|
-
const temporary =
|
|
39374
|
+
const temporary = join26(
|
|
38773
39375
|
directory,
|
|
38774
|
-
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${
|
|
39376
|
+
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
38775
39377
|
);
|
|
38776
39378
|
try {
|
|
38777
|
-
|
|
39379
|
+
writeFileSync8(temporary, `${JSON.stringify(state)}
|
|
38778
39380
|
`, {
|
|
38779
39381
|
encoding: "utf8",
|
|
38780
39382
|
mode: 384,
|
|
@@ -38790,17 +39392,17 @@ function writeStateFile(path, directory, state) {
|
|
|
38790
39392
|
}
|
|
38791
39393
|
}
|
|
38792
39394
|
function cleanupStateFiles(directory, now) {
|
|
38793
|
-
if (!
|
|
39395
|
+
if (!existsSync15(directory)) return;
|
|
38794
39396
|
let names;
|
|
38795
39397
|
try {
|
|
38796
|
-
names =
|
|
39398
|
+
names = readdirSync7(directory);
|
|
38797
39399
|
} catch {
|
|
38798
39400
|
return;
|
|
38799
39401
|
}
|
|
38800
39402
|
const files = [];
|
|
38801
39403
|
const residue = [];
|
|
38802
39404
|
for (const name of names) {
|
|
38803
|
-
const path =
|
|
39405
|
+
const path = join26(directory, name);
|
|
38804
39406
|
try {
|
|
38805
39407
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
38806
39408
|
if (name.endsWith(".json")) {
|
|
@@ -38822,7 +39424,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
38822
39424
|
for (const path of residue) {
|
|
38823
39425
|
try {
|
|
38824
39426
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
38825
|
-
|
|
39427
|
+
rmSync10(path, { recursive: true, force: true });
|
|
38826
39428
|
}
|
|
38827
39429
|
} catch {
|
|
38828
39430
|
}
|
|
@@ -39265,16 +39867,25 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
39265
39867
|
// src/hooks/reauth-notice.ts
|
|
39266
39868
|
var REAUTH_NOTICE = "[prim] authentication ended \u2014 run `prim auth login` to resume decision capture";
|
|
39267
39869
|
function reauthNoticeFields(agent) {
|
|
39268
|
-
if (agent === "claude_code")
|
|
39870
|
+
if (agent === "claude_code") {
|
|
39871
|
+
if (isClaudeCloudSession()) {
|
|
39872
|
+
const notice = `Primitive is not connected in this Claude Code cloud session: ${hasMachineConfiguration() ? `its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}` : `its sign-in ended. To fix it, ${CLOUD_CREDENTIALS_REMEDY}`}.`;
|
|
39873
|
+
return {
|
|
39874
|
+
systemMessage: notice,
|
|
39875
|
+
additionalContext: `${notice} Tell the user this in one sentence before starting their task.`
|
|
39876
|
+
};
|
|
39877
|
+
}
|
|
39269
39878
|
return {
|
|
39270
39879
|
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
39880
|
};
|
|
39881
|
+
}
|
|
39272
39882
|
return;
|
|
39273
39883
|
}
|
|
39274
39884
|
|
|
39275
39885
|
// src/hooks/session-start-core.ts
|
|
39276
39886
|
var DAEMON_TIMEOUT_MS = 250;
|
|
39277
39887
|
var REPOSITORY_BIND_TIMEOUT_MS = 1e3;
|
|
39888
|
+
var CLOUD_REPOSITORY_BIND_TIMEOUT_MS = 1e4;
|
|
39278
39889
|
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
39890
|
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
39891
|
function primReminder(action, rationaleAction) {
|
|
@@ -39295,6 +39906,7 @@ async function activeProjectRoot(cwd) {
|
|
|
39295
39906
|
if (!shellGateActive) {
|
|
39296
39907
|
try {
|
|
39297
39908
|
setRepoActive(root, true);
|
|
39909
|
+
markActivationImplicit(root);
|
|
39298
39910
|
shellGateActive = true;
|
|
39299
39911
|
} catch {
|
|
39300
39912
|
}
|
|
@@ -39316,7 +39928,9 @@ async function activeProjectRoot(cwd) {
|
|
|
39316
39928
|
}
|
|
39317
39929
|
try {
|
|
39318
39930
|
const binding = await bindRepository(root, {
|
|
39319
|
-
signal: AbortSignal.timeout(
|
|
39931
|
+
signal: AbortSignal.timeout(
|
|
39932
|
+
isClaudeCloudSession() ? CLOUD_REPOSITORY_BIND_TIMEOUT_MS : REPOSITORY_BIND_TIMEOUT_MS
|
|
39933
|
+
),
|
|
39320
39934
|
quietRefresh: true
|
|
39321
39935
|
});
|
|
39322
39936
|
try {
|
|
@@ -39331,7 +39945,9 @@ async function activeProjectRoot(cwd) {
|
|
|
39331
39945
|
return null;
|
|
39332
39946
|
}
|
|
39333
39947
|
}
|
|
39334
|
-
function claudeBindingReminder(binding) {
|
|
39948
|
+
function claudeBindingReminder(binding, cloud = false) {
|
|
39949
|
+
if (cloud && binding.status !== "connected")
|
|
39950
|
+
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
39951
|
if (binding.status === "connected") {
|
|
39336
39952
|
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
39953
|
}
|
|
@@ -39355,6 +39971,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39355
39971
|
return { output: buildHookOutput({}) };
|
|
39356
39972
|
}
|
|
39357
39973
|
const cwd = envelope.cwd ?? process.cwd();
|
|
39974
|
+
withdrawImplicitActivation(cwd);
|
|
39358
39975
|
if (!gitToplevel(cwd) || !isRepoActiveForCapture(cwd)) {
|
|
39359
39976
|
if (repoActiveFlag(cwd) === "false") clearHooksWired(cwd);
|
|
39360
39977
|
return { output: agent === "cursor" ? {} : buildHookOutput({}) };
|
|
@@ -39446,8 +40063,16 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39446
40063
|
};
|
|
39447
40064
|
}
|
|
39448
40065
|
if (agent === "claude_code") {
|
|
40066
|
+
let cloudNotice;
|
|
40067
|
+
if (active && !claudeBinding && isClaudeCloudSession()) {
|
|
40068
|
+
try {
|
|
40069
|
+
cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd });
|
|
40070
|
+
} catch {
|
|
40071
|
+
}
|
|
40072
|
+
}
|
|
39449
40073
|
const additionalContext = [
|
|
39450
|
-
|
|
40074
|
+
cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
|
|
40075
|
+
claudeBinding ? claudeBindingReminder(claudeBinding, isClaudeCloudSession()) : void 0,
|
|
39451
40076
|
active && skillState.installed > 0 ? PRIM_SKILL_REMINDER : void 0
|
|
39452
40077
|
].filter((value) => value !== void 0).join("\n\n");
|
|
39453
40078
|
const reloadSkills = skillState.refreshed > 0;
|
|
@@ -39463,7 +40088,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39463
40088
|
const rendered = lease ? renderFeedback(lease) : void 0;
|
|
39464
40089
|
return {
|
|
39465
40090
|
output: buildHookOutput({
|
|
39466
|
-
systemMessage: rendered?.systemMessage,
|
|
40091
|
+
systemMessage: [cloudNotice, rendered?.systemMessage].filter(Boolean).join("\n\n") || void 0,
|
|
39467
40092
|
additionalContext,
|
|
39468
40093
|
reloadSkills
|
|
39469
40094
|
}),
|
|
@@ -39478,7 +40103,9 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39478
40103
|
};
|
|
39479
40104
|
}
|
|
39480
40105
|
}
|
|
39481
|
-
return {
|
|
40106
|
+
return {
|
|
40107
|
+
output: buildHookOutput({ systemMessage: cloudNotice, additionalContext, reloadSkills })
|
|
40108
|
+
};
|
|
39482
40109
|
}
|
|
39483
40110
|
await activeProjectRoot(cwd);
|
|
39484
40111
|
return { output: buildHookOutput({}) };
|