@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
- package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
- package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
- package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
- package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
- package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
- package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
- package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
- package/dist/daemon/server.js +1769 -487
- package/dist/hook-runtime/daemon/server.js +1769 -487
- package/dist/hook-runtime/hooks/post-commit.js +611 -337
- package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
- package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
- package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
- package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
- package/dist/hook-runtime/hooks/session-end.js +538 -385
- package/dist/hook-runtime/hooks/session-start.js +1379 -233
- package/dist/hook-runtime/index.js +5438 -4052
- package/dist/hook-runtime/statusline-main.js +547 -273
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +64 -22
- package/dist/index.js +396 -52
- package/dist/statusline-main.js +547 -273
- package/package.json +1 -1
|
@@ -54,34 +54,34 @@ var require_ucs2length = __commonJS({
|
|
|
54
54
|
|
|
55
55
|
// src/hooks/post-tool-use.ts
|
|
56
56
|
import { readFileSync as readFileSync22 } from "fs";
|
|
57
|
-
import { dirname as dirname14, join as
|
|
57
|
+
import { dirname as dirname14, join as join27 } from "path";
|
|
58
58
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
59
59
|
|
|
60
60
|
// src/binding.ts
|
|
61
|
-
import { existsSync as
|
|
62
|
-
import { dirname as
|
|
61
|
+
import { existsSync as existsSync6, readFileSync as readFileSync9 } from "fs";
|
|
62
|
+
import { dirname as dirname8, join as join12 } from "path";
|
|
63
63
|
|
|
64
64
|
// src/lib/credentials.ts
|
|
65
|
-
import { createHash as
|
|
66
|
-
import { readFileSync as
|
|
67
|
-
import { join as
|
|
65
|
+
import { createHash as createHash7 } from "crypto";
|
|
66
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
67
|
+
import { join as join11 } from "path";
|
|
68
68
|
|
|
69
69
|
// src/lib/machine-credentials.ts
|
|
70
|
-
import { execFileSync } from "child_process";
|
|
71
|
-
import { createHash as
|
|
70
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
71
|
+
import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
72
72
|
import {
|
|
73
|
-
chmodSync,
|
|
74
|
-
existsSync as
|
|
73
|
+
chmodSync as chmodSync2,
|
|
74
|
+
existsSync as existsSync5,
|
|
75
75
|
linkSync,
|
|
76
|
-
lstatSync as
|
|
77
|
-
mkdirSync as
|
|
78
|
-
readFileSync as
|
|
79
|
-
rmSync as
|
|
80
|
-
writeFileSync as
|
|
76
|
+
lstatSync as lstatSync5,
|
|
77
|
+
mkdirSync as mkdirSync4,
|
|
78
|
+
readFileSync as readFileSync7,
|
|
79
|
+
rmSync as rmSync7,
|
|
80
|
+
writeFileSync as writeFileSync4
|
|
81
81
|
} from "fs";
|
|
82
|
-
import { createRequire } from "module";
|
|
83
|
-
import { dirname as
|
|
84
|
-
import { fileURLToPath as
|
|
82
|
+
import { createRequire as createRequire2 } from "module";
|
|
83
|
+
import { dirname as dirname7, join as join10 } from "path";
|
|
84
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
85
85
|
|
|
86
86
|
// src/lib/atomic-file.ts
|
|
87
87
|
import { randomUUID } from "crypto";
|
|
@@ -332,18 +332,71 @@ async function withFileLock(lockDir, operation, options = {}) {
|
|
|
332
332
|
}
|
|
333
333
|
}
|
|
334
334
|
|
|
335
|
-
// src/lib/
|
|
336
|
-
import {
|
|
337
|
-
import {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
335
|
+
// src/lib/hook-runtime.ts
|
|
336
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
337
|
+
import {
|
|
338
|
+
constants as constants2,
|
|
339
|
+
accessSync,
|
|
340
|
+
chmodSync,
|
|
341
|
+
copyFileSync,
|
|
342
|
+
existsSync as existsSync4,
|
|
343
|
+
lstatSync,
|
|
344
|
+
mkdirSync as mkdirSync3,
|
|
345
|
+
mkdtempSync,
|
|
346
|
+
readFileSync as readFileSync3,
|
|
347
|
+
readdirSync,
|
|
348
|
+
realpathSync,
|
|
349
|
+
renameSync as renameSync2,
|
|
350
|
+
rmSync as rmSync3,
|
|
351
|
+
statSync as statSync2,
|
|
352
|
+
utimesSync,
|
|
353
|
+
writeFileSync as writeFileSync3
|
|
354
|
+
} from "fs";
|
|
355
|
+
import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
|
|
342
356
|
|
|
343
357
|
// src/lib/bin-path.ts
|
|
344
358
|
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
345
359
|
import { dirname as dirname3, isAbsolute, join as join2 } from "path";
|
|
346
360
|
import { fileURLToPath } from "url";
|
|
361
|
+
|
|
362
|
+
// src/lib/semver.ts
|
|
363
|
+
function parseSemver(value) {
|
|
364
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
365
|
+
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u.exec(
|
|
366
|
+
value
|
|
367
|
+
);
|
|
368
|
+
if (!match) return;
|
|
369
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
370
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
371
|
+
return;
|
|
372
|
+
}
|
|
373
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
374
|
+
}
|
|
375
|
+
function compareSemver(left, right) {
|
|
376
|
+
const a = parseSemver(left);
|
|
377
|
+
const b = parseSemver(right);
|
|
378
|
+
if (!a || !b) return;
|
|
379
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
380
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
381
|
+
}
|
|
382
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
383
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
384
|
+
}
|
|
385
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
386
|
+
const x = a.prerelease[i];
|
|
387
|
+
const y = b.prerelease[i];
|
|
388
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
389
|
+
if (x === y) continue;
|
|
390
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
391
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
392
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
393
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
394
|
+
return x < y ? -1 : 1;
|
|
395
|
+
}
|
|
396
|
+
return 0;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// src/lib/bin-path.ts
|
|
347
400
|
var PKG_NAME = "@primitive.ai/prim";
|
|
348
401
|
var ROOT_WALK_LIMIT = 6;
|
|
349
402
|
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
@@ -418,6 +471,309 @@ function detachedHookShimCommand(bin, args = "") {
|
|
|
418
471
|
return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
|
|
419
472
|
}
|
|
420
473
|
|
|
474
|
+
// src/lib/git-hook-contract.ts
|
|
475
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
476
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
477
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
478
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
479
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
480
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
481
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
482
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
483
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
484
|
+
prim_hook=\${1-}
|
|
485
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
486
|
+
case "$prim_hook" in
|
|
487
|
+
pre-commit)
|
|
488
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
489
|
+
;;
|
|
490
|
+
post-commit)
|
|
491
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
492
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
493
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
494
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
495
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
496
|
+
(
|
|
497
|
+
trap '' HUP
|
|
498
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
499
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
500
|
+
) </dev/null >/dev/null 2>&1 &
|
|
501
|
+
;;
|
|
502
|
+
post-rewrite)
|
|
503
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
504
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
505
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
506
|
+
rm -f "$prim_pairs"
|
|
507
|
+
exit 0
|
|
508
|
+
fi
|
|
509
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
510
|
+
(
|
|
511
|
+
trap '' HUP
|
|
512
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
513
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
514
|
+
) </dev/null >/dev/null 2>&1 &
|
|
515
|
+
;;
|
|
516
|
+
esac
|
|
517
|
+
exit 0
|
|
518
|
+
`;
|
|
519
|
+
|
|
520
|
+
// src/lib/native-keyring.ts
|
|
521
|
+
import { existsSync as existsSync3 } from "fs";
|
|
522
|
+
import { createRequire } from "module";
|
|
523
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
524
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
525
|
+
var require2 = createRequire(import.meta.url);
|
|
526
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
527
|
+
|
|
528
|
+
// src/lib/paths.ts
|
|
529
|
+
import { homedir } from "os";
|
|
530
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
531
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
532
|
+
function absolutePath(value, variable) {
|
|
533
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
534
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
535
|
+
}
|
|
536
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
537
|
+
const normalized = normalize(value);
|
|
538
|
+
return normalized === value ? value : void 0;
|
|
539
|
+
}
|
|
540
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
541
|
+
const env = options.env ?? process.env;
|
|
542
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
543
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
544
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
545
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
546
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
547
|
+
if (!home) {
|
|
548
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
549
|
+
}
|
|
550
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
551
|
+
}
|
|
552
|
+
function primConfigDirectory(options = {}) {
|
|
553
|
+
return resolvePrimConfigDirectory(options).path;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// src/lib/hook-runtime.ts
|
|
557
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
558
|
+
var RELEASE_PREFIX = "release-";
|
|
559
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
560
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
561
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
562
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
563
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
564
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
565
|
+
prim: "dist/index.js",
|
|
566
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
567
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
568
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
569
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
570
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
571
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
572
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
573
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
574
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
575
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
576
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
577
|
+
};
|
|
578
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
579
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
580
|
+
bin,
|
|
581
|
+
target.replace(/^dist\//u, "")
|
|
582
|
+
])
|
|
583
|
+
);
|
|
584
|
+
function hookRuntimePaths(options = {}) {
|
|
585
|
+
const env = options.env ?? process.env;
|
|
586
|
+
const configDir = primConfigDirectory({
|
|
587
|
+
...options,
|
|
588
|
+
env,
|
|
589
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
590
|
+
});
|
|
591
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
592
|
+
return {
|
|
593
|
+
configDir,
|
|
594
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
595
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
596
|
+
runtimeDir,
|
|
597
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
598
|
+
current: join5(runtimeDir, "current"),
|
|
599
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
function sha256(path) {
|
|
603
|
+
return createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
604
|
+
}
|
|
605
|
+
function exactManifest(manifest) {
|
|
606
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
607
|
+
`;
|
|
608
|
+
}
|
|
609
|
+
function exactKeys(value, expected) {
|
|
610
|
+
const actual = Object.keys(value).sort();
|
|
611
|
+
const wanted = [...expected].sort();
|
|
612
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
613
|
+
}
|
|
614
|
+
function releaseId(manifest) {
|
|
615
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
616
|
+
}
|
|
617
|
+
function runtimePackageJson(manifest) {
|
|
618
|
+
return `${JSON.stringify(
|
|
619
|
+
{
|
|
620
|
+
name: "@primitive.ai/prim",
|
|
621
|
+
version: manifest.version,
|
|
622
|
+
type: "module",
|
|
623
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
624
|
+
},
|
|
625
|
+
null,
|
|
626
|
+
2
|
|
627
|
+
)}
|
|
628
|
+
`;
|
|
629
|
+
}
|
|
630
|
+
function validateRelease(releaseDir, manifest) {
|
|
631
|
+
try {
|
|
632
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
633
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
637
|
+
return false;
|
|
638
|
+
}
|
|
639
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
640
|
+
`) {
|
|
641
|
+
return false;
|
|
642
|
+
}
|
|
643
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
644
|
+
const target = join5(releaseDir, relativePath);
|
|
645
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
646
|
+
}
|
|
647
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
648
|
+
if (sha256(join5(releaseDir, path)) !== digest) return false;
|
|
649
|
+
}
|
|
650
|
+
return true;
|
|
651
|
+
} catch {
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
656
|
+
try {
|
|
657
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
658
|
+
for (const relativePath of [
|
|
659
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
660
|
+
...Object.keys(manifest.native ?? {})
|
|
661
|
+
]) {
|
|
662
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
663
|
+
directories.add(join5(releaseDir, directory));
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
667
|
+
const files = [
|
|
668
|
+
"manifest.json",
|
|
669
|
+
"package.json",
|
|
670
|
+
"node",
|
|
671
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
672
|
+
...Object.keys(manifest.native ?? {})
|
|
673
|
+
];
|
|
674
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
|
|
675
|
+
if (![...directories].every(
|
|
676
|
+
(directory) => readdirSync(directory).every((name2) => owned.has(join5(directory, name2)))
|
|
677
|
+
))
|
|
678
|
+
return false;
|
|
679
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
680
|
+
} catch {
|
|
681
|
+
return false;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
685
|
+
try {
|
|
686
|
+
const manifestPath = join5(releaseDir, "manifest.json");
|
|
687
|
+
const manifestStat = statSync2(manifestPath);
|
|
688
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
689
|
+
const raw = readFileSync3(manifestPath, "utf8");
|
|
690
|
+
const parsed = JSON.parse(raw);
|
|
691
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
692
|
+
if (!exactKeys(parsed, [
|
|
693
|
+
"schemaVersion",
|
|
694
|
+
"version",
|
|
695
|
+
"nodePath",
|
|
696
|
+
"files",
|
|
697
|
+
..."native" in parsed ? ["native"] : []
|
|
698
|
+
]))
|
|
699
|
+
return null;
|
|
700
|
+
const candidate = parsed;
|
|
701
|
+
if (candidate.schemaVersion !== HOOK_RUNTIME_SCHEMA_VERSION || typeof candidate.version !== "string" || compareSemver(candidate.version, candidate.version) !== 0 || typeof candidate.nodePath !== "string" || !isAbsolute3(candidate.nodePath) || /[\r\n]/u.test(candidate.nodePath) || !candidate.files || typeof candidate.files !== "object" || Array.isArray(candidate.files) || !exactKeys(candidate.files, Object.keys(HOOK_RUNTIME_ENTRIES)) || Object.values(candidate.files).some(
|
|
702
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
703
|
+
)) {
|
|
704
|
+
return null;
|
|
705
|
+
}
|
|
706
|
+
if (candidate.native !== void 0 && (!candidate.native || typeof candidate.native !== "object" || Array.isArray(candidate.native) || !exactKeys(candidate.native, KEYRING_NATIVE_FILES) || Object.values(candidate.native).some(
|
|
707
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
708
|
+
)))
|
|
709
|
+
return null;
|
|
710
|
+
const manifest = candidate;
|
|
711
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
712
|
+
return null;
|
|
713
|
+
}
|
|
714
|
+
return manifest;
|
|
715
|
+
} catch {
|
|
716
|
+
return null;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
function readSelectedRelease(paths) {
|
|
720
|
+
let raw;
|
|
721
|
+
try {
|
|
722
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
723
|
+
} catch (error) {
|
|
724
|
+
if (error.code === "ENOENT") return null;
|
|
725
|
+
throw error;
|
|
726
|
+
}
|
|
727
|
+
const name2 = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
728
|
+
if (`${name2}
|
|
729
|
+
` !== raw || !RELEASE_NAME_RE.test(name2)) {
|
|
730
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
731
|
+
}
|
|
732
|
+
const dir = join5(paths.releasesDir, name2);
|
|
733
|
+
const manifest = readReleaseManifest(dir, name2);
|
|
734
|
+
if (!manifest) {
|
|
735
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
736
|
+
}
|
|
737
|
+
return { name: name2, dir, manifest };
|
|
738
|
+
}
|
|
739
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
740
|
+
try {
|
|
741
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
742
|
+
if (!selected?.manifest.native) return void 0;
|
|
743
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
744
|
+
return existsSync4(loader) ? loader : void 0;
|
|
745
|
+
} catch {
|
|
746
|
+
return void 0;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
750
|
+
set -eu
|
|
751
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
752
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
753
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
754
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
755
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
756
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
757
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
758
|
+
case "\${1-}" in
|
|
759
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
760
|
+
*) exit 64 ;;
|
|
761
|
+
esac
|
|
762
|
+
shift
|
|
763
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
764
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
765
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
766
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
767
|
+
`;
|
|
768
|
+
|
|
769
|
+
// src/lib/machine-broker.ts
|
|
770
|
+
import { spawn } from "child_process";
|
|
771
|
+
import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
|
|
772
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
|
|
773
|
+
import { createServer } from "http";
|
|
774
|
+
import { basename, join as join6 } from "path";
|
|
775
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
776
|
+
|
|
421
777
|
// src/lib/loopback-fetch.ts
|
|
422
778
|
import { request } from "http";
|
|
423
779
|
import { Readable } from "stream";
|
|
@@ -454,6 +810,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
454
810
|
}
|
|
455
811
|
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
812
|
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';
|
|
813
|
+
var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
|
|
814
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
457
815
|
function cloudSetupPointer(message, env = process.env) {
|
|
458
816
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
459
817
|
}
|
|
@@ -595,10 +953,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
595
953
|
"access_token",
|
|
596
954
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
597
955
|
);
|
|
598
|
-
const
|
|
956
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
599
957
|
return {
|
|
600
958
|
accessToken,
|
|
601
|
-
refreshToken:
|
|
959
|
+
refreshToken: refreshToken3,
|
|
602
960
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
603
961
|
};
|
|
604
962
|
}
|
|
@@ -849,34 +1207,6 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
849
1207
|
return parseInjectedMachineIdentity(response.status, value, apiUrl, clientId);
|
|
850
1208
|
}
|
|
851
1209
|
|
|
852
|
-
// src/lib/paths.ts
|
|
853
|
-
import { homedir } from "os";
|
|
854
|
-
import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
|
|
855
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
856
|
-
function absolutePath(value, variable) {
|
|
857
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
858
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
859
|
-
}
|
|
860
|
-
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
861
|
-
const normalized = normalize(value);
|
|
862
|
-
return normalized === value ? value : void 0;
|
|
863
|
-
}
|
|
864
|
-
function resolvePrimConfigDirectory(options = {}) {
|
|
865
|
-
const env = options.env ?? process.env;
|
|
866
|
-
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
867
|
-
if (explicit) return { path: explicit, source: "explicit" };
|
|
868
|
-
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
869
|
-
if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
|
|
870
|
-
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
871
|
-
if (!home) {
|
|
872
|
-
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
873
|
-
}
|
|
874
|
-
return { path: join3(home, ".config", "prim"), source: "default" };
|
|
875
|
-
}
|
|
876
|
-
function primConfigDirectory(options = {}) {
|
|
877
|
-
return resolvePrimConfigDirectory(options).path;
|
|
878
|
-
}
|
|
879
|
-
|
|
880
1210
|
// src/lib/machine-broker.ts
|
|
881
1211
|
var MAX_RESPONSE_BYTES = 96 * 1024;
|
|
882
1212
|
var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
|
|
@@ -886,14 +1216,14 @@ var FORWARD_REQUEST_PROOF = "forward-request";
|
|
|
886
1216
|
var FORWARD_ANSWER_PROOF = "forward-answer";
|
|
887
1217
|
var IDLE_MS = 5 * 6e4;
|
|
888
1218
|
function descriptorPath(directory, generation) {
|
|
889
|
-
return
|
|
1219
|
+
return join6(directory, `machine_broker_${generation}.json`);
|
|
890
1220
|
}
|
|
891
1221
|
function readDescriptor(path) {
|
|
892
1222
|
try {
|
|
893
|
-
const stat =
|
|
1223
|
+
const stat = lstatSync2(path);
|
|
894
1224
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
895
1225
|
return void 0;
|
|
896
|
-
const data = JSON.parse(
|
|
1226
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
897
1227
|
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;
|
|
898
1228
|
} catch {
|
|
899
1229
|
return void 0;
|
|
@@ -906,7 +1236,7 @@ function matches(left, right) {
|
|
|
906
1236
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
907
1237
|
}
|
|
908
1238
|
function tokenHash(token) {
|
|
909
|
-
return token ?
|
|
1239
|
+
return token ? createHash2("sha256").update(token).digest("hex") : void 0;
|
|
910
1240
|
}
|
|
911
1241
|
async function brokerRequest(descriptor, environment, options) {
|
|
912
1242
|
const body = JSON.stringify({
|
|
@@ -983,7 +1313,7 @@ async function acquireBrokerCredential(options) {
|
|
|
983
1313
|
async function ensureBroker(options) {
|
|
984
1314
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
985
1315
|
return withFileLock(
|
|
986
|
-
|
|
1316
|
+
join6(options.directory, "machine-broker.lock"),
|
|
987
1317
|
async () => {
|
|
988
1318
|
const current = readDescriptor(path);
|
|
989
1319
|
if (current) {
|
|
@@ -996,7 +1326,7 @@ async function ensureBroker(options) {
|
|
|
996
1326
|
options.signal.throwIfAborted();
|
|
997
1327
|
}
|
|
998
1328
|
}
|
|
999
|
-
const bundled =
|
|
1329
|
+
const bundled = fileURLToPath3(import.meta.url);
|
|
1000
1330
|
const entry = basename(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
1001
1331
|
if (!entry)
|
|
1002
1332
|
throw new MachineAuthError(
|
|
@@ -1134,23 +1464,23 @@ async function forwardBrokerRequest(options) {
|
|
|
1134
1464
|
}
|
|
1135
1465
|
|
|
1136
1466
|
// src/lib/machine-retry.ts
|
|
1137
|
-
import { createHash as
|
|
1138
|
-
import { lstatSync as
|
|
1139
|
-
import { join as
|
|
1467
|
+
import { createHash as createHash3 } from "crypto";
|
|
1468
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
|
|
1469
|
+
import { join as join7 } from "path";
|
|
1140
1470
|
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
1141
1471
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
1142
1472
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
1143
1473
|
signal?.throwIfAborted();
|
|
1144
|
-
const key =
|
|
1145
|
-
const path =
|
|
1474
|
+
const key = createHash3("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1475
|
+
const path = join7(directory, `machine_retry_${key}.json`);
|
|
1146
1476
|
let state = {
|
|
1147
1477
|
failures: 0,
|
|
1148
1478
|
retryAt: 0
|
|
1149
1479
|
};
|
|
1150
1480
|
try {
|
|
1151
|
-
const stat =
|
|
1481
|
+
const stat = lstatSync3(path);
|
|
1152
1482
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
1153
|
-
const data = JSON.parse(
|
|
1483
|
+
const data = JSON.parse(readFileSync5(path, "utf8"));
|
|
1154
1484
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
1155
1485
|
throw new Error("Invalid retry state");
|
|
1156
1486
|
state = data;
|
|
@@ -1174,7 +1504,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
1174
1504
|
);
|
|
1175
1505
|
try {
|
|
1176
1506
|
const result = await request3();
|
|
1177
|
-
|
|
1507
|
+
rmSync5(path, { force: true });
|
|
1178
1508
|
return result;
|
|
1179
1509
|
} catch (error) {
|
|
1180
1510
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -1201,32 +1531,1264 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
1201
1531
|
}
|
|
1202
1532
|
}
|
|
1203
1533
|
|
|
1534
|
+
// src/lib/session-identity.ts
|
|
1535
|
+
import { execFile } from "child_process";
|
|
1536
|
+
import { createHash as createHash5 } from "crypto";
|
|
1537
|
+
import { rmSync as rmSync6 } from "fs";
|
|
1538
|
+
import { join as join9 } from "path";
|
|
1539
|
+
import { promisify } from "util";
|
|
1540
|
+
|
|
1541
|
+
// src/lib/git.ts
|
|
1542
|
+
import { execFileSync } from "child_process";
|
|
1543
|
+
import { createHash as createHash4 } from "crypto";
|
|
1544
|
+
import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
|
|
1545
|
+
import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
|
|
1546
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
1547
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1548
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1549
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
1550
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
1551
|
+
function gitChildEnvironment(env = process.env) {
|
|
1552
|
+
return Object.fromEntries(
|
|
1553
|
+
Object.entries(env).filter(([name2]) => !CREDENTIAL_VARIABLE.test(name2))
|
|
1554
|
+
);
|
|
1555
|
+
}
|
|
1556
|
+
function gitToplevel(cwd) {
|
|
1557
|
+
try {
|
|
1558
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1559
|
+
cwd,
|
|
1560
|
+
encoding: "utf-8",
|
|
1561
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1562
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1563
|
+
env: gitChildEnvironment()
|
|
1564
|
+
}).trim();
|
|
1565
|
+
} catch {
|
|
1566
|
+
return null;
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
function gitValue(cwd, args) {
|
|
1570
|
+
try {
|
|
1571
|
+
const value = execFileSync("git", args, {
|
|
1572
|
+
cwd,
|
|
1573
|
+
encoding: "utf-8",
|
|
1574
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1575
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1576
|
+
env: gitChildEnvironment()
|
|
1577
|
+
}).trim();
|
|
1578
|
+
return value || void 0;
|
|
1579
|
+
} catch {
|
|
1580
|
+
return void 0;
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
function currentBranch(cwd) {
|
|
1584
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
1585
|
+
}
|
|
1586
|
+
function parseGithubRepositoryName(path) {
|
|
1587
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
1588
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
1589
|
+
return null;
|
|
1590
|
+
}
|
|
1591
|
+
return `${parts[0]}/${parts[1]}`;
|
|
1592
|
+
}
|
|
1593
|
+
function githubRepositoryFromRemote(remote) {
|
|
1594
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
1595
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
1596
|
+
remote
|
|
1597
|
+
);
|
|
1598
|
+
const path = match?.[1] ?? match?.[2];
|
|
1599
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
1600
|
+
}
|
|
1601
|
+
function checkoutSettingsText(repoRoot) {
|
|
1602
|
+
const path = join8(repoRoot, ".claude", "settings.json");
|
|
1603
|
+
try {
|
|
1604
|
+
if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
|
|
1605
|
+
const stat = lstatSync4(path);
|
|
1606
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
1607
|
+
return readFileSync6(path, "utf8");
|
|
1608
|
+
} catch {
|
|
1609
|
+
return null;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
function checkoutDeclaration(repoRoot, name2) {
|
|
1613
|
+
const text = checkoutSettingsText(repoRoot);
|
|
1614
|
+
if (text === null) return null;
|
|
1615
|
+
let parsed;
|
|
1616
|
+
try {
|
|
1617
|
+
parsed = JSON.parse(text);
|
|
1618
|
+
} catch {
|
|
1619
|
+
return null;
|
|
1620
|
+
}
|
|
1621
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
1622
|
+
const value = typeof env === "object" && env !== null ? env[name2] : void 0;
|
|
1623
|
+
return typeof value === "string" ? value : null;
|
|
1624
|
+
}
|
|
1625
|
+
function declaredGithubRepository(repoRoot) {
|
|
1626
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
1627
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
1628
|
+
}
|
|
1629
|
+
function githubRepositoryFullName(cwd) {
|
|
1630
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
1631
|
+
if (remote) {
|
|
1632
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
1633
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
1634
|
+
}
|
|
1635
|
+
const root = gitToplevel(cwd);
|
|
1636
|
+
return root ? declaredGithubRepository(root) : null;
|
|
1637
|
+
}
|
|
1638
|
+
function canonicalGitRoot(cwd) {
|
|
1639
|
+
try {
|
|
1640
|
+
const top = gitToplevel(cwd);
|
|
1641
|
+
return top ? realpathSync2.native(top) : null;
|
|
1642
|
+
} catch {
|
|
1643
|
+
return null;
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
function relatedWorktreeTarget(path, cwd, origin) {
|
|
1647
|
+
let parent = dirname6(resolve2(cwd, path));
|
|
1648
|
+
while (true) {
|
|
1649
|
+
try {
|
|
1650
|
+
realpathSync2.native(parent);
|
|
1651
|
+
break;
|
|
1652
|
+
} catch {
|
|
1653
|
+
const next = dirname6(parent);
|
|
1654
|
+
if (next === parent) return null;
|
|
1655
|
+
parent = next;
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
const target = resolveRepositoryContext(parent);
|
|
1659
|
+
if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
|
|
1660
|
+
const common = (root) => {
|
|
1661
|
+
const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
|
|
1662
|
+
try {
|
|
1663
|
+
return value ? realpathSync2.native(resolve2(root, value)) : void 0;
|
|
1664
|
+
} catch {
|
|
1665
|
+
return void 0;
|
|
1666
|
+
}
|
|
1667
|
+
};
|
|
1668
|
+
const originCommon = common(origin.repoRoot);
|
|
1669
|
+
return originCommon && originCommon === common(target.repoRoot) ? target : null;
|
|
1670
|
+
}
|
|
1671
|
+
function normalizeOriginRemote(remote) {
|
|
1672
|
+
const value = remote.trim();
|
|
1673
|
+
if (!value) return void 0;
|
|
1674
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
1675
|
+
if (scp?.host && scp.path) {
|
|
1676
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1677
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
1678
|
+
}
|
|
1679
|
+
try {
|
|
1680
|
+
const url = new URL(value);
|
|
1681
|
+
url.username = "";
|
|
1682
|
+
url.password = "";
|
|
1683
|
+
url.search = "";
|
|
1684
|
+
url.hash = "";
|
|
1685
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1686
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1687
|
+
return void 0;
|
|
1688
|
+
} catch {
|
|
1689
|
+
return void 0;
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
function opaqueRepoKey(source, value) {
|
|
1693
|
+
return `repo_v1_${createHash4("sha256").update(`${source}\0${value}`).digest("hex")}`;
|
|
1694
|
+
}
|
|
1695
|
+
function resolveRepositoryContext(cwd = process.cwd()) {
|
|
1696
|
+
const top = gitToplevel(cwd);
|
|
1697
|
+
if (!top) return null;
|
|
1698
|
+
let repoRoot;
|
|
1699
|
+
try {
|
|
1700
|
+
repoRoot = realpathSync2.native(top);
|
|
1701
|
+
} catch {
|
|
1702
|
+
repoRoot = resolve2(top);
|
|
1703
|
+
}
|
|
1704
|
+
const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
|
|
1705
|
+
const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
|
|
1706
|
+
const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
|
|
1707
|
+
if (normalizedOrigin) {
|
|
1708
|
+
return {
|
|
1709
|
+
repoRoot,
|
|
1710
|
+
repoKey: opaqueRepoKey("origin", normalizedOrigin),
|
|
1711
|
+
identitySource: "origin",
|
|
1712
|
+
repoFullName
|
|
1713
|
+
};
|
|
1714
|
+
}
|
|
1715
|
+
if (repoFullName) {
|
|
1716
|
+
return {
|
|
1717
|
+
repoRoot,
|
|
1718
|
+
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
1719
|
+
identitySource: "declared",
|
|
1720
|
+
repoFullName
|
|
1721
|
+
};
|
|
1722
|
+
}
|
|
1723
|
+
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
1724
|
+
if (roots && roots.length > 0) {
|
|
1725
|
+
return {
|
|
1726
|
+
repoRoot,
|
|
1727
|
+
repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
|
|
1728
|
+
identitySource: "root_commit",
|
|
1729
|
+
repoFullName
|
|
1730
|
+
};
|
|
1731
|
+
}
|
|
1732
|
+
return { repoRoot, repoFullName };
|
|
1733
|
+
}
|
|
1734
|
+
function nearestExistingAncestor(path) {
|
|
1735
|
+
const suffix = [];
|
|
1736
|
+
let cursor = path;
|
|
1737
|
+
while (true) {
|
|
1738
|
+
try {
|
|
1739
|
+
lstatSync4(cursor);
|
|
1740
|
+
break;
|
|
1741
|
+
} catch (error) {
|
|
1742
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
1743
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
1744
|
+
const parent = dirname6(cursor);
|
|
1745
|
+
if (parent === cursor) return null;
|
|
1746
|
+
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
1747
|
+
cursor = parent;
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
try {
|
|
1751
|
+
return { real: realpathSync2.native(cursor), suffix };
|
|
1752
|
+
} catch {
|
|
1753
|
+
return null;
|
|
1754
|
+
}
|
|
1755
|
+
}
|
|
1756
|
+
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
1757
|
+
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
1758
|
+
return { ok: false, reason: "invalid_path" };
|
|
1759
|
+
}
|
|
1760
|
+
const absolute = resolve2(baseDir, filePath);
|
|
1761
|
+
const resolved = nearestExistingAncestor(absolute);
|
|
1762
|
+
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
1763
|
+
const target = resolve2(resolved.real, ...resolved.suffix);
|
|
1764
|
+
const rel = relative(context.repoRoot, target);
|
|
1765
|
+
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
1766
|
+
if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1767
|
+
return { ok: false, reason: "outside_repository" };
|
|
1768
|
+
}
|
|
1769
|
+
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
1770
|
+
}
|
|
1771
|
+
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
1772
|
+
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
1773
|
+
return null;
|
|
1774
|
+
const absolute = resolve2(cwd, filePath);
|
|
1775
|
+
let target;
|
|
1776
|
+
try {
|
|
1777
|
+
const stat = lstatSync4(absolute);
|
|
1778
|
+
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
1779
|
+
target = realpathSync2.native(absolute);
|
|
1780
|
+
} catch (error) {
|
|
1781
|
+
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
1782
|
+
return null;
|
|
1783
|
+
}
|
|
1784
|
+
try {
|
|
1785
|
+
const parent = realpathSync2.native(dirname6(absolute));
|
|
1786
|
+
if (!lstatSync4(parent).isDirectory()) return null;
|
|
1787
|
+
target = resolve2(parent, basename2(absolute));
|
|
1788
|
+
} catch {
|
|
1789
|
+
return null;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
const rel = relative(repositoryRoot, target);
|
|
1793
|
+
if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
1794
|
+
return null;
|
|
1795
|
+
}
|
|
1796
|
+
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
1797
|
+
}
|
|
1798
|
+
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
1799
|
+
if (typeof contextOrCwd === "string") {
|
|
1800
|
+
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
1801
|
+
}
|
|
1802
|
+
return canonicalRepositoryPathScoped(
|
|
1803
|
+
filePath,
|
|
1804
|
+
contextOrCwd,
|
|
1805
|
+
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
1806
|
+
);
|
|
1807
|
+
}
|
|
1808
|
+
|
|
1809
|
+
// src/lib/terminal-safe.ts
|
|
1810
|
+
function replaceIsolatedSurrogates(value) {
|
|
1811
|
+
let out = "";
|
|
1812
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1813
|
+
const unit = value.charCodeAt(index);
|
|
1814
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1815
|
+
const next = value.charCodeAt(index + 1);
|
|
1816
|
+
if (next >= 56320 && next <= 57343) {
|
|
1817
|
+
out += value[index] + value[index + 1];
|
|
1818
|
+
index += 1;
|
|
1819
|
+
} else {
|
|
1820
|
+
out += "\uFFFD";
|
|
1821
|
+
}
|
|
1822
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1823
|
+
out += "\uFFFD";
|
|
1824
|
+
} else {
|
|
1825
|
+
out += value[index];
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
return out;
|
|
1829
|
+
}
|
|
1830
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1831
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1832
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1833
|
+
point === 1564 || // Arabic letter mark
|
|
1834
|
+
point === 6158 || // Mongolian vowel separator
|
|
1835
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1836
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1837
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1838
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1839
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1840
|
+
point >= 917504 && point <= 917631;
|
|
1841
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1842
|
+
}
|
|
1843
|
+
function terminalSafeText(value) {
|
|
1844
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1845
|
+
}
|
|
1846
|
+
function terminalSafeLine(value) {
|
|
1847
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1848
|
+
}
|
|
1849
|
+
var stripControlChars = terminalSafeText;
|
|
1850
|
+
|
|
1851
|
+
// src/lib/session-identity.ts
|
|
1852
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1853
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1854
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1855
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1856
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1857
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1858
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1859
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1860
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1861
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1862
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1863
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1864
|
+
token: "/api/cli/session-identity/token",
|
|
1865
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1866
|
+
link: "/api/cli/session-identity/link"
|
|
1867
|
+
};
|
|
1868
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1869
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1870
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1871
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1872
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1873
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1874
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1875
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1876
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1877
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1878
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1879
|
+
}
|
|
1880
|
+
function sessionIdentityMode(deps = {}) {
|
|
1881
|
+
const env = deps.env ?? process.env;
|
|
1882
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1883
|
+
}
|
|
1884
|
+
function failure(code, cause, remedy) {
|
|
1885
|
+
return { status: "failed", code, cause, remedy };
|
|
1886
|
+
}
|
|
1887
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1888
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1889
|
+
var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
|
|
1890
|
+
var SESSION_REVOKED = failure(
|
|
1891
|
+
"session_revoked",
|
|
1892
|
+
"Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
|
|
1893
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1894
|
+
);
|
|
1895
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1896
|
+
"challenge_expired",
|
|
1897
|
+
"this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
|
|
1898
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1899
|
+
);
|
|
1900
|
+
var CHALLENGE_GONE = failure(
|
|
1901
|
+
"challenge_not_found",
|
|
1902
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1903
|
+
NEW_SESSION_REMEDY
|
|
1904
|
+
);
|
|
1905
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1906
|
+
function rejectionFailure(reason, repository) {
|
|
1907
|
+
switch (reason) {
|
|
1908
|
+
case "identity_mismatch":
|
|
1909
|
+
return failure(
|
|
1910
|
+
"identity_mismatch",
|
|
1911
|
+
"the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
|
|
1912
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1913
|
+
);
|
|
1914
|
+
case "push_after_expiry":
|
|
1915
|
+
return failure(
|
|
1916
|
+
"push_after_expiry",
|
|
1917
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1918
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1919
|
+
);
|
|
1920
|
+
case "repository_mismatch":
|
|
1921
|
+
return failure(
|
|
1922
|
+
"repository_mismatch",
|
|
1923
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1924
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1925
|
+
);
|
|
1926
|
+
case "conflicting_push":
|
|
1927
|
+
return failure(
|
|
1928
|
+
"conflicting_push",
|
|
1929
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1930
|
+
NEW_SESSION_REMEDY
|
|
1931
|
+
);
|
|
1932
|
+
case "unsupported_sender":
|
|
1933
|
+
return failure(
|
|
1934
|
+
"unsupported_sender",
|
|
1935
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1936
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1937
|
+
);
|
|
1938
|
+
default:
|
|
1939
|
+
return failure(
|
|
1940
|
+
"challenge_rejected",
|
|
1941
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1942
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1943
|
+
);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1946
|
+
function sessionIdentityMessage(outcome) {
|
|
1947
|
+
if (outcome.status === "link_required")
|
|
1948
|
+
return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
|
|
1949
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1950
|
+
}
|
|
1951
|
+
function hash(value) {
|
|
1952
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1953
|
+
}
|
|
1954
|
+
function sessionContext(deps) {
|
|
1955
|
+
const env = deps.env ?? process.env;
|
|
1956
|
+
const environment = environmentCredentials(deps);
|
|
1957
|
+
if (!environment)
|
|
1958
|
+
return failure(
|
|
1959
|
+
"environment_credential_missing",
|
|
1960
|
+
"the cloud environment has no environment credential",
|
|
1961
|
+
'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
|
|
1962
|
+
);
|
|
1963
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1964
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1965
|
+
return failure(
|
|
1966
|
+
"session_id_missing",
|
|
1967
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1968
|
+
NEW_SESSION_REMEDY
|
|
1969
|
+
);
|
|
1970
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1971
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1972
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1973
|
+
return {
|
|
1974
|
+
directory,
|
|
1975
|
+
apiUrl,
|
|
1976
|
+
clientId: environment.clientId,
|
|
1977
|
+
generation: environment.generation,
|
|
1978
|
+
sessionId,
|
|
1979
|
+
tokenPath: join9(directory, `session_identity_${key}.json`),
|
|
1980
|
+
statePath: join9(directory, `session_identity_${key}.state.json`),
|
|
1981
|
+
lockPath: join9(directory, "session-identity.lock")
|
|
1982
|
+
};
|
|
1983
|
+
}
|
|
1984
|
+
function readRecord(path) {
|
|
1985
|
+
try {
|
|
1986
|
+
const value = readMachineMetadata(path);
|
|
1987
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1988
|
+
} catch {
|
|
1989
|
+
return void 0;
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
function finiteNumber(value) {
|
|
1993
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1994
|
+
}
|
|
1995
|
+
function readToken(context) {
|
|
1996
|
+
const data = readRecord(context.tokenPath);
|
|
1997
|
+
if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
|
|
1998
|
+
return void 0;
|
|
1999
|
+
const identity = data.identity;
|
|
2000
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
2001
|
+
return void 0;
|
|
2002
|
+
return data;
|
|
2003
|
+
}
|
|
2004
|
+
function readState(context) {
|
|
2005
|
+
const data = readRecord(context.statePath);
|
|
2006
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
2007
|
+
return void 0;
|
|
2008
|
+
return data;
|
|
2009
|
+
}
|
|
2010
|
+
function writeToken(context, record) {
|
|
2011
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2012
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
2013
|
+
rmSync6(context.statePath, { force: true });
|
|
2014
|
+
}
|
|
2015
|
+
function writeState(context, state) {
|
|
2016
|
+
try {
|
|
2017
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2018
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
2019
|
+
} catch {
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
function tokenValid(record, now = Date.now()) {
|
|
2023
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
2024
|
+
}
|
|
2025
|
+
function tokenFresh(record, now = Date.now()) {
|
|
2026
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
2027
|
+
}
|
|
2028
|
+
function toCredential(record) {
|
|
2029
|
+
return {
|
|
2030
|
+
issuer: record.issuer,
|
|
2031
|
+
audience: record.audience,
|
|
2032
|
+
...record.identity,
|
|
2033
|
+
accessToken: record.accessToken,
|
|
2034
|
+
expiresAt: record.expiresAt,
|
|
2035
|
+
apiUrl: record.apiUrl,
|
|
2036
|
+
generation: record.generation,
|
|
2037
|
+
storage: "environment",
|
|
2038
|
+
session: {
|
|
2039
|
+
userId: record.userId,
|
|
2040
|
+
displayName: record.displayName,
|
|
2041
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2042
|
+
refreshAfter: record.refreshAfter
|
|
2043
|
+
}
|
|
2044
|
+
};
|
|
2045
|
+
}
|
|
2046
|
+
function identified(record, reused) {
|
|
2047
|
+
return {
|
|
2048
|
+
status: "ok",
|
|
2049
|
+
credential: toCredential(record),
|
|
2050
|
+
displayName: record.displayName,
|
|
2051
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2052
|
+
reused
|
|
2053
|
+
};
|
|
2054
|
+
}
|
|
2055
|
+
function cachedSessionCredential(deps = {}) {
|
|
2056
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
2057
|
+
let context;
|
|
2058
|
+
try {
|
|
2059
|
+
context = sessionContext(deps);
|
|
2060
|
+
} catch {
|
|
2061
|
+
return void 0;
|
|
2062
|
+
}
|
|
2063
|
+
if ("status" in context) return void 0;
|
|
2064
|
+
const record = readToken(context);
|
|
2065
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
2066
|
+
}
|
|
2067
|
+
function outcomeFromState(state) {
|
|
2068
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
2069
|
+
return {
|
|
2070
|
+
status: "link_required",
|
|
2071
|
+
githubLogin: state.githubLogin,
|
|
2072
|
+
challengeId: state.challengeId,
|
|
2073
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
2074
|
+
};
|
|
2075
|
+
return failure(
|
|
2076
|
+
state.code,
|
|
2077
|
+
state.cause ?? "the last identity check failed",
|
|
2078
|
+
state.remedy ?? RETRY_REMEDY
|
|
2079
|
+
);
|
|
2080
|
+
}
|
|
2081
|
+
function parseInstant(value) {
|
|
2082
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
2083
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
2084
|
+
const parsed = Date.parse(value);
|
|
2085
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2086
|
+
}
|
|
2087
|
+
return void 0;
|
|
2088
|
+
}
|
|
2089
|
+
async function sendJson(url, init, fetchImpl) {
|
|
2090
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
2091
|
+
let value;
|
|
2092
|
+
try {
|
|
2093
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
2094
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2095
|
+
} catch {
|
|
2096
|
+
value = void 0;
|
|
2097
|
+
}
|
|
2098
|
+
return { status: response.status, value };
|
|
2099
|
+
}
|
|
2100
|
+
function environmentOnly(deps) {
|
|
2101
|
+
return { ...deps, environmentOnly: true };
|
|
2102
|
+
}
|
|
2103
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
2104
|
+
const send = async (credential2) => {
|
|
2105
|
+
const headers = { "Content-Type": "application/json" };
|
|
2106
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
2107
|
+
if (credential2.tokenInjection) {
|
|
2108
|
+
const response = await forwardMachineRequest(
|
|
2109
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
2110
|
+
signal,
|
|
2111
|
+
environmentOnly(deps)
|
|
2112
|
+
);
|
|
2113
|
+
const parsed = await response.json().catch(() => void 0);
|
|
2114
|
+
return {
|
|
2115
|
+
status: response.status,
|
|
2116
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
2117
|
+
};
|
|
2118
|
+
}
|
|
2119
|
+
return sendJson(
|
|
2120
|
+
`${credential2.apiUrl}${path}`,
|
|
2121
|
+
{
|
|
2122
|
+
method,
|
|
2123
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
2124
|
+
...text === void 0 ? {} : { body: text },
|
|
2125
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
2126
|
+
},
|
|
2127
|
+
deps.fetch ?? fetch
|
|
2128
|
+
);
|
|
2129
|
+
};
|
|
2130
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2131
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2132
|
+
let answer = await send(credential);
|
|
2133
|
+
if (answer.status === 401) {
|
|
2134
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
2135
|
+
if (!credential)
|
|
2136
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2137
|
+
answer = await send(credential);
|
|
2138
|
+
}
|
|
2139
|
+
return answer;
|
|
2140
|
+
}
|
|
2141
|
+
function environmentFailure(error, apiUrl) {
|
|
2142
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2143
|
+
return failure(
|
|
2144
|
+
"environment_credential_rejected",
|
|
2145
|
+
"Primitive rejected the cloud environment's credential",
|
|
2146
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
2147
|
+
);
|
|
2148
|
+
const host = (() => {
|
|
2149
|
+
try {
|
|
2150
|
+
return new URL(apiUrl).hostname;
|
|
2151
|
+
} catch {
|
|
2152
|
+
return "Primitive";
|
|
2153
|
+
}
|
|
2154
|
+
})();
|
|
2155
|
+
return failure(
|
|
2156
|
+
"identity_unavailable",
|
|
2157
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
2158
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
2159
|
+
);
|
|
2160
|
+
}
|
|
2161
|
+
function answerError(answer) {
|
|
2162
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
2163
|
+
}
|
|
2164
|
+
async function git(root, args, signal) {
|
|
2165
|
+
try {
|
|
2166
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
2167
|
+
cwd: root,
|
|
2168
|
+
encoding: "utf8",
|
|
2169
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
2170
|
+
signal,
|
|
2171
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
2172
|
+
maxBuffer: 1024 * 1024
|
|
2173
|
+
});
|
|
2174
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
2175
|
+
} catch (error) {
|
|
2176
|
+
const failed = error;
|
|
2177
|
+
return {
|
|
2178
|
+
ok: false,
|
|
2179
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
2180
|
+
stdout: failed.stdout ?? "",
|
|
2181
|
+
stderr: failed.stderr ?? "",
|
|
2182
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
2183
|
+
};
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
function gitDetail(stderr) {
|
|
2187
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
2188
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
2189
|
+
}
|
|
2190
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
2191
|
+
await new Promise((resolve8, reject) => {
|
|
2192
|
+
const timer = setTimeout(resolve8, milliseconds);
|
|
2193
|
+
signal?.addEventListener(
|
|
2194
|
+
"abort",
|
|
2195
|
+
() => {
|
|
2196
|
+
clearTimeout(timer);
|
|
2197
|
+
reject(signal.reason);
|
|
2198
|
+
},
|
|
2199
|
+
{ once: true }
|
|
2200
|
+
);
|
|
2201
|
+
});
|
|
2202
|
+
}
|
|
2203
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
2204
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
2205
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
2206
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
2207
|
+
let unreachable;
|
|
2208
|
+
for (; ; ) {
|
|
2209
|
+
const remaining = deadline - Date.now();
|
|
2210
|
+
if (remaining <= 0) break;
|
|
2211
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
2212
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
2213
|
+
let answer;
|
|
2214
|
+
try {
|
|
2215
|
+
answer = await environmentRequest(
|
|
2216
|
+
"GET",
|
|
2217
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
2218
|
+
void 0,
|
|
2219
|
+
deps,
|
|
2220
|
+
signal
|
|
2221
|
+
);
|
|
2222
|
+
} catch (error) {
|
|
2223
|
+
signal?.throwIfAborted();
|
|
2224
|
+
unreachable = error;
|
|
2225
|
+
continue;
|
|
2226
|
+
}
|
|
2227
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2228
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2229
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
2230
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
2231
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
2232
|
+
continue;
|
|
2233
|
+
}
|
|
2234
|
+
unreachable = void 0;
|
|
2235
|
+
const status = answer.value;
|
|
2236
|
+
if (status?.status === "verified")
|
|
2237
|
+
return {
|
|
2238
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
2239
|
+
};
|
|
2240
|
+
if (status?.status === "expired")
|
|
2241
|
+
return failure(
|
|
2242
|
+
"challenge_expired",
|
|
2243
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
2244
|
+
NEW_SESSION_REMEDY
|
|
2245
|
+
);
|
|
2246
|
+
if (status?.status === "rejected")
|
|
2247
|
+
return rejectionFailure(status.reason, repository);
|
|
2248
|
+
}
|
|
2249
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
2250
|
+
return failure(
|
|
2251
|
+
"webhook_timeout",
|
|
2252
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
2253
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2254
|
+
);
|
|
2255
|
+
}
|
|
2256
|
+
function parseTokenAnswer(value) {
|
|
2257
|
+
if (!value) return void 0;
|
|
2258
|
+
const user = value.user;
|
|
2259
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
2260
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
2261
|
+
if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
|
|
2262
|
+
return void 0;
|
|
2263
|
+
return {
|
|
2264
|
+
accessToken: value.accessToken,
|
|
2265
|
+
expiresAt,
|
|
2266
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
2267
|
+
userId: user.id,
|
|
2268
|
+
displayName: user.displayName,
|
|
2269
|
+
organizationId: value.organizationId
|
|
2270
|
+
};
|
|
2271
|
+
}
|
|
2272
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
2273
|
+
"server_contract",
|
|
2274
|
+
"Primitive's answer did not identify the linked member",
|
|
2275
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
2276
|
+
);
|
|
2277
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
2278
|
+
let identity;
|
|
2279
|
+
let environment;
|
|
2280
|
+
try {
|
|
2281
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2282
|
+
identity = await verifyMachineIdentity(
|
|
2283
|
+
context.apiUrl,
|
|
2284
|
+
answer.accessToken,
|
|
2285
|
+
context.clientId,
|
|
2286
|
+
signal,
|
|
2287
|
+
deps.fetch
|
|
2288
|
+
);
|
|
2289
|
+
} catch (error) {
|
|
2290
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
2291
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2292
|
+
return environmentFailure(error, context.apiUrl);
|
|
2293
|
+
}
|
|
2294
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
2295
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2296
|
+
return {
|
|
2297
|
+
version: 1,
|
|
2298
|
+
apiUrl: context.apiUrl,
|
|
2299
|
+
clientId: context.clientId,
|
|
2300
|
+
generation: context.generation,
|
|
2301
|
+
sessionId: context.sessionId,
|
|
2302
|
+
issuer: environment.issuer,
|
|
2303
|
+
audience: environment.audience,
|
|
2304
|
+
accessToken: answer.accessToken,
|
|
2305
|
+
expiresAt: answer.expiresAt,
|
|
2306
|
+
refreshAfter: answer.refreshAfter,
|
|
2307
|
+
userId: answer.userId,
|
|
2308
|
+
displayName: answer.displayName,
|
|
2309
|
+
organizationId: answer.organizationId,
|
|
2310
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
2311
|
+
identity,
|
|
2312
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
2313
|
+
};
|
|
2314
|
+
}
|
|
2315
|
+
async function refreshToken(context, record, deps, signal) {
|
|
2316
|
+
let answer;
|
|
2317
|
+
try {
|
|
2318
|
+
answer = await environmentRequest(
|
|
2319
|
+
"POST",
|
|
2320
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
2321
|
+
{ accessToken: record.accessToken },
|
|
2322
|
+
deps,
|
|
2323
|
+
signal
|
|
2324
|
+
);
|
|
2325
|
+
} catch (error) {
|
|
2326
|
+
signal?.throwIfAborted();
|
|
2327
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
2328
|
+
}
|
|
2329
|
+
const code = answerError(answer);
|
|
2330
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
2331
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
2332
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2333
|
+
return {
|
|
2334
|
+
status: "refused",
|
|
2335
|
+
failure: environmentFailure(
|
|
2336
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
2337
|
+
context.apiUrl
|
|
2338
|
+
)
|
|
2339
|
+
};
|
|
2340
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2341
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
2342
|
+
return { status: "unavailable" };
|
|
2343
|
+
return {
|
|
2344
|
+
status: "ok",
|
|
2345
|
+
record: {
|
|
2346
|
+
...record,
|
|
2347
|
+
accessToken: token.accessToken,
|
|
2348
|
+
expiresAt: token.expiresAt,
|
|
2349
|
+
refreshAfter: token.refreshAfter,
|
|
2350
|
+
displayName: token.displayName
|
|
2351
|
+
}
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
function exchangeRefusal(answer, repository) {
|
|
2355
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2356
|
+
if (answer.status !== 409) return void 0;
|
|
2357
|
+
switch (answerError(answer)) {
|
|
2358
|
+
case "identity_mismatch":
|
|
2359
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
2360
|
+
case "challenge_rejected":
|
|
2361
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
2362
|
+
case "challenge_expired":
|
|
2363
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
2364
|
+
case "challenge_already_exchanged":
|
|
2365
|
+
return failure(
|
|
2366
|
+
"challenge_already_exchanged",
|
|
2367
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
2368
|
+
NEW_SESSION_REMEDY
|
|
2369
|
+
);
|
|
2370
|
+
case "challenge_pending":
|
|
2371
|
+
return failure(
|
|
2372
|
+
"webhook_timeout",
|
|
2373
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
2374
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2375
|
+
);
|
|
2376
|
+
default:
|
|
2377
|
+
return void 0;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
2381
|
+
let answer;
|
|
2382
|
+
try {
|
|
2383
|
+
answer = await environmentRequest(
|
|
2384
|
+
"POST",
|
|
2385
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
2386
|
+
{ challengeId: challenge.challengeId },
|
|
2387
|
+
deps,
|
|
2388
|
+
signal
|
|
2389
|
+
);
|
|
2390
|
+
} catch (error) {
|
|
2391
|
+
signal?.throwIfAborted();
|
|
2392
|
+
return environmentFailure(error, context.apiUrl);
|
|
2393
|
+
}
|
|
2394
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
2395
|
+
const login = answer.value?.githubLogin;
|
|
2396
|
+
return {
|
|
2397
|
+
status: "link_required",
|
|
2398
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
2399
|
+
challengeId: challenge.challengeId,
|
|
2400
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
2401
|
+
};
|
|
2402
|
+
}
|
|
2403
|
+
const refused = exchangeRefusal(
|
|
2404
|
+
answer,
|
|
2405
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
2406
|
+
);
|
|
2407
|
+
if (refused) return refused;
|
|
2408
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2409
|
+
if (!token) {
|
|
2410
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2411
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2412
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2413
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2414
|
+
context.apiUrl
|
|
2415
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2416
|
+
}
|
|
2417
|
+
return recordFor(
|
|
2418
|
+
context,
|
|
2419
|
+
token,
|
|
2420
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
2421
|
+
deps,
|
|
2422
|
+
signal
|
|
2423
|
+
);
|
|
2424
|
+
}
|
|
2425
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2426
|
+
const env = deps.env ?? process.env;
|
|
2427
|
+
const repository = githubRepositoryFullName(root);
|
|
2428
|
+
if (!repository)
|
|
2429
|
+
return failure(
|
|
2430
|
+
"repository_unidentified",
|
|
2431
|
+
"this checkout does not name its GitHub repository",
|
|
2432
|
+
"run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
|
|
2433
|
+
);
|
|
2434
|
+
const branch = currentBranch(root);
|
|
2435
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2436
|
+
return failure(
|
|
2437
|
+
"not_session_branch",
|
|
2438
|
+
`this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
|
|
2439
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2440
|
+
);
|
|
2441
|
+
attempt.branch = branch;
|
|
2442
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2443
|
+
if (!baseSha) {
|
|
2444
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2445
|
+
baseSha = head.stdout.trim();
|
|
2446
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2447
|
+
return failure(
|
|
2448
|
+
"no_commit",
|
|
2449
|
+
"this checkout has no commit to create the session branch at",
|
|
2450
|
+
NEW_SESSION_REMEDY
|
|
2451
|
+
);
|
|
2452
|
+
}
|
|
2453
|
+
const published = await git(
|
|
2454
|
+
root,
|
|
2455
|
+
[
|
|
2456
|
+
"for-each-ref",
|
|
2457
|
+
"--count=1",
|
|
2458
|
+
"--format=%(refname)",
|
|
2459
|
+
"--contains",
|
|
2460
|
+
baseSha,
|
|
2461
|
+
"refs/remotes/origin/"
|
|
2462
|
+
],
|
|
2463
|
+
signal
|
|
2464
|
+
);
|
|
2465
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2466
|
+
return failure(
|
|
2467
|
+
"unpublished_commits",
|
|
2468
|
+
`this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
|
|
2469
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2470
|
+
);
|
|
2471
|
+
attempt.baseSha = baseSha;
|
|
2472
|
+
const remote = await git(
|
|
2473
|
+
root,
|
|
2474
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2475
|
+
signal
|
|
2476
|
+
);
|
|
2477
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2478
|
+
if (remote.ok && recorded) {
|
|
2479
|
+
Object.assign(attempt, recorded);
|
|
2480
|
+
return { ...recorded, repository };
|
|
2481
|
+
}
|
|
2482
|
+
if (remote.ok)
|
|
2483
|
+
return failure(
|
|
2484
|
+
"branch_exists",
|
|
2485
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
2486
|
+
NEW_SESSION_REMEDY
|
|
2487
|
+
);
|
|
2488
|
+
if (remote.code !== 2)
|
|
2489
|
+
return failure(
|
|
2490
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
2491
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
2492
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
2493
|
+
);
|
|
2494
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
2495
|
+
Object.assign(attempt, recorded);
|
|
2496
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
2497
|
+
}
|
|
2498
|
+
let answer;
|
|
2499
|
+
try {
|
|
2500
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
2501
|
+
answer = await environmentRequest(
|
|
2502
|
+
"POST",
|
|
2503
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
2504
|
+
{
|
|
2505
|
+
repositoryFullName: repository,
|
|
2506
|
+
claudeSessionId: context.sessionId,
|
|
2507
|
+
branch,
|
|
2508
|
+
baseSha,
|
|
2509
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
2510
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
2511
|
+
},
|
|
2512
|
+
deps,
|
|
2513
|
+
signal
|
|
2514
|
+
);
|
|
2515
|
+
} catch (error) {
|
|
2516
|
+
signal?.throwIfAborted();
|
|
2517
|
+
return environmentFailure(error, context.apiUrl);
|
|
2518
|
+
}
|
|
2519
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
2520
|
+
return failure(
|
|
2521
|
+
"repository_not_connected",
|
|
2522
|
+
`${repository} is not connected to Primitive`,
|
|
2523
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
2524
|
+
);
|
|
2525
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2526
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2527
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
2528
|
+
return failure(
|
|
2529
|
+
"challenge_open",
|
|
2530
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
2531
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
2532
|
+
);
|
|
2533
|
+
if (answer.status === 429)
|
|
2534
|
+
return failure(
|
|
2535
|
+
"too_many_challenges",
|
|
2536
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
2537
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
2538
|
+
);
|
|
2539
|
+
const challengeId = answer.value?.challengeId;
|
|
2540
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
2541
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
2542
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2543
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2544
|
+
context.apiUrl
|
|
2545
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2546
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
2547
|
+
attempt.challengeId = challengeId;
|
|
2548
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
2549
|
+
return pushSessionBranch(
|
|
2550
|
+
root,
|
|
2551
|
+
repository,
|
|
2552
|
+
branch,
|
|
2553
|
+
baseSha,
|
|
2554
|
+
{ challengeId, challengeExpiresAt },
|
|
2555
|
+
signal
|
|
2556
|
+
);
|
|
2557
|
+
}
|
|
2558
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
2559
|
+
const push = await git(
|
|
2560
|
+
root,
|
|
2561
|
+
[
|
|
2562
|
+
"-c",
|
|
2563
|
+
"core.hooksPath=/dev/null",
|
|
2564
|
+
"-c",
|
|
2565
|
+
"push.followTags=false",
|
|
2566
|
+
"-c",
|
|
2567
|
+
"push.recurseSubmodules=no",
|
|
2568
|
+
"-c",
|
|
2569
|
+
"push.gpgSign=false",
|
|
2570
|
+
"-c",
|
|
2571
|
+
"push.pushOption=",
|
|
2572
|
+
"push",
|
|
2573
|
+
"--no-verify",
|
|
2574
|
+
"--no-follow-tags",
|
|
2575
|
+
"--no-recurse-submodules",
|
|
2576
|
+
"--no-signed",
|
|
2577
|
+
"--quiet",
|
|
2578
|
+
"origin",
|
|
2579
|
+
`${baseSha}:refs/heads/${branch}`
|
|
2580
|
+
],
|
|
2581
|
+
signal
|
|
2582
|
+
);
|
|
2583
|
+
if (!push.ok)
|
|
2584
|
+
return push.timedOut ? failure(
|
|
2585
|
+
"push_timeout",
|
|
2586
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
2587
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
2588
|
+
) : failure(
|
|
2589
|
+
"push_refused",
|
|
2590
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
2591
|
+
`check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
|
|
2592
|
+
);
|
|
2593
|
+
return { ...challenge, repository };
|
|
2594
|
+
}
|
|
2595
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
2596
|
+
let context;
|
|
2597
|
+
try {
|
|
2598
|
+
context = sessionContext(deps);
|
|
2599
|
+
} catch (error) {
|
|
2600
|
+
return failure(
|
|
2601
|
+
"environment_credential_invalid",
|
|
2602
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
2603
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
2604
|
+
);
|
|
2605
|
+
}
|
|
2606
|
+
if ("status" in context) return context;
|
|
2607
|
+
const ctx = context;
|
|
2608
|
+
const startedAt = Date.now();
|
|
2609
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
2610
|
+
return withFileLock(
|
|
2611
|
+
ctx.lockPath,
|
|
2612
|
+
async () => {
|
|
2613
|
+
const record = readToken(ctx);
|
|
2614
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
2615
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
2616
|
+
if (record) {
|
|
2617
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
2618
|
+
if (refreshed.status === "ok") {
|
|
2619
|
+
writeToken(ctx, refreshed.record);
|
|
2620
|
+
return identified(refreshed.record, true);
|
|
2621
|
+
}
|
|
2622
|
+
if (refreshed.status === "refused") {
|
|
2623
|
+
rmSync6(ctx.tokenPath, { force: true });
|
|
2624
|
+
writeState(ctx, {
|
|
2625
|
+
sessionId: ctx.sessionId,
|
|
2626
|
+
status: "failed",
|
|
2627
|
+
code: refreshed.failure.code,
|
|
2628
|
+
cause: refreshed.failure.cause,
|
|
2629
|
+
remedy: refreshed.failure.remedy,
|
|
2630
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
2631
|
+
at: Date.now()
|
|
2632
|
+
});
|
|
2633
|
+
return refreshed.failure;
|
|
2634
|
+
}
|
|
2635
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
2636
|
+
}
|
|
2637
|
+
const state = readState(ctx);
|
|
2638
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
2639
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
2640
|
+
if (!options.explicit) {
|
|
2641
|
+
if (!root || !(record || state))
|
|
2642
|
+
return failure(
|
|
2643
|
+
"not_identified",
|
|
2644
|
+
"this session has not identified who started it yet",
|
|
2645
|
+
RETRY_REMEDY
|
|
2646
|
+
);
|
|
2647
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
2648
|
+
} else if (state && state.at >= startedAt) {
|
|
2649
|
+
return outcomeFromState(state);
|
|
2650
|
+
}
|
|
2651
|
+
if (!root)
|
|
2652
|
+
return failure(
|
|
2653
|
+
"repository_missing",
|
|
2654
|
+
"this is not a git repository",
|
|
2655
|
+
"run it in the repository the session cloned"
|
|
2656
|
+
);
|
|
2657
|
+
const attempt = { root };
|
|
2658
|
+
const remember = (outcome) => {
|
|
2659
|
+
writeState(ctx, {
|
|
2660
|
+
sessionId: ctx.sessionId,
|
|
2661
|
+
status: outcome.status,
|
|
2662
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
2663
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
2664
|
+
githubLogin: outcome.githubLogin
|
|
2665
|
+
},
|
|
2666
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
2667
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
2668
|
+
repositoryRoot: root,
|
|
2669
|
+
branch: attempt.branch ?? state?.branch,
|
|
2670
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
2671
|
+
at: Date.now()
|
|
2672
|
+
});
|
|
2673
|
+
return outcome;
|
|
2674
|
+
};
|
|
2675
|
+
let challenge;
|
|
2676
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
2677
|
+
attempt.challengeId = state.challengeId;
|
|
2678
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2679
|
+
attempt.branch = state.branch;
|
|
2680
|
+
attempt.baseSha = state.baseSha;
|
|
2681
|
+
challenge = {
|
|
2682
|
+
challengeId: state.challengeId,
|
|
2683
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2684
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
2685
|
+
};
|
|
2686
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
2687
|
+
attempt.challengeId = state.challengeId;
|
|
2688
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2689
|
+
const exchanged2 = await exchangeChallenge(
|
|
2690
|
+
ctx,
|
|
2691
|
+
{
|
|
2692
|
+
challengeId: state.challengeId,
|
|
2693
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2694
|
+
githubLogin: state.githubLogin
|
|
2695
|
+
},
|
|
2696
|
+
root,
|
|
2697
|
+
deps,
|
|
2698
|
+
options.signal
|
|
2699
|
+
);
|
|
2700
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
2701
|
+
writeToken(ctx, exchanged2);
|
|
2702
|
+
return identified(exchanged2, false);
|
|
2703
|
+
} else if (!options.explicit) {
|
|
2704
|
+
return state ? outcomeFromState(state) : failure(
|
|
2705
|
+
"not_identified",
|
|
2706
|
+
"this session has not identified who started it yet",
|
|
2707
|
+
RETRY_REMEDY
|
|
2708
|
+
);
|
|
2709
|
+
} else {
|
|
2710
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
2711
|
+
if ("status" in pushed) return remember(pushed);
|
|
2712
|
+
challenge = pushed;
|
|
2713
|
+
}
|
|
2714
|
+
const verified = await pollChallenge(
|
|
2715
|
+
ctx.apiUrl,
|
|
2716
|
+
challenge.challengeId,
|
|
2717
|
+
challenge.repository,
|
|
2718
|
+
// A hook process waits only briefly for a late notice.
|
|
2719
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
2720
|
+
options.signal
|
|
2721
|
+
);
|
|
2722
|
+
if ("status" in verified) return remember(verified);
|
|
2723
|
+
const exchanged = await exchangeChallenge(
|
|
2724
|
+
ctx,
|
|
2725
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
2726
|
+
root,
|
|
2727
|
+
deps,
|
|
2728
|
+
options.signal
|
|
2729
|
+
);
|
|
2730
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
2731
|
+
writeToken(ctx, exchanged);
|
|
2732
|
+
return identified(exchanged, false);
|
|
2733
|
+
},
|
|
2734
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
2735
|
+
);
|
|
2736
|
+
}
|
|
2737
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
2738
|
+
const cached2 = cachedSessionCredential(deps);
|
|
2739
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
2740
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
2741
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2742
|
+
let outcome;
|
|
2743
|
+
try {
|
|
2744
|
+
outcome = await ensureSessionIdentity(
|
|
2745
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
2746
|
+
deps
|
|
2747
|
+
);
|
|
2748
|
+
} catch (error) {
|
|
2749
|
+
options.signal?.throwIfAborted();
|
|
2750
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2751
|
+
throw new MachineAuthError(
|
|
2752
|
+
"identity_unavailable",
|
|
2753
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
2754
|
+
);
|
|
2755
|
+
}
|
|
2756
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
2757
|
+
throw new MachineAuthError(
|
|
2758
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
2759
|
+
sessionIdentityMessage(outcome)
|
|
2760
|
+
);
|
|
2761
|
+
}
|
|
2762
|
+
|
|
1204
2763
|
// src/lib/machine-credentials.ts
|
|
1205
|
-
|
|
2764
|
+
function sessionScoped(deps) {
|
|
2765
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2766
|
+
}
|
|
2767
|
+
var require3 = createRequire2(import.meta.url);
|
|
1206
2768
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1207
|
-
var
|
|
2769
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1208
2770
|
var PROFILE_FILE = "machine_profile.json";
|
|
1209
|
-
var
|
|
2771
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
1210
2772
|
var cached;
|
|
1211
2773
|
function configurationDirectory(deps) {
|
|
1212
2774
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
1213
2775
|
}
|
|
1214
2776
|
function apiUrlFor(deps) {
|
|
1215
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
2777
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1216
2778
|
}
|
|
1217
|
-
function
|
|
1218
|
-
return
|
|
2779
|
+
function hash2(value) {
|
|
2780
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
1219
2781
|
}
|
|
1220
2782
|
function recordPath(directory, generation) {
|
|
1221
|
-
return
|
|
2783
|
+
return join10(directory, `machine_${generation}.json`);
|
|
1222
2784
|
}
|
|
1223
2785
|
function storageKey(directory, generation) {
|
|
1224
|
-
return `${
|
|
2786
|
+
return `${hash2(directory)}:${generation}`;
|
|
1225
2787
|
}
|
|
1226
2788
|
function environmentContextPath(deps, clientId) {
|
|
1227
|
-
return
|
|
2789
|
+
return join10(
|
|
1228
2790
|
configurationDirectory(deps),
|
|
1229
|
-
`machine_context_${
|
|
2791
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1230
2792
|
);
|
|
1231
2793
|
}
|
|
1232
2794
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -1284,27 +2846,33 @@ function readEnvironmentContext(environment, deps) {
|
|
|
1284
2846
|
return void 0;
|
|
1285
2847
|
}
|
|
1286
2848
|
}
|
|
1287
|
-
function
|
|
1288
|
-
let directory =
|
|
2849
|
+
function keyringLoaderPath(start, options = {}) {
|
|
2850
|
+
let directory = start;
|
|
1289
2851
|
for (let depth = 0; depth < 5; depth++) {
|
|
1290
|
-
const loader =
|
|
1291
|
-
if (
|
|
1292
|
-
|
|
1293
|
-
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1294
|
-
}
|
|
1295
|
-
directory = dirname4(directory);
|
|
2852
|
+
const loader = join10(directory, "native", "keyring.cjs");
|
|
2853
|
+
if (existsSync5(loader)) return loader;
|
|
2854
|
+
directory = dirname7(directory);
|
|
1296
2855
|
}
|
|
1297
|
-
|
|
2856
|
+
try {
|
|
2857
|
+
createRequire2(join10(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
2858
|
+
return void 0;
|
|
2859
|
+
} catch {
|
|
2860
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
function keyringEntry(key) {
|
|
2864
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath4(import.meta.url)));
|
|
2865
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
1298
2866
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
1299
2867
|
}
|
|
1300
2868
|
function protectPath(path, directory) {
|
|
1301
2869
|
if (process.platform !== "win32") {
|
|
1302
|
-
|
|
2870
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
1303
2871
|
return;
|
|
1304
2872
|
}
|
|
1305
2873
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
1306
2874
|
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)`;
|
|
1307
|
-
|
|
2875
|
+
execFileSync2(
|
|
1308
2876
|
"powershell.exe",
|
|
1309
2877
|
[
|
|
1310
2878
|
"-NoProfile",
|
|
@@ -1316,8 +2884,8 @@ function protectPath(path, directory) {
|
|
|
1316
2884
|
);
|
|
1317
2885
|
}
|
|
1318
2886
|
function ensureDirectory(directory) {
|
|
1319
|
-
|
|
1320
|
-
if (
|
|
2887
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
2888
|
+
if (lstatSync5(directory).isSymbolicLink())
|
|
1321
2889
|
throw new MachineAuthError(
|
|
1322
2890
|
"unsafe_storage",
|
|
1323
2891
|
"Credential directory must not be a symbolic link."
|
|
@@ -1329,17 +2897,20 @@ function writePrivate(path, value) {
|
|
|
1329
2897
|
`, { mode: 384 });
|
|
1330
2898
|
protectPath(path, false);
|
|
1331
2899
|
}
|
|
2900
|
+
function readMachineMetadata(path) {
|
|
2901
|
+
return readPrivate(path);
|
|
2902
|
+
}
|
|
1332
2903
|
function readPrivate(path) {
|
|
1333
2904
|
let raw;
|
|
1334
2905
|
try {
|
|
1335
|
-
const stat =
|
|
2906
|
+
const stat = lstatSync5(path);
|
|
1336
2907
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1337
2908
|
throw new MachineAuthError(
|
|
1338
2909
|
"unsafe_storage",
|
|
1339
2910
|
"Machine credential files must be owner-only regular files."
|
|
1340
2911
|
);
|
|
1341
2912
|
}
|
|
1342
|
-
raw =
|
|
2913
|
+
raw = readFileSync7(path, "utf8");
|
|
1343
2914
|
} catch (error) {
|
|
1344
2915
|
if (error.code === "ENOENT") return void 0;
|
|
1345
2916
|
throw error;
|
|
@@ -1384,7 +2955,7 @@ function parseProfile(value) {
|
|
|
1384
2955
|
};
|
|
1385
2956
|
}
|
|
1386
2957
|
function readMachineProfile(deps = {}) {
|
|
1387
|
-
const value = readPrivate(
|
|
2958
|
+
const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
1388
2959
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1389
2960
|
}
|
|
1390
2961
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -1393,20 +2964,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
1393
2964
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1394
2965
|
function networkSecretBrokerKey(deps, clientId) {
|
|
1395
2966
|
const directory = configurationDirectory(deps);
|
|
1396
|
-
const path =
|
|
2967
|
+
const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1397
2968
|
const known = brokerKeys.get(path);
|
|
1398
2969
|
if (known) return known;
|
|
1399
2970
|
ensureDirectory(directory);
|
|
1400
2971
|
const read = () => {
|
|
1401
2972
|
try {
|
|
1402
|
-
const stat =
|
|
2973
|
+
const stat = lstatSync5(path);
|
|
1403
2974
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1404
2975
|
throw new MachineAuthError(
|
|
1405
2976
|
"unsafe_storage",
|
|
1406
2977
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1407
2978
|
true
|
|
1408
2979
|
);
|
|
1409
|
-
const value =
|
|
2980
|
+
const value = readFileSync7(path, "utf8").trim();
|
|
1410
2981
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1411
2982
|
} catch (error) {
|
|
1412
2983
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -1425,16 +2996,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
1425
2996
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1426
2997
|
true
|
|
1427
2998
|
);
|
|
1428
|
-
const staged = `${path}.${process.pid}.${
|
|
2999
|
+
const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
|
|
1429
3000
|
try {
|
|
1430
|
-
|
|
3001
|
+
writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
|
|
1431
3002
|
`, { mode: 384, flag: "wx" });
|
|
1432
3003
|
protectPath(staged, false);
|
|
1433
3004
|
linkSync(staged, path);
|
|
1434
3005
|
} catch (error) {
|
|
1435
3006
|
if (error.code !== "EEXIST") throw error;
|
|
1436
3007
|
} finally {
|
|
1437
|
-
|
|
3008
|
+
rmSync7(staged, { force: true });
|
|
1438
3009
|
}
|
|
1439
3010
|
}
|
|
1440
3011
|
const key = read()?.key;
|
|
@@ -1467,7 +3038,7 @@ function environmentCredentials(deps) {
|
|
|
1467
3038
|
"conflicting_credentials",
|
|
1468
3039
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1469
3040
|
);
|
|
1470
|
-
const generation =
|
|
3041
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1471
3042
|
const credentials = {
|
|
1472
3043
|
clientId,
|
|
1473
3044
|
generation,
|
|
@@ -1488,12 +3059,12 @@ function environmentCredentials(deps) {
|
|
|
1488
3059
|
return {
|
|
1489
3060
|
clientId,
|
|
1490
3061
|
clientSecret,
|
|
1491
|
-
generation:
|
|
3062
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1492
3063
|
};
|
|
1493
3064
|
}
|
|
1494
3065
|
function hasMachineConfiguration(deps = {}) {
|
|
1495
3066
|
const env = deps.env ?? process.env;
|
|
1496
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
3067
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
|
|
1497
3068
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1498
3069
|
throw new MachineAuthError(
|
|
1499
3070
|
"conflicting_credentials",
|
|
@@ -1505,6 +3076,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1505
3076
|
}
|
|
1506
3077
|
function machineContext(deps = {}) {
|
|
1507
3078
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3079
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1508
3080
|
const environment = environmentCredentials(deps);
|
|
1509
3081
|
if (environment) {
|
|
1510
3082
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1519,6 +3091,7 @@ function machineContext(deps = {}) {
|
|
|
1519
3091
|
return profile;
|
|
1520
3092
|
}
|
|
1521
3093
|
function cachedMachineCredential(deps = {}) {
|
|
3094
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1522
3095
|
const context = machineContext(deps);
|
|
1523
3096
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1524
3097
|
}
|
|
@@ -1527,7 +3100,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
1527
3100
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1528
3101
|
if (!generation) return false;
|
|
1529
3102
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1530
|
-
return readPrivate(
|
|
3103
|
+
return readPrivate(join10(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1531
3104
|
}
|
|
1532
3105
|
var environmentTerminal;
|
|
1533
3106
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -1591,6 +3164,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
1591
3164
|
}
|
|
1592
3165
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1593
3166
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3167
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1594
3168
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1595
3169
|
const apiUrl = apiUrlFor(deps);
|
|
1596
3170
|
const environment = environmentCredentials(deps);
|
|
@@ -1619,7 +3193,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1619
3193
|
}
|
|
1620
3194
|
}
|
|
1621
3195
|
return withFileLock(
|
|
1622
|
-
|
|
3196
|
+
join10(directory2, "credentials.lock"),
|
|
1623
3197
|
async () => {
|
|
1624
3198
|
if (machineSessionEnded(deps))
|
|
1625
3199
|
throw new MachineAuthError(
|
|
@@ -1627,7 +3201,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1627
3201
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1628
3202
|
true
|
|
1629
3203
|
);
|
|
1630
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
3204
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1631
3205
|
return cached;
|
|
1632
3206
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1633
3207
|
throw networkRejection.error;
|
|
@@ -1701,7 +3275,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1701
3275
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1702
3276
|
try {
|
|
1703
3277
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1704
|
-
|
|
3278
|
+
rmSync7(contextPath, { force: true });
|
|
1705
3279
|
} catch {
|
|
1706
3280
|
}
|
|
1707
3281
|
throw error;
|
|
@@ -1711,7 +3285,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1711
3285
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1712
3286
|
try {
|
|
1713
3287
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1714
|
-
|
|
3288
|
+
rmSync7(contextPath, { force: true });
|
|
1715
3289
|
} catch {
|
|
1716
3290
|
}
|
|
1717
3291
|
}
|
|
@@ -1725,7 +3299,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1725
3299
|
const expected = machineContext(deps);
|
|
1726
3300
|
const directory = configurationDirectory(deps);
|
|
1727
3301
|
return withFileLock(
|
|
1728
|
-
|
|
3302
|
+
join10(directory, "credentials.lock"),
|
|
1729
3303
|
async () => {
|
|
1730
3304
|
const profile = readMachineProfile(deps);
|
|
1731
3305
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1740,7 +3314,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1740
3314
|
true
|
|
1741
3315
|
);
|
|
1742
3316
|
let record = await loadRecord(profile, deps, signal);
|
|
1743
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
3317
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1744
3318
|
try {
|
|
1745
3319
|
const { tokens, identity } = await withMachineCooldown(
|
|
1746
3320
|
directory,
|
|
@@ -1775,7 +3349,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1775
3349
|
await persistRecord(record, deps, signal);
|
|
1776
3350
|
} catch (error) {
|
|
1777
3351
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1778
|
-
writePrivate(
|
|
3352
|
+
writePrivate(join10(directory, "machine_terminal.json"), profile.generation);
|
|
1779
3353
|
throw error;
|
|
1780
3354
|
}
|
|
1781
3355
|
}
|
|
@@ -1821,31 +3395,37 @@ function machineCaptureActor(deps = {}) {
|
|
|
1821
3395
|
return injected ? { kind: "machine", apiUrl: apiUrlFor(deps), clientId: injected.clientId } : void 0;
|
|
1822
3396
|
}
|
|
1823
3397
|
function machineJournalBucket(identity) {
|
|
1824
|
-
return `_machine_${
|
|
3398
|
+
return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
1825
3399
|
}
|
|
1826
3400
|
function identityPending(actor) {
|
|
1827
3401
|
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
1828
3402
|
}
|
|
1829
3403
|
function machinePendingBucket(identity) {
|
|
1830
|
-
return `_machine_pending_${
|
|
3404
|
+
return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
3405
|
+
}
|
|
3406
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
3407
|
+
ensureDirectory(directory);
|
|
3408
|
+
}
|
|
3409
|
+
function writeMachineMetadata(path, value) {
|
|
3410
|
+
writePrivate(path, value);
|
|
1831
3411
|
}
|
|
1832
3412
|
|
|
1833
3413
|
// src/lib/credentials.ts
|
|
1834
3414
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1835
|
-
var TOKEN_FILE_PATH =
|
|
1836
|
-
var REFRESH_TOKEN_PATH =
|
|
1837
|
-
var TOKEN_EXPIRES_PATH =
|
|
1838
|
-
var TERMINAL_REFRESH_PATH =
|
|
1839
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1840
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1841
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1842
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3415
|
+
var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
|
|
3416
|
+
var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
|
|
3417
|
+
var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
|
|
3418
|
+
var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3419
|
+
var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3420
|
+
var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
|
|
3421
|
+
var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3422
|
+
var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
|
|
1843
3423
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1844
3424
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1845
3425
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1846
3426
|
function readTrimmed(path) {
|
|
1847
3427
|
try {
|
|
1848
|
-
const value =
|
|
3428
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
1849
3429
|
return value || void 0;
|
|
1850
3430
|
} catch {
|
|
1851
3431
|
return void 0;
|
|
@@ -1867,22 +3447,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1867
3447
|
);
|
|
1868
3448
|
if (metadata.state === "legacy_broker") {
|
|
1869
3449
|
if (metadata.metadata) {
|
|
1870
|
-
const
|
|
1871
|
-
if (!
|
|
3450
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3451
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1872
3452
|
return void 0;
|
|
1873
3453
|
}
|
|
1874
3454
|
}
|
|
1875
3455
|
return { token: stored, source: "token_file" };
|
|
1876
3456
|
}
|
|
1877
3457
|
if (metadata.state === "invalid") return void 0;
|
|
1878
|
-
const
|
|
1879
|
-
if (!
|
|
3458
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3459
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1880
3460
|
return void 0;
|
|
1881
3461
|
}
|
|
1882
3462
|
return { token: stored, source: "token_file" };
|
|
1883
3463
|
}
|
|
1884
3464
|
function credentialFingerprint(value) {
|
|
1885
|
-
return
|
|
3465
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
1886
3466
|
}
|
|
1887
3467
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
1888
3468
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -1902,7 +3482,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
1902
3482
|
function readBoundedCredentialJson(path) {
|
|
1903
3483
|
let raw;
|
|
1904
3484
|
try {
|
|
1905
|
-
raw =
|
|
3485
|
+
raw = readFileSync8(path, "utf8");
|
|
1906
3486
|
} catch (error) {
|
|
1907
3487
|
return error.code === "ENOENT" ? void 0 : null;
|
|
1908
3488
|
}
|
|
@@ -1979,14 +3559,14 @@ function jwtOrganizationId(token) {
|
|
|
1979
3559
|
|
|
1980
3560
|
// src/binding.ts
|
|
1981
3561
|
var PRIM_CONFIG_DIR = primConfigDirectory();
|
|
1982
|
-
var SESSIONS_DIR =
|
|
3562
|
+
var SESSIONS_DIR = join12(PRIM_CONFIG_DIR, "sessions");
|
|
1983
3563
|
var WORKSPACE_FILE = ".prim/workspace.json";
|
|
1984
3564
|
function readJsonSafe(path) {
|
|
1985
|
-
if (!
|
|
3565
|
+
if (!existsSync6(path)) {
|
|
1986
3566
|
return;
|
|
1987
3567
|
}
|
|
1988
3568
|
try {
|
|
1989
|
-
return JSON.parse(
|
|
3569
|
+
return JSON.parse(readFileSync9(path, "utf-8"));
|
|
1990
3570
|
} catch {
|
|
1991
3571
|
return;
|
|
1992
3572
|
}
|
|
@@ -1995,17 +3575,17 @@ function fromSessionMarker(sessionId) {
|
|
|
1995
3575
|
if (!sessionId) {
|
|
1996
3576
|
return;
|
|
1997
3577
|
}
|
|
1998
|
-
const marker = readJsonSafe(
|
|
3578
|
+
const marker = readJsonSafe(join12(SESSIONS_DIR, `${sessionId}.json`));
|
|
1999
3579
|
return marker?.orgId;
|
|
2000
3580
|
}
|
|
2001
3581
|
function fromWorkspaceFile(startDir) {
|
|
2002
3582
|
let dir = startDir;
|
|
2003
3583
|
while (true) {
|
|
2004
|
-
const config = readJsonSafe(
|
|
3584
|
+
const config = readJsonSafe(join12(dir, WORKSPACE_FILE));
|
|
2005
3585
|
if (config?.orgId) {
|
|
2006
3586
|
return config.orgId;
|
|
2007
3587
|
}
|
|
2008
|
-
const parent =
|
|
3588
|
+
const parent = dirname8(dir);
|
|
2009
3589
|
if (parent === dir) {
|
|
2010
3590
|
return;
|
|
2011
3591
|
}
|
|
@@ -2042,132 +3622,12 @@ import { existsSync as existsSync9 } from "fs";
|
|
|
2042
3622
|
|
|
2043
3623
|
// src/demo/diagnostics.ts
|
|
2044
3624
|
import { existsSync as existsSync8 } from "fs";
|
|
2045
|
-
import { join as
|
|
2046
|
-
|
|
2047
|
-
// src/lib/hook-runtime.ts
|
|
2048
|
-
import { createHash as createHash5, randomBytes as randomBytes4 } from "crypto";
|
|
2049
|
-
import {
|
|
2050
|
-
constants as constants2,
|
|
2051
|
-
accessSync,
|
|
2052
|
-
chmodSync as chmodSync2,
|
|
2053
|
-
copyFileSync,
|
|
2054
|
-
existsSync as existsSync6,
|
|
2055
|
-
lstatSync as lstatSync4,
|
|
2056
|
-
mkdirSync as mkdirSync4,
|
|
2057
|
-
mkdtempSync,
|
|
2058
|
-
readFileSync as readFileSync8,
|
|
2059
|
-
readdirSync as readdirSync2,
|
|
2060
|
-
realpathSync,
|
|
2061
|
-
renameSync as renameSync2,
|
|
2062
|
-
rmSync as rmSync6,
|
|
2063
|
-
statSync as statSync2,
|
|
2064
|
-
utimesSync,
|
|
2065
|
-
writeFileSync as writeFileSync4
|
|
2066
|
-
} from "fs";
|
|
2067
|
-
import { delimiter, dirname as dirname7, isAbsolute as isAbsolute3, join as join10, resolve } from "path";
|
|
2068
|
-
|
|
2069
|
-
// src/lib/git-hook-contract.ts
|
|
2070
|
-
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
2071
|
-
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
2072
|
-
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
2073
|
-
# where prim is active (git config prim.active true) and never fails the hook.
|
|
2074
|
-
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
2075
|
-
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
2076
|
-
[ -x "$prim_launcher" ] || exit 0
|
|
2077
|
-
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
2078
|
-
prim_hook=\${1-}
|
|
2079
|
-
if [ "$#" -gt 0 ]; then shift; fi
|
|
2080
|
-
case "$prim_hook" in
|
|
2081
|
-
pre-commit)
|
|
2082
|
-
"$prim_launcher" prim-pre-commit "$@" || :
|
|
2083
|
-
;;
|
|
2084
|
-
post-commit)
|
|
2085
|
-
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
2086
|
-
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
2087
|
-
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
2088
|
-
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
2089
|
-
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
2090
|
-
(
|
|
2091
|
-
trap '' HUP
|
|
2092
|
-
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
2093
|
-
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
2094
|
-
) </dev/null >/dev/null 2>&1 &
|
|
2095
|
-
;;
|
|
2096
|
-
post-rewrite)
|
|
2097
|
-
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
2098
|
-
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
2099
|
-
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
2100
|
-
rm -f "$prim_pairs"
|
|
2101
|
-
exit 0
|
|
2102
|
-
fi
|
|
2103
|
-
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
2104
|
-
(
|
|
2105
|
-
trap '' HUP
|
|
2106
|
-
trap 'rm -f "$prim_pairs"' 0
|
|
2107
|
-
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
2108
|
-
) </dev/null >/dev/null 2>&1 &
|
|
2109
|
-
;;
|
|
2110
|
-
esac
|
|
2111
|
-
exit 0
|
|
2112
|
-
`;
|
|
2113
|
-
|
|
2114
|
-
// src/lib/native-keyring.ts
|
|
2115
|
-
import { existsSync as existsSync5 } from "fs";
|
|
2116
|
-
import { createRequire as createRequire2 } from "module";
|
|
2117
|
-
import { dirname as dirname6, join as join9 } from "path";
|
|
2118
|
-
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
2119
|
-
var require3 = createRequire2(import.meta.url);
|
|
2120
|
-
|
|
2121
|
-
// src/lib/hook-runtime.ts
|
|
2122
|
-
var RELEASE_PREFIX = "release-";
|
|
2123
|
-
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
2124
|
-
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
2125
|
-
var HOOK_RUNTIME_ENTRIES = {
|
|
2126
|
-
// SessionStart self-healing resolves this exact CLI entry to run
|
|
2127
|
-
// `daemon ensure`; it must travel with the immutable hook release.
|
|
2128
|
-
prim: "dist/index.js",
|
|
2129
|
-
"prim-hook": "dist/hooks/prim-hook.js",
|
|
2130
|
-
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
2131
|
-
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
2132
|
-
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
2133
|
-
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
2134
|
-
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
2135
|
-
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
2136
|
-
"prim-session-start": "dist/hooks/session-start.js",
|
|
2137
|
-
"prim-session-end": "dist/hooks/session-end.js",
|
|
2138
|
-
"prim-daemon-server": "dist/daemon/server.js",
|
|
2139
|
-
"prim-statusline": "dist/statusline-main.js"
|
|
2140
|
-
};
|
|
2141
|
-
var SOURCE_ENTRIES = Object.fromEntries(
|
|
2142
|
-
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
2143
|
-
bin,
|
|
2144
|
-
target.replace(/^dist\//u, "")
|
|
2145
|
-
])
|
|
2146
|
-
);
|
|
2147
|
-
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
2148
|
-
set -eu
|
|
2149
|
-
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
2150
|
-
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
2151
|
-
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
2152
|
-
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
2153
|
-
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
2154
|
-
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
2155
|
-
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
2156
|
-
case "\${1-}" in
|
|
2157
|
-
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
2158
|
-
*) exit 64 ;;
|
|
2159
|
-
esac
|
|
2160
|
-
shift
|
|
2161
|
-
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
2162
|
-
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
2163
|
-
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
2164
|
-
exec "$prim_node" "$prim_entry" "$@"
|
|
2165
|
-
`;
|
|
3625
|
+
import { join as join14 } from "path";
|
|
2166
3626
|
|
|
2167
3627
|
// src/demo/state.ts
|
|
2168
|
-
import { createHash as
|
|
2169
|
-
import { existsSync as existsSync7, lstatSync as
|
|
2170
|
-
import { join as
|
|
3628
|
+
import { createHash as createHash8, randomUUID as randomUUID3 } from "crypto";
|
|
3629
|
+
import { existsSync as existsSync7, lstatSync as lstatSync6, readFileSync as readFileSync10, readdirSync as readdirSync3 } from "fs";
|
|
3630
|
+
import { join as join13, resolve as resolve3 } from "path";
|
|
2171
3631
|
|
|
2172
3632
|
// src/generated/cli-http-v1.validators.js
|
|
2173
3633
|
var import_ucs2length = __toESM(require_ucs2length(), 1);
|
|
@@ -28855,15 +30315,15 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
28855
30315
|
|
|
28856
30316
|
// src/demo/state.ts
|
|
28857
30317
|
var RUN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
28858
|
-
var demoDirectory = () =>
|
|
30318
|
+
var demoDirectory = () => join13(primConfigDirectory(), "demo");
|
|
28859
30319
|
var runPath = (id2) => {
|
|
28860
30320
|
if (!RUN_ID.test(id2)) throw new Error("invalid demo run ID");
|
|
28861
|
-
return
|
|
30321
|
+
return join13(demoDirectory(), "runs", `${id2}.json`);
|
|
28862
30322
|
};
|
|
28863
30323
|
function readDemoJson(path) {
|
|
28864
|
-
const stat =
|
|
30324
|
+
const stat = lstatSync6(path);
|
|
28865
30325
|
if (!stat.isFile() || stat.size > 16384) throw new Error(`invalid demo state: ${path}`);
|
|
28866
|
-
return JSON.parse(
|
|
30326
|
+
return JSON.parse(readFileSync10(path, "utf8"));
|
|
28867
30327
|
}
|
|
28868
30328
|
function saveDemoJson(path, value) {
|
|
28869
30329
|
atomicWriteFile(path, `${JSON.stringify(value)}
|
|
@@ -28900,11 +30360,11 @@ function demoCommand(run, action, choice, reason) {
|
|
|
28900
30360
|
].map(quote).join(" ");
|
|
28901
30361
|
}
|
|
28902
30362
|
function sessionKey(agent, session) {
|
|
28903
|
-
return
|
|
30363
|
+
return createHash8("sha256").update(`${agent}\0${session}`).digest("hex");
|
|
28904
30364
|
}
|
|
28905
30365
|
function exclusionPath(key) {
|
|
28906
30366
|
if (!/^[0-9a-f]{64}$/u.test(key)) throw new Error("invalid demo session identity");
|
|
28907
|
-
return
|
|
30367
|
+
return join13(demoDirectory(), "excluded-sessions", `${key}.json`);
|
|
28908
30368
|
}
|
|
28909
30369
|
function sessionExcluded(agent, session) {
|
|
28910
30370
|
if (typeof session !== "string" || !session) return false;
|
|
@@ -28943,7 +30403,7 @@ function demoArgv(command) {
|
|
|
28943
30403
|
}
|
|
28944
30404
|
|
|
28945
30405
|
// src/demo/diagnostics.ts
|
|
28946
|
-
var observationPath = (id2) =>
|
|
30406
|
+
var observationPath = (id2) => join14(demoDirectory(), "observations", `${id2}.json`);
|
|
28947
30407
|
function observeRun(id2, observation) {
|
|
28948
30408
|
try {
|
|
28949
30409
|
saveDemoJson(observationPath(id2), observation);
|
|
@@ -29032,14 +30492,14 @@ function observeDemoInvocation(envelope, agent, checkExclusion = true) {
|
|
|
29032
30492
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
29033
30493
|
import { existsSync as existsSync11, readFileSync as readFileSync12 } from "fs";
|
|
29034
30494
|
import { homedir as homedir2 } from "os";
|
|
29035
|
-
import { join as
|
|
30495
|
+
import { join as join16 } from "path";
|
|
29036
30496
|
|
|
29037
30497
|
// src/lib/cloud-prepared.ts
|
|
29038
|
-
import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as
|
|
29039
|
-
import { join as
|
|
30498
|
+
import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync11, rmSync as rmSync8, writeFileSync as writeFileSync5 } from "fs";
|
|
30499
|
+
import { join as join15 } from "path";
|
|
29040
30500
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
29041
30501
|
function cloudPreparedPath(env = process.env) {
|
|
29042
|
-
return
|
|
30502
|
+
return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
29043
30503
|
}
|
|
29044
30504
|
function isPreparedCloudSession(env = process.env) {
|
|
29045
30505
|
if (!isClaudeCloudSession(env)) return false;
|
|
@@ -29051,17 +30511,17 @@ function isPreparedCloudSession(env = process.env) {
|
|
|
29051
30511
|
}
|
|
29052
30512
|
|
|
29053
30513
|
// src/lib/demo-pause.ts
|
|
29054
|
-
import { execFileSync as
|
|
30514
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
29055
30515
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
29056
30516
|
var PAUSE_KEY = "prim.demoPause";
|
|
29057
|
-
var
|
|
29058
|
-
function
|
|
30517
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
30518
|
+
function git2(cwd, args) {
|
|
29059
30519
|
try {
|
|
29060
|
-
return
|
|
30520
|
+
return execFileSync3("git", args, {
|
|
29061
30521
|
cwd,
|
|
29062
30522
|
encoding: "utf-8",
|
|
29063
30523
|
stdio: ["ignore", "pipe", "ignore"],
|
|
29064
|
-
timeout:
|
|
30524
|
+
timeout: GIT_TIMEOUT_MS3
|
|
29065
30525
|
});
|
|
29066
30526
|
} catch {
|
|
29067
30527
|
return void 0;
|
|
@@ -29069,10 +30529,10 @@ function git(cwd, args) {
|
|
|
29069
30529
|
}
|
|
29070
30530
|
function setLocal(cwd, key, value) {
|
|
29071
30531
|
try {
|
|
29072
|
-
|
|
30532
|
+
execFileSync3(
|
|
29073
30533
|
"git",
|
|
29074
30534
|
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
29075
|
-
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout:
|
|
30535
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
|
|
29076
30536
|
);
|
|
29077
30537
|
} catch (error) {
|
|
29078
30538
|
if (value !== null || error.status !== 5) throw error;
|
|
@@ -29086,7 +30546,7 @@ function parsePause(value) {
|
|
|
29086
30546
|
function readCaptureConfig(cwd) {
|
|
29087
30547
|
let active;
|
|
29088
30548
|
let pause;
|
|
29089
|
-
const out =
|
|
30549
|
+
const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
29090
30550
|
for (const line of out.split("\n")) {
|
|
29091
30551
|
const space3 = line.indexOf(" ");
|
|
29092
30552
|
const key = line.slice(0, space3).toLowerCase();
|
|
@@ -29111,273 +30571,13 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
29111
30571
|
}
|
|
29112
30572
|
}
|
|
29113
30573
|
|
|
29114
|
-
// src/lib/git.ts
|
|
29115
|
-
import { execFileSync as execFileSync3 } from "child_process";
|
|
29116
|
-
import { createHash as createHash7 } from "crypto";
|
|
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";
|
|
29119
|
-
var GIT_TIMEOUT_MS2 = 1e3;
|
|
29120
|
-
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
29121
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
29122
|
-
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
29123
|
-
function gitToplevel(cwd) {
|
|
29124
|
-
try {
|
|
29125
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
29126
|
-
cwd,
|
|
29127
|
-
encoding: "utf-8",
|
|
29128
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29129
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29130
|
-
}).trim();
|
|
29131
|
-
} catch {
|
|
29132
|
-
return null;
|
|
29133
|
-
}
|
|
29134
|
-
}
|
|
29135
|
-
function gitValue(cwd, args) {
|
|
29136
|
-
try {
|
|
29137
|
-
const value = execFileSync3("git", args, {
|
|
29138
|
-
cwd,
|
|
29139
|
-
encoding: "utf-8",
|
|
29140
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29141
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29142
|
-
}).trim();
|
|
29143
|
-
return value || void 0;
|
|
29144
|
-
} catch {
|
|
29145
|
-
return void 0;
|
|
29146
|
-
}
|
|
29147
|
-
}
|
|
29148
|
-
function currentBranch(cwd) {
|
|
29149
|
-
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
29150
|
-
}
|
|
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;
|
|
29160
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
29161
|
-
remote
|
|
29162
|
-
);
|
|
29163
|
-
const path = match?.[1] ?? match?.[2];
|
|
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 {
|
|
29174
|
-
return null;
|
|
29175
|
-
}
|
|
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;
|
|
29202
|
-
}
|
|
29203
|
-
function canonicalGitRoot(cwd) {
|
|
29204
|
-
try {
|
|
29205
|
-
const top = gitToplevel(cwd);
|
|
29206
|
-
return top ? realpathSync2.native(top) : null;
|
|
29207
|
-
} catch {
|
|
29208
|
-
return null;
|
|
29209
|
-
}
|
|
29210
|
-
}
|
|
29211
|
-
function relatedWorktreeTarget(path, cwd, origin) {
|
|
29212
|
-
let parent = dirname8(resolve3(cwd, path));
|
|
29213
|
-
while (true) {
|
|
29214
|
-
try {
|
|
29215
|
-
realpathSync2.native(parent);
|
|
29216
|
-
break;
|
|
29217
|
-
} catch {
|
|
29218
|
-
const next = dirname8(parent);
|
|
29219
|
-
if (next === parent) return null;
|
|
29220
|
-
parent = next;
|
|
29221
|
-
}
|
|
29222
|
-
}
|
|
29223
|
-
const target = resolveRepositoryContext(parent);
|
|
29224
|
-
if (!target || !target.repoKey || target.repoKey !== origin.repoKey) return null;
|
|
29225
|
-
const common = (root) => {
|
|
29226
|
-
const value = gitValue(root, ["rev-parse", "--git-common-dir"]);
|
|
29227
|
-
try {
|
|
29228
|
-
return value ? realpathSync2.native(resolve3(root, value)) : void 0;
|
|
29229
|
-
} catch {
|
|
29230
|
-
return void 0;
|
|
29231
|
-
}
|
|
29232
|
-
};
|
|
29233
|
-
const originCommon = common(origin.repoRoot);
|
|
29234
|
-
return originCommon && originCommon === common(target.repoRoot) ? target : null;
|
|
29235
|
-
}
|
|
29236
|
-
function normalizeOriginRemote(remote) {
|
|
29237
|
-
const value = remote.trim();
|
|
29238
|
-
if (!value) return void 0;
|
|
29239
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
29240
|
-
if (scp?.host && scp.path) {
|
|
29241
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
29242
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
29243
|
-
}
|
|
29244
|
-
try {
|
|
29245
|
-
const url = new URL(value);
|
|
29246
|
-
url.username = "";
|
|
29247
|
-
url.password = "";
|
|
29248
|
-
url.search = "";
|
|
29249
|
-
url.hash = "";
|
|
29250
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
29251
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
29252
|
-
return void 0;
|
|
29253
|
-
} catch {
|
|
29254
|
-
return void 0;
|
|
29255
|
-
}
|
|
29256
|
-
}
|
|
29257
|
-
function opaqueRepoKey(source, value) {
|
|
29258
|
-
return `repo_v1_${createHash7("sha256").update(`${source}\0${value}`).digest("hex")}`;
|
|
29259
|
-
}
|
|
29260
|
-
function resolveRepositoryContext(cwd = process.cwd()) {
|
|
29261
|
-
const top = gitToplevel(cwd);
|
|
29262
|
-
if (!top) return null;
|
|
29263
|
-
let repoRoot;
|
|
29264
|
-
try {
|
|
29265
|
-
repoRoot = realpathSync2.native(top);
|
|
29266
|
-
} catch {
|
|
29267
|
-
repoRoot = resolve3(top);
|
|
29268
|
-
}
|
|
29269
|
-
const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
|
|
29270
|
-
const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
|
|
29271
|
-
const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
|
|
29272
|
-
if (normalizedOrigin) {
|
|
29273
|
-
return {
|
|
29274
|
-
repoRoot,
|
|
29275
|
-
repoKey: opaqueRepoKey("origin", normalizedOrigin),
|
|
29276
|
-
identitySource: "origin",
|
|
29277
|
-
repoFullName
|
|
29278
|
-
};
|
|
29279
|
-
}
|
|
29280
|
-
if (repoFullName) {
|
|
29281
|
-
return {
|
|
29282
|
-
repoRoot,
|
|
29283
|
-
repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
|
|
29284
|
-
identitySource: "declared",
|
|
29285
|
-
repoFullName
|
|
29286
|
-
};
|
|
29287
|
-
}
|
|
29288
|
-
const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
|
|
29289
|
-
if (roots && roots.length > 0) {
|
|
29290
|
-
return {
|
|
29291
|
-
repoRoot,
|
|
29292
|
-
repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
|
|
29293
|
-
identitySource: "root_commit",
|
|
29294
|
-
repoFullName
|
|
29295
|
-
};
|
|
29296
|
-
}
|
|
29297
|
-
return { repoRoot, repoFullName };
|
|
29298
|
-
}
|
|
29299
|
-
function nearestExistingAncestor(path) {
|
|
29300
|
-
const suffix = [];
|
|
29301
|
-
let cursor = path;
|
|
29302
|
-
while (true) {
|
|
29303
|
-
try {
|
|
29304
|
-
lstatSync6(cursor);
|
|
29305
|
-
break;
|
|
29306
|
-
} catch (error) {
|
|
29307
|
-
const code = typeof error === "object" && error !== null && "code" in error ? error.code : void 0;
|
|
29308
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") return null;
|
|
29309
|
-
const parent = dirname8(cursor);
|
|
29310
|
-
if (parent === cursor) return null;
|
|
29311
|
-
suffix.unshift(cursor.slice(parent.length + (parent.endsWith(sep) ? 0 : 1)));
|
|
29312
|
-
cursor = parent;
|
|
29313
|
-
}
|
|
29314
|
-
}
|
|
29315
|
-
try {
|
|
29316
|
-
return { real: realpathSync2.native(cursor), suffix };
|
|
29317
|
-
} catch {
|
|
29318
|
-
return null;
|
|
29319
|
-
}
|
|
29320
|
-
}
|
|
29321
|
-
function canonicalRepositoryPathScoped(filePath, context, baseDir) {
|
|
29322
|
-
if (!filePath || filePath !== filePath.trim() || filePath.includes("\0")) {
|
|
29323
|
-
return { ok: false, reason: "invalid_path" };
|
|
29324
|
-
}
|
|
29325
|
-
const absolute = resolve3(baseDir, filePath);
|
|
29326
|
-
const resolved = nearestExistingAncestor(absolute);
|
|
29327
|
-
if (!resolved) return { ok: false, reason: "invalid_path" };
|
|
29328
|
-
const target = resolve3(resolved.real, ...resolved.suffix);
|
|
29329
|
-
const rel = relative(context.repoRoot, target);
|
|
29330
|
-
if (!rel || rel === ".") return { ok: false, reason: "invalid_path" };
|
|
29331
|
-
if (isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
29332
|
-
return { ok: false, reason: "outside_repository" };
|
|
29333
|
-
}
|
|
29334
|
-
return { ok: true, file: sep === "/" ? rel : rel.split(sep).join("/") };
|
|
29335
|
-
}
|
|
29336
|
-
function canonicalRepositoryPathLegacy(filePath, cwd, repositoryRoot = canonicalGitRoot(cwd)) {
|
|
29337
|
-
if (!repositoryRoot || !filePath || [...filePath].some((char) => char < " " || char === "\x7F" || "~*?[]{}$`\\".includes(char)))
|
|
29338
|
-
return null;
|
|
29339
|
-
const absolute = resolve3(cwd, filePath);
|
|
29340
|
-
let target;
|
|
29341
|
-
try {
|
|
29342
|
-
const stat = lstatSync6(absolute);
|
|
29343
|
-
if (!stat.isFile() || stat.isSymbolicLink()) return null;
|
|
29344
|
-
target = realpathSync2.native(absolute);
|
|
29345
|
-
} catch (error) {
|
|
29346
|
-
if (!(error instanceof Error) || error.code !== "ENOENT") {
|
|
29347
|
-
return null;
|
|
29348
|
-
}
|
|
29349
|
-
try {
|
|
29350
|
-
const parent = realpathSync2.native(dirname8(absolute));
|
|
29351
|
-
if (!lstatSync6(parent).isDirectory()) return null;
|
|
29352
|
-
target = resolve3(parent, basename2(absolute));
|
|
29353
|
-
} catch {
|
|
29354
|
-
return null;
|
|
29355
|
-
}
|
|
29356
|
-
}
|
|
29357
|
-
const rel = relative(repositoryRoot, target);
|
|
29358
|
-
if (!rel || isAbsolute4(rel) || rel === ".." || rel.startsWith(`..${sep}`)) {
|
|
29359
|
-
return null;
|
|
29360
|
-
}
|
|
29361
|
-
return sep === "/" ? rel : rel.split(sep).join("/");
|
|
29362
|
-
}
|
|
29363
|
-
function canonicalRepositoryPath(filePath, contextOrCwd, baseDirOrRoot) {
|
|
29364
|
-
if (typeof contextOrCwd === "string") {
|
|
29365
|
-
return canonicalRepositoryPathLegacy(filePath, contextOrCwd, baseDirOrRoot);
|
|
29366
|
-
}
|
|
29367
|
-
return canonicalRepositoryPathScoped(
|
|
29368
|
-
filePath,
|
|
29369
|
-
contextOrCwd,
|
|
29370
|
-
baseDirOrRoot ?? contextOrCwd.repoRoot
|
|
29371
|
-
);
|
|
29372
|
-
}
|
|
29373
|
-
|
|
29374
30574
|
// src/lib/activation.ts
|
|
29375
30575
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
29376
30576
|
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
29377
30577
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
29378
30578
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
29379
30579
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
29380
|
-
var
|
|
30580
|
+
var GIT_TIMEOUT_MS4 = 1e3;
|
|
29381
30581
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
29382
30582
|
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
29383
30583
|
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
@@ -29387,7 +30587,7 @@ function repoActiveFlag(cwd, strict = false) {
|
|
|
29387
30587
|
cwd,
|
|
29388
30588
|
encoding: "utf-8",
|
|
29389
30589
|
stdio: ["ignore", "pipe", "ignore"],
|
|
29390
|
-
timeout:
|
|
30590
|
+
timeout: GIT_TIMEOUT_MS4
|
|
29391
30591
|
}).trim();
|
|
29392
30592
|
if (value === "true") return "true";
|
|
29393
30593
|
if (value === "false") return "false";
|
|
@@ -29408,7 +30608,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
29408
30608
|
cwd,
|
|
29409
30609
|
encoding: "utf-8",
|
|
29410
30610
|
stdio: ["ignore", "pipe", "ignore"],
|
|
29411
|
-
timeout:
|
|
30611
|
+
timeout: GIT_TIMEOUT_MS4
|
|
29412
30612
|
}).trim();
|
|
29413
30613
|
return value || void 0;
|
|
29414
30614
|
} catch {
|
|
@@ -29419,7 +30619,7 @@ function setLocalGitConfigValue(cwd, key, value) {
|
|
|
29419
30619
|
execFileSync4("git", ["config", "--local", key, value], {
|
|
29420
30620
|
cwd,
|
|
29421
30621
|
stdio: ["ignore", "ignore", "pipe"],
|
|
29422
|
-
timeout:
|
|
30622
|
+
timeout: GIT_TIMEOUT_MS4
|
|
29423
30623
|
});
|
|
29424
30624
|
}
|
|
29425
30625
|
function repoSyncId(cwd) {
|
|
@@ -29440,7 +30640,7 @@ function repositoryBindingState(cwd) {
|
|
|
29440
30640
|
function projectPrimInstallAt(root) {
|
|
29441
30641
|
if (root === null || root === homedir2()) return false;
|
|
29442
30642
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
29443
|
-
const path =
|
|
30643
|
+
const path = join16(root, rel);
|
|
29444
30644
|
if (existsSync11(path)) {
|
|
29445
30645
|
try {
|
|
29446
30646
|
const content2 = readFileSync12(path, "utf-8");
|
|
@@ -29555,14 +30755,14 @@ function publicDecisionResponse(value) {
|
|
|
29555
30755
|
}
|
|
29556
30756
|
|
|
29557
30757
|
// src/client.ts
|
|
29558
|
-
import { createHash as
|
|
29559
|
-
import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as
|
|
30758
|
+
import { createHash as createHash9 } from "crypto";
|
|
30759
|
+
import { chmodSync as chmodSync4, existsSync as existsSync12, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
|
|
29560
30760
|
import { dirname as dirname9 } from "path";
|
|
29561
30761
|
|
|
29562
30762
|
// src/daemon/client-instance-id.ts
|
|
29563
30763
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
29564
30764
|
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
29565
|
-
import { join as
|
|
30765
|
+
import { join as join17 } from "path";
|
|
29566
30766
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
29567
30767
|
var INSTANCE_FILE_MODE = 384;
|
|
29568
30768
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -29613,8 +30813,8 @@ function atomicWrite(path, value) {
|
|
|
29613
30813
|
}
|
|
29614
30814
|
async function getOrCreateClientInstanceId(options) {
|
|
29615
30815
|
const configDir = options.configDir;
|
|
29616
|
-
const path =
|
|
29617
|
-
const lockPath =
|
|
30816
|
+
const path = join17(configDir, "client_instance_id");
|
|
30817
|
+
const lockPath = join17(configDir, "client-instance.lock");
|
|
29618
30818
|
ensurePrivateConfigDirectory(configDir);
|
|
29619
30819
|
return withFileLock(
|
|
29620
30820
|
lockPath,
|
|
@@ -29658,53 +30858,11 @@ async function ingestUploaderHeaders() {
|
|
|
29658
30858
|
return headers;
|
|
29659
30859
|
}
|
|
29660
30860
|
|
|
29661
|
-
// src/lib/terminal-safe.ts
|
|
29662
|
-
function replaceIsolatedSurrogates(value) {
|
|
29663
|
-
let out = "";
|
|
29664
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
29665
|
-
const unit = value.charCodeAt(index);
|
|
29666
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
29667
|
-
const next = value.charCodeAt(index + 1);
|
|
29668
|
-
if (next >= 56320 && next <= 57343) {
|
|
29669
|
-
out += value[index] + value[index + 1];
|
|
29670
|
-
index += 1;
|
|
29671
|
-
} else {
|
|
29672
|
-
out += "\uFFFD";
|
|
29673
|
-
}
|
|
29674
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
29675
|
-
out += "\uFFFD";
|
|
29676
|
-
} else {
|
|
29677
|
-
out += value[index];
|
|
29678
|
-
}
|
|
29679
|
-
}
|
|
29680
|
-
return out;
|
|
29681
|
-
}
|
|
29682
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
29683
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
29684
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
29685
|
-
point === 1564 || // Arabic letter mark
|
|
29686
|
-
point === 6158 || // Mongolian vowel separator
|
|
29687
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
29688
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
29689
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
29690
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
29691
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
29692
|
-
point >= 917504 && point <= 917631;
|
|
29693
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
29694
|
-
}
|
|
29695
|
-
function terminalSafeText(value) {
|
|
29696
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
29697
|
-
}
|
|
29698
|
-
function terminalSafeLine(value) {
|
|
29699
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
29700
|
-
}
|
|
29701
|
-
var stripControlChars = terminalSafeText;
|
|
29702
|
-
|
|
29703
30861
|
// src/client.ts
|
|
29704
30862
|
var CONFIG_DIR_MODE = 448;
|
|
29705
30863
|
var CREDENTIAL_FILE_MODE = 384;
|
|
29706
30864
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
29707
|
-
var
|
|
30865
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
29708
30866
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
29709
30867
|
function authExpiredMessage() {
|
|
29710
30868
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
@@ -29721,7 +30879,7 @@ function getSiteUrl() {
|
|
|
29721
30879
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
29722
30880
|
}
|
|
29723
30881
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
29724
|
-
return primApiUrl?.trim() ||
|
|
30882
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
29725
30883
|
}
|
|
29726
30884
|
function expiresAtFor(token, expiresIn) {
|
|
29727
30885
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
@@ -29737,7 +30895,7 @@ function atomicWrite2(path, content2) {
|
|
|
29737
30895
|
}
|
|
29738
30896
|
function removeCredentialFile(path) {
|
|
29739
30897
|
if (!existsSync12(path)) return false;
|
|
29740
|
-
|
|
30898
|
+
rmSync9(path, { force: true });
|
|
29741
30899
|
return true;
|
|
29742
30900
|
}
|
|
29743
30901
|
function getTokenExpiresAt() {
|
|
@@ -29752,23 +30910,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
29752
30910
|
const expiresAt = getTokenExpiresAt();
|
|
29753
30911
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
29754
30912
|
}
|
|
29755
|
-
function refreshFingerprint(
|
|
29756
|
-
return
|
|
30913
|
+
function refreshFingerprint(refreshToken3) {
|
|
30914
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
29757
30915
|
}
|
|
29758
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
30916
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
29759
30917
|
return {
|
|
29760
30918
|
version: 1,
|
|
29761
30919
|
family: "legacy_broker",
|
|
29762
30920
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29763
|
-
refreshTokenHash: refreshFingerprint(
|
|
30921
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29764
30922
|
};
|
|
29765
30923
|
}
|
|
29766
|
-
function credentialFamilyMetadata(accessToken,
|
|
30924
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
29767
30925
|
const hashes = {
|
|
29768
30926
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
29769
|
-
refreshTokenHash: refreshFingerprint(
|
|
30927
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
29770
30928
|
};
|
|
29771
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
30929
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
29772
30930
|
}
|
|
29773
30931
|
function writeCredentialMigrationSentinel() {
|
|
29774
30932
|
atomicWrite2(
|
|
@@ -29780,11 +30938,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
29780
30938
|
`
|
|
29781
30939
|
);
|
|
29782
30940
|
}
|
|
29783
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
29784
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
30941
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
30942
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
29785
30943
|
return { state: "invalid" };
|
|
29786
30944
|
}
|
|
29787
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30945
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29788
30946
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
29789
30947
|
return { state: "invalid" };
|
|
29790
30948
|
}
|
|
@@ -29801,17 +30959,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
29801
30959
|
const metadata = readStoredCredentialMetadata();
|
|
29802
30960
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
29803
30961
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
29804
|
-
const
|
|
29805
|
-
if (!(accessToken &&
|
|
29806
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
30962
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
30963
|
+
if (!(accessToken && refreshToken3)) return;
|
|
30964
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
29807
30965
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29808
30966
|
`);
|
|
29809
30967
|
}
|
|
29810
30968
|
function terminalFingerprint() {
|
|
29811
30969
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
29812
30970
|
}
|
|
29813
|
-
function writeTerminalFingerprint(
|
|
29814
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
30971
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
30972
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
29815
30973
|
`);
|
|
29816
30974
|
}
|
|
29817
30975
|
function clearTerminalFingerprint() {
|
|
@@ -29820,20 +30978,20 @@ function clearTerminalFingerprint() {
|
|
|
29820
30978
|
function isSessionEnded() {
|
|
29821
30979
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
29822
30980
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
29823
|
-
const
|
|
30981
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
29824
30982
|
const ended = terminalFingerprint();
|
|
29825
|
-
return Boolean(
|
|
30983
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
29826
30984
|
}
|
|
29827
30985
|
function withCredentialLock(operation, options = {}) {
|
|
29828
30986
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
29829
30987
|
}
|
|
29830
30988
|
function commitCredentialsUnlocked(credentials) {
|
|
29831
30989
|
const accessToken = credentials.accessToken.trim();
|
|
29832
|
-
const
|
|
29833
|
-
if (!accessToken || !
|
|
30990
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
30991
|
+
if (!accessToken || !refreshToken3) {
|
|
29834
30992
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
29835
30993
|
}
|
|
29836
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
30994
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
29837
30995
|
if (credentials.metadata !== void 0) {
|
|
29838
30996
|
preserveMarkerlessLegacyGeneration();
|
|
29839
30997
|
writeCredentialMigrationSentinel();
|
|
@@ -29841,10 +30999,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
29841
30999
|
`);
|
|
29842
31000
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
29843
31001
|
`);
|
|
29844
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
31002
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29845
31003
|
`);
|
|
29846
31004
|
} else {
|
|
29847
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
31005
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
29848
31006
|
`);
|
|
29849
31007
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
29850
31008
|
`);
|
|
@@ -29881,15 +31039,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
29881
31039
|
`
|
|
29882
31040
|
);
|
|
29883
31041
|
}
|
|
29884
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
31042
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
29885
31043
|
const current = readStoredCredentialMetadata();
|
|
29886
31044
|
if (expected.state === "legacy_broker") {
|
|
29887
31045
|
if (current.state !== "legacy_broker") return false;
|
|
29888
31046
|
if (!expected.metadata) return current.metadata === void 0;
|
|
29889
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
31047
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
29890
31048
|
}
|
|
29891
31049
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
29892
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
31050
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
29893
31051
|
}
|
|
29894
31052
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
29895
31053
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -30058,7 +31216,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
30058
31216
|
);
|
|
30059
31217
|
}
|
|
30060
31218
|
var _refreshInFlight;
|
|
30061
|
-
function
|
|
31219
|
+
function refreshToken2(options = {}) {
|
|
30062
31220
|
if (hasMachineConfiguration())
|
|
30063
31221
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
30064
31222
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -30196,7 +31354,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
30196
31354
|
if (response.status === 401)
|
|
30197
31355
|
throw new HttpError(
|
|
30198
31356
|
401,
|
|
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(
|
|
31357
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
30200
31358
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
30201
31359
|
)
|
|
30202
31360
|
);
|
|
@@ -30217,7 +31375,7 @@ async function request2(method, path, body, options) {
|
|
|
30217
31375
|
let refreshAttempted = false;
|
|
30218
31376
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
30219
31377
|
refreshAttempted = true;
|
|
30220
|
-
const token = await
|
|
31378
|
+
const token = await refreshToken2({
|
|
30221
31379
|
signal: options?.signal,
|
|
30222
31380
|
quiet: options?.quietRefresh
|
|
30223
31381
|
});
|
|
@@ -30236,7 +31394,7 @@ async function request2(method, path, body, options) {
|
|
|
30236
31394
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
30237
31395
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
30238
31396
|
refreshAttempted = true;
|
|
30239
|
-
retryToken = await
|
|
31397
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
30240
31398
|
}
|
|
30241
31399
|
if (retryToken) {
|
|
30242
31400
|
_cachedCredential = {
|
|
@@ -30260,7 +31418,7 @@ async function getPinnedClient(options = {}) {
|
|
|
30260
31418
|
const siteUrl = getSiteUrl();
|
|
30261
31419
|
let credential = selectedCredential();
|
|
30262
31420
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
30263
|
-
const token2 = await
|
|
31421
|
+
const token2 = await refreshToken2({
|
|
30264
31422
|
signal: options.signal,
|
|
30265
31423
|
quiet: options.quietRefresh
|
|
30266
31424
|
});
|
|
@@ -30648,8 +31806,8 @@ import {
|
|
|
30648
31806
|
unlinkSync,
|
|
30649
31807
|
writeFileSync as writeFileSync6
|
|
30650
31808
|
} from "fs";
|
|
30651
|
-
import { dirname as dirname10, isAbsolute as isAbsolute5, join as
|
|
30652
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
31809
|
+
import { dirname as dirname10, isAbsolute as isAbsolute5, join as join19, resolve as resolve5 } from "path";
|
|
31810
|
+
var WORKSPACE_ID_RELATIVE_PATH = join19("prim", "workspace-id");
|
|
30653
31811
|
var MAX_ANCESTORS = 64;
|
|
30654
31812
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
30655
31813
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -30708,11 +31866,11 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
30708
31866
|
function resolveFromFilesystem(cwd) {
|
|
30709
31867
|
let current = resolve5(cwd);
|
|
30710
31868
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
30711
|
-
const dotGit =
|
|
31869
|
+
const dotGit = join19(current, ".git");
|
|
30712
31870
|
try {
|
|
30713
31871
|
const stat = lstatSync8(dotGit);
|
|
30714
31872
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
30715
|
-
return
|
|
31873
|
+
return join19(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
30716
31874
|
}
|
|
30717
31875
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
30718
31876
|
const contents = readFileSync15(dotGit, "utf8");
|
|
@@ -30720,7 +31878,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
30720
31878
|
if (match?.[1]) {
|
|
30721
31879
|
const gitDirectory = isAbsolute5(match[1]) ? resolve5(match[1]) : resolve5(current, match[1]);
|
|
30722
31880
|
if (isGitDirectory(gitDirectory)) {
|
|
30723
|
-
return
|
|
31881
|
+
return join19(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
30724
31882
|
}
|
|
30725
31883
|
}
|
|
30726
31884
|
}
|
|
@@ -30739,7 +31897,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
30739
31897
|
}
|
|
30740
31898
|
function isGitDirectory(path) {
|
|
30741
31899
|
try {
|
|
30742
|
-
return statSync3(
|
|
31900
|
+
return statSync3(join19(path, "HEAD")).isFile();
|
|
30743
31901
|
} catch {
|
|
30744
31902
|
return false;
|
|
30745
31903
|
}
|
|
@@ -30777,7 +31935,7 @@ function inspectPath(path) {
|
|
|
30777
31935
|
function createWorkspaceId(path) {
|
|
30778
31936
|
const parent = dirname10(path);
|
|
30779
31937
|
const workspaceId = randomUUID4();
|
|
30780
|
-
const temporaryPath =
|
|
31938
|
+
const temporaryPath = join19(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
30781
31939
|
let temporaryCreated = false;
|
|
30782
31940
|
let publishing = false;
|
|
30783
31941
|
try {
|
|
@@ -30847,7 +32005,7 @@ function parseAgent(argv) {
|
|
|
30847
32005
|
}
|
|
30848
32006
|
|
|
30849
32007
|
// src/hooks/codex-context.ts
|
|
30850
|
-
import { createHash as
|
|
32008
|
+
import { createHash as createHash11, randomBytes as randomBytes7 } from "crypto";
|
|
30851
32009
|
import {
|
|
30852
32010
|
chmodSync as chmodSync6,
|
|
30853
32011
|
existsSync as existsSync13,
|
|
@@ -30855,31 +32013,31 @@ import {
|
|
|
30855
32013
|
readFileSync as readFileSync16,
|
|
30856
32014
|
readdirSync as readdirSync4,
|
|
30857
32015
|
renameSync as renameSync3,
|
|
30858
|
-
rmSync as
|
|
32016
|
+
rmSync as rmSync10,
|
|
30859
32017
|
statSync as statSync4,
|
|
30860
32018
|
unlinkSync as unlinkSync2,
|
|
30861
32019
|
writeFileSync as writeFileSync7
|
|
30862
32020
|
} from "fs";
|
|
30863
|
-
import { join as
|
|
32021
|
+
import { join as join21 } from "path";
|
|
30864
32022
|
|
|
30865
32023
|
// src/daemon/principal.ts
|
|
30866
|
-
import { createHash as
|
|
32024
|
+
import { createHash as createHash10 } from "crypto";
|
|
30867
32025
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
30868
32026
|
function boundedClaim(value) {
|
|
30869
32027
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
30870
32028
|
}
|
|
30871
|
-
function
|
|
30872
|
-
return
|
|
32029
|
+
function sha2562(value) {
|
|
32030
|
+
return createHash10("sha256").update(value).digest("hex");
|
|
30873
32031
|
}
|
|
30874
32032
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
30875
32033
|
if (hasMachineConfiguration()) {
|
|
30876
32034
|
const machine = machineContext();
|
|
30877
32035
|
return machine ? {
|
|
30878
|
-
principalId:
|
|
32036
|
+
principalId: sha2562(
|
|
30879
32037
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
30880
32038
|
),
|
|
30881
32039
|
organizationId: machine.workosOrganizationId,
|
|
30882
|
-
credentialFingerprint:
|
|
32040
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
30883
32041
|
} : void 0;
|
|
30884
32042
|
}
|
|
30885
32043
|
if (!token) return void 0;
|
|
@@ -30889,9 +32047,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
30889
32047
|
if (!(subject && organizationId)) return void 0;
|
|
30890
32048
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
30891
32049
|
return {
|
|
30892
|
-
principalId:
|
|
32050
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
30893
32051
|
organizationId,
|
|
30894
|
-
credentialFingerprint:
|
|
32052
|
+
credentialFingerprint: sha2562(token)
|
|
30895
32053
|
};
|
|
30896
32054
|
}
|
|
30897
32055
|
function daemonPrincipalsMatch(caller, daemon) {
|
|
@@ -30923,8 +32081,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
30923
32081
|
|
|
30924
32082
|
// src/daemon/client.ts
|
|
30925
32083
|
import { createConnection } from "net";
|
|
30926
|
-
import { join as
|
|
30927
|
-
var SOCK_PATH =
|
|
32084
|
+
import { join as join20 } from "path";
|
|
32085
|
+
var SOCK_PATH = join20(primConfigDirectory(), "sock");
|
|
30928
32086
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
30929
32087
|
var nextRequestId = 1;
|
|
30930
32088
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -31227,10 +32385,10 @@ function appendCodexContext(output, context) {
|
|
|
31227
32385
|
return next;
|
|
31228
32386
|
}
|
|
31229
32387
|
function stateRoot(namespace) {
|
|
31230
|
-
return
|
|
32388
|
+
return join21(primConfigDirectory(), namespace, "decision-digests");
|
|
31231
32389
|
}
|
|
31232
32390
|
function draftStateRoot(namespace) {
|
|
31233
|
-
return
|
|
32391
|
+
return join21(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
31234
32392
|
}
|
|
31235
32393
|
function workspaceFor(cwd) {
|
|
31236
32394
|
try {
|
|
@@ -31241,13 +32399,13 @@ function workspaceFor(cwd) {
|
|
|
31241
32399
|
}
|
|
31242
32400
|
function statePath(args) {
|
|
31243
32401
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
31244
|
-
const key =
|
|
31245
|
-
return
|
|
32402
|
+
const key = createHash11("sha256").update(identity).digest("hex");
|
|
32403
|
+
return join21(stateRoot(args.namespace), `${key}.json`);
|
|
31246
32404
|
}
|
|
31247
32405
|
function draftStatePath(args) {
|
|
31248
32406
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
31249
|
-
const key =
|
|
31250
|
-
return
|
|
32407
|
+
const key = createHash11("sha256").update(identity).digest("hex");
|
|
32408
|
+
return join21(draftStateRoot(args.namespace), `${key}.json`);
|
|
31251
32409
|
}
|
|
31252
32410
|
function parseState(value) {
|
|
31253
32411
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -31285,7 +32443,7 @@ function parseDraftState(value) {
|
|
|
31285
32443
|
updatedAt: record.updatedAt
|
|
31286
32444
|
};
|
|
31287
32445
|
}
|
|
31288
|
-
function
|
|
32446
|
+
function readState2(path) {
|
|
31289
32447
|
if (!existsSync13(path)) return void 0;
|
|
31290
32448
|
try {
|
|
31291
32449
|
return parseState(JSON.parse(readFileSync16(path, "utf8")));
|
|
@@ -31304,7 +32462,7 @@ function readDraftState(path) {
|
|
|
31304
32462
|
function writeStateFile(path, directory, state) {
|
|
31305
32463
|
mkdirSync8(directory, { recursive: true, mode: 448 });
|
|
31306
32464
|
chmodSync6(directory, 448);
|
|
31307
|
-
const temporary =
|
|
32465
|
+
const temporary = join21(
|
|
31308
32466
|
directory,
|
|
31309
32467
|
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
31310
32468
|
);
|
|
@@ -31335,7 +32493,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
31335
32493
|
const files = [];
|
|
31336
32494
|
const residue = [];
|
|
31337
32495
|
for (const name2 of names) {
|
|
31338
|
-
const path =
|
|
32496
|
+
const path = join21(directory, name2);
|
|
31339
32497
|
try {
|
|
31340
32498
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
31341
32499
|
if (name2.endsWith(".json")) {
|
|
@@ -31357,7 +32515,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
31357
32515
|
for (const path of residue) {
|
|
31358
32516
|
try {
|
|
31359
32517
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
31360
|
-
|
|
32518
|
+
rmSync10(path, { recursive: true, force: true });
|
|
31361
32519
|
}
|
|
31362
32520
|
} catch {
|
|
31363
32521
|
}
|
|
@@ -31443,7 +32601,7 @@ async function commitState(path, args, namespace) {
|
|
|
31443
32601
|
await withFileLock(
|
|
31444
32602
|
`${path}.lock`,
|
|
31445
32603
|
() => {
|
|
31446
|
-
const latest =
|
|
32604
|
+
const latest = readState2(path);
|
|
31447
32605
|
writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
|
|
31448
32606
|
cleanupStateFiles(stateRoot(namespace), args.now);
|
|
31449
32607
|
},
|
|
@@ -31490,7 +32648,7 @@ async function prepareCodexContext(options) {
|
|
|
31490
32648
|
const siteUrl = getSiteUrl();
|
|
31491
32649
|
const workspace = workspaceFor(options.cwd);
|
|
31492
32650
|
const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
|
|
31493
|
-
const previous =
|
|
32651
|
+
const previous = readState2(path);
|
|
31494
32652
|
const principal = resolveDaemonPrincipal();
|
|
31495
32653
|
const privatePath = principal ? draftStatePath({
|
|
31496
32654
|
cwd: options.cwd,
|
|
@@ -31642,7 +32800,7 @@ async function prepareCodexContext(options) {
|
|
|
31642
32800
|
// src/commands/cursor-install.ts
|
|
31643
32801
|
import { existsSync as existsSync15, readFileSync as readFileSync18 } from "fs";
|
|
31644
32802
|
import { homedir as homedir4 } from "os";
|
|
31645
|
-
import { isAbsolute as isAbsolute6, join as
|
|
32803
|
+
import { isAbsolute as isAbsolute6, join as join23 } from "path";
|
|
31646
32804
|
|
|
31647
32805
|
// src/lib/preflight-host.ts
|
|
31648
32806
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
@@ -31650,7 +32808,7 @@ import { execFileSync as execFileSync6 } from "child_process";
|
|
|
31650
32808
|
// src/commands/claude-install.ts
|
|
31651
32809
|
import { existsSync as existsSync14, lstatSync as lstatSync9, readFileSync as readFileSync17 } from "fs";
|
|
31652
32810
|
import { homedir as homedir3 } from "os";
|
|
31653
|
-
import { join as
|
|
32811
|
+
import { join as join22 } from "path";
|
|
31654
32812
|
var CAPTURE_BIN = "prim-hook";
|
|
31655
32813
|
var GATE_BIN = "prim-pre-tool-use";
|
|
31656
32814
|
var POST_TOOL_USE_BIN = "prim-post-tool-use";
|
|
@@ -31659,7 +32817,7 @@ var SESSION_END_BIN = "prim-session-end";
|
|
|
31659
32817
|
var STATUSLINE_BIN = "prim-statusline";
|
|
31660
32818
|
var STATUSLINE_ARGS = "";
|
|
31661
32819
|
var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
|
|
31662
|
-
var USER_SCOPE_PATH =
|
|
32820
|
+
var USER_SCOPE_PATH = join22(homedir3(), ".claude", "settings.json");
|
|
31663
32821
|
function projectRoot() {
|
|
31664
32822
|
return gitToplevel() ?? process.cwd();
|
|
31665
32823
|
}
|
|
@@ -31739,11 +32897,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform2 =
|
|
|
31739
32897
|
const explicit = env.CURSOR_CONFIG_DIR?.trim();
|
|
31740
32898
|
if (explicit && isAbsolute6(explicit)) return explicit;
|
|
31741
32899
|
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
31742
|
-
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return
|
|
31743
|
-
return
|
|
32900
|
+
if (platform2 !== "darwin" && xdg && isAbsolute6(xdg)) return join23(xdg, "cursor");
|
|
32901
|
+
return join23(home, ".cursor");
|
|
31744
32902
|
}
|
|
31745
32903
|
function cursorHooksPath(scope, root = projectRoot()) {
|
|
31746
|
-
return scope === "user" ?
|
|
32904
|
+
return scope === "user" ? join23(cursorConfigDirectory(), "hooks.json") : join23(root, ".cursor", "hooks.json");
|
|
31747
32905
|
}
|
|
31748
32906
|
function plainObject(value) {
|
|
31749
32907
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
@@ -31974,7 +33132,7 @@ function extractFileTargets(toolName, toolInput, agent = "claude_code") {
|
|
|
31974
33132
|
|
|
31975
33133
|
// src/hooks/redact.ts
|
|
31976
33134
|
import { existsSync as existsSync16, readFileSync as readFileSync19, statSync as statSync5 } from "fs";
|
|
31977
|
-
import { join as
|
|
33135
|
+
import { join as join24 } from "path";
|
|
31978
33136
|
import { Worker } from "worker_threads";
|
|
31979
33137
|
var USER_HOME_RULES = [
|
|
31980
33138
|
{
|
|
@@ -32055,7 +33213,7 @@ function normalizedWorkspaceFlags(value) {
|
|
|
32055
33213
|
return [...new Set(`g${requested}`)].sort().join("");
|
|
32056
33214
|
}
|
|
32057
33215
|
function loadWorkspaceRules(cwd) {
|
|
32058
|
-
const path =
|
|
33216
|
+
const path = join24(cwd, WORKSPACE_FILE2);
|
|
32059
33217
|
if (!existsSync16(path)) return [];
|
|
32060
33218
|
let cfg;
|
|
32061
33219
|
try {
|
|
@@ -38419,7 +39577,7 @@ var TokenGroup = class {
|
|
|
38419
39577
|
}
|
|
38420
39578
|
token(input, stack) {
|
|
38421
39579
|
let { parser: parser3 } = stack.p;
|
|
38422
|
-
|
|
39580
|
+
readToken2(this.data, input, stack, this.id, parser3.data, parser3.tokenPrecTable);
|
|
38423
39581
|
}
|
|
38424
39582
|
};
|
|
38425
39583
|
TokenGroup.prototype.contextual = TokenGroup.prototype.fallback = TokenGroup.prototype.extend = false;
|
|
@@ -38433,7 +39591,7 @@ var LocalTokenGroup = class {
|
|
|
38433
39591
|
let start = input.pos, skipped = 0;
|
|
38434
39592
|
for (; ; ) {
|
|
38435
39593
|
let atEof = input.next < 0, nextPos = input.resolveOffset(1, 1);
|
|
38436
|
-
|
|
39594
|
+
readToken2(this.data, input, stack, 0, this.data, this.precTable);
|
|
38437
39595
|
if (input.token.value > -1)
|
|
38438
39596
|
break;
|
|
38439
39597
|
if (this.elseToken == null)
|
|
@@ -38466,7 +39624,7 @@ var ExternalTokenizer = class {
|
|
|
38466
39624
|
this.extend = !!options.extend;
|
|
38467
39625
|
}
|
|
38468
39626
|
};
|
|
38469
|
-
function
|
|
39627
|
+
function readToken2(data, input, stack, group, precTable, precOffset) {
|
|
38470
39628
|
let state = 0, groupMask = 1 << group, { dialect } = stack.p.parser;
|
|
38471
39629
|
scan: for (; ; ) {
|
|
38472
39630
|
if ((groupMask & data[state]) == 0)
|
|
@@ -40279,7 +41437,7 @@ var newline2 = 10;
|
|
|
40279
41437
|
var carriageReturn = 13;
|
|
40280
41438
|
var space2 = 32;
|
|
40281
41439
|
var tab = 9;
|
|
40282
|
-
var
|
|
41440
|
+
var hash3 = 35;
|
|
40283
41441
|
var parenOpen = 40;
|
|
40284
41442
|
var dot2 = 46;
|
|
40285
41443
|
var braceOpen = 123;
|
|
@@ -40332,7 +41490,7 @@ var newlines = new ExternalTokenizer((input, stack) => {
|
|
|
40332
41490
|
input.advance();
|
|
40333
41491
|
spaces2++;
|
|
40334
41492
|
}
|
|
40335
|
-
if (input.next == newline2 || input.next == carriageReturn || input.next ==
|
|
41493
|
+
if (input.next == newline2 || input.next == carriageReturn || input.next == hash3)
|
|
40336
41494
|
input.acceptToken(blankLineStart, -spaces2);
|
|
40337
41495
|
} else if (isLineBreak(input.next)) {
|
|
40338
41496
|
input.acceptToken(newline$1, 1);
|
|
@@ -40351,7 +41509,7 @@ var indentation = new ExternalTokenizer((input, stack) => {
|
|
|
40351
41509
|
input.advance();
|
|
40352
41510
|
chars++;
|
|
40353
41511
|
}
|
|
40354
|
-
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next !=
|
|
41512
|
+
if (depth != context.indent && input.next != newline2 && input.next != carriageReturn && input.next != hash3) {
|
|
40355
41513
|
if (depth < context.indent) input.acceptToken(dedent, -chars);
|
|
40356
41514
|
else input.acceptToken(indent);
|
|
40357
41515
|
}
|
|
@@ -40425,7 +41583,7 @@ var legacyPrint = new ExternalTokenizer((input) => {
|
|
|
40425
41583
|
for (let off = 0; ; off++) {
|
|
40426
41584
|
let next = input.peek(off);
|
|
40427
41585
|
if (next == space2 || next == tab) continue;
|
|
40428
|
-
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next !=
|
|
41586
|
+
if (next != parenOpen && next != dot2 && next != newline2 && next != carriageReturn && next != hash3)
|
|
40429
41587
|
input.acceptToken(printKeyword);
|
|
40430
41588
|
return;
|
|
40431
41589
|
}
|
|
@@ -41636,7 +42794,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
|
|
|
41636
42794
|
}
|
|
41637
42795
|
|
|
41638
42796
|
// src/hooks/normalize.ts
|
|
41639
|
-
import { createHash as
|
|
42797
|
+
import { createHash as createHash12 } from "crypto";
|
|
41640
42798
|
import { realpathSync as realpathSync4 } from "fs";
|
|
41641
42799
|
import { isAbsolute as isAbsolute8, resolve as resolve7 } from "path";
|
|
41642
42800
|
var HERMES_EVENT_MAP = {
|
|
@@ -41681,7 +42839,7 @@ function requiredId(value, field) {
|
|
|
41681
42839
|
}
|
|
41682
42840
|
function cursorToolUseId(value) {
|
|
41683
42841
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
41684
|
-
return `cursor:tool:v1:${
|
|
42842
|
+
return `cursor:tool:v1:${createHash12("sha256").update(value).digest("hex")}`;
|
|
41685
42843
|
}
|
|
41686
42844
|
function workspaceCandidates(value) {
|
|
41687
42845
|
if (!Array.isArray(value)) return [];
|
|
@@ -41778,7 +42936,7 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
41778
42936
|
]);
|
|
41779
42937
|
return {
|
|
41780
42938
|
...parsed,
|
|
41781
|
-
tool_use_id: `codex:fallback:v1:${
|
|
42939
|
+
tool_use_id: `codex:fallback:v1:${createHash12("sha256").update(stableToolIdentity).digest("hex")}`
|
|
41782
42940
|
};
|
|
41783
42941
|
}
|
|
41784
42942
|
return parsed;
|
|
@@ -41922,7 +43080,7 @@ import {
|
|
|
41922
43080
|
readSync,
|
|
41923
43081
|
readdirSync as readdirSync6
|
|
41924
43082
|
} from "fs";
|
|
41925
|
-
import { dirname as dirname13, join as
|
|
43083
|
+
import { dirname as dirname13, join as join26 } from "path";
|
|
41926
43084
|
|
|
41927
43085
|
// src/drain-progress.ts
|
|
41928
43086
|
import {
|
|
@@ -41930,13 +43088,13 @@ import {
|
|
|
41930
43088
|
existsSync as existsSync17,
|
|
41931
43089
|
readFileSync as readFileSync20,
|
|
41932
43090
|
readdirSync as readdirSync5,
|
|
41933
|
-
rmSync as
|
|
43091
|
+
rmSync as rmSync11,
|
|
41934
43092
|
rmdirSync
|
|
41935
43093
|
} from "fs";
|
|
41936
|
-
import { basename as basename3, dirname as dirname12, join as
|
|
43094
|
+
import { basename as basename3, dirname as dirname12, join as join25 } from "path";
|
|
41937
43095
|
|
|
41938
43096
|
// src/journal.ts
|
|
41939
|
-
var JOURNAL_DIR =
|
|
43097
|
+
var JOURNAL_DIR = join26(primConfigDirectory(), "moves");
|
|
41940
43098
|
var UNBOUND_BUCKET = "_unbound";
|
|
41941
43099
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
41942
43100
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
@@ -41948,7 +43106,7 @@ function envSlug(apiUrl) {
|
|
|
41948
43106
|
return slug;
|
|
41949
43107
|
}
|
|
41950
43108
|
function currentEnvDir() {
|
|
41951
|
-
return
|
|
43109
|
+
return join26(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
41952
43110
|
}
|
|
41953
43111
|
var DIR_MODE = 448;
|
|
41954
43112
|
var FILE_MODE2 = 384;
|
|
@@ -41964,10 +43122,10 @@ function appendMoveToPath(path, move) {
|
|
|
41964
43122
|
}
|
|
41965
43123
|
function bucketDir(orgId) {
|
|
41966
43124
|
const safe = orgId !== void 0 && SAFE_BUCKET.test(orgId) && !RESERVED_BUCKETS.has(orgId);
|
|
41967
|
-
return
|
|
43125
|
+
return join26(currentEnvDir(), safe ? orgId : UNBOUND_BUCKET);
|
|
41968
43126
|
}
|
|
41969
43127
|
function journalPath(orgId) {
|
|
41970
|
-
return
|
|
43128
|
+
return join26(bucketDir(orgId), JOURNAL_BASENAME);
|
|
41971
43129
|
}
|
|
41972
43130
|
function appendMove(move, orgId) {
|
|
41973
43131
|
const actor = machineCaptureActor();
|
|
@@ -41997,7 +43155,7 @@ async function deliverPostToolMove(move, orgId) {
|
|
|
41997
43155
|
}
|
|
41998
43156
|
|
|
41999
43157
|
// src/hooks/prim-hook-core.ts
|
|
42000
|
-
import { createHash as
|
|
43158
|
+
import { createHash as createHash13, randomUUID as randomUUID5 } from "crypto";
|
|
42001
43159
|
import { platform } from "os";
|
|
42002
43160
|
|
|
42003
43161
|
// src/protocol/move.ts
|
|
@@ -42071,9 +43229,9 @@ function toMove(parsed, cliVersion, agent = "claude_code", workspaceId, reposito
|
|
|
42071
43229
|
const toolOutcome = toolOutcomeFor(parsed, agent);
|
|
42072
43230
|
let moveId;
|
|
42073
43231
|
if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && invocationId) {
|
|
42074
|
-
moveId = `posttool:v1:${
|
|
43232
|
+
moveId = `posttool:v1:${createHash13("sha256").update(JSON.stringify([agent, sessionId, eventType, invocationId])).digest("hex")}`;
|
|
42075
43233
|
} else if (CORRELATED_TOOL_EVENTS.has(eventType) && sessionId && agent !== "cursor") {
|
|
42076
|
-
moveId = `posttool:fallback:v1:${
|
|
43234
|
+
moveId = `posttool:fallback:v1:${createHash13("sha256").update(
|
|
42077
43235
|
JSON.stringify([
|
|
42078
43236
|
agent,
|
|
42079
43237
|
sessionId,
|
|
@@ -42149,7 +43307,7 @@ function editingToolsFor(agent) {
|
|
|
42149
43307
|
var here = dirname14(fileURLToPath5(import.meta.url));
|
|
42150
43308
|
function resolveCliVersion() {
|
|
42151
43309
|
try {
|
|
42152
|
-
const pkg = JSON.parse(readFileSync22(
|
|
43310
|
+
const pkg = JSON.parse(readFileSync22(join27(here, "..", "..", "package.json"), "utf-8"));
|
|
42153
43311
|
return pkg.version ?? "unknown";
|
|
42154
43312
|
} catch {
|
|
42155
43313
|
return "unknown";
|