@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
|
@@ -53,8 +53,8 @@ var require_ucs2length = __commonJS({
|
|
|
53
53
|
});
|
|
54
54
|
|
|
55
55
|
// src/hooks/post-tool-use.ts
|
|
56
|
-
import { readFileSync as
|
|
57
|
-
import { dirname as dirname14, join as
|
|
56
|
+
import { readFileSync as readFileSync22 } from "fs";
|
|
57
|
+
import { dirname as dirname14, join as join26 } from "path";
|
|
58
58
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
59
59
|
|
|
60
60
|
// src/binding.ts
|
|
@@ -68,8 +68,17 @@ import { join as join7 } from "path";
|
|
|
68
68
|
|
|
69
69
|
// src/lib/machine-credentials.ts
|
|
70
70
|
import { execFileSync } from "child_process";
|
|
71
|
-
import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
|
|
72
|
-
import {
|
|
71
|
+
import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
72
|
+
import {
|
|
73
|
+
chmodSync,
|
|
74
|
+
existsSync as existsSync3,
|
|
75
|
+
linkSync,
|
|
76
|
+
lstatSync as lstatSync3,
|
|
77
|
+
mkdirSync as mkdirSync3,
|
|
78
|
+
readFileSync as readFileSync5,
|
|
79
|
+
rmSync as rmSync5,
|
|
80
|
+
writeFileSync as writeFileSync3
|
|
81
|
+
} from "fs";
|
|
73
82
|
import { createRequire } from "module";
|
|
74
83
|
import { dirname as dirname4, join as join6 } from "path";
|
|
75
84
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
@@ -388,6 +397,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
|
|
|
388
397
|
'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; ',
|
|
389
398
|
"fi; fi; "
|
|
390
399
|
].join("");
|
|
400
|
+
var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
|
|
391
401
|
function stableHookCommand(bin, args = "") {
|
|
392
402
|
if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
|
|
393
403
|
throw new Error("invalid stable hook command");
|
|
@@ -399,7 +409,7 @@ function stableHookCommand(bin, args = "") {
|
|
|
399
409
|
`prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
|
|
400
410
|
PRIM_CONFIG_SHELL_RESOLVER,
|
|
401
411
|
`case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
|
|
402
|
-
|
|
412
|
+
LAUNCHER_EXEC
|
|
403
413
|
].join("");
|
|
404
414
|
const suffix = args ? ` ${args}` : "";
|
|
405
415
|
return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
|
|
@@ -408,6 +418,47 @@ function detachedHookShimCommand(bin, args = "") {
|
|
|
408
418
|
return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
|
|
409
419
|
}
|
|
410
420
|
|
|
421
|
+
// src/lib/loopback-fetch.ts
|
|
422
|
+
import { request } from "http";
|
|
423
|
+
import { Readable } from "stream";
|
|
424
|
+
function loopbackFetch(url, init = {}) {
|
|
425
|
+
const target = new URL(url);
|
|
426
|
+
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
427
|
+
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
428
|
+
return new Promise((resolve8, reject) => {
|
|
429
|
+
const outgoing = request(
|
|
430
|
+
target,
|
|
431
|
+
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
432
|
+
(incoming) => {
|
|
433
|
+
try {
|
|
434
|
+
const headers = new Headers();
|
|
435
|
+
for (const [name2, value] of Object.entries(incoming.headers))
|
|
436
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
437
|
+
const status = incoming.statusCode ?? 502;
|
|
438
|
+
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
439
|
+
resolve8(new Response(body, { status, headers }));
|
|
440
|
+
} catch (error) {
|
|
441
|
+
incoming.destroy();
|
|
442
|
+
reject(error);
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
);
|
|
446
|
+
outgoing.once("error", reject);
|
|
447
|
+
outgoing.end(init.body);
|
|
448
|
+
});
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/lib/cloud-env.ts
|
|
452
|
+
function isClaudeCloudSession(env = process.env) {
|
|
453
|
+
return env.CLAUDE_CODE_REMOTE === "true";
|
|
454
|
+
}
|
|
455
|
+
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';
|
|
456
|
+
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';
|
|
457
|
+
function cloudSetupPointer(message, env = process.env) {
|
|
458
|
+
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
459
|
+
}
|
|
460
|
+
var CLOUD_SETUP_POINTER = "; in this Claude Code cloud session, run `prim setup --cloud` for the fix";
|
|
461
|
+
|
|
411
462
|
// src/lib/workos-connect.ts
|
|
412
463
|
var TOKEN_PATH = "/oauth2/token";
|
|
413
464
|
var DISCOVERY_MAX_BYTES = 16 * 1024;
|
|
@@ -603,9 +654,19 @@ function parseMachineConfiguration(value) {
|
|
|
603
654
|
...record.developer_enrollment === true ? { developerEnrollment: true } : {}
|
|
604
655
|
};
|
|
605
656
|
}
|
|
657
|
+
function rejectedCredentialsMessage(message, env = process.env) {
|
|
658
|
+
return isClaudeCloudSession(env) ? `The cloud environment's credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.` : message;
|
|
659
|
+
}
|
|
606
660
|
function machineSignal(signal) {
|
|
607
661
|
return signal ? AbortSignal.any([signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
608
662
|
}
|
|
663
|
+
function hostOf(url) {
|
|
664
|
+
try {
|
|
665
|
+
return new URL(url).hostname;
|
|
666
|
+
} catch {
|
|
667
|
+
return "Primitive";
|
|
668
|
+
}
|
|
669
|
+
}
|
|
609
670
|
async function fetchMachine(url, options, fetchImpl) {
|
|
610
671
|
try {
|
|
611
672
|
return await fetchImpl(url, options);
|
|
@@ -613,7 +674,9 @@ async function fetchMachine(url, options, fetchImpl) {
|
|
|
613
674
|
options.signal?.throwIfAborted();
|
|
614
675
|
throw new MachineAuthError(
|
|
615
676
|
"authentication_unavailable",
|
|
616
|
-
|
|
677
|
+
// A cloud VM reaches only the hosts its environment allows, and both of
|
|
678
|
+
// Primitive's are blocked by default: name the one that failed.
|
|
679
|
+
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."
|
|
617
680
|
);
|
|
618
681
|
}
|
|
619
682
|
}
|
|
@@ -640,8 +703,9 @@ async function discoverMachineConfiguration(apiUrl, signal, fetchImpl = fetch) {
|
|
|
640
703
|
);
|
|
641
704
|
return parseMachineConfiguration(await readMachineJson(response, 16 * 1024));
|
|
642
705
|
}
|
|
643
|
-
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch) {
|
|
644
|
-
|
|
706
|
+
async function exchangeMachineCredentials(configuration, clientId, clientSecret, signal, fetchImpl = fetch, options = {}) {
|
|
707
|
+
const network = options.secretInjection === "network";
|
|
708
|
+
if (!/^client_[\w-]+$/u.test(clientId) || !network && !machineString(clientSecret)) {
|
|
645
709
|
throw new MachineAuthError(
|
|
646
710
|
"invalid_credentials",
|
|
647
711
|
"A machine client ID and secret are required.",
|
|
@@ -655,11 +719,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
655
719
|
redirect: "error",
|
|
656
720
|
signal: machineSignal(signal),
|
|
657
721
|
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
client_secret: clientSecret
|
|
662
|
-
|
|
722
|
+
// With a network secret the agent proxy authenticates the client with
|
|
723
|
+
// HTTP Basic (client_secret_basic); the body carries no credential.
|
|
724
|
+
body: new URLSearchParams(
|
|
725
|
+
network ? { grant_type: "client_credentials" } : { grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }
|
|
726
|
+
)
|
|
663
727
|
},
|
|
664
728
|
fetchImpl
|
|
665
729
|
);
|
|
@@ -667,7 +731,9 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
667
731
|
const terminal = response.status === 400 || response.status === 401 || response.status === 403;
|
|
668
732
|
throw new MachineAuthError(
|
|
669
733
|
terminal ? "machine_credentials_rejected" : "token_service_unavailable",
|
|
670
|
-
terminal ?
|
|
734
|
+
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(
|
|
735
|
+
"Machine credentials were rejected. Ask your administrator to rotate or enable them."
|
|
736
|
+
) : "The machine token service is temporarily unavailable.",
|
|
671
737
|
terminal,
|
|
672
738
|
terminal ? void 0 : machineRetryAt(response)
|
|
673
739
|
);
|
|
@@ -687,6 +753,11 @@ async function exchangeMachineCredentials(configuration, clientId, clientSecret,
|
|
|
687
753
|
} catch {
|
|
688
754
|
throw new MachineAuthError("invalid_response", "The token service returned an invalid JWT.");
|
|
689
755
|
}
|
|
756
|
+
if (claims.iss === configuration.issuer && claims.aud === configuration.audience && (claims.sub !== clientId || claims.client_id !== clientId))
|
|
757
|
+
throw new MachineAuthError(
|
|
758
|
+
"token_client_mismatch",
|
|
759
|
+
"The token service issued a token for another machine client."
|
|
760
|
+
);
|
|
690
761
|
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()) {
|
|
691
762
|
throw new MachineAuthError(
|
|
692
763
|
"token_identity_mismatch",
|
|
@@ -732,12 +803,51 @@ async function verifyMachineIdentity(apiUrl, accessToken, clientId, signal, fetc
|
|
|
732
803
|
const terminal = response.status === 401 || response.status === 403;
|
|
733
804
|
throw new MachineAuthError(
|
|
734
805
|
terminal ? "machine_access_rejected" : "verification_unavailable",
|
|
735
|
-
terminal ?
|
|
806
|
+
terminal ? rejectedCredentialsMessage(
|
|
807
|
+
"The API rejected this machine. Ask your administrator to check its registration and scopes."
|
|
808
|
+
) : "Machine verification is temporarily unavailable.",
|
|
736
809
|
terminal
|
|
737
810
|
);
|
|
738
811
|
}
|
|
739
812
|
return parseMachineIdentity(await readMachineJson(response, 16 * 1024), clientId);
|
|
740
813
|
}
|
|
814
|
+
function parseInjectedMachineIdentity(status, value, apiUrl, clientId) {
|
|
815
|
+
const rejected = () => new MachineAuthError(
|
|
816
|
+
"network_token_rejected",
|
|
817
|
+
`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.`,
|
|
818
|
+
true
|
|
819
|
+
);
|
|
820
|
+
if (status === 401 || status === 403) throw rejected();
|
|
821
|
+
if (status < 200 || status > 299)
|
|
822
|
+
throw new MachineAuthError(
|
|
823
|
+
"verification_unavailable",
|
|
824
|
+
"Machine verification is temporarily unavailable."
|
|
825
|
+
);
|
|
826
|
+
let data;
|
|
827
|
+
try {
|
|
828
|
+
data = machineRecord(value);
|
|
829
|
+
} catch {
|
|
830
|
+
throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
|
|
831
|
+
}
|
|
832
|
+
if (data.authenticated !== true) throw rejected();
|
|
833
|
+
const principal = data.principal && typeof data.principal === "object" ? data.principal : {};
|
|
834
|
+
if (principal.kind === "machine" && typeof principal.clientId === "string" && principal.clientId !== clientId)
|
|
835
|
+
throw new MachineAuthError(
|
|
836
|
+
"network_secret_mismatch",
|
|
837
|
+
`The proxy's token belongs to another machine. Check that the network secret's client ID equals PRIM_M2M_CLIENT_ID (${clientId}).`,
|
|
838
|
+
true
|
|
839
|
+
);
|
|
840
|
+
return parseMachineIdentity(data, clientId);
|
|
841
|
+
}
|
|
842
|
+
async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl = fetch) {
|
|
843
|
+
const response = await fetchMachine(
|
|
844
|
+
`${machineApiUrl(apiUrl)}/api/cli/auth/status`,
|
|
845
|
+
{ redirect: "error", signal: machineSignal(signal) },
|
|
846
|
+
fetchImpl
|
|
847
|
+
);
|
|
848
|
+
const value = response.ok ? await readMachineJson(response, 16 * 1024) : void 0;
|
|
849
|
+
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
850
|
+
}
|
|
741
851
|
|
|
742
852
|
// src/lib/paths.ts
|
|
743
853
|
import { homedir } from "os";
|
|
@@ -769,6 +879,11 @@ function primConfigDirectory(options = {}) {
|
|
|
769
879
|
|
|
770
880
|
// src/lib/machine-broker.ts
|
|
771
881
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
882
|
+
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
883
|
+
var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
884
|
+
var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
|
|
885
|
+
var FORWARD_REQUEST_PROOF = "forward-request";
|
|
886
|
+
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
772
887
|
var IDLE_MS = 5 * 6e4;
|
|
773
888
|
function descriptorPath(directory, generation) {
|
|
774
889
|
return join4(directory, `machine_broker_${generation}.json`);
|
|
@@ -784,8 +899,8 @@ function readDescriptor(path) {
|
|
|
784
899
|
return void 0;
|
|
785
900
|
}
|
|
786
901
|
}
|
|
787
|
-
function signature(secret, nonce, body) {
|
|
788
|
-
return createHmac("sha256", secret).update(`${nonce}\0${body}`).digest("hex");
|
|
902
|
+
function signature(secret, nonce, body, purpose) {
|
|
903
|
+
return createHmac("sha256", secret).update(purpose ? `${nonce}\0${purpose}\0${body}` : `${nonce}\0${body}`).digest("hex");
|
|
789
904
|
}
|
|
790
905
|
function matches(left, right) {
|
|
791
906
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
@@ -800,10 +915,9 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
800
915
|
observedTokenHash: tokenHash(options.observedToken),
|
|
801
916
|
timestamp: Date.now()
|
|
802
917
|
});
|
|
803
|
-
const response = await
|
|
918
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/credential`, {
|
|
804
919
|
method: "POST",
|
|
805
920
|
body,
|
|
806
|
-
redirect: "error",
|
|
807
921
|
signal: options.signal,
|
|
808
922
|
headers: {
|
|
809
923
|
"Content-Type": "application/json",
|
|
@@ -834,6 +948,15 @@ async function brokerRequest(descriptor, environment, options) {
|
|
|
834
948
|
);
|
|
835
949
|
return credential;
|
|
836
950
|
}
|
|
951
|
+
function brokerEnvironment(options) {
|
|
952
|
+
const routed = options.environment.secretInjection || options.environment.tokenInjection;
|
|
953
|
+
return {
|
|
954
|
+
...options.env,
|
|
955
|
+
PRIM_API_URL: options.apiUrl,
|
|
956
|
+
PRIM_CONFIG_DIR: options.directory,
|
|
957
|
+
...routed ? { NODE_USE_ENV_PROXY: "1" } : {}
|
|
958
|
+
};
|
|
959
|
+
}
|
|
837
960
|
async function acquireBrokerCredential(options) {
|
|
838
961
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
839
962
|
const existing = readDescriptor(path);
|
|
@@ -845,15 +968,28 @@ async function acquireBrokerCredential(options) {
|
|
|
845
968
|
if (error instanceof MachineAuthError) throw error;
|
|
846
969
|
}
|
|
847
970
|
}
|
|
848
|
-
const descriptor = await
|
|
971
|
+
const descriptor = await ensureBroker(options);
|
|
972
|
+
try {
|
|
973
|
+
return await brokerRequest(descriptor, options.environment, options);
|
|
974
|
+
} catch (error) {
|
|
975
|
+
options.signal.throwIfAborted();
|
|
976
|
+
if (error instanceof MachineAuthError) throw error;
|
|
977
|
+
throw new MachineAuthError(
|
|
978
|
+
"broker_unavailable",
|
|
979
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
980
|
+
);
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
async function ensureBroker(options) {
|
|
984
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
985
|
+
return withFileLock(
|
|
849
986
|
join4(options.directory, "machine-broker.lock"),
|
|
850
987
|
async () => {
|
|
851
988
|
const current = readDescriptor(path);
|
|
852
989
|
if (current) {
|
|
853
990
|
try {
|
|
854
|
-
const response = await
|
|
855
|
-
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
856
|
-
redirect: "error"
|
|
991
|
+
const response = await loopbackFetch(`http://127.0.0.1:${current.port}/health`, {
|
|
992
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(500)])
|
|
857
993
|
});
|
|
858
994
|
if (response.ok && await response.text() === current.nonce) return current;
|
|
859
995
|
} catch {
|
|
@@ -872,7 +1008,7 @@ async function acquireBrokerCredential(options) {
|
|
|
872
1008
|
detached: true,
|
|
873
1009
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
874
1010
|
windowsHide: true,
|
|
875
|
-
env:
|
|
1011
|
+
env: brokerEnvironment(options)
|
|
876
1012
|
});
|
|
877
1013
|
let settled = false;
|
|
878
1014
|
const finish2 = (error) => {
|
|
@@ -924,27 +1060,93 @@ async function acquireBrokerCredential(options) {
|
|
|
924
1060
|
},
|
|
925
1061
|
{ signal: options.signal }
|
|
926
1062
|
);
|
|
1063
|
+
}
|
|
1064
|
+
async function forwardOnce(descriptor, environment, request3, signal) {
|
|
1065
|
+
const body = JSON.stringify({
|
|
1066
|
+
generation: environment.generation,
|
|
1067
|
+
timestamp: Date.now(),
|
|
1068
|
+
method: request3.method,
|
|
1069
|
+
path: request3.path,
|
|
1070
|
+
headers: request3.headers ?? {},
|
|
1071
|
+
...request3.body === void 0 ? {} : { body: request3.body }
|
|
1072
|
+
});
|
|
1073
|
+
const response = await loopbackFetch(`http://127.0.0.1:${descriptor.port}/forward`, {
|
|
1074
|
+
method: "POST",
|
|
1075
|
+
body,
|
|
1076
|
+
signal,
|
|
1077
|
+
headers: {
|
|
1078
|
+
"Content-Type": "application/json",
|
|
1079
|
+
"X-Prim-Proof": signature(
|
|
1080
|
+
environment.clientSecret,
|
|
1081
|
+
descriptor.nonce,
|
|
1082
|
+
body,
|
|
1083
|
+
FORWARD_REQUEST_PROOF
|
|
1084
|
+
)
|
|
1085
|
+
}
|
|
1086
|
+
});
|
|
1087
|
+
const envelope = machineRecord(await readBoundedJson(response, MAX_FORWARD_RESPONSE_BYTES));
|
|
1088
|
+
if (typeof envelope.body !== "string" || !matches(
|
|
1089
|
+
signature(environment.clientSecret, descriptor.nonce, envelope.body, FORWARD_ANSWER_PROOF),
|
|
1090
|
+
envelope.proof
|
|
1091
|
+
))
|
|
1092
|
+
throw new MachineAuthError(
|
|
1093
|
+
"broker_unavailable",
|
|
1094
|
+
"Machine credential broker could not be authenticated. Retry the command."
|
|
1095
|
+
);
|
|
1096
|
+
const data = machineRecord(JSON.parse(envelope.body));
|
|
1097
|
+
if (data.error) {
|
|
1098
|
+
const error = machineRecord(data.error);
|
|
1099
|
+
throw new MachineAuthError(String(error.code), String(error.message), error.terminal === true);
|
|
1100
|
+
}
|
|
1101
|
+
const status = data.status;
|
|
1102
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
|
|
1103
|
+
throw new MachineAuthError("broker_unavailable", "Machine credential broker answered oddly.");
|
|
1104
|
+
const headers = new Headers();
|
|
1105
|
+
for (const [name2, value] of Object.entries(machineRecord(data.headers ?? {})))
|
|
1106
|
+
if (typeof value === "string") headers.set(name2, value);
|
|
1107
|
+
const text = typeof data.body === "string" ? data.body : "";
|
|
1108
|
+
return new Response([204, 205, 304].includes(status) ? null : text, { status, headers });
|
|
1109
|
+
}
|
|
1110
|
+
async function forwardBrokerRequest(options) {
|
|
1111
|
+
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1112
|
+
const unavailable = () => new MachineAuthError(
|
|
1113
|
+
"broker_unavailable",
|
|
1114
|
+
"Machine credential broker is unavailable. Retry the command."
|
|
1115
|
+
);
|
|
1116
|
+
const existing = readDescriptor(path);
|
|
1117
|
+
if (existing) {
|
|
1118
|
+
try {
|
|
1119
|
+
return await forwardOnce(existing, options.environment, options.request, options.signal);
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
options.signal.throwIfAborted();
|
|
1122
|
+
if (error instanceof MachineAuthError) throw error;
|
|
1123
|
+
if (error.code !== "ECONNREFUSED") throw unavailable();
|
|
1124
|
+
}
|
|
1125
|
+
}
|
|
1126
|
+
const descriptor = await ensureBroker(options);
|
|
927
1127
|
try {
|
|
928
|
-
return await
|
|
1128
|
+
return await forwardOnce(descriptor, options.environment, options.request, options.signal);
|
|
929
1129
|
} catch (error) {
|
|
930
1130
|
options.signal.throwIfAborted();
|
|
931
1131
|
if (error instanceof MachineAuthError) throw error;
|
|
932
|
-
throw
|
|
933
|
-
"broker_unavailable",
|
|
934
|
-
"Machine credential broker is unavailable. Retry the command."
|
|
935
|
-
);
|
|
1132
|
+
throw unavailable();
|
|
936
1133
|
}
|
|
937
1134
|
}
|
|
938
1135
|
|
|
939
1136
|
// src/lib/machine-retry.ts
|
|
940
1137
|
import { createHash as createHash2 } from "crypto";
|
|
941
|
-
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
1138
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
|
|
942
1139
|
import { join as join5 } from "path";
|
|
943
|
-
|
|
1140
|
+
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
1141
|
+
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1142
|
+
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
944
1143
|
signal?.throwIfAborted();
|
|
945
1144
|
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
946
1145
|
const path = join5(directory, `machine_retry_${key}.json`);
|
|
947
|
-
let state = {
|
|
1146
|
+
let state = {
|
|
1147
|
+
failures: 0,
|
|
1148
|
+
retryAt: 0
|
|
1149
|
+
};
|
|
948
1150
|
try {
|
|
949
1151
|
const stat = lstatSync2(path);
|
|
950
1152
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
@@ -959,12 +1161,19 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
959
1161
|
if (state.retryAt > Date.now())
|
|
960
1162
|
throw new MachineAuthError(
|
|
961
1163
|
"token_service_unavailable",
|
|
962
|
-
"Machine authentication is cooling down after a temporary failure. Retry later."
|
|
1164
|
+
!isClaudeCloudSession() ? "Machine authentication is cooling down after a temporary failure. Retry later." : state.serverRetryAfter === true ? (
|
|
1165
|
+
// Cloud setup keeps this wait too, so pointing at it would loop.
|
|
1166
|
+
`${SERVER_WAIT_PREFIX}; retry in about ${Math.ceil((state.retryAt - Date.now()) / 1e3)}s`
|
|
1167
|
+
) : (
|
|
1168
|
+
// The cooldown hides the failure that started it; cloud setup
|
|
1169
|
+
// retries at once and names the cause.
|
|
1170
|
+
cloudSetupPointer("Machine authentication is cooling down after a temporary failure")
|
|
1171
|
+
),
|
|
963
1172
|
false,
|
|
964
1173
|
state.retryAt
|
|
965
1174
|
);
|
|
966
1175
|
try {
|
|
967
|
-
const result = await
|
|
1176
|
+
const result = await request3();
|
|
968
1177
|
rmSync4(path, { force: true });
|
|
969
1178
|
return result;
|
|
970
1179
|
} catch (error) {
|
|
@@ -976,8 +1185,16 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request2
|
|
|
976
1185
|
].includes(error.code)) {
|
|
977
1186
|
const failures = Math.min(16, state.failures + 1);
|
|
978
1187
|
const backoff = Math.min(6e4, 1e3 * 2 ** (failures - 1));
|
|
979
|
-
const retryAt = error.retryAt
|
|
980
|
-
atomicWriteFile(
|
|
1188
|
+
const retryAt = error.retryAt === void 0 ? Date.now() + Math.ceil(backoff * (1 + Math.random())) : Math.min(error.retryAt, Date.now() + MAX_SERVER_WAIT_MS);
|
|
1189
|
+
atomicWriteFile(
|
|
1190
|
+
path,
|
|
1191
|
+
JSON.stringify({
|
|
1192
|
+
failures,
|
|
1193
|
+
retryAt,
|
|
1194
|
+
...error.retryAt === void 0 ? {} : { serverRetryAfter: true }
|
|
1195
|
+
}),
|
|
1196
|
+
{ mode: 384 }
|
|
1197
|
+
);
|
|
981
1198
|
throw new MachineAuthError(error.code, error.message, false, retryAt);
|
|
982
1199
|
}
|
|
983
1200
|
throw error;
|
|
@@ -1170,10 +1387,98 @@ function readMachineProfile(deps = {}) {
|
|
|
1170
1387
|
const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1171
1388
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1172
1389
|
}
|
|
1390
|
+
var NETWORK_SECRET_AUTH = "network-secret";
|
|
1391
|
+
var NETWORK_TOKEN_AUTH = "network-token";
|
|
1392
|
+
var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
1393
|
+
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1394
|
+
function networkSecretBrokerKey(deps, clientId) {
|
|
1395
|
+
const directory = configurationDirectory(deps);
|
|
1396
|
+
const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1397
|
+
const known = brokerKeys.get(path);
|
|
1398
|
+
if (known) return known;
|
|
1399
|
+
ensureDirectory(directory);
|
|
1400
|
+
const read = () => {
|
|
1401
|
+
try {
|
|
1402
|
+
const stat = lstatSync3(path);
|
|
1403
|
+
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1404
|
+
throw new MachineAuthError(
|
|
1405
|
+
"unsafe_storage",
|
|
1406
|
+
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1407
|
+
true
|
|
1408
|
+
);
|
|
1409
|
+
const value = readFileSync5(path, "utf8").trim();
|
|
1410
|
+
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1411
|
+
} catch (error) {
|
|
1412
|
+
if (error.code === "ENOENT") return void 0;
|
|
1413
|
+
throw error;
|
|
1414
|
+
}
|
|
1415
|
+
};
|
|
1416
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
1417
|
+
const existing = read();
|
|
1418
|
+
if (existing?.key) {
|
|
1419
|
+
brokerKeys.set(path, existing.key);
|
|
1420
|
+
return existing.key;
|
|
1421
|
+
}
|
|
1422
|
+
if (existing)
|
|
1423
|
+
throw new MachineAuthError(
|
|
1424
|
+
"unsafe_storage",
|
|
1425
|
+
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1426
|
+
true
|
|
1427
|
+
);
|
|
1428
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
1429
|
+
try {
|
|
1430
|
+
writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
|
|
1431
|
+
`, { mode: 384, flag: "wx" });
|
|
1432
|
+
protectPath(staged, false);
|
|
1433
|
+
linkSync(staged, path);
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
if (error.code !== "EEXIST") throw error;
|
|
1436
|
+
} finally {
|
|
1437
|
+
rmSync5(staged, { force: true });
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
const key = read()?.key;
|
|
1441
|
+
if (!key)
|
|
1442
|
+
throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
|
|
1443
|
+
brokerKeys.set(path, key);
|
|
1444
|
+
return key;
|
|
1445
|
+
}
|
|
1173
1446
|
function environmentCredentials(deps) {
|
|
1174
1447
|
const env = deps.env ?? process.env;
|
|
1175
|
-
const {
|
|
1176
|
-
|
|
1448
|
+
const {
|
|
1449
|
+
PRIM_M2M_CLIENT_ID: clientId,
|
|
1450
|
+
PRIM_M2M_CLIENT_SECRET: clientSecret,
|
|
1451
|
+
PRIM_M2M_CLIENT_AUTH: auth
|
|
1452
|
+
} = env;
|
|
1453
|
+
if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
|
|
1454
|
+
if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
|
|
1455
|
+
throw new MachineAuthError(
|
|
1456
|
+
"incomplete_machine_credentials",
|
|
1457
|
+
`PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
|
|
1458
|
+
);
|
|
1459
|
+
if (auth !== void 0) {
|
|
1460
|
+
if (!clientId || !/^client_[\w-]+$/u.test(clientId))
|
|
1461
|
+
throw new MachineAuthError(
|
|
1462
|
+
"incomplete_machine_credentials",
|
|
1463
|
+
`Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
|
|
1464
|
+
);
|
|
1465
|
+
if (clientSecret !== void 0)
|
|
1466
|
+
throw new MachineAuthError(
|
|
1467
|
+
"conflicting_credentials",
|
|
1468
|
+
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1469
|
+
);
|
|
1470
|
+
const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1471
|
+
const credentials = {
|
|
1472
|
+
clientId,
|
|
1473
|
+
generation,
|
|
1474
|
+
...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
|
|
1475
|
+
};
|
|
1476
|
+
Object.defineProperty(credentials, "clientSecret", {
|
|
1477
|
+
enumerable: true,
|
|
1478
|
+
get: () => networkSecretBrokerKey(deps, clientId)
|
|
1479
|
+
});
|
|
1480
|
+
return credentials;
|
|
1481
|
+
}
|
|
1177
1482
|
if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
|
|
1178
1483
|
throw new MachineAuthError(
|
|
1179
1484
|
"incomplete_machine_credentials",
|
|
@@ -1188,7 +1493,7 @@ function environmentCredentials(deps) {
|
|
|
1188
1493
|
}
|
|
1189
1494
|
function hasMachineConfiguration(deps = {}) {
|
|
1190
1495
|
const env = deps.env ?? process.env;
|
|
1191
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1496
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
|
|
1192
1497
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1193
1498
|
throw new MachineAuthError(
|
|
1194
1499
|
"conflicting_credentials",
|
|
@@ -1225,6 +1530,8 @@ function machineSessionEnded(deps = {}) {
|
|
|
1225
1530
|
return readPrivate(join6(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1226
1531
|
}
|
|
1227
1532
|
var environmentTerminal;
|
|
1533
|
+
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
1534
|
+
var networkRejection;
|
|
1228
1535
|
async function loadRecord(profile, deps, signal) {
|
|
1229
1536
|
const directory = configurationDirectory(deps);
|
|
1230
1537
|
let value;
|
|
@@ -1288,6 +1595,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1288
1595
|
const apiUrl = apiUrlFor(deps);
|
|
1289
1596
|
const environment = environmentCredentials(deps);
|
|
1290
1597
|
if (environment) {
|
|
1598
|
+
const networkManaged = Boolean(environment.secretInjection || environment.tokenInjection);
|
|
1291
1599
|
const observedToken2 = cached?.generation === environment.generation ? cached.accessToken : void 0;
|
|
1292
1600
|
const directory2 = configurationDirectory(deps);
|
|
1293
1601
|
ensureDirectory(directory2);
|
|
@@ -1305,7 +1613,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1305
1613
|
writeEnvironmentContext(cached, deps);
|
|
1306
1614
|
return cached;
|
|
1307
1615
|
} catch (error) {
|
|
1308
|
-
if (error instanceof MachineAuthError && error.terminal)
|
|
1616
|
+
if (error instanceof MachineAuthError && error.terminal && !networkManaged)
|
|
1309
1617
|
environmentTerminal = environment.generation;
|
|
1310
1618
|
throw error;
|
|
1311
1619
|
}
|
|
@@ -1316,11 +1624,13 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1316
1624
|
if (machineSessionEnded(deps))
|
|
1317
1625
|
throw new MachineAuthError(
|
|
1318
1626
|
"machine_credentials_rejected",
|
|
1319
|
-
"Rotate the injected machine credentials.",
|
|
1627
|
+
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1320
1628
|
true
|
|
1321
1629
|
);
|
|
1322
1630
|
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS)
|
|
1323
1631
|
return cached;
|
|
1632
|
+
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1633
|
+
throw networkRejection.error;
|
|
1324
1634
|
try {
|
|
1325
1635
|
const { configuration, tokens, identity } = await withMachineCooldown(
|
|
1326
1636
|
directory2,
|
|
@@ -1329,13 +1639,36 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1329
1639
|
signal,
|
|
1330
1640
|
async () => {
|
|
1331
1641
|
const configuration2 = await discoverMachineConfiguration(apiUrl, signal, deps.fetch);
|
|
1642
|
+
if (environment.tokenInjection) {
|
|
1643
|
+
const identity3 = await verifyInjectedMachineIdentity(
|
|
1644
|
+
apiUrl,
|
|
1645
|
+
environment.clientId,
|
|
1646
|
+
signal,
|
|
1647
|
+
deps.fetch
|
|
1648
|
+
);
|
|
1649
|
+
const tokens3 = {
|
|
1650
|
+
accessToken: "",
|
|
1651
|
+
expiresAt: Date.now() + INJECTED_IDENTITY_TTL_MS
|
|
1652
|
+
};
|
|
1653
|
+
return { configuration: configuration2, tokens: tokens3, identity: identity3 };
|
|
1654
|
+
}
|
|
1332
1655
|
const tokens2 = await exchangeMachineCredentials(
|
|
1333
1656
|
configuration2,
|
|
1334
1657
|
environment.clientId,
|
|
1335
|
-
|
|
1658
|
+
// The broker key is not a client secret; the proxy supplies that.
|
|
1659
|
+
environment.secretInjection ? "" : environment.clientSecret,
|
|
1336
1660
|
signal,
|
|
1337
|
-
deps.fetch
|
|
1338
|
-
|
|
1661
|
+
deps.fetch,
|
|
1662
|
+
{ secretInjection: environment.secretInjection }
|
|
1663
|
+
).catch((error) => {
|
|
1664
|
+
if (environment.secretInjection && error instanceof MachineAuthError && error.code === "token_client_mismatch")
|
|
1665
|
+
throw new MachineAuthError(
|
|
1666
|
+
"network_secret_mismatch",
|
|
1667
|
+
`The token service issued a token for another machine. Check that the network secret's username equals PRIM_M2M_CLIENT_ID (${environment.clientId}).`,
|
|
1668
|
+
true
|
|
1669
|
+
);
|
|
1670
|
+
throw error;
|
|
1671
|
+
});
|
|
1339
1672
|
const identity2 = await verifyMachineIdentity(
|
|
1340
1673
|
apiUrl,
|
|
1341
1674
|
tokens2.accessToken,
|
|
@@ -1352,11 +1685,27 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1352
1685
|
...identity,
|
|
1353
1686
|
apiUrl,
|
|
1354
1687
|
generation: environment.generation,
|
|
1355
|
-
storage: "environment"
|
|
1688
|
+
storage: "environment",
|
|
1689
|
+
...environment.tokenInjection ? { tokenInjection: "network" } : {}
|
|
1356
1690
|
};
|
|
1357
1691
|
writeEnvironmentContext(cached, deps);
|
|
1358
1692
|
return cached;
|
|
1359
1693
|
} catch (error) {
|
|
1694
|
+
if (networkManaged && error instanceof MachineAuthError && error.terminal) {
|
|
1695
|
+
networkRejection = {
|
|
1696
|
+
generation: environment.generation,
|
|
1697
|
+
until: Date.now() + NETWORK_REJECTION_PAUSE_MS,
|
|
1698
|
+
error
|
|
1699
|
+
};
|
|
1700
|
+
if (cached?.generation === environment.generation) cached = void 0;
|
|
1701
|
+
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1702
|
+
try {
|
|
1703
|
+
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1704
|
+
rmSync5(contextPath, { force: true });
|
|
1705
|
+
} catch {
|
|
1706
|
+
}
|
|
1707
|
+
throw error;
|
|
1708
|
+
}
|
|
1360
1709
|
if (error instanceof MachineAuthError && error.terminal) {
|
|
1361
1710
|
environmentTerminal = environment.generation;
|
|
1362
1711
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
@@ -1437,6 +1786,24 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1437
1786
|
{ signal }
|
|
1438
1787
|
);
|
|
1439
1788
|
}
|
|
1789
|
+
async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
1790
|
+
const environment = environmentCredentials(deps);
|
|
1791
|
+
if (!environment?.tokenInjection)
|
|
1792
|
+
throw new MachineAuthError(
|
|
1793
|
+
"identity_changed",
|
|
1794
|
+
"Machine identity changed; restart the operation."
|
|
1795
|
+
);
|
|
1796
|
+
const directory = configurationDirectory(deps);
|
|
1797
|
+
ensureDirectory(directory);
|
|
1798
|
+
return forwardBrokerRequest({
|
|
1799
|
+
directory,
|
|
1800
|
+
apiUrl: apiUrlFor(deps),
|
|
1801
|
+
environment,
|
|
1802
|
+
env: deps.env ?? process.env,
|
|
1803
|
+
request: request3,
|
|
1804
|
+
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
1805
|
+
});
|
|
1806
|
+
}
|
|
1440
1807
|
function machineCaptureActor(deps = {}) {
|
|
1441
1808
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
1442
1809
|
const context = machineContext(deps);
|
|
@@ -1456,6 +1823,12 @@ function machineCaptureActor(deps = {}) {
|
|
|
1456
1823
|
function machineJournalBucket(identity) {
|
|
1457
1824
|
return `_machine_${hash(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
1458
1825
|
}
|
|
1826
|
+
function identityPending(actor) {
|
|
1827
|
+
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
1828
|
+
}
|
|
1829
|
+
function machinePendingBucket(identity) {
|
|
1830
|
+
return `_machine_pending_${hash(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
1831
|
+
}
|
|
1459
1832
|
|
|
1460
1833
|
// src/lib/credentials.ts
|
|
1461
1834
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
@@ -1481,7 +1854,7 @@ function readTrimmed(path) {
|
|
|
1481
1854
|
function resolveAuthCredential(options = {}) {
|
|
1482
1855
|
if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
|
|
1483
1856
|
const machine = cachedMachineCredential({ env: options.env });
|
|
1484
|
-
return machine ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1857
|
+
return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
|
|
1485
1858
|
}
|
|
1486
1859
|
const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
|
|
1487
1860
|
if (envToken) return { token: envToken, source: "environment" };
|
|
@@ -1672,7 +2045,7 @@ import { existsSync as existsSync8 } from "fs";
|
|
|
1672
2045
|
import { join as join12 } from "path";
|
|
1673
2046
|
|
|
1674
2047
|
// src/lib/hook-runtime.ts
|
|
1675
|
-
import { createHash as createHash5, randomBytes as
|
|
2048
|
+
import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
|
|
1676
2049
|
import {
|
|
1677
2050
|
constants as constants2,
|
|
1678
2051
|
accessSync,
|
|
@@ -1683,13 +2056,13 @@ import {
|
|
|
1683
2056
|
mkdirSync as mkdirSync4,
|
|
1684
2057
|
mkdtempSync,
|
|
1685
2058
|
readFileSync as readFileSync8,
|
|
1686
|
-
readdirSync,
|
|
2059
|
+
readdirSync as readdirSync2,
|
|
1687
2060
|
realpathSync,
|
|
1688
2061
|
renameSync as renameSync2,
|
|
1689
2062
|
rmSync as rmSync6,
|
|
1690
2063
|
statSync as statSync2,
|
|
1691
2064
|
utimesSync,
|
|
1692
|
-
writeFileSync as
|
|
2065
|
+
writeFileSync as writeFileSync4
|
|
1693
2066
|
} from "fs";
|
|
1694
2067
|
import { delimiter, dirname as dirname7, isAbsolute as isAbsolute3, join as join10, resolve } from "path";
|
|
1695
2068
|
|
|
@@ -1793,7 +2166,7 @@ exec "$prim_node" "$prim_entry" "$@"
|
|
|
1793
2166
|
|
|
1794
2167
|
// src/demo/state.ts
|
|
1795
2168
|
import { createHash as createHash6, randomUUID as randomUUID3 } from "crypto";
|
|
1796
|
-
import { existsSync as existsSync7, lstatSync as lstatSync5, readFileSync as readFileSync9, readdirSync as
|
|
2169
|
+
import { existsSync as existsSync7, lstatSync as lstatSync5, readFileSync as readFileSync9, readdirSync as readdirSync3 } from "fs";
|
|
1797
2170
|
import { join as join11, resolve as resolve2 } from "path";
|
|
1798
2171
|
|
|
1799
2172
|
// src/generated/cli-http-v1.validators.js
|
|
@@ -28657,9 +29030,25 @@ function observeDemoInvocation(envelope, agent, checkExclusion = true) {
|
|
|
28657
29030
|
|
|
28658
29031
|
// src/lib/activation.ts
|
|
28659
29032
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
28660
|
-
import { existsSync as
|
|
29033
|
+
import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
|
|
28661
29034
|
import { homedir as homedir2 } from "os";
|
|
29035
|
+
import { join as join15 } from "path";
|
|
29036
|
+
|
|
29037
|
+
// src/lib/cloud-prepared.ts
|
|
29038
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "fs";
|
|
28662
29039
|
import { join as join13 } from "path";
|
|
29040
|
+
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
29041
|
+
function cloudPreparedPath(env = process.env) {
|
|
29042
|
+
return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
29043
|
+
}
|
|
29044
|
+
function isPreparedCloudSession(env = process.env) {
|
|
29045
|
+
if (!isClaudeCloudSession(env)) return false;
|
|
29046
|
+
try {
|
|
29047
|
+
return existsSync10(cloudPreparedPath(env));
|
|
29048
|
+
} catch {
|
|
29049
|
+
return false;
|
|
29050
|
+
}
|
|
29051
|
+
}
|
|
28663
29052
|
|
|
28664
29053
|
// src/lib/demo-pause.ts
|
|
28665
29054
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
@@ -28725,11 +29114,12 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
28725
29114
|
// src/lib/git.ts
|
|
28726
29115
|
import { execFileSync as execFileSync3 } from "child_process";
|
|
28727
29116
|
import { createHash as createHash7 } from "crypto";
|
|
28728
|
-
import { lstatSync as lstatSync6, realpathSync as realpathSync2 } from "fs";
|
|
28729
|
-
import { basename as basename2, dirname as dirname8, isAbsolute as isAbsolute4, relative, resolve as resolve3, sep } from "path";
|
|
29117
|
+
import { lstatSync as lstatSync6, readFileSync as readFileSync11, realpathSync as realpathSync2 } from "fs";
|
|
29118
|
+
import { basename as basename2, dirname as dirname8, isAbsolute as isAbsolute4, join as join14, relative, resolve as resolve3, sep } from "path";
|
|
28730
29119
|
var GIT_TIMEOUT_MS2 = 1e3;
|
|
29120
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
28731
29121
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
28732
|
-
var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
|
|
29122
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
28733
29123
|
function gitToplevel(cwd) {
|
|
28734
29124
|
try {
|
|
28735
29125
|
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
@@ -28758,19 +29148,57 @@ function gitValue(cwd, args) {
|
|
|
28758
29148
|
function currentBranch(cwd) {
|
|
28759
29149
|
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
28760
29150
|
}
|
|
28761
|
-
function
|
|
28762
|
-
const
|
|
28763
|
-
if (
|
|
29151
|
+
function parseGithubRepositoryName(path) {
|
|
29152
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
29153
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
29154
|
+
return null;
|
|
29155
|
+
}
|
|
29156
|
+
return `${parts[0]}/${parts[1]}`;
|
|
29157
|
+
}
|
|
29158
|
+
function githubRepositoryFromRemote(remote) {
|
|
29159
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
28764
29160
|
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
28765
29161
|
remote
|
|
28766
29162
|
);
|
|
28767
29163
|
const path = match?.[1] ?? match?.[2];
|
|
28768
|
-
|
|
28769
|
-
|
|
28770
|
-
|
|
29164
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
29165
|
+
}
|
|
29166
|
+
function checkoutSettingsText(repoRoot) {
|
|
29167
|
+
const path = join14(repoRoot, ".claude", "settings.json");
|
|
29168
|
+
try {
|
|
29169
|
+
if (!lstatSync6(join14(repoRoot, ".claude")).isDirectory()) return null;
|
|
29170
|
+
const stat = lstatSync6(path);
|
|
29171
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
29172
|
+
return readFileSync11(path, "utf8");
|
|
29173
|
+
} catch {
|
|
28771
29174
|
return null;
|
|
28772
29175
|
}
|
|
28773
|
-
|
|
29176
|
+
}
|
|
29177
|
+
function checkoutDeclaration(repoRoot, name2) {
|
|
29178
|
+
const text = checkoutSettingsText(repoRoot);
|
|
29179
|
+
if (text === null) return null;
|
|
29180
|
+
let parsed;
|
|
29181
|
+
try {
|
|
29182
|
+
parsed = JSON.parse(text);
|
|
29183
|
+
} catch {
|
|
29184
|
+
return null;
|
|
29185
|
+
}
|
|
29186
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
29187
|
+
const value = typeof env === "object" && env !== null ? env[name2] : void 0;
|
|
29188
|
+
return typeof value === "string" ? value : null;
|
|
29189
|
+
}
|
|
29190
|
+
function declaredGithubRepository(repoRoot) {
|
|
29191
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
29192
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
29193
|
+
}
|
|
29194
|
+
function githubRepositoryFullName(cwd) {
|
|
29195
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
29196
|
+
if (remote) {
|
|
29197
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
29198
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
29199
|
+
}
|
|
29200
|
+
const root = gitToplevel(cwd);
|
|
29201
|
+
return root ? declaredGithubRepository(root) : null;
|
|
28774
29202
|
}
|
|
28775
29203
|
function canonicalGitRoot(cwd) {
|
|
28776
29204
|
try {
|
|
@@ -28849,6 +29277,14 @@ function resolveRepositoryContext(cwd = process.cwd()) {
|
|
|
28849
29277
|
repoFullName
|
|
28850
29278
|
};
|
|
28851
29279
|
}
|
|
29280
|
+
if (repoFullName) {
|
|
29281
|
+
return {
|
|
29282
|
+
repoRoot,
|
|
29283
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
29284
|
+
identitySource: "declared",
|
|
29285
|
+
repoFullName
|
|
29286
|
+
};
|
|
29287
|
+
}
|
|
28852
29288
|
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
28853
29289
|
if (roots && roots.length > 0) {
|
|
28854
29290
|
return {
|
|
@@ -28937,6 +29373,7 @@ function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
|
28937
29373
|
|
|
28938
29374
|
// src/lib/activation.ts
|
|
28939
29375
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
29376
|
+
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
28940
29377
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
28941
29378
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
28942
29379
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
@@ -29000,14 +29437,13 @@ function repositoryBindingState(cwd) {
|
|
|
29000
29437
|
if (marker !== void 0) return "invalid";
|
|
29001
29438
|
return rawId === void 0 ? "unbound" : repoSyncId(cwd) ? void 0 : "unbound";
|
|
29002
29439
|
}
|
|
29003
|
-
function
|
|
29004
|
-
const root = gitToplevel(cwd);
|
|
29440
|
+
function projectPrimInstallAt(root) {
|
|
29005
29441
|
if (root === null || root === homedir2()) return false;
|
|
29006
29442
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
29007
|
-
const path =
|
|
29008
|
-
if (
|
|
29443
|
+
const path = join15(root, rel);
|
|
29444
|
+
if (existsSync11(path)) {
|
|
29009
29445
|
try {
|
|
29010
|
-
const content2 =
|
|
29446
|
+
const content2 = readFileSync12(path, "utf-8");
|
|
29011
29447
|
if (PRIM_HOOK_BINS.some((bin) => content2.includes(bin))) return true;
|
|
29012
29448
|
} catch {
|
|
29013
29449
|
}
|
|
@@ -29015,12 +29451,27 @@ function hasProjectPrimInstall(cwd) {
|
|
|
29015
29451
|
}
|
|
29016
29452
|
return false;
|
|
29017
29453
|
}
|
|
29454
|
+
var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
|
|
29455
|
+
function declaresInactiveAt(root) {
|
|
29456
|
+
if (root === null || root === homedir2()) return false;
|
|
29457
|
+
if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
|
|
29458
|
+
const text = checkoutSettingsText(root);
|
|
29459
|
+
if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
|
|
29460
|
+
try {
|
|
29461
|
+
JSON.parse(text);
|
|
29462
|
+
return false;
|
|
29463
|
+
} catch {
|
|
29464
|
+
return true;
|
|
29465
|
+
}
|
|
29466
|
+
}
|
|
29018
29467
|
function isRepoActiveForCapture(cwd, options = {}) {
|
|
29019
29468
|
let { active: flag, pause } = readCaptureConfig(cwd);
|
|
29020
29469
|
if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
|
|
29021
29470
|
if (flag === "true") return true;
|
|
29022
29471
|
if (flag === "false") return false;
|
|
29023
|
-
|
|
29472
|
+
const root = gitToplevel(cwd);
|
|
29473
|
+
if (declaresInactiveAt(root)) return false;
|
|
29474
|
+
return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
|
|
29024
29475
|
}
|
|
29025
29476
|
function decisionIngestionStatus(cwd) {
|
|
29026
29477
|
return isRepoActiveForCapture(cwd) ? "enabled" : "disabled";
|
|
@@ -29105,13 +29556,13 @@ function publicDecisionResponse(value) {
|
|
|
29105
29556
|
|
|
29106
29557
|
// src/client.ts
|
|
29107
29558
|
import { createHash as createHash8 } from "crypto";
|
|
29108
|
-
import { chmodSync as chmodSync4, existsSync as
|
|
29559
|
+
import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync8 } from "fs";
|
|
29109
29560
|
import { dirname as dirname9 } from "path";
|
|
29110
29561
|
|
|
29111
29562
|
// src/daemon/client-instance-id.ts
|
|
29112
|
-
import { randomBytes as
|
|
29113
|
-
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as
|
|
29114
|
-
import { join as
|
|
29563
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
29564
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
29565
|
+
import { join as join16 } from "path";
|
|
29115
29566
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
29116
29567
|
var INSTANCE_FILE_MODE = 384;
|
|
29117
29568
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -29148,7 +29599,7 @@ function readExisting(path) {
|
|
|
29148
29599
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
29149
29600
|
throw new Error("stored client instance identity is invalid");
|
|
29150
29601
|
}
|
|
29151
|
-
const raw =
|
|
29602
|
+
const raw = readFileSync13(path, "utf8");
|
|
29152
29603
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
29153
29604
|
if (raw !== value && raw !== `${value}
|
|
29154
29605
|
` || !isClientInstanceId(value)) {
|
|
@@ -29162,8 +29613,8 @@ function atomicWrite(path, value) {
|
|
|
29162
29613
|
}
|
|
29163
29614
|
async function getOrCreateClientInstanceId(options) {
|
|
29164
29615
|
const configDir = options.configDir;
|
|
29165
|
-
const path =
|
|
29166
|
-
const lockPath =
|
|
29616
|
+
const path = join16(configDir, "client_instance_id");
|
|
29617
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
29167
29618
|
ensurePrivateConfigDirectory(configDir);
|
|
29168
29619
|
return withFileLock(
|
|
29169
29620
|
lockPath,
|
|
@@ -29172,7 +29623,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
29172
29623
|
if (existing !== void 0) {
|
|
29173
29624
|
return existing;
|
|
29174
29625
|
}
|
|
29175
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
29626
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
29176
29627
|
"base64url"
|
|
29177
29628
|
)}`;
|
|
29178
29629
|
if (!isClientInstanceId(generated)) {
|
|
@@ -29255,9 +29706,12 @@ var CREDENTIAL_FILE_MODE = 384;
|
|
|
29255
29706
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29256
29707
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
29257
29708
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
29709
|
+
function authExpiredMessage() {
|
|
29710
|
+
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
29711
|
+
}
|
|
29258
29712
|
function readTrimmed2(path) {
|
|
29259
29713
|
try {
|
|
29260
|
-
const value =
|
|
29714
|
+
const value = readFileSync14(path, "utf8").trim();
|
|
29261
29715
|
return value || void 0;
|
|
29262
29716
|
} catch {
|
|
29263
29717
|
return void 0;
|
|
@@ -29274,7 +29728,7 @@ function expiresAtFor(token, expiresIn) {
|
|
|
29274
29728
|
}
|
|
29275
29729
|
function ensureConfigDirectory() {
|
|
29276
29730
|
const directory = dirname9(TOKEN_FILE_PATH);
|
|
29277
|
-
|
|
29731
|
+
mkdirSync6(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
29278
29732
|
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
29279
29733
|
}
|
|
29280
29734
|
function atomicWrite2(path, content2) {
|
|
@@ -29282,8 +29736,8 @@ function atomicWrite2(path, content2) {
|
|
|
29282
29736
|
atomicWriteFile(path, content2, { mode: CREDENTIAL_FILE_MODE });
|
|
29283
29737
|
}
|
|
29284
29738
|
function removeCredentialFile(path) {
|
|
29285
|
-
if (!
|
|
29286
|
-
|
|
29739
|
+
if (!existsSync12(path)) return false;
|
|
29740
|
+
rmSync8(path, { force: true });
|
|
29287
29741
|
return true;
|
|
29288
29742
|
}
|
|
29289
29743
|
function getTokenExpiresAt() {
|
|
@@ -29636,7 +30090,7 @@ var CliManagementResponseError = class extends Error {
|
|
|
29636
30090
|
var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
29637
30091
|
async function managementResponseValue(response) {
|
|
29638
30092
|
if (response.status === 401) {
|
|
29639
|
-
throw new HttpError(401,
|
|
30093
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29640
30094
|
}
|
|
29641
30095
|
let value;
|
|
29642
30096
|
try {
|
|
@@ -29658,23 +30112,50 @@ function selectedCredential() {
|
|
|
29658
30112
|
}
|
|
29659
30113
|
return _cachedCredential;
|
|
29660
30114
|
}
|
|
30115
|
+
async function requestHeaders(method, path) {
|
|
30116
|
+
return {
|
|
30117
|
+
"Content-Type": "application/json",
|
|
30118
|
+
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
30119
|
+
};
|
|
30120
|
+
}
|
|
29661
30121
|
async function fetchWithToken(method, path, body, options, token, siteUrl) {
|
|
29662
30122
|
return fetch(`${siteUrl}${path}`, {
|
|
29663
30123
|
method,
|
|
29664
|
-
headers: {
|
|
29665
|
-
Authorization: `Bearer ${token}`,
|
|
29666
|
-
"Content-Type": "application/json",
|
|
29667
|
-
...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
|
|
29668
|
-
},
|
|
30124
|
+
headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
|
|
29669
30125
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
29670
30126
|
signal: options?.signal,
|
|
29671
30127
|
redirect: options?.redirect
|
|
29672
30128
|
});
|
|
29673
30129
|
}
|
|
30130
|
+
async function fetchAsMachine(credential, method, path, body, options) {
|
|
30131
|
+
if (!credential.tokenInjection)
|
|
30132
|
+
return fetchWithToken(
|
|
30133
|
+
method,
|
|
30134
|
+
path,
|
|
30135
|
+
body,
|
|
30136
|
+
{ ...options, redirect: "error" },
|
|
30137
|
+
credential.accessToken,
|
|
30138
|
+
credential.apiUrl
|
|
30139
|
+
);
|
|
30140
|
+
try {
|
|
30141
|
+
return await forwardMachineRequest(
|
|
30142
|
+
{
|
|
30143
|
+
method,
|
|
30144
|
+
path,
|
|
30145
|
+
headers: await requestHeaders(method, path),
|
|
30146
|
+
...body === void 0 ? {} : { body: JSON.stringify(body) }
|
|
30147
|
+
},
|
|
30148
|
+
options.signal
|
|
30149
|
+
);
|
|
30150
|
+
} catch (error) {
|
|
30151
|
+
if (!(error instanceof MachineAuthError)) throw error;
|
|
30152
|
+
throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
|
|
30153
|
+
}
|
|
30154
|
+
}
|
|
29674
30155
|
async function responseValue(response) {
|
|
29675
30156
|
if (!response.ok) {
|
|
29676
30157
|
if (response.status === 401) {
|
|
29677
|
-
throw new HttpError(401,
|
|
30158
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29678
30159
|
}
|
|
29679
30160
|
const errorBody = await response.json().catch(() => null);
|
|
29680
30161
|
const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
|
|
@@ -29701,14 +30182,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29701
30182
|
const current = await acquireMachineCredential({ signal: requestOptions.signal });
|
|
29702
30183
|
if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
|
|
29703
30184
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29704
|
-
let response = await
|
|
29705
|
-
method,
|
|
29706
|
-
path,
|
|
29707
|
-
body,
|
|
29708
|
-
{ ...requestOptions, redirect: "error" },
|
|
29709
|
-
current.accessToken,
|
|
29710
|
-
selected.apiUrl
|
|
29711
|
-
);
|
|
30185
|
+
let response = await fetchAsMachine(current, method, path, body, requestOptions);
|
|
29712
30186
|
if (response.status === 401) {
|
|
29713
30187
|
const renewed = await acquireMachineCredential({
|
|
29714
30188
|
force: true,
|
|
@@ -29717,19 +30191,14 @@ async function machineClient(options = {}, management = false) {
|
|
|
29717
30191
|
if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
|
|
29718
30192
|
throw new HttpError(409, "Machine identity changed; restart the operation.");
|
|
29719
30193
|
}
|
|
29720
|
-
response = await
|
|
29721
|
-
method,
|
|
29722
|
-
path,
|
|
29723
|
-
body,
|
|
29724
|
-
{ ...requestOptions, redirect: "error" },
|
|
29725
|
-
renewed.accessToken,
|
|
29726
|
-
renewed.apiUrl
|
|
29727
|
-
);
|
|
30194
|
+
response = await fetchAsMachine(renewed, method, path, body, requestOptions);
|
|
29728
30195
|
}
|
|
29729
30196
|
if (response.status === 401)
|
|
29730
30197
|
throw new HttpError(
|
|
29731
30198
|
401,
|
|
29732
|
-
"Machine access was rejected.
|
|
30199
|
+
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(
|
|
30200
|
+
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
30201
|
+
)
|
|
29733
30202
|
);
|
|
29734
30203
|
return parse2(response);
|
|
29735
30204
|
};
|
|
@@ -29739,7 +30208,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
29739
30208
|
delete: (path, body, opts) => send("DELETE", path, body, opts)
|
|
29740
30209
|
};
|
|
29741
30210
|
}
|
|
29742
|
-
async function
|
|
30211
|
+
async function request2(method, path, body, options) {
|
|
29743
30212
|
const machine = await machineClient(options);
|
|
29744
30213
|
if (machine)
|
|
29745
30214
|
return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
|
|
@@ -29755,10 +30224,10 @@ async function request(method, path, body, options) {
|
|
|
29755
30224
|
if (token) credential = { token, source: "token_file" };
|
|
29756
30225
|
}
|
|
29757
30226
|
if (!credential) {
|
|
29758
|
-
throw new HttpError(401,
|
|
30227
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29759
30228
|
}
|
|
29760
30229
|
if (isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
29761
|
-
throw new HttpError(401,
|
|
30230
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29762
30231
|
}
|
|
29763
30232
|
const tokenUsed = credential.token;
|
|
29764
30233
|
let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
|
|
@@ -29781,8 +30250,8 @@ async function request(method, path, body, options) {
|
|
|
29781
30250
|
}
|
|
29782
30251
|
function getClient() {
|
|
29783
30252
|
return {
|
|
29784
|
-
get: (path, options) =>
|
|
29785
|
-
post: (path, body, options) =>
|
|
30253
|
+
get: (path, options) => request2("GET", path, void 0, options),
|
|
30254
|
+
post: (path, body, options) => request2("POST", path, body, options)
|
|
29786
30255
|
};
|
|
29787
30256
|
}
|
|
29788
30257
|
async function getPinnedClient(options = {}) {
|
|
@@ -29798,7 +30267,7 @@ async function getPinnedClient(options = {}) {
|
|
|
29798
30267
|
if (token2) credential = { token: token2, source: "token_file" };
|
|
29799
30268
|
}
|
|
29800
30269
|
if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
|
|
29801
|
-
throw new HttpError(401,
|
|
30270
|
+
throw new HttpError(401, authExpiredMessage());
|
|
29802
30271
|
}
|
|
29803
30272
|
const token = credential.token;
|
|
29804
30273
|
const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
|
|
@@ -30170,17 +30639,17 @@ import {
|
|
|
30170
30639
|
closeSync as closeSync2,
|
|
30171
30640
|
fchmodSync as fchmodSync2,
|
|
30172
30641
|
fsyncSync as fsyncSync2,
|
|
30173
|
-
linkSync,
|
|
30642
|
+
linkSync as linkSync2,
|
|
30174
30643
|
lstatSync as lstatSync8,
|
|
30175
|
-
mkdirSync as
|
|
30644
|
+
mkdirSync as mkdirSync7,
|
|
30176
30645
|
openSync as openSync2,
|
|
30177
|
-
readFileSync as
|
|
30646
|
+
readFileSync as readFileSync15,
|
|
30178
30647
|
statSync as statSync3,
|
|
30179
30648
|
unlinkSync,
|
|
30180
|
-
writeFileSync as
|
|
30649
|
+
writeFileSync as writeFileSync6
|
|
30181
30650
|
} from "fs";
|
|
30182
|
-
import { dirname as dirname10, isAbsolute as isAbsolute5, join as
|
|
30183
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
30651
|
+
import { dirname as dirname10, isAbsolute as isAbsolute5, join as join18, resolve as resolve5 } from "path";
|
|
30652
|
+
var WORKSPACE_ID_RELATIVE_PATH = join18("prim", "workspace-id");
|
|
30184
30653
|
var MAX_ANCESTORS = 64;
|
|
30185
30654
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
30186
30655
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -30239,19 +30708,19 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
30239
30708
|
function resolveFromFilesystem(cwd) {
|
|
30240
30709
|
let current = resolve5(cwd);
|
|
30241
30710
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
30242
|
-
const dotGit =
|
|
30711
|
+
const dotGit = join18(current, ".git");
|
|
30243
30712
|
try {
|
|
30244
30713
|
const stat = lstatSync8(dotGit);
|
|
30245
30714
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
30246
|
-
return
|
|
30715
|
+
return join18(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
30247
30716
|
}
|
|
30248
30717
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
30249
|
-
const contents =
|
|
30718
|
+
const contents = readFileSync15(dotGit, "utf8");
|
|
30250
30719
|
const match = /^gitdir: (.+?)(?:\r?\n)?$/.exec(contents);
|
|
30251
30720
|
if (match?.[1]) {
|
|
30252
30721
|
const gitDirectory = isAbsolute5(match[1]) ? resolve5(match[1]) : resolve5(current, match[1]);
|
|
30253
30722
|
if (isGitDirectory(gitDirectory)) {
|
|
30254
|
-
return
|
|
30723
|
+
return join18(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
30255
30724
|
}
|
|
30256
30725
|
}
|
|
30257
30726
|
}
|
|
@@ -30270,7 +30739,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
30270
30739
|
}
|
|
30271
30740
|
function isGitDirectory(path) {
|
|
30272
30741
|
try {
|
|
30273
|
-
return statSync3(
|
|
30742
|
+
return statSync3(join18(path, "HEAD")).isFile();
|
|
30274
30743
|
} catch {
|
|
30275
30744
|
return false;
|
|
30276
30745
|
}
|
|
@@ -30289,7 +30758,7 @@ function inspectPath(path) {
|
|
|
30289
30758
|
return { status: "corrupt", path, reason: "invalid_content" };
|
|
30290
30759
|
}
|
|
30291
30760
|
try {
|
|
30292
|
-
const contents =
|
|
30761
|
+
const contents = readFileSync15(path, "utf8");
|
|
30293
30762
|
const workspaceId = contents.endsWith("\n") ? contents.slice(0, -1) : contents;
|
|
30294
30763
|
if ((contents === workspaceId || contents === `${workspaceId}
|
|
30295
30764
|
`) && isCanonicalWorkspaceId(workspaceId)) {
|
|
@@ -30308,11 +30777,11 @@ function inspectPath(path) {
|
|
|
30308
30777
|
function createWorkspaceId(path) {
|
|
30309
30778
|
const parent = dirname10(path);
|
|
30310
30779
|
const workspaceId = randomUUID4();
|
|
30311
|
-
const temporaryPath =
|
|
30780
|
+
const temporaryPath = join18(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
30312
30781
|
let temporaryCreated = false;
|
|
30313
30782
|
let publishing = false;
|
|
30314
30783
|
try {
|
|
30315
|
-
|
|
30784
|
+
mkdirSync7(parent, { recursive: true, mode: 448 });
|
|
30316
30785
|
chmodSync5(parent, 448);
|
|
30317
30786
|
const fd = openSync2(
|
|
30318
30787
|
temporaryPath,
|
|
@@ -30321,7 +30790,7 @@ function createWorkspaceId(path) {
|
|
|
30321
30790
|
);
|
|
30322
30791
|
temporaryCreated = true;
|
|
30323
30792
|
try {
|
|
30324
|
-
|
|
30793
|
+
writeFileSync6(fd, `${workspaceId}
|
|
30325
30794
|
`, "utf8");
|
|
30326
30795
|
fchmodSync2(fd, 384);
|
|
30327
30796
|
fsyncSync2(fd);
|
|
@@ -30329,7 +30798,7 @@ function createWorkspaceId(path) {
|
|
|
30329
30798
|
closeSync2(fd);
|
|
30330
30799
|
}
|
|
30331
30800
|
publishing = true;
|
|
30332
|
-
|
|
30801
|
+
linkSync2(temporaryPath, path);
|
|
30333
30802
|
return { status: "ready", workspaceId, path, created: true };
|
|
30334
30803
|
} catch (error) {
|
|
30335
30804
|
if (publishing && errorCode(error) === "EEXIST") return inspectAfterRace(path);
|
|
@@ -30378,20 +30847,20 @@ function parseAgent(argv) {
|
|
|
30378
30847
|
}
|
|
30379
30848
|
|
|
30380
30849
|
// src/hooks/codex-context.ts
|
|
30381
|
-
import { createHash as createHash10, randomBytes as
|
|
30850
|
+
import { createHash as createHash10, randomBytes as randomBytes7 } from "crypto";
|
|
30382
30851
|
import {
|
|
30383
30852
|
chmodSync as chmodSync6,
|
|
30384
|
-
existsSync as
|
|
30385
|
-
mkdirSync as
|
|
30386
|
-
readFileSync as
|
|
30387
|
-
readdirSync as
|
|
30853
|
+
existsSync as existsSync13,
|
|
30854
|
+
mkdirSync as mkdirSync8,
|
|
30855
|
+
readFileSync as readFileSync16,
|
|
30856
|
+
readdirSync as readdirSync4,
|
|
30388
30857
|
renameSync as renameSync3,
|
|
30389
|
-
rmSync as
|
|
30858
|
+
rmSync as rmSync9,
|
|
30390
30859
|
statSync as statSync4,
|
|
30391
30860
|
unlinkSync as unlinkSync2,
|
|
30392
|
-
writeFileSync as
|
|
30861
|
+
writeFileSync as writeFileSync7
|
|
30393
30862
|
} from "fs";
|
|
30394
|
-
import { join as
|
|
30863
|
+
import { join as join20 } from "path";
|
|
30395
30864
|
|
|
30396
30865
|
// src/daemon/principal.ts
|
|
30397
30866
|
import { createHash as createHash9 } from "crypto";
|
|
@@ -30454,14 +30923,14 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
30454
30923
|
|
|
30455
30924
|
// src/daemon/client.ts
|
|
30456
30925
|
import { createConnection } from "net";
|
|
30457
|
-
import { join as
|
|
30458
|
-
var SOCK_PATH =
|
|
30926
|
+
import { join as join19 } from "path";
|
|
30927
|
+
var SOCK_PATH = join19(primConfigDirectory(), "sock");
|
|
30459
30928
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
30460
30929
|
var nextRequestId = 1;
|
|
30461
30930
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
30462
30931
|
const id2 = nextRequestId++;
|
|
30463
30932
|
const caller = resolveDaemonPrincipal();
|
|
30464
|
-
const
|
|
30933
|
+
const request3 = {
|
|
30465
30934
|
id: id2,
|
|
30466
30935
|
method,
|
|
30467
30936
|
params,
|
|
@@ -30500,7 +30969,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30500
30969
|
});
|
|
30501
30970
|
socket.on("connect", () => {
|
|
30502
30971
|
try {
|
|
30503
|
-
socket?.write(`${JSON.stringify(
|
|
30972
|
+
socket?.write(`${JSON.stringify(request3)}
|
|
30504
30973
|
`);
|
|
30505
30974
|
} catch {
|
|
30506
30975
|
clearTimeout(timer);
|
|
@@ -30545,7 +31014,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
30545
31014
|
}
|
|
30546
31015
|
|
|
30547
31016
|
// src/daemon/decision-digest-cache.ts
|
|
30548
|
-
import { randomBytes as
|
|
31017
|
+
import { randomBytes as randomBytes6 } from "crypto";
|
|
30549
31018
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
30550
31019
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
30551
31020
|
var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
|
|
@@ -30758,10 +31227,10 @@ function appendCodexContext(output, context) {
|
|
|
30758
31227
|
return next;
|
|
30759
31228
|
}
|
|
30760
31229
|
function stateRoot(namespace) {
|
|
30761
|
-
return
|
|
31230
|
+
return join20(primConfigDirectory(), namespace, "decision-digests");
|
|
30762
31231
|
}
|
|
30763
31232
|
function draftStateRoot(namespace) {
|
|
30764
|
-
return
|
|
31233
|
+
return join20(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
30765
31234
|
}
|
|
30766
31235
|
function workspaceFor(cwd) {
|
|
30767
31236
|
try {
|
|
@@ -30773,12 +31242,12 @@ function workspaceFor(cwd) {
|
|
|
30773
31242
|
function statePath(args) {
|
|
30774
31243
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
30775
31244
|
const key = createHash10("sha256").update(identity).digest("hex");
|
|
30776
|
-
return
|
|
31245
|
+
return join20(stateRoot(args.namespace), `${key}.json`);
|
|
30777
31246
|
}
|
|
30778
31247
|
function draftStatePath(args) {
|
|
30779
31248
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
30780
31249
|
const key = createHash10("sha256").update(identity).digest("hex");
|
|
30781
|
-
return
|
|
31250
|
+
return join20(draftStateRoot(args.namespace), `${key}.json`);
|
|
30782
31251
|
}
|
|
30783
31252
|
function parseState(value) {
|
|
30784
31253
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -30817,30 +31286,30 @@ function parseDraftState(value) {
|
|
|
30817
31286
|
};
|
|
30818
31287
|
}
|
|
30819
31288
|
function readState(path) {
|
|
30820
|
-
if (!
|
|
31289
|
+
if (!existsSync13(path)) return void 0;
|
|
30821
31290
|
try {
|
|
30822
|
-
return parseState(JSON.parse(
|
|
31291
|
+
return parseState(JSON.parse(readFileSync16(path, "utf8")));
|
|
30823
31292
|
} catch {
|
|
30824
31293
|
return void 0;
|
|
30825
31294
|
}
|
|
30826
31295
|
}
|
|
30827
31296
|
function readDraftState(path) {
|
|
30828
|
-
if (!
|
|
31297
|
+
if (!existsSync13(path)) return void 0;
|
|
30829
31298
|
try {
|
|
30830
|
-
return parseDraftState(JSON.parse(
|
|
31299
|
+
return parseDraftState(JSON.parse(readFileSync16(path, "utf8")));
|
|
30831
31300
|
} catch {
|
|
30832
31301
|
return void 0;
|
|
30833
31302
|
}
|
|
30834
31303
|
}
|
|
30835
31304
|
function writeStateFile(path, directory, state) {
|
|
30836
|
-
|
|
31305
|
+
mkdirSync8(directory, { recursive: true, mode: 448 });
|
|
30837
31306
|
chmodSync6(directory, 448);
|
|
30838
|
-
const temporary =
|
|
31307
|
+
const temporary = join20(
|
|
30839
31308
|
directory,
|
|
30840
|
-
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${
|
|
31309
|
+
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
30841
31310
|
);
|
|
30842
31311
|
try {
|
|
30843
|
-
|
|
31312
|
+
writeFileSync7(temporary, `${JSON.stringify(state)}
|
|
30844
31313
|
`, {
|
|
30845
31314
|
encoding: "utf8",
|
|
30846
31315
|
mode: 384,
|
|
@@ -30856,17 +31325,17 @@ function writeStateFile(path, directory, state) {
|
|
|
30856
31325
|
}
|
|
30857
31326
|
}
|
|
30858
31327
|
function cleanupStateFiles(directory, now) {
|
|
30859
|
-
if (!
|
|
31328
|
+
if (!existsSync13(directory)) return;
|
|
30860
31329
|
let names;
|
|
30861
31330
|
try {
|
|
30862
|
-
names =
|
|
31331
|
+
names = readdirSync4(directory);
|
|
30863
31332
|
} catch {
|
|
30864
31333
|
return;
|
|
30865
31334
|
}
|
|
30866
31335
|
const files = [];
|
|
30867
31336
|
const residue = [];
|
|
30868
31337
|
for (const name2 of names) {
|
|
30869
|
-
const path =
|
|
31338
|
+
const path = join20(directory, name2);
|
|
30870
31339
|
try {
|
|
30871
31340
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
30872
31341
|
if (name2.endsWith(".json")) {
|
|
@@ -30888,7 +31357,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
30888
31357
|
for (const path of residue) {
|
|
30889
31358
|
try {
|
|
30890
31359
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
30891
|
-
|
|
31360
|
+
rmSync9(path, { recursive: true, force: true });
|
|
30892
31361
|
}
|
|
30893
31362
|
} catch {
|
|
30894
31363
|
}
|
|
@@ -31171,17 +31640,17 @@ async function prepareCodexContext(options) {
|
|
|
31171
31640
|
}
|
|
31172
31641
|
|
|
31173
31642
|
// src/commands/cursor-install.ts
|
|
31174
|
-
import { existsSync as
|
|
31643
|
+
import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
|
|
31175
31644
|
import { homedir as homedir4 } from "os";
|
|
31176
|
-
import { isAbsolute as isAbsolute6, join as
|
|
31645
|
+
import { isAbsolute as isAbsolute6, join as join22 } from "path";
|
|
31177
31646
|
|
|
31178
31647
|
// src/lib/preflight-host.ts
|
|
31179
31648
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
31180
31649
|
|
|
31181
31650
|
// src/commands/claude-install.ts
|
|
31182
|
-
import { existsSync as
|
|
31651
|
+
import { existsSync as existsSync14, lstatSync as lstatSync9, readFileSync as readFileSync17 } from "fs";
|
|
31183
31652
|
import { homedir as homedir3 } from "os";
|
|
31184
|
-
import { join as
|
|
31653
|
+
import { join as join21 } from "path";
|
|
31185
31654
|
var CAPTURE_BIN = "prim-hook";
|
|
31186
31655
|
var GATE_BIN = "prim-pre-tool-use";
|
|
31187
31656
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -31190,7 +31659,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
31190
31659
|
var STATUSLINE_BIN = "prim-statusline";
|
|
31191
31660
|
var STATUSLINE_ARGS = "";
|
|
31192
31661
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
31193
|
-
var USER_SCOPE_PATH =
|
|
31662
|
+
var USER_SCOPE_PATH = join21(homedir3(), ".claude", "settings.json");
|
|
31194
31663
|
function projectRoot() {
|
|
31195
31664
|
return gitToplevel() ?? process.cwd();
|
|
31196
31665
|
}
|
|
@@ -31270,20 +31739,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
|
|
|
31270
31739
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
31271
31740
|
if (explicit && isAbsolute6(explicit)) return explicit;
|
|
31272
31741
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
31273
|
-
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return
|
|
31274
|
-
return
|
|
31742
|
+
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join22(xdg, "cursor");
|
|
31743
|
+
return join22(home, ".cursor");
|
|
31275
31744
|
}
|
|
31276
31745
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
31277
|
-
return scope === "user" ?
|
|
31746
|
+
return scope === "user" ? join22(cursorConfigDirectory(), "hooks.json") : join22(root, ".cursor", "hooks.json");
|
|
31278
31747
|
}
|
|
31279
31748
|
function plainObject(value) {
|
|
31280
31749
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
31281
31750
|
}
|
|
31282
31751
|
function readCursorHooks(path) {
|
|
31283
|
-
if (!
|
|
31752
|
+
if (!existsSync15(path)) return {};
|
|
31284
31753
|
let parsed;
|
|
31285
31754
|
try {
|
|
31286
|
-
parsed = JSON.parse(
|
|
31755
|
+
parsed = JSON.parse(readFileSync18(path, "utf8"));
|
|
31287
31756
|
} catch {
|
|
31288
31757
|
throw new Error(`invalid Cursor hooks JSON at ${path}`);
|
|
31289
31758
|
}
|
|
@@ -31504,8 +31973,8 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
|
|
|
31504
31973
|
}
|
|
31505
31974
|
|
|
31506
31975
|
// src/hooks/redact.ts
|
|
31507
|
-
import { existsSync as
|
|
31508
|
-
import { join as
|
|
31976
|
+
import { existsSync as existsSync16, readFileSync as readFileSync19, statSync as statSync5 } from "fs";
|
|
31977
|
+
import { join as join23 } from "path";
|
|
31509
31978
|
import { Worker } from "worker_threads";
|
|
31510
31979
|
var USER_HOME_RULES = [
|
|
31511
31980
|
{
|
|
@@ -31549,6 +32018,11 @@ var DEFAULT_RULES = [
|
|
|
31549
32018
|
pattern: /\bAWS_(?:SECRET_ACCESS_KEY|SESSION_TOKEN)"?\s*[:=]\s*["']?[A-Za-z0-9/+=]{20,}["']?/gi,
|
|
31550
32019
|
reason: "aws-secret"
|
|
31551
32020
|
},
|
|
32021
|
+
{
|
|
32022
|
+
// `prim auth enroll --print-env` output an agent may write into a file.
|
|
32023
|
+
pattern: /\bPRIM_M2M_CLIENT_SECRET"?\s*[:=]\s*["']?[^\s"']+["']?/g,
|
|
32024
|
+
reason: "prim-m2m-secret"
|
|
32025
|
+
},
|
|
31552
32026
|
{ pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g, reason: "gcp-api-key" },
|
|
31553
32027
|
{
|
|
31554
32028
|
pattern: /\bya29\.[0-9A-Za-z_-]{20,}(?![0-9A-Za-z_-])/g,
|
|
@@ -31581,15 +32055,15 @@ function normalizedWorkspaceFlags(value) {
|
|
|
31581
32055
|
return [...new Set(`g${requested}`)].sort().join("");
|
|
31582
32056
|
}
|
|
31583
32057
|
function loadWorkspaceRules(cwd) {
|
|
31584
|
-
const path =
|
|
31585
|
-
if (!
|
|
32058
|
+
const path = join23(cwd, WORKSPACE_FILE2);
|
|
32059
|
+
if (!existsSync16(path)) return [];
|
|
31586
32060
|
let cfg;
|
|
31587
32061
|
try {
|
|
31588
32062
|
if (statSync5(path).size > MAX_WORKSPACE_CONFIG_BYTES) {
|
|
31589
32063
|
debugRedaction(`ignoring oversized ${WORKSPACE_FILE2}`);
|
|
31590
32064
|
return [];
|
|
31591
32065
|
}
|
|
31592
|
-
cfg = JSON.parse(
|
|
32066
|
+
cfg = JSON.parse(readFileSync19(path, "utf-8"));
|
|
31593
32067
|
} catch {
|
|
31594
32068
|
debugRedaction(`ignoring unparseable ${WORKSPACE_FILE2}`);
|
|
31595
32069
|
return [];
|
|
@@ -41403,14 +41877,17 @@ function parseOrganizationBinding(value) {
|
|
|
41403
41877
|
}
|
|
41404
41878
|
function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
41405
41879
|
const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
|
|
41406
|
-
const
|
|
41880
|
+
const request3 = {
|
|
41407
41881
|
batch: batch.map((move) => {
|
|
41408
41882
|
if (typeof move !== "object" || move === null || Array.isArray(move)) {
|
|
41409
41883
|
return move;
|
|
41410
41884
|
}
|
|
41411
41885
|
const { captureActor, ...wireMove } = move;
|
|
41412
41886
|
if (binding.captureAuthorityKind === "workos_m2m") {
|
|
41413
|
-
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.
|
|
41887
|
+
if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || // An identity-pending actor names only its client and is bound to
|
|
41888
|
+
// the identity verified for it. Any other actor is a claim about a
|
|
41889
|
+
// verified identity and must match this one exactly.
|
|
41890
|
+
!identityPending(captureActor) && (captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId))
|
|
41414
41891
|
throw new InvalidJournalEnvelopeError();
|
|
41415
41892
|
} else if (captureActor) throw new InvalidJournalEnvelopeError();
|
|
41416
41893
|
return {
|
|
@@ -41426,40 +41903,40 @@ function buildOrganizationBoundMoveRequest(batch, binding) {
|
|
|
41426
41903
|
};
|
|
41427
41904
|
})
|
|
41428
41905
|
};
|
|
41429
|
-
if (!isMoveIngestRequest(
|
|
41906
|
+
if (!isMoveIngestRequest(request3)) {
|
|
41430
41907
|
throw new InvalidJournalEnvelopeError();
|
|
41431
41908
|
}
|
|
41432
|
-
return
|
|
41909
|
+
return request3;
|
|
41433
41910
|
}
|
|
41434
41911
|
|
|
41435
41912
|
// src/journal.ts
|
|
41436
41913
|
import {
|
|
41437
41914
|
appendFileSync,
|
|
41438
41915
|
closeSync as closeSync3,
|
|
41439
|
-
existsSync as
|
|
41916
|
+
existsSync as existsSync18,
|
|
41440
41917
|
fstatSync,
|
|
41441
|
-
mkdirSync as
|
|
41918
|
+
mkdirSync as mkdirSync9,
|
|
41442
41919
|
openSync as openSync3,
|
|
41443
41920
|
opendirSync,
|
|
41444
|
-
readFileSync as
|
|
41921
|
+
readFileSync as readFileSync21,
|
|
41445
41922
|
readSync,
|
|
41446
|
-
readdirSync as
|
|
41923
|
+
readdirSync as readdirSync6
|
|
41447
41924
|
} from "fs";
|
|
41448
|
-
import { dirname as dirname13, join as
|
|
41925
|
+
import { dirname as dirname13, join as join25 } from "path";
|
|
41449
41926
|
|
|
41450
41927
|
// src/drain-progress.ts
|
|
41451
41928
|
import {
|
|
41452
41929
|
chmodSync as chmodSync7,
|
|
41453
|
-
existsSync as
|
|
41454
|
-
readFileSync as
|
|
41455
|
-
readdirSync as
|
|
41456
|
-
rmSync as
|
|
41930
|
+
existsSync as existsSync17,
|
|
41931
|
+
readFileSync as readFileSync20,
|
|
41932
|
+
readdirSync as readdirSync5,
|
|
41933
|
+
rmSync as rmSync10,
|
|
41457
41934
|
rmdirSync
|
|
41458
41935
|
} from "fs";
|
|
41459
|
-
import { basename as basename3, dirname as dirname12, join as
|
|
41936
|
+
import { basename as basename3, dirname as dirname12, join as join24 } from "path";
|
|
41460
41937
|
|
|
41461
41938
|
// src/journal.ts
|
|
41462
|
-
var JOURNAL_DIR =
|
|
41939
|
+
var JOURNAL_DIR = join25(primConfigDirectory(), "moves");
|
|
41463
41940
|
var UNBOUND_BUCKET = "_unbound";
|
|
41464
41941
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
41465
41942
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
@@ -41471,7 +41948,7 @@ function envSlug(apiUrl) {
|
|
|
41471
41948
|
return slug;
|
|
41472
41949
|
}
|
|
41473
41950
|
function currentEnvDir() {
|
|
41474
|
-
return
|
|
41951
|
+
return join25(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
41475
41952
|
}
|
|
41476
41953
|
var DIR_MODE = 448;
|
|
41477
41954
|
var FILE_MODE2 = 384;
|
|
@@ -41479,23 +41956,24 @@ var SAFE_BUCKET = /^[A-Za-z0-9_-]+$/;
|
|
|
41479
41956
|
var RESERVED_BUCKETS = /* @__PURE__ */ new Set([UNBOUND_BUCKET, "_legacy"]);
|
|
41480
41957
|
function appendMoveToPath(path, move) {
|
|
41481
41958
|
const dir = dirname13(path);
|
|
41482
|
-
if (!
|
|
41483
|
-
|
|
41959
|
+
if (!existsSync18(dir)) {
|
|
41960
|
+
mkdirSync9(dir, { recursive: true, mode: DIR_MODE });
|
|
41484
41961
|
}
|
|
41485
41962
|
appendFileSync(path, `${JSON.stringify(move)}
|
|
41486
41963
|
`, { mode: FILE_MODE2 });
|
|
41487
41964
|
}
|
|
41488
41965
|
function bucketDir(orgId) {
|
|
41489
41966
|
const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
|
|
41490
|
-
return
|
|
41967
|
+
return join25(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
|
|
41491
41968
|
}
|
|
41492
41969
|
function journalPath(orgId) {
|
|
41493
|
-
return
|
|
41970
|
+
return join25(bucketDir(orgId), JOURNAL_BASENAME);
|
|
41494
41971
|
}
|
|
41495
41972
|
function appendMove(move, orgId) {
|
|
41496
41973
|
const actor = machineCaptureActor();
|
|
41497
41974
|
const captured = actor ? { ...move, captureActor: actor } : move;
|
|
41498
|
-
|
|
41975
|
+
const bucket = actor ? identityPending(actor) ? machinePendingBucket(actor) : machineJournalBucket(actor) : orgId;
|
|
41976
|
+
appendMoveToPath(journalPath(bucket), captured);
|
|
41499
41977
|
return captured;
|
|
41500
41978
|
}
|
|
41501
41979
|
var FLUSHING_PREFIX = `${JOURNAL_BASENAME}.flushing.`;
|
|
@@ -41506,15 +41984,15 @@ async function deliverPostToolMove(move, orgId) {
|
|
|
41506
41984
|
const captured = appendMove(move, orgId);
|
|
41507
41985
|
const signal = AbortSignal.timeout(INGEST_TIMEOUT_MS);
|
|
41508
41986
|
const client = captured.captureActor ? await getPinnedClient({ signal }) : getClient();
|
|
41509
|
-
let
|
|
41987
|
+
let request3 = { batch: [captured] };
|
|
41510
41988
|
if (captured.captureActor) {
|
|
41511
41989
|
const binding = parseOrganizationBinding(
|
|
41512
41990
|
await client.get("/api/cli/auth/status", { signal, quietRefresh: true })
|
|
41513
41991
|
);
|
|
41514
41992
|
if (binding.state !== "current") throw new InvalidJournalEnvelopeError();
|
|
41515
|
-
|
|
41993
|
+
request3 = buildOrganizationBoundMoveRequest([captured], binding.binding);
|
|
41516
41994
|
}
|
|
41517
|
-
const response = await client.post("/api/cli/moves/ingest",
|
|
41995
|
+
const response = await client.post("/api/cli/moves/ingest", request3, { signal });
|
|
41518
41996
|
return requireDurableIngestAcknowledgement(response, 1, move.env.gitRoot ?? move.env.cwd);
|
|
41519
41997
|
}
|
|
41520
41998
|
|
|
@@ -41671,7 +42149,7 @@ function editingToolsFor(agent) {
|
|
|
41671
42149
|
var here = dirname14(fileURLToPath5(import.meta.url));
|
|
41672
42150
|
function resolveCliVersion() {
|
|
41673
42151
|
try {
|
|
41674
|
-
const pkg = JSON.parse(
|
|
42152
|
+
const pkg = JSON.parse(readFileSync22(join26(here, "..", "..", "package.json"), "utf-8"));
|
|
41675
42153
|
return pkg.version ?? "unknown";
|
|
41676
42154
|
} catch {
|
|
41677
42155
|
return "unknown";
|