@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
package/dist/daemon/server.js
CHANGED
|
@@ -53,11 +53,11 @@ var require_ucs2length = __commonJS({
|
|
|
53
53
|
|
|
54
54
|
// src/lib/machine-broker.ts
|
|
55
55
|
import { spawn } from "child_process";
|
|
56
|
-
import { createHash as
|
|
57
|
-
import { lstatSync as
|
|
56
|
+
import { createHash as createHash6, createHmac, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
57
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync7, rmSync as rmSync7 } from "fs";
|
|
58
58
|
import { createServer } from "http";
|
|
59
|
-
import { basename, join as
|
|
60
|
-
import { fileURLToPath as
|
|
59
|
+
import { basename as basename2, join as join10 } from "path";
|
|
60
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
61
61
|
|
|
62
62
|
// src/lib/atomic-file.ts
|
|
63
63
|
import { randomUUID } from "crypto";
|
|
@@ -142,8 +142,48 @@ function atomicWriteFile(target, content, options = {}) {
|
|
|
142
142
|
import { existsSync, readFileSync } from "fs";
|
|
143
143
|
import { dirname as dirname2, isAbsolute, join } from "path";
|
|
144
144
|
import { fileURLToPath } from "url";
|
|
145
|
+
|
|
146
|
+
// src/lib/semver.ts
|
|
147
|
+
function parseSemver(value) {
|
|
148
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
149
|
+
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(
|
|
150
|
+
value
|
|
151
|
+
);
|
|
152
|
+
if (!match) return;
|
|
153
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
154
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
158
|
+
}
|
|
159
|
+
function compareSemver(left, right) {
|
|
160
|
+
const a = parseSemver(left);
|
|
161
|
+
const b = parseSemver(right);
|
|
162
|
+
if (!a || !b) return;
|
|
163
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
164
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
165
|
+
}
|
|
166
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
167
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
168
|
+
}
|
|
169
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
170
|
+
const x = a.prerelease[i];
|
|
171
|
+
const y = b.prerelease[i];
|
|
172
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
173
|
+
if (x === y) continue;
|
|
174
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
175
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
176
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
177
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
178
|
+
return x < y ? -1 : 1;
|
|
179
|
+
}
|
|
180
|
+
return 0;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// src/lib/bin-path.ts
|
|
145
184
|
var PKG_NAME = "@primitive.ai/prim";
|
|
146
185
|
var ROOT_WALK_LIMIT = 6;
|
|
186
|
+
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
147
187
|
var resolvedRoot;
|
|
148
188
|
function locateRoot() {
|
|
149
189
|
if (resolvedRoot !== void 0) {
|
|
@@ -284,14 +324,14 @@ function throwIfAborted(signal) {
|
|
|
284
324
|
}
|
|
285
325
|
async function defaultSleep(ms, signal) {
|
|
286
326
|
if (!signal) {
|
|
287
|
-
await new Promise((
|
|
327
|
+
await new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
288
328
|
return;
|
|
289
329
|
}
|
|
290
330
|
throwIfAborted(signal);
|
|
291
|
-
await new Promise((
|
|
331
|
+
await new Promise((resolve4, reject) => {
|
|
292
332
|
const timer = setTimeout(() => {
|
|
293
333
|
signal.removeEventListener("abort", onAbort);
|
|
294
|
-
|
|
334
|
+
resolve4();
|
|
295
335
|
}, ms);
|
|
296
336
|
const onAbort = () => {
|
|
297
337
|
clearTimeout(timer);
|
|
@@ -340,7 +380,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
340
380
|
const target = new URL(url);
|
|
341
381
|
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
342
382
|
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
343
|
-
return new Promise((
|
|
383
|
+
return new Promise((resolve4, reject) => {
|
|
344
384
|
const outgoing = request(
|
|
345
385
|
target,
|
|
346
386
|
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
@@ -351,7 +391,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
351
391
|
if (typeof value === "string") headers.set(name, value);
|
|
352
392
|
const status = incoming.statusCode ?? 502;
|
|
353
393
|
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
354
|
-
|
|
394
|
+
resolve4(new Response(body, { status, headers }));
|
|
355
395
|
} catch (error) {
|
|
356
396
|
incoming.destroy();
|
|
357
397
|
reject(error);
|
|
@@ -364,21 +404,338 @@ function loopbackFetch(url, init = {}) {
|
|
|
364
404
|
}
|
|
365
405
|
|
|
366
406
|
// src/lib/machine-credentials.ts
|
|
367
|
-
import { execFileSync } from "child_process";
|
|
368
|
-
import { createHash as
|
|
407
|
+
import { execFileSync as execFileSync2 } from "child_process";
|
|
408
|
+
import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
369
409
|
import {
|
|
370
|
-
chmodSync,
|
|
371
|
-
existsSync as
|
|
410
|
+
chmodSync as chmodSync2,
|
|
411
|
+
existsSync as existsSync5,
|
|
372
412
|
linkSync,
|
|
373
|
-
lstatSync as
|
|
413
|
+
lstatSync as lstatSync4,
|
|
414
|
+
mkdirSync as mkdirSync4,
|
|
415
|
+
readFileSync as readFileSync6,
|
|
416
|
+
rmSync as rmSync6,
|
|
417
|
+
writeFileSync as writeFileSync4
|
|
418
|
+
} from "fs";
|
|
419
|
+
import { createRequire as createRequire2 } from "module";
|
|
420
|
+
import { dirname as dirname7, join as join9 } from "path";
|
|
421
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
422
|
+
|
|
423
|
+
// src/lib/hook-runtime.ts
|
|
424
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
425
|
+
import {
|
|
426
|
+
constants as constants2,
|
|
427
|
+
accessSync,
|
|
428
|
+
chmodSync,
|
|
429
|
+
copyFileSync,
|
|
430
|
+
existsSync as existsSync4,
|
|
431
|
+
lstatSync,
|
|
374
432
|
mkdirSync as mkdirSync3,
|
|
375
|
-
|
|
376
|
-
|
|
433
|
+
mkdtempSync,
|
|
434
|
+
readFileSync as readFileSync3,
|
|
435
|
+
readdirSync,
|
|
436
|
+
realpathSync,
|
|
437
|
+
renameSync as renameSync2,
|
|
438
|
+
rmSync as rmSync3,
|
|
439
|
+
statSync as statSync2,
|
|
440
|
+
utimesSync,
|
|
377
441
|
writeFileSync as writeFileSync3
|
|
378
442
|
} from "fs";
|
|
443
|
+
import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
|
|
444
|
+
|
|
445
|
+
// src/lib/git-hook-contract.ts
|
|
446
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
447
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
448
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
449
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
450
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
451
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
452
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
453
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
454
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
455
|
+
prim_hook=\${1-}
|
|
456
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
457
|
+
case "$prim_hook" in
|
|
458
|
+
pre-commit)
|
|
459
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
460
|
+
;;
|
|
461
|
+
post-commit)
|
|
462
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
463
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
464
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
465
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
466
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
467
|
+
(
|
|
468
|
+
trap '' HUP
|
|
469
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
470
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
471
|
+
) </dev/null >/dev/null 2>&1 &
|
|
472
|
+
;;
|
|
473
|
+
post-rewrite)
|
|
474
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
475
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
476
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
477
|
+
rm -f "$prim_pairs"
|
|
478
|
+
exit 0
|
|
479
|
+
fi
|
|
480
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
481
|
+
(
|
|
482
|
+
trap '' HUP
|
|
483
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
484
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
485
|
+
) </dev/null >/dev/null 2>&1 &
|
|
486
|
+
;;
|
|
487
|
+
esac
|
|
488
|
+
exit 0
|
|
489
|
+
`;
|
|
490
|
+
|
|
491
|
+
// src/lib/native-keyring.ts
|
|
492
|
+
import { existsSync as existsSync3 } from "fs";
|
|
379
493
|
import { createRequire } from "module";
|
|
380
|
-
import { dirname as dirname4, join as
|
|
494
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
381
495
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
496
|
+
var require2 = createRequire(import.meta.url);
|
|
497
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
498
|
+
|
|
499
|
+
// src/lib/paths.ts
|
|
500
|
+
import { homedir } from "os";
|
|
501
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
502
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
503
|
+
function absolutePath(value, variable) {
|
|
504
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
505
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
506
|
+
}
|
|
507
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
508
|
+
const normalized = normalize(value);
|
|
509
|
+
return normalized === value ? value : void 0;
|
|
510
|
+
}
|
|
511
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
512
|
+
const env = options.env ?? process.env;
|
|
513
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
514
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
515
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
516
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
517
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
518
|
+
if (!home) {
|
|
519
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
520
|
+
}
|
|
521
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
522
|
+
}
|
|
523
|
+
function primConfigDirectory(options = {}) {
|
|
524
|
+
return resolvePrimConfigDirectory(options).path;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// src/lib/hook-runtime.ts
|
|
528
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
529
|
+
var RELEASE_PREFIX = "release-";
|
|
530
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
531
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
532
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
533
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
534
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
535
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
536
|
+
prim: "dist/index.js",
|
|
537
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
538
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
539
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
540
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
541
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
542
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
543
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
544
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
545
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
546
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
547
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
548
|
+
};
|
|
549
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
550
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
551
|
+
bin,
|
|
552
|
+
target.replace(/^dist\//u, "")
|
|
553
|
+
])
|
|
554
|
+
);
|
|
555
|
+
function hookRuntimePaths(options = {}) {
|
|
556
|
+
const env = options.env ?? process.env;
|
|
557
|
+
const configDir = primConfigDirectory({
|
|
558
|
+
...options,
|
|
559
|
+
env,
|
|
560
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
561
|
+
});
|
|
562
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
563
|
+
return {
|
|
564
|
+
configDir,
|
|
565
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
566
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
567
|
+
runtimeDir,
|
|
568
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
569
|
+
current: join5(runtimeDir, "current"),
|
|
570
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
function sha256(path) {
|
|
574
|
+
return createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
575
|
+
}
|
|
576
|
+
function exactManifest(manifest) {
|
|
577
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
578
|
+
`;
|
|
579
|
+
}
|
|
580
|
+
function exactKeys(value, expected) {
|
|
581
|
+
const actual = Object.keys(value).sort();
|
|
582
|
+
const wanted = [...expected].sort();
|
|
583
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
584
|
+
}
|
|
585
|
+
function releaseId(manifest) {
|
|
586
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
587
|
+
}
|
|
588
|
+
function runtimePackageJson(manifest) {
|
|
589
|
+
return `${JSON.stringify(
|
|
590
|
+
{
|
|
591
|
+
name: "@primitive.ai/prim",
|
|
592
|
+
version: manifest.version,
|
|
593
|
+
type: "module",
|
|
594
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
595
|
+
},
|
|
596
|
+
null,
|
|
597
|
+
2
|
|
598
|
+
)}
|
|
599
|
+
`;
|
|
600
|
+
}
|
|
601
|
+
function validateRelease(releaseDir, manifest) {
|
|
602
|
+
try {
|
|
603
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
604
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
605
|
+
return false;
|
|
606
|
+
}
|
|
607
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
608
|
+
return false;
|
|
609
|
+
}
|
|
610
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
611
|
+
`) {
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
615
|
+
const target = join5(releaseDir, relativePath);
|
|
616
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
617
|
+
}
|
|
618
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
619
|
+
if (sha256(join5(releaseDir, path)) !== digest) return false;
|
|
620
|
+
}
|
|
621
|
+
return true;
|
|
622
|
+
} catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
627
|
+
try {
|
|
628
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
629
|
+
for (const relativePath of [
|
|
630
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
631
|
+
...Object.keys(manifest.native ?? {})
|
|
632
|
+
]) {
|
|
633
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
634
|
+
directories.add(join5(releaseDir, directory));
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
638
|
+
const files = [
|
|
639
|
+
"manifest.json",
|
|
640
|
+
"package.json",
|
|
641
|
+
"node",
|
|
642
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
643
|
+
...Object.keys(manifest.native ?? {})
|
|
644
|
+
];
|
|
645
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
|
|
646
|
+
if (![...directories].every(
|
|
647
|
+
(directory) => readdirSync(directory).every((name) => owned.has(join5(directory, name)))
|
|
648
|
+
))
|
|
649
|
+
return false;
|
|
650
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
651
|
+
} catch {
|
|
652
|
+
return false;
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
656
|
+
try {
|
|
657
|
+
const manifestPath = join5(releaseDir, "manifest.json");
|
|
658
|
+
const manifestStat = statSync2(manifestPath);
|
|
659
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
660
|
+
const raw = readFileSync3(manifestPath, "utf8");
|
|
661
|
+
const parsed = JSON.parse(raw);
|
|
662
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
663
|
+
if (!exactKeys(parsed, [
|
|
664
|
+
"schemaVersion",
|
|
665
|
+
"version",
|
|
666
|
+
"nodePath",
|
|
667
|
+
"files",
|
|
668
|
+
..."native" in parsed ? ["native"] : []
|
|
669
|
+
]))
|
|
670
|
+
return null;
|
|
671
|
+
const candidate = parsed;
|
|
672
|
+
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(
|
|
673
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
674
|
+
)) {
|
|
675
|
+
return null;
|
|
676
|
+
}
|
|
677
|
+
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(
|
|
678
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
679
|
+
)))
|
|
680
|
+
return null;
|
|
681
|
+
const manifest = candidate;
|
|
682
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
683
|
+
return null;
|
|
684
|
+
}
|
|
685
|
+
return manifest;
|
|
686
|
+
} catch {
|
|
687
|
+
return null;
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
function readSelectedRelease(paths) {
|
|
691
|
+
let raw;
|
|
692
|
+
try {
|
|
693
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
694
|
+
} catch (error) {
|
|
695
|
+
if (error.code === "ENOENT") return null;
|
|
696
|
+
throw error;
|
|
697
|
+
}
|
|
698
|
+
const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
699
|
+
if (`${name}
|
|
700
|
+
` !== raw || !RELEASE_NAME_RE.test(name)) {
|
|
701
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
702
|
+
}
|
|
703
|
+
const dir = join5(paths.releasesDir, name);
|
|
704
|
+
const manifest = readReleaseManifest(dir, name);
|
|
705
|
+
if (!manifest) {
|
|
706
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
707
|
+
}
|
|
708
|
+
return { name, dir, manifest };
|
|
709
|
+
}
|
|
710
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
711
|
+
try {
|
|
712
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
713
|
+
if (!selected?.manifest.native) return void 0;
|
|
714
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
715
|
+
return existsSync4(loader) ? loader : void 0;
|
|
716
|
+
} catch {
|
|
717
|
+
return void 0;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
721
|
+
set -eu
|
|
722
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
723
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
724
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
725
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
726
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
727
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
728
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
729
|
+
case "\${1-}" in
|
|
730
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
731
|
+
*) exit 64 ;;
|
|
732
|
+
esac
|
|
733
|
+
shift
|
|
734
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
735
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
736
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
737
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
738
|
+
`;
|
|
382
739
|
|
|
383
740
|
// src/lib/cloud-env.ts
|
|
384
741
|
function isClaudeCloudSession(env = process.env) {
|
|
@@ -386,6 +743,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
386
743
|
}
|
|
387
744
|
var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
|
|
388
745
|
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';
|
|
746
|
+
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}.`;
|
|
747
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
389
748
|
function cloudSetupPointer(message, env = process.env) {
|
|
390
749
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
391
750
|
}
|
|
@@ -527,10 +886,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
527
886
|
"access_token",
|
|
528
887
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
529
888
|
);
|
|
530
|
-
const
|
|
889
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
531
890
|
return {
|
|
532
891
|
accessToken,
|
|
533
|
-
refreshToken:
|
|
892
|
+
refreshToken: refreshToken3,
|
|
534
893
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
535
894
|
};
|
|
536
895
|
}
|
|
@@ -782,23 +1141,23 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
782
1141
|
}
|
|
783
1142
|
|
|
784
1143
|
// src/lib/machine-retry.ts
|
|
785
|
-
import { createHash } from "crypto";
|
|
786
|
-
import { lstatSync, readFileSync as
|
|
787
|
-
import { join as
|
|
1144
|
+
import { createHash as createHash2 } from "crypto";
|
|
1145
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync2, rmSync as rmSync4 } from "fs";
|
|
1146
|
+
import { join as join6 } from "path";
|
|
788
1147
|
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
789
1148
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
790
1149
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
791
1150
|
signal?.throwIfAborted();
|
|
792
|
-
const key =
|
|
793
|
-
const path =
|
|
1151
|
+
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1152
|
+
const path = join6(directory, `machine_retry_${key}.json`);
|
|
794
1153
|
let state = {
|
|
795
1154
|
failures: 0,
|
|
796
1155
|
retryAt: 0
|
|
797
1156
|
};
|
|
798
1157
|
try {
|
|
799
|
-
const stat =
|
|
1158
|
+
const stat = lstatSync2(path);
|
|
800
1159
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
801
|
-
const data = JSON.parse(
|
|
1160
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
802
1161
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
803
1162
|
throw new Error("Invalid retry state");
|
|
804
1163
|
state = data;
|
|
@@ -822,7 +1181,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
822
1181
|
);
|
|
823
1182
|
try {
|
|
824
1183
|
const result = await request3();
|
|
825
|
-
|
|
1184
|
+
rmSync4(path, { force: true });
|
|
826
1185
|
return result;
|
|
827
1186
|
} catch (error) {
|
|
828
1187
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -849,60 +1208,1115 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
849
1208
|
}
|
|
850
1209
|
}
|
|
851
1210
|
|
|
852
|
-
// src/lib/
|
|
853
|
-
import {
|
|
854
|
-
import {
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1211
|
+
// src/lib/session-identity.ts
|
|
1212
|
+
import { execFile } from "child_process";
|
|
1213
|
+
import { createHash as createHash4 } from "crypto";
|
|
1214
|
+
import { rmSync as rmSync5 } from "fs";
|
|
1215
|
+
import { join as join8 } from "path";
|
|
1216
|
+
import { promisify } from "util";
|
|
1217
|
+
|
|
1218
|
+
// src/lib/git.ts
|
|
1219
|
+
import { execFileSync } from "child_process";
|
|
1220
|
+
import { createHash as createHash3 } from "crypto";
|
|
1221
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
1222
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve2, sep } from "path";
|
|
1223
|
+
var GIT_TIMEOUT_MS = 1e3;
|
|
1224
|
+
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
1225
|
+
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
1226
|
+
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
1227
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
1228
|
+
function gitChildEnvironment(env = process.env) {
|
|
1229
|
+
return Object.fromEntries(
|
|
1230
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
1231
|
+
);
|
|
1232
|
+
}
|
|
1233
|
+
function gitToplevel(cwd) {
|
|
1234
|
+
try {
|
|
1235
|
+
return execFileSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1236
|
+
cwd,
|
|
1237
|
+
encoding: "utf-8",
|
|
1238
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1239
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1240
|
+
env: gitChildEnvironment()
|
|
1241
|
+
}).trim();
|
|
1242
|
+
} catch {
|
|
1243
|
+
return null;
|
|
859
1244
|
}
|
|
860
|
-
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
861
|
-
const normalized = normalize(value);
|
|
862
|
-
return normalized === value ? value : void 0;
|
|
863
1245
|
}
|
|
864
|
-
function
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
1246
|
+
function gitValue(cwd, args) {
|
|
1247
|
+
try {
|
|
1248
|
+
const value = execFileSync("git", args, {
|
|
1249
|
+
cwd,
|
|
1250
|
+
encoding: "utf-8",
|
|
1251
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
1252
|
+
timeout: GIT_TIMEOUT_MS,
|
|
1253
|
+
env: gitChildEnvironment()
|
|
1254
|
+
}).trim();
|
|
1255
|
+
return value || void 0;
|
|
1256
|
+
} catch {
|
|
1257
|
+
return void 0;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
function currentBranch(cwd) {
|
|
1261
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
1262
|
+
}
|
|
1263
|
+
function parseGithubRepositoryName(path) {
|
|
1264
|
+
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
1265
|
+
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
1266
|
+
return null;
|
|
1267
|
+
}
|
|
1268
|
+
return `${parts[0]}/${parts[1]}`;
|
|
1269
|
+
}
|
|
1270
|
+
function githubRepositoryFromRemote(remote) {
|
|
1271
|
+
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
1272
|
+
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
1273
|
+
remote
|
|
1274
|
+
);
|
|
1275
|
+
const path = match?.[1] ?? match?.[2];
|
|
1276
|
+
return path ? parseGithubRepositoryName(path) : null;
|
|
1277
|
+
}
|
|
1278
|
+
function checkoutSettingsText(repoRoot) {
|
|
1279
|
+
const path = join7(repoRoot, ".claude", "settings.json");
|
|
1280
|
+
try {
|
|
1281
|
+
if (!lstatSync3(join7(repoRoot, ".claude")).isDirectory()) return null;
|
|
1282
|
+
const stat = lstatSync3(path);
|
|
1283
|
+
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
1284
|
+
return readFileSync5(path, "utf8");
|
|
1285
|
+
} catch {
|
|
1286
|
+
return null;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
function checkoutDeclaration(repoRoot, name) {
|
|
1290
|
+
const text = checkoutSettingsText(repoRoot);
|
|
1291
|
+
if (text === null) return null;
|
|
1292
|
+
let parsed;
|
|
1293
|
+
try {
|
|
1294
|
+
parsed = JSON.parse(text);
|
|
1295
|
+
} catch {
|
|
1296
|
+
return null;
|
|
1297
|
+
}
|
|
1298
|
+
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
1299
|
+
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
1300
|
+
return typeof value === "string" ? value : null;
|
|
1301
|
+
}
|
|
1302
|
+
function declaredGithubRepository(repoRoot) {
|
|
1303
|
+
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
1304
|
+
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
1305
|
+
}
|
|
1306
|
+
function githubRepositoryFullName(cwd) {
|
|
1307
|
+
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
1308
|
+
if (remote) {
|
|
1309
|
+
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
1310
|
+
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
1311
|
+
}
|
|
1312
|
+
const root = gitToplevel(cwd);
|
|
1313
|
+
return root ? declaredGithubRepository(root) : null;
|
|
1314
|
+
}
|
|
1315
|
+
function normalizeOriginRemote(remote) {
|
|
1316
|
+
const value = remote.trim();
|
|
1317
|
+
if (!value) return void 0;
|
|
1318
|
+
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
1319
|
+
if (scp?.host && scp.path) {
|
|
1320
|
+
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1321
|
+
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
1322
|
+
}
|
|
1323
|
+
try {
|
|
1324
|
+
const url = new URL(value);
|
|
1325
|
+
url.username = "";
|
|
1326
|
+
url.password = "";
|
|
1327
|
+
url.search = "";
|
|
1328
|
+
url.hash = "";
|
|
1329
|
+
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
1330
|
+
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
1331
|
+
return void 0;
|
|
1332
|
+
} catch {
|
|
1333
|
+
return void 0;
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
// src/lib/terminal-safe.ts
|
|
1338
|
+
function replaceIsolatedSurrogates(value) {
|
|
1339
|
+
let out = "";
|
|
1340
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1341
|
+
const unit = value.charCodeAt(index);
|
|
1342
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
1343
|
+
const next = value.charCodeAt(index + 1);
|
|
1344
|
+
if (next >= 56320 && next <= 57343) {
|
|
1345
|
+
out += value[index] + value[index + 1];
|
|
1346
|
+
index += 1;
|
|
1347
|
+
} else {
|
|
1348
|
+
out += "\uFFFD";
|
|
1349
|
+
}
|
|
1350
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
1351
|
+
out += "\uFFFD";
|
|
1352
|
+
} else {
|
|
1353
|
+
out += value[index];
|
|
1354
|
+
}
|
|
1355
|
+
}
|
|
1356
|
+
return out;
|
|
1357
|
+
}
|
|
1358
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
1359
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
1360
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
1361
|
+
point === 1564 || // Arabic letter mark
|
|
1362
|
+
point === 6158 || // Mongolian vowel separator
|
|
1363
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
1364
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
1365
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
1366
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
1367
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
1368
|
+
point >= 917504 && point <= 917631;
|
|
1369
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
1370
|
+
}
|
|
1371
|
+
function terminalSafeText(value) {
|
|
1372
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
1373
|
+
}
|
|
1374
|
+
function terminalSafeLine(value) {
|
|
1375
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
1376
|
+
}
|
|
1377
|
+
var stripControlChars = terminalSafeText;
|
|
1378
|
+
|
|
1379
|
+
// src/lib/session-identity.ts
|
|
1380
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
1381
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
1382
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
1383
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
1384
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
1385
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
1386
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
1387
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
1388
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
1389
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
1390
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
1391
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
1392
|
+
token: "/api/cli/session-identity/token",
|
|
1393
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
1394
|
+
link: "/api/cli/session-identity/link"
|
|
1395
|
+
};
|
|
1396
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
1397
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
1398
|
+
var GIT_TIMEOUT_MS2 = 1e4;
|
|
1399
|
+
var POLL_BUDGET_MS = 15e3;
|
|
1400
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
1401
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
1402
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
1403
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
1404
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
1405
|
+
function sessionIdentityRequested(env = process.env) {
|
|
1406
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
1407
|
+
}
|
|
1408
|
+
function sessionIdentityMode(deps = {}) {
|
|
1409
|
+
const env = deps.env ?? process.env;
|
|
1410
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
1411
|
+
}
|
|
1412
|
+
function failure(code, cause, remedy) {
|
|
1413
|
+
return { status: "failed", code, cause, remedy };
|
|
1414
|
+
}
|
|
1415
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
1416
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
1417
|
+
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';
|
|
1418
|
+
var SESSION_REVOKED = failure(
|
|
1419
|
+
"session_revoked",
|
|
1420
|
+
"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",
|
|
1421
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
1422
|
+
);
|
|
1423
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
1424
|
+
"challenge_expired",
|
|
1425
|
+
"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)",
|
|
1426
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
1427
|
+
);
|
|
1428
|
+
var CHALLENGE_GONE = failure(
|
|
1429
|
+
"challenge_not_found",
|
|
1430
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
1431
|
+
NEW_SESSION_REMEDY
|
|
1432
|
+
);
|
|
1433
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
1434
|
+
function rejectionFailure(reason, repository) {
|
|
1435
|
+
switch (reason) {
|
|
1436
|
+
case "identity_mismatch":
|
|
1437
|
+
return failure(
|
|
1438
|
+
"identity_mismatch",
|
|
1439
|
+
"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",
|
|
1440
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
1441
|
+
);
|
|
1442
|
+
case "push_after_expiry":
|
|
1443
|
+
return failure(
|
|
1444
|
+
"push_after_expiry",
|
|
1445
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
1446
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
1447
|
+
);
|
|
1448
|
+
case "repository_mismatch":
|
|
1449
|
+
return failure(
|
|
1450
|
+
"repository_mismatch",
|
|
1451
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
1452
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
1453
|
+
);
|
|
1454
|
+
case "conflicting_push":
|
|
1455
|
+
return failure(
|
|
1456
|
+
"conflicting_push",
|
|
1457
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
1458
|
+
NEW_SESSION_REMEDY
|
|
1459
|
+
);
|
|
1460
|
+
case "unsupported_sender":
|
|
1461
|
+
return failure(
|
|
1462
|
+
"unsupported_sender",
|
|
1463
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
1464
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
1465
|
+
);
|
|
1466
|
+
default:
|
|
1467
|
+
return failure(
|
|
1468
|
+
"challenge_rejected",
|
|
1469
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
1470
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
1471
|
+
);
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
function sessionIdentityMessage(outcome) {
|
|
1475
|
+
if (outcome.status === "link_required")
|
|
1476
|
+
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.`;
|
|
1477
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1478
|
+
}
|
|
1479
|
+
function hash(value) {
|
|
1480
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1481
|
+
}
|
|
1482
|
+
function sessionContext(deps) {
|
|
1483
|
+
const env = deps.env ?? process.env;
|
|
1484
|
+
const environment = environmentCredentials(deps);
|
|
1485
|
+
if (!environment)
|
|
1486
|
+
return failure(
|
|
1487
|
+
"environment_credential_missing",
|
|
1488
|
+
"the cloud environment has no environment credential",
|
|
1489
|
+
'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'
|
|
1490
|
+
);
|
|
1491
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
1492
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
1493
|
+
return failure(
|
|
1494
|
+
"session_id_missing",
|
|
1495
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
1496
|
+
NEW_SESSION_REMEDY
|
|
1497
|
+
);
|
|
1498
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
1499
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
1500
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
1501
|
+
return {
|
|
1502
|
+
directory,
|
|
1503
|
+
apiUrl,
|
|
1504
|
+
clientId: environment.clientId,
|
|
1505
|
+
generation: environment.generation,
|
|
1506
|
+
sessionId,
|
|
1507
|
+
tokenPath: join8(directory, `session_identity_${key}.json`),
|
|
1508
|
+
statePath: join8(directory, `session_identity_${key}.state.json`),
|
|
1509
|
+
lockPath: join8(directory, "session-identity.lock")
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
function readRecord(path) {
|
|
1513
|
+
try {
|
|
1514
|
+
const value = readMachineMetadata(path);
|
|
1515
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
1516
|
+
} catch {
|
|
1517
|
+
return void 0;
|
|
1518
|
+
}
|
|
1519
|
+
}
|
|
1520
|
+
function finiteNumber(value) {
|
|
1521
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
1522
|
+
}
|
|
1523
|
+
function readToken(context) {
|
|
1524
|
+
const data = readRecord(context.tokenPath);
|
|
1525
|
+
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))
|
|
1526
|
+
return void 0;
|
|
1527
|
+
const identity = data.identity;
|
|
1528
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
1529
|
+
return void 0;
|
|
1530
|
+
return data;
|
|
1531
|
+
}
|
|
1532
|
+
function readState(context) {
|
|
1533
|
+
const data = readRecord(context.statePath);
|
|
1534
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
1535
|
+
return void 0;
|
|
1536
|
+
return data;
|
|
1537
|
+
}
|
|
1538
|
+
function writeToken(context, record) {
|
|
1539
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1540
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
1541
|
+
rmSync5(context.statePath, { force: true });
|
|
1542
|
+
}
|
|
1543
|
+
function writeState(context, state) {
|
|
1544
|
+
try {
|
|
1545
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
1546
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
1547
|
+
} catch {
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
function tokenValid(record, now = Date.now()) {
|
|
1551
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
1552
|
+
}
|
|
1553
|
+
function tokenFresh(record, now = Date.now()) {
|
|
1554
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
1555
|
+
}
|
|
1556
|
+
function toCredential(record) {
|
|
1557
|
+
return {
|
|
1558
|
+
issuer: record.issuer,
|
|
1559
|
+
audience: record.audience,
|
|
1560
|
+
...record.identity,
|
|
1561
|
+
accessToken: record.accessToken,
|
|
1562
|
+
expiresAt: record.expiresAt,
|
|
1563
|
+
apiUrl: record.apiUrl,
|
|
1564
|
+
generation: record.generation,
|
|
1565
|
+
storage: "environment",
|
|
1566
|
+
session: {
|
|
1567
|
+
userId: record.userId,
|
|
1568
|
+
displayName: record.displayName,
|
|
1569
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1570
|
+
refreshAfter: record.refreshAfter
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
function identified(record, reused) {
|
|
1575
|
+
return {
|
|
1576
|
+
status: "ok",
|
|
1577
|
+
credential: toCredential(record),
|
|
1578
|
+
displayName: record.displayName,
|
|
1579
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
1580
|
+
reused
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
function cachedSessionCredential(deps = {}) {
|
|
1584
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
1585
|
+
let context;
|
|
1586
|
+
try {
|
|
1587
|
+
context = sessionContext(deps);
|
|
1588
|
+
} catch {
|
|
1589
|
+
return void 0;
|
|
1590
|
+
}
|
|
1591
|
+
if ("status" in context) return void 0;
|
|
1592
|
+
const record = readToken(context);
|
|
1593
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
1594
|
+
}
|
|
1595
|
+
function outcomeFromState(state) {
|
|
1596
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
1597
|
+
return {
|
|
1598
|
+
status: "link_required",
|
|
1599
|
+
githubLogin: state.githubLogin,
|
|
1600
|
+
challengeId: state.challengeId,
|
|
1601
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
1602
|
+
};
|
|
1603
|
+
return failure(
|
|
1604
|
+
state.code,
|
|
1605
|
+
state.cause ?? "the last identity check failed",
|
|
1606
|
+
state.remedy ?? RETRY_REMEDY
|
|
1607
|
+
);
|
|
1608
|
+
}
|
|
1609
|
+
function parseInstant(value) {
|
|
1610
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
1611
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
1612
|
+
const parsed = Date.parse(value);
|
|
1613
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
1614
|
+
}
|
|
1615
|
+
return void 0;
|
|
1616
|
+
}
|
|
1617
|
+
async function sendJson(url, init, fetchImpl) {
|
|
1618
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
1619
|
+
let value;
|
|
1620
|
+
try {
|
|
1621
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
1622
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
1623
|
+
} catch {
|
|
1624
|
+
value = void 0;
|
|
1625
|
+
}
|
|
1626
|
+
return { status: response.status, value };
|
|
1627
|
+
}
|
|
1628
|
+
function environmentOnly(deps) {
|
|
1629
|
+
return { ...deps, environmentOnly: true };
|
|
1630
|
+
}
|
|
1631
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
1632
|
+
const send = async (credential2) => {
|
|
1633
|
+
const headers = { "Content-Type": "application/json" };
|
|
1634
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
1635
|
+
if (credential2.tokenInjection) {
|
|
1636
|
+
const response = await forwardMachineRequest(
|
|
1637
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
1638
|
+
signal,
|
|
1639
|
+
environmentOnly(deps)
|
|
1640
|
+
);
|
|
1641
|
+
const parsed = await response.json().catch(() => void 0);
|
|
1642
|
+
return {
|
|
1643
|
+
status: response.status,
|
|
1644
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
1645
|
+
};
|
|
1646
|
+
}
|
|
1647
|
+
return sendJson(
|
|
1648
|
+
`${credential2.apiUrl}${path}`,
|
|
1649
|
+
{
|
|
1650
|
+
method,
|
|
1651
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
1652
|
+
...text === void 0 ? {} : { body: text },
|
|
1653
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS2)
|
|
1654
|
+
},
|
|
1655
|
+
deps.fetch ?? fetch
|
|
1656
|
+
);
|
|
1657
|
+
};
|
|
1658
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1659
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1660
|
+
let answer = await send(credential);
|
|
1661
|
+
if (answer.status === 401) {
|
|
1662
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
1663
|
+
if (!credential)
|
|
1664
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
1665
|
+
answer = await send(credential);
|
|
1666
|
+
}
|
|
1667
|
+
return answer;
|
|
1668
|
+
}
|
|
1669
|
+
function environmentFailure(error, apiUrl) {
|
|
1670
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
1671
|
+
return failure(
|
|
1672
|
+
"environment_credential_rejected",
|
|
1673
|
+
"Primitive rejected the cloud environment's credential",
|
|
1674
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
1675
|
+
);
|
|
1676
|
+
const host = (() => {
|
|
1677
|
+
try {
|
|
1678
|
+
return new URL(apiUrl).hostname;
|
|
1679
|
+
} catch {
|
|
1680
|
+
return "Primitive";
|
|
1681
|
+
}
|
|
1682
|
+
})();
|
|
1683
|
+
return failure(
|
|
1684
|
+
"identity_unavailable",
|
|
1685
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
1686
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
1687
|
+
);
|
|
1688
|
+
}
|
|
1689
|
+
function answerError(answer) {
|
|
1690
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
1691
|
+
}
|
|
1692
|
+
async function git(root, args, signal) {
|
|
1693
|
+
try {
|
|
1694
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
1695
|
+
cwd: root,
|
|
1696
|
+
encoding: "utf8",
|
|
1697
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
1698
|
+
signal,
|
|
1699
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
1700
|
+
maxBuffer: 1024 * 1024
|
|
1701
|
+
});
|
|
1702
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
1703
|
+
} catch (error) {
|
|
1704
|
+
const failed = error;
|
|
1705
|
+
return {
|
|
1706
|
+
ok: false,
|
|
1707
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
1708
|
+
stdout: failed.stdout ?? "",
|
|
1709
|
+
stderr: failed.stderr ?? "",
|
|
1710
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
function gitDetail(stderr) {
|
|
1715
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
1716
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1717
|
+
}
|
|
1718
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
1719
|
+
await new Promise((resolve4, reject) => {
|
|
1720
|
+
const timer = setTimeout(resolve4, milliseconds);
|
|
1721
|
+
signal?.addEventListener(
|
|
1722
|
+
"abort",
|
|
1723
|
+
() => {
|
|
1724
|
+
clearTimeout(timer);
|
|
1725
|
+
reject(signal.reason);
|
|
1726
|
+
},
|
|
1727
|
+
{ once: true }
|
|
1728
|
+
);
|
|
1729
|
+
});
|
|
1730
|
+
}
|
|
1731
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
1732
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
1733
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
1734
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
1735
|
+
let unreachable;
|
|
1736
|
+
for (; ; ) {
|
|
1737
|
+
const remaining = deadline - Date.now();
|
|
1738
|
+
if (remaining <= 0) break;
|
|
1739
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
1740
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
1741
|
+
let answer;
|
|
1742
|
+
try {
|
|
1743
|
+
answer = await environmentRequest(
|
|
1744
|
+
"GET",
|
|
1745
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
1746
|
+
void 0,
|
|
1747
|
+
deps,
|
|
1748
|
+
signal
|
|
1749
|
+
);
|
|
1750
|
+
} catch (error) {
|
|
1751
|
+
signal?.throwIfAborted();
|
|
1752
|
+
unreachable = error;
|
|
1753
|
+
continue;
|
|
1754
|
+
}
|
|
1755
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1756
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1757
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
1758
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
1759
|
+
unreachable = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
1760
|
+
continue;
|
|
1761
|
+
}
|
|
1762
|
+
unreachable = void 0;
|
|
1763
|
+
const status = answer.value;
|
|
1764
|
+
if (status?.status === "verified")
|
|
1765
|
+
return {
|
|
1766
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
1767
|
+
};
|
|
1768
|
+
if (status?.status === "expired")
|
|
1769
|
+
return failure(
|
|
1770
|
+
"challenge_expired",
|
|
1771
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
1772
|
+
NEW_SESSION_REMEDY
|
|
1773
|
+
);
|
|
1774
|
+
if (status?.status === "rejected")
|
|
1775
|
+
return rejectionFailure(status.reason, repository);
|
|
1776
|
+
}
|
|
1777
|
+
if (unreachable) return environmentFailure(unreachable, apiUrl);
|
|
1778
|
+
return failure(
|
|
1779
|
+
"webhook_timeout",
|
|
1780
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
1781
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1782
|
+
);
|
|
1783
|
+
}
|
|
1784
|
+
function parseTokenAnswer(value) {
|
|
1785
|
+
if (!value) return void 0;
|
|
1786
|
+
const user = value.user;
|
|
1787
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
1788
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
1789
|
+
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))
|
|
1790
|
+
return void 0;
|
|
1791
|
+
return {
|
|
1792
|
+
accessToken: value.accessToken,
|
|
1793
|
+
expiresAt,
|
|
1794
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
1795
|
+
userId: user.id,
|
|
1796
|
+
displayName: user.displayName,
|
|
1797
|
+
organizationId: value.organizationId
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
1801
|
+
"server_contract",
|
|
1802
|
+
"Primitive's answer did not identify the linked member",
|
|
1803
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
1804
|
+
);
|
|
1805
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
1806
|
+
let identity;
|
|
1807
|
+
let environment;
|
|
1808
|
+
try {
|
|
1809
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
1810
|
+
identity = await verifyMachineIdentity(
|
|
1811
|
+
context.apiUrl,
|
|
1812
|
+
answer.accessToken,
|
|
1813
|
+
context.clientId,
|
|
1814
|
+
signal,
|
|
1815
|
+
deps.fetch
|
|
1816
|
+
);
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
1819
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1820
|
+
return environmentFailure(error, context.apiUrl);
|
|
1821
|
+
}
|
|
1822
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
1823
|
+
return SERVER_CONTRACT_FAILURE;
|
|
1824
|
+
return {
|
|
1825
|
+
version: 1,
|
|
1826
|
+
apiUrl: context.apiUrl,
|
|
1827
|
+
clientId: context.clientId,
|
|
1828
|
+
generation: context.generation,
|
|
1829
|
+
sessionId: context.sessionId,
|
|
1830
|
+
issuer: environment.issuer,
|
|
1831
|
+
audience: environment.audience,
|
|
1832
|
+
accessToken: answer.accessToken,
|
|
1833
|
+
expiresAt: answer.expiresAt,
|
|
1834
|
+
refreshAfter: answer.refreshAfter,
|
|
1835
|
+
userId: answer.userId,
|
|
1836
|
+
displayName: answer.displayName,
|
|
1837
|
+
organizationId: answer.organizationId,
|
|
1838
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
1839
|
+
identity,
|
|
1840
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
async function refreshToken(context, record, deps, signal) {
|
|
1844
|
+
let answer;
|
|
1845
|
+
try {
|
|
1846
|
+
answer = await environmentRequest(
|
|
1847
|
+
"POST",
|
|
1848
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
1849
|
+
{ accessToken: record.accessToken },
|
|
1850
|
+
deps,
|
|
1851
|
+
signal
|
|
1852
|
+
);
|
|
1853
|
+
} catch (error) {
|
|
1854
|
+
signal?.throwIfAborted();
|
|
1855
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
1856
|
+
}
|
|
1857
|
+
const code = answerError(answer);
|
|
1858
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
1859
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
1860
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1861
|
+
return {
|
|
1862
|
+
status: "refused",
|
|
1863
|
+
failure: environmentFailure(
|
|
1864
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
1865
|
+
context.apiUrl
|
|
1866
|
+
)
|
|
1867
|
+
};
|
|
1868
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1869
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
1870
|
+
return { status: "unavailable" };
|
|
1871
|
+
return {
|
|
1872
|
+
status: "ok",
|
|
1873
|
+
record: {
|
|
1874
|
+
...record,
|
|
1875
|
+
accessToken: token.accessToken,
|
|
1876
|
+
expiresAt: token.expiresAt,
|
|
1877
|
+
refreshAfter: token.refreshAfter,
|
|
1878
|
+
displayName: token.displayName
|
|
1879
|
+
}
|
|
1880
|
+
};
|
|
1881
|
+
}
|
|
1882
|
+
function exchangeRefusal(answer, repository) {
|
|
1883
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
1884
|
+
if (answer.status !== 409) return void 0;
|
|
1885
|
+
switch (answerError(answer)) {
|
|
1886
|
+
case "identity_mismatch":
|
|
1887
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
1888
|
+
case "challenge_rejected":
|
|
1889
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
1890
|
+
case "challenge_expired":
|
|
1891
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
1892
|
+
case "challenge_already_exchanged":
|
|
1893
|
+
return failure(
|
|
1894
|
+
"challenge_already_exchanged",
|
|
1895
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
1896
|
+
NEW_SESSION_REMEDY
|
|
1897
|
+
);
|
|
1898
|
+
case "challenge_pending":
|
|
1899
|
+
return failure(
|
|
1900
|
+
"webhook_timeout",
|
|
1901
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
1902
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
1903
|
+
);
|
|
1904
|
+
default:
|
|
1905
|
+
return void 0;
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
1909
|
+
let answer;
|
|
1910
|
+
try {
|
|
1911
|
+
answer = await environmentRequest(
|
|
1912
|
+
"POST",
|
|
1913
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
1914
|
+
{ challengeId: challenge.challengeId },
|
|
1915
|
+
deps,
|
|
1916
|
+
signal
|
|
1917
|
+
);
|
|
1918
|
+
} catch (error) {
|
|
1919
|
+
signal?.throwIfAborted();
|
|
1920
|
+
return environmentFailure(error, context.apiUrl);
|
|
1921
|
+
}
|
|
1922
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
1923
|
+
const login = answer.value?.githubLogin;
|
|
1924
|
+
return {
|
|
1925
|
+
status: "link_required",
|
|
1926
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
1927
|
+
challengeId: challenge.challengeId,
|
|
1928
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
const refused = exchangeRefusal(
|
|
1932
|
+
answer,
|
|
1933
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
1934
|
+
);
|
|
1935
|
+
if (refused) return refused;
|
|
1936
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
1937
|
+
if (!token) {
|
|
1938
|
+
if (answer.status === 401 || answer.status === 403)
|
|
1939
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
1940
|
+
return answer.status >= 500 ? environmentFailure(
|
|
1941
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
1942
|
+
context.apiUrl
|
|
1943
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
1944
|
+
}
|
|
1945
|
+
return recordFor(
|
|
1946
|
+
context,
|
|
1947
|
+
token,
|
|
1948
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
1949
|
+
deps,
|
|
1950
|
+
signal
|
|
1951
|
+
);
|
|
1952
|
+
}
|
|
1953
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
1954
|
+
const env = deps.env ?? process.env;
|
|
1955
|
+
const repository = githubRepositoryFullName(root);
|
|
1956
|
+
if (!repository)
|
|
1957
|
+
return failure(
|
|
1958
|
+
"repository_unidentified",
|
|
1959
|
+
"this checkout does not name its GitHub repository",
|
|
1960
|
+
"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"
|
|
1961
|
+
);
|
|
1962
|
+
const branch = currentBranch(root);
|
|
1963
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
1964
|
+
return failure(
|
|
1965
|
+
"not_session_branch",
|
|
1966
|
+
`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`,
|
|
1967
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
1968
|
+
);
|
|
1969
|
+
attempt.branch = branch;
|
|
1970
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
1971
|
+
if (!baseSha) {
|
|
1972
|
+
const head = await git(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
1973
|
+
baseSha = head.stdout.trim();
|
|
1974
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
1975
|
+
return failure(
|
|
1976
|
+
"no_commit",
|
|
1977
|
+
"this checkout has no commit to create the session branch at",
|
|
1978
|
+
NEW_SESSION_REMEDY
|
|
1979
|
+
);
|
|
1980
|
+
}
|
|
1981
|
+
const published = await git(
|
|
1982
|
+
root,
|
|
1983
|
+
[
|
|
1984
|
+
"for-each-ref",
|
|
1985
|
+
"--count=1",
|
|
1986
|
+
"--format=%(refname)",
|
|
1987
|
+
"--contains",
|
|
1988
|
+
baseSha,
|
|
1989
|
+
"refs/remotes/origin/"
|
|
1990
|
+
],
|
|
1991
|
+
signal
|
|
1992
|
+
);
|
|
1993
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
1994
|
+
return failure(
|
|
1995
|
+
"unpublished_commits",
|
|
1996
|
+
`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`,
|
|
1997
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
1998
|
+
);
|
|
1999
|
+
attempt.baseSha = baseSha;
|
|
2000
|
+
const remote = await git(
|
|
2001
|
+
root,
|
|
2002
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2003
|
+
signal
|
|
2004
|
+
);
|
|
2005
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2006
|
+
if (remote.ok && recorded) {
|
|
2007
|
+
Object.assign(attempt, recorded);
|
|
2008
|
+
return { ...recorded, repository };
|
|
2009
|
+
}
|
|
2010
|
+
if (remote.ok)
|
|
2011
|
+
return failure(
|
|
2012
|
+
"branch_exists",
|
|
2013
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
2014
|
+
NEW_SESSION_REMEDY
|
|
2015
|
+
);
|
|
2016
|
+
if (remote.code !== 2)
|
|
2017
|
+
return failure(
|
|
2018
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
2019
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
2020
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
2021
|
+
);
|
|
2022
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
2023
|
+
Object.assign(attempt, recorded);
|
|
2024
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
2025
|
+
}
|
|
2026
|
+
let answer;
|
|
2027
|
+
try {
|
|
2028
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
2029
|
+
answer = await environmentRequest(
|
|
2030
|
+
"POST",
|
|
2031
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
2032
|
+
{
|
|
2033
|
+
repositoryFullName: repository,
|
|
2034
|
+
claudeSessionId: context.sessionId,
|
|
2035
|
+
branch,
|
|
2036
|
+
baseSha,
|
|
2037
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
2038
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
2039
|
+
},
|
|
2040
|
+
deps,
|
|
2041
|
+
signal
|
|
2042
|
+
);
|
|
2043
|
+
} catch (error) {
|
|
2044
|
+
signal?.throwIfAborted();
|
|
2045
|
+
return environmentFailure(error, context.apiUrl);
|
|
2046
|
+
}
|
|
2047
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
2048
|
+
return failure(
|
|
2049
|
+
"repository_not_connected",
|
|
2050
|
+
`${repository} is not connected to Primitive`,
|
|
2051
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
2052
|
+
);
|
|
2053
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2054
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2055
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
2056
|
+
return failure(
|
|
2057
|
+
"challenge_open",
|
|
2058
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
2059
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
2060
|
+
);
|
|
2061
|
+
if (answer.status === 429)
|
|
2062
|
+
return failure(
|
|
2063
|
+
"too_many_challenges",
|
|
2064
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
2065
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
2066
|
+
);
|
|
2067
|
+
const challengeId = answer.value?.challengeId;
|
|
2068
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
2069
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
2070
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2071
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2072
|
+
context.apiUrl
|
|
2073
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2074
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
2075
|
+
attempt.challengeId = challengeId;
|
|
2076
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
2077
|
+
return pushSessionBranch(
|
|
2078
|
+
root,
|
|
2079
|
+
repository,
|
|
2080
|
+
branch,
|
|
2081
|
+
baseSha,
|
|
2082
|
+
{ challengeId, challengeExpiresAt },
|
|
2083
|
+
signal
|
|
2084
|
+
);
|
|
2085
|
+
}
|
|
2086
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
2087
|
+
const push = await git(
|
|
2088
|
+
root,
|
|
2089
|
+
[
|
|
2090
|
+
"-c",
|
|
2091
|
+
"core.hooksPath=/dev/null",
|
|
2092
|
+
"-c",
|
|
2093
|
+
"push.followTags=false",
|
|
2094
|
+
"-c",
|
|
2095
|
+
"push.recurseSubmodules=no",
|
|
2096
|
+
"-c",
|
|
2097
|
+
"push.gpgSign=false",
|
|
2098
|
+
"-c",
|
|
2099
|
+
"push.pushOption=",
|
|
2100
|
+
"push",
|
|
2101
|
+
"--no-verify",
|
|
2102
|
+
"--no-follow-tags",
|
|
2103
|
+
"--no-recurse-submodules",
|
|
2104
|
+
"--no-signed",
|
|
2105
|
+
"--quiet",
|
|
2106
|
+
"origin",
|
|
2107
|
+
`${baseSha}:refs/heads/${branch}`
|
|
2108
|
+
],
|
|
2109
|
+
signal
|
|
2110
|
+
);
|
|
2111
|
+
if (!push.ok)
|
|
2112
|
+
return push.timedOut ? failure(
|
|
2113
|
+
"push_timeout",
|
|
2114
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS2 / 1e3} s`,
|
|
2115
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
2116
|
+
) : failure(
|
|
2117
|
+
"push_refused",
|
|
2118
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
2119
|
+
`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}`
|
|
2120
|
+
);
|
|
2121
|
+
return { ...challenge, repository };
|
|
2122
|
+
}
|
|
2123
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
2124
|
+
let context;
|
|
2125
|
+
try {
|
|
2126
|
+
context = sessionContext(deps);
|
|
2127
|
+
} catch (error) {
|
|
2128
|
+
return failure(
|
|
2129
|
+
"environment_credential_invalid",
|
|
2130
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
2131
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
2132
|
+
);
|
|
873
2133
|
}
|
|
874
|
-
|
|
2134
|
+
if ("status" in context) return context;
|
|
2135
|
+
const ctx = context;
|
|
2136
|
+
const startedAt2 = Date.now();
|
|
2137
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
2138
|
+
return withFileLock(
|
|
2139
|
+
ctx.lockPath,
|
|
2140
|
+
async () => {
|
|
2141
|
+
const record = readToken(ctx);
|
|
2142
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
2143
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
2144
|
+
if (record) {
|
|
2145
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
2146
|
+
if (refreshed.status === "ok") {
|
|
2147
|
+
writeToken(ctx, refreshed.record);
|
|
2148
|
+
return identified(refreshed.record, true);
|
|
2149
|
+
}
|
|
2150
|
+
if (refreshed.status === "refused") {
|
|
2151
|
+
rmSync5(ctx.tokenPath, { force: true });
|
|
2152
|
+
writeState(ctx, {
|
|
2153
|
+
sessionId: ctx.sessionId,
|
|
2154
|
+
status: "failed",
|
|
2155
|
+
code: refreshed.failure.code,
|
|
2156
|
+
cause: refreshed.failure.cause,
|
|
2157
|
+
remedy: refreshed.failure.remedy,
|
|
2158
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
2159
|
+
at: Date.now()
|
|
2160
|
+
});
|
|
2161
|
+
return refreshed.failure;
|
|
2162
|
+
}
|
|
2163
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
2164
|
+
}
|
|
2165
|
+
const state = readState(ctx);
|
|
2166
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
2167
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
2168
|
+
if (!options.explicit) {
|
|
2169
|
+
if (!root || !(record || state))
|
|
2170
|
+
return failure(
|
|
2171
|
+
"not_identified",
|
|
2172
|
+
"this session has not identified who started it yet",
|
|
2173
|
+
RETRY_REMEDY
|
|
2174
|
+
);
|
|
2175
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
2176
|
+
} else if (state && state.at >= startedAt2) {
|
|
2177
|
+
return outcomeFromState(state);
|
|
2178
|
+
}
|
|
2179
|
+
if (!root)
|
|
2180
|
+
return failure(
|
|
2181
|
+
"repository_missing",
|
|
2182
|
+
"this is not a git repository",
|
|
2183
|
+
"run it in the repository the session cloned"
|
|
2184
|
+
);
|
|
2185
|
+
const attempt = { root };
|
|
2186
|
+
const remember = (outcome) => {
|
|
2187
|
+
writeState(ctx, {
|
|
2188
|
+
sessionId: ctx.sessionId,
|
|
2189
|
+
status: outcome.status,
|
|
2190
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
2191
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
2192
|
+
githubLogin: outcome.githubLogin
|
|
2193
|
+
},
|
|
2194
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
2195
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
2196
|
+
repositoryRoot: root,
|
|
2197
|
+
branch: attempt.branch ?? state?.branch,
|
|
2198
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
2199
|
+
at: Date.now()
|
|
2200
|
+
});
|
|
2201
|
+
return outcome;
|
|
2202
|
+
};
|
|
2203
|
+
let challenge;
|
|
2204
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
2205
|
+
attempt.challengeId = state.challengeId;
|
|
2206
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2207
|
+
attempt.branch = state.branch;
|
|
2208
|
+
attempt.baseSha = state.baseSha;
|
|
2209
|
+
challenge = {
|
|
2210
|
+
challengeId: state.challengeId,
|
|
2211
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2212
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
2213
|
+
};
|
|
2214
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
2215
|
+
attempt.challengeId = state.challengeId;
|
|
2216
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
2217
|
+
const exchanged2 = await exchangeChallenge(
|
|
2218
|
+
ctx,
|
|
2219
|
+
{
|
|
2220
|
+
challengeId: state.challengeId,
|
|
2221
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
2222
|
+
githubLogin: state.githubLogin
|
|
2223
|
+
},
|
|
2224
|
+
root,
|
|
2225
|
+
deps,
|
|
2226
|
+
options.signal
|
|
2227
|
+
);
|
|
2228
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
2229
|
+
writeToken(ctx, exchanged2);
|
|
2230
|
+
return identified(exchanged2, false);
|
|
2231
|
+
} else if (!options.explicit) {
|
|
2232
|
+
return state ? outcomeFromState(state) : failure(
|
|
2233
|
+
"not_identified",
|
|
2234
|
+
"this session has not identified who started it yet",
|
|
2235
|
+
RETRY_REMEDY
|
|
2236
|
+
);
|
|
2237
|
+
} else {
|
|
2238
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
2239
|
+
if ("status" in pushed) return remember(pushed);
|
|
2240
|
+
challenge = pushed;
|
|
2241
|
+
}
|
|
2242
|
+
const verified = await pollChallenge(
|
|
2243
|
+
ctx.apiUrl,
|
|
2244
|
+
challenge.challengeId,
|
|
2245
|
+
challenge.repository,
|
|
2246
|
+
// A hook process waits only briefly for a late notice.
|
|
2247
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
2248
|
+
options.signal
|
|
2249
|
+
);
|
|
2250
|
+
if ("status" in verified) return remember(verified);
|
|
2251
|
+
const exchanged = await exchangeChallenge(
|
|
2252
|
+
ctx,
|
|
2253
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
2254
|
+
root,
|
|
2255
|
+
deps,
|
|
2256
|
+
options.signal
|
|
2257
|
+
);
|
|
2258
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
2259
|
+
writeToken(ctx, exchanged);
|
|
2260
|
+
return identified(exchanged, false);
|
|
2261
|
+
},
|
|
2262
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
2263
|
+
);
|
|
875
2264
|
}
|
|
876
|
-
function
|
|
877
|
-
|
|
2265
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
2266
|
+
const cached2 = cachedSessionCredential(deps);
|
|
2267
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
2268
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
2269
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2270
|
+
let outcome;
|
|
2271
|
+
try {
|
|
2272
|
+
outcome = await ensureSessionIdentity(
|
|
2273
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
2274
|
+
deps
|
|
2275
|
+
);
|
|
2276
|
+
} catch (error) {
|
|
2277
|
+
options.signal?.throwIfAborted();
|
|
2278
|
+
if (error instanceof MachineAuthError) throw error;
|
|
2279
|
+
throw new MachineAuthError(
|
|
2280
|
+
"identity_unavailable",
|
|
2281
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
2282
|
+
);
|
|
2283
|
+
}
|
|
2284
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
2285
|
+
throw new MachineAuthError(
|
|
2286
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
2287
|
+
sessionIdentityMessage(outcome)
|
|
2288
|
+
);
|
|
878
2289
|
}
|
|
879
2290
|
|
|
880
2291
|
// src/lib/machine-credentials.ts
|
|
881
|
-
|
|
2292
|
+
function sessionScoped(deps) {
|
|
2293
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
2294
|
+
}
|
|
2295
|
+
var require3 = createRequire2(import.meta.url);
|
|
882
2296
|
var SERVICE = "ai.primitive.prim.machine";
|
|
883
|
-
var
|
|
2297
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
884
2298
|
var PROFILE_FILE = "machine_profile.json";
|
|
885
|
-
var
|
|
2299
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
886
2300
|
var cached;
|
|
887
2301
|
function configurationDirectory(deps) {
|
|
888
2302
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
889
2303
|
}
|
|
890
2304
|
function apiUrlFor(deps) {
|
|
891
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
2305
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
892
2306
|
}
|
|
893
|
-
function
|
|
894
|
-
return
|
|
2307
|
+
function hash2(value) {
|
|
2308
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
895
2309
|
}
|
|
896
2310
|
function recordPath(directory, generation) {
|
|
897
|
-
return
|
|
2311
|
+
return join9(directory, `machine_${generation}.json`);
|
|
898
2312
|
}
|
|
899
2313
|
function storageKey(directory, generation) {
|
|
900
|
-
return `${
|
|
2314
|
+
return `${hash2(directory)}:${generation}`;
|
|
901
2315
|
}
|
|
902
2316
|
function environmentContextPath(deps, clientId) {
|
|
903
|
-
return
|
|
2317
|
+
return join9(
|
|
904
2318
|
configurationDirectory(deps),
|
|
905
|
-
`machine_context_${
|
|
2319
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
906
2320
|
);
|
|
907
2321
|
}
|
|
908
2322
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -960,27 +2374,33 @@ function readEnvironmentContext(environment, deps) {
|
|
|
960
2374
|
return void 0;
|
|
961
2375
|
}
|
|
962
2376
|
}
|
|
963
|
-
function
|
|
964
|
-
let directory =
|
|
2377
|
+
function keyringLoaderPath(start, options = {}) {
|
|
2378
|
+
let directory = start;
|
|
965
2379
|
for (let depth = 0; depth < 5; depth++) {
|
|
966
|
-
const loader =
|
|
967
|
-
if (
|
|
968
|
-
|
|
969
|
-
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
970
|
-
}
|
|
971
|
-
directory = dirname4(directory);
|
|
2380
|
+
const loader = join9(directory, "native", "keyring.cjs");
|
|
2381
|
+
if (existsSync5(loader)) return loader;
|
|
2382
|
+
directory = dirname7(directory);
|
|
972
2383
|
}
|
|
973
|
-
|
|
2384
|
+
try {
|
|
2385
|
+
createRequire2(join9(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
2386
|
+
return void 0;
|
|
2387
|
+
} catch {
|
|
2388
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
function keyringEntry(key) {
|
|
2392
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath3(import.meta.url)));
|
|
2393
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
974
2394
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
975
2395
|
}
|
|
976
2396
|
function protectPath(path, directory) {
|
|
977
2397
|
if (process.platform !== "win32") {
|
|
978
|
-
|
|
2398
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
979
2399
|
return;
|
|
980
2400
|
}
|
|
981
2401
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
982
2402
|
const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
|
|
983
|
-
|
|
2403
|
+
execFileSync2(
|
|
984
2404
|
"powershell.exe",
|
|
985
2405
|
[
|
|
986
2406
|
"-NoProfile",
|
|
@@ -992,8 +2412,8 @@ function protectPath(path, directory) {
|
|
|
992
2412
|
);
|
|
993
2413
|
}
|
|
994
2414
|
function ensureDirectory(directory) {
|
|
995
|
-
|
|
996
|
-
if (
|
|
2415
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
2416
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
997
2417
|
throw new MachineAuthError(
|
|
998
2418
|
"unsafe_storage",
|
|
999
2419
|
"Credential directory must not be a symbolic link."
|
|
@@ -1005,17 +2425,20 @@ function writePrivate(path, value) {
|
|
|
1005
2425
|
`, { mode: 384 });
|
|
1006
2426
|
protectPath(path, false);
|
|
1007
2427
|
}
|
|
2428
|
+
function readMachineMetadata(path) {
|
|
2429
|
+
return readPrivate(path);
|
|
2430
|
+
}
|
|
1008
2431
|
function readPrivate(path) {
|
|
1009
2432
|
let raw;
|
|
1010
2433
|
try {
|
|
1011
|
-
const stat =
|
|
2434
|
+
const stat = lstatSync4(path);
|
|
1012
2435
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
1013
2436
|
throw new MachineAuthError(
|
|
1014
2437
|
"unsafe_storage",
|
|
1015
2438
|
"Machine credential files must be owner-only regular files."
|
|
1016
2439
|
);
|
|
1017
2440
|
}
|
|
1018
|
-
raw =
|
|
2441
|
+
raw = readFileSync6(path, "utf8");
|
|
1019
2442
|
} catch (error) {
|
|
1020
2443
|
if (error.code === "ENOENT") return void 0;
|
|
1021
2444
|
throw error;
|
|
@@ -1060,7 +2483,7 @@ function parseProfile(value) {
|
|
|
1060
2483
|
};
|
|
1061
2484
|
}
|
|
1062
2485
|
function readMachineProfile(deps = {}) {
|
|
1063
|
-
const value = readPrivate(
|
|
2486
|
+
const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
|
|
1064
2487
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
1065
2488
|
}
|
|
1066
2489
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -1069,20 +2492,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
1069
2492
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
1070
2493
|
function networkSecretBrokerKey(deps, clientId) {
|
|
1071
2494
|
const directory = configurationDirectory(deps);
|
|
1072
|
-
const path =
|
|
2495
|
+
const path = join9(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
1073
2496
|
const known = brokerKeys.get(path);
|
|
1074
2497
|
if (known) return known;
|
|
1075
2498
|
ensureDirectory(directory);
|
|
1076
2499
|
const read = () => {
|
|
1077
2500
|
try {
|
|
1078
|
-
const stat =
|
|
2501
|
+
const stat = lstatSync4(path);
|
|
1079
2502
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
1080
2503
|
throw new MachineAuthError(
|
|
1081
2504
|
"unsafe_storage",
|
|
1082
2505
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
1083
2506
|
true
|
|
1084
2507
|
);
|
|
1085
|
-
const value =
|
|
2508
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
1086
2509
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
1087
2510
|
} catch (error) {
|
|
1088
2511
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -1101,16 +2524,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
1101
2524
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
1102
2525
|
true
|
|
1103
2526
|
);
|
|
1104
|
-
const staged = `${path}.${process.pid}.${
|
|
2527
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
1105
2528
|
try {
|
|
1106
|
-
|
|
2529
|
+
writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
|
|
1107
2530
|
`, { mode: 384, flag: "wx" });
|
|
1108
2531
|
protectPath(staged, false);
|
|
1109
2532
|
linkSync(staged, path);
|
|
1110
2533
|
} catch (error) {
|
|
1111
2534
|
if (error.code !== "EEXIST") throw error;
|
|
1112
2535
|
} finally {
|
|
1113
|
-
|
|
2536
|
+
rmSync6(staged, { force: true });
|
|
1114
2537
|
}
|
|
1115
2538
|
}
|
|
1116
2539
|
const key = read()?.key;
|
|
@@ -1143,7 +2566,7 @@ function environmentCredentials(deps) {
|
|
|
1143
2566
|
"conflicting_credentials",
|
|
1144
2567
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
1145
2568
|
);
|
|
1146
|
-
const generation =
|
|
2569
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
1147
2570
|
const credentials = {
|
|
1148
2571
|
clientId,
|
|
1149
2572
|
generation,
|
|
@@ -1164,12 +2587,12 @@ function environmentCredentials(deps) {
|
|
|
1164
2587
|
return {
|
|
1165
2588
|
clientId,
|
|
1166
2589
|
clientSecret,
|
|
1167
|
-
generation:
|
|
2590
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
1168
2591
|
};
|
|
1169
2592
|
}
|
|
1170
2593
|
function hasMachineConfiguration(deps = {}) {
|
|
1171
2594
|
const env = deps.env ?? process.env;
|
|
1172
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
2595
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join9(configurationDirectory(deps), PROFILE_FILE));
|
|
1173
2596
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
1174
2597
|
throw new MachineAuthError(
|
|
1175
2598
|
"conflicting_credentials",
|
|
@@ -1181,6 +2604,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
1181
2604
|
}
|
|
1182
2605
|
function machineContext(deps = {}) {
|
|
1183
2606
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2607
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1184
2608
|
const environment = environmentCredentials(deps);
|
|
1185
2609
|
if (environment) {
|
|
1186
2610
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -1195,6 +2619,7 @@ function machineContext(deps = {}) {
|
|
|
1195
2619
|
return profile;
|
|
1196
2620
|
}
|
|
1197
2621
|
function cachedMachineCredential(deps = {}) {
|
|
2622
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
1198
2623
|
const context = machineContext(deps);
|
|
1199
2624
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
1200
2625
|
}
|
|
@@ -1203,7 +2628,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
1203
2628
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
1204
2629
|
if (!generation) return false;
|
|
1205
2630
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
1206
|
-
return readPrivate(
|
|
2631
|
+
return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
1207
2632
|
}
|
|
1208
2633
|
var environmentTerminal;
|
|
1209
2634
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -1267,6 +2692,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
1267
2692
|
}
|
|
1268
2693
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
1269
2694
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
2695
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
1270
2696
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
1271
2697
|
const apiUrl = apiUrlFor(deps);
|
|
1272
2698
|
const environment = environmentCredentials(deps);
|
|
@@ -1295,7 +2721,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1295
2721
|
}
|
|
1296
2722
|
}
|
|
1297
2723
|
return withFileLock(
|
|
1298
|
-
|
|
2724
|
+
join9(directory2, "credentials.lock"),
|
|
1299
2725
|
async () => {
|
|
1300
2726
|
if (machineSessionEnded(deps))
|
|
1301
2727
|
throw new MachineAuthError(
|
|
@@ -1303,7 +2729,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1303
2729
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
1304
2730
|
true
|
|
1305
2731
|
);
|
|
1306
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
2732
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
1307
2733
|
return cached;
|
|
1308
2734
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
1309
2735
|
throw networkRejection.error;
|
|
@@ -1377,7 +2803,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1377
2803
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1378
2804
|
try {
|
|
1379
2805
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1380
|
-
|
|
2806
|
+
rmSync6(contextPath, { force: true });
|
|
1381
2807
|
} catch {
|
|
1382
2808
|
}
|
|
1383
2809
|
throw error;
|
|
@@ -1387,7 +2813,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1387
2813
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
1388
2814
|
try {
|
|
1389
2815
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
1390
|
-
|
|
2816
|
+
rmSync6(contextPath, { force: true });
|
|
1391
2817
|
} catch {
|
|
1392
2818
|
}
|
|
1393
2819
|
}
|
|
@@ -1401,7 +2827,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1401
2827
|
const expected = machineContext(deps);
|
|
1402
2828
|
const directory = configurationDirectory(deps);
|
|
1403
2829
|
return withFileLock(
|
|
1404
|
-
|
|
2830
|
+
join9(directory, "credentials.lock"),
|
|
1405
2831
|
async () => {
|
|
1406
2832
|
const profile = readMachineProfile(deps);
|
|
1407
2833
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -1416,7 +2842,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1416
2842
|
true
|
|
1417
2843
|
);
|
|
1418
2844
|
let record = await loadRecord(profile, deps, signal);
|
|
1419
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
2845
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
1420
2846
|
try {
|
|
1421
2847
|
const { tokens, identity } = await withMachineCooldown(
|
|
1422
2848
|
directory,
|
|
@@ -1451,7 +2877,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
1451
2877
|
await persistRecord(record, deps, signal);
|
|
1452
2878
|
} catch (error) {
|
|
1453
2879
|
if (error instanceof MachineAuthError && error.terminal)
|
|
1454
|
-
writePrivate(
|
|
2880
|
+
writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
|
|
1455
2881
|
throw error;
|
|
1456
2882
|
}
|
|
1457
2883
|
}
|
|
@@ -1481,13 +2907,19 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
1481
2907
|
});
|
|
1482
2908
|
}
|
|
1483
2909
|
function machineJournalBucket(identity) {
|
|
1484
|
-
return `_machine_${
|
|
2910
|
+
return `_machine_${hash2(`${identity.apiUrl}\0${identity.clientId}${identity.authorizedUserId ? `\0${identity.authorizedUserId}` : ""}`)}`;
|
|
1485
2911
|
}
|
|
1486
2912
|
function identityPending(actor) {
|
|
1487
2913
|
return actor.machineId === void 0 && actor.organizationId === void 0 && actor.authorizedUserId === void 0;
|
|
1488
2914
|
}
|
|
1489
2915
|
function machinePendingBucket(identity) {
|
|
1490
|
-
return `_machine_pending_${
|
|
2916
|
+
return `_machine_pending_${hash2(`${identity.apiUrl}\0${identity.clientId}`)}`;
|
|
2917
|
+
}
|
|
2918
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
2919
|
+
ensureDirectory(directory);
|
|
2920
|
+
}
|
|
2921
|
+
function writeMachineMetadata(path, value) {
|
|
2922
|
+
writePrivate(path, value);
|
|
1491
2923
|
}
|
|
1492
2924
|
|
|
1493
2925
|
// src/lib/machine-broker.ts
|
|
@@ -1502,14 +2934,14 @@ var FORWARD_TIMEOUT_MS = 3e4;
|
|
|
1502
2934
|
var FORWARD_METHODS = ["GET", "POST", "DELETE"];
|
|
1503
2935
|
var IDLE_MS = 5 * 6e4;
|
|
1504
2936
|
function descriptorPath(directory, generation) {
|
|
1505
|
-
return
|
|
2937
|
+
return join10(directory, `machine_broker_${generation}.json`);
|
|
1506
2938
|
}
|
|
1507
2939
|
function readDescriptor(path) {
|
|
1508
2940
|
try {
|
|
1509
|
-
const stat =
|
|
2941
|
+
const stat = lstatSync5(path);
|
|
1510
2942
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
1511
2943
|
return void 0;
|
|
1512
|
-
const data = JSON.parse(
|
|
2944
|
+
const data = JSON.parse(readFileSync7(path, "utf8"));
|
|
1513
2945
|
return Number.isInteger(data.port) && data.port > 0 && data.port <= 65535 && /^[a-f0-9]{64}$/u.test(data.nonce) && Number.isInteger(data.pid) ? data : void 0;
|
|
1514
2946
|
} catch {
|
|
1515
2947
|
return void 0;
|
|
@@ -1522,7 +2954,7 @@ function matches(left, right) {
|
|
|
1522
2954
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
1523
2955
|
}
|
|
1524
2956
|
function tokenHash(token) {
|
|
1525
|
-
return token ?
|
|
2957
|
+
return token ? createHash6("sha256").update(token).digest("hex") : void 0;
|
|
1526
2958
|
}
|
|
1527
2959
|
async function brokerRequest(descriptor, environment, options) {
|
|
1528
2960
|
const body = JSON.stringify({
|
|
@@ -1599,7 +3031,7 @@ async function acquireBrokerCredential(options) {
|
|
|
1599
3031
|
async function ensureBroker(options) {
|
|
1600
3032
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
1601
3033
|
return withFileLock(
|
|
1602
|
-
|
|
3034
|
+
join10(options.directory, "machine-broker.lock"),
|
|
1603
3035
|
async () => {
|
|
1604
3036
|
const current = readDescriptor(path);
|
|
1605
3037
|
if (current) {
|
|
@@ -1612,14 +3044,14 @@ async function ensureBroker(options) {
|
|
|
1612
3044
|
options.signal.throwIfAborted();
|
|
1613
3045
|
}
|
|
1614
3046
|
}
|
|
1615
|
-
const bundled =
|
|
1616
|
-
const entry =
|
|
3047
|
+
const bundled = fileURLToPath4(import.meta.url);
|
|
3048
|
+
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
1617
3049
|
if (!entry)
|
|
1618
3050
|
throw new MachineAuthError(
|
|
1619
3051
|
"broker_unavailable",
|
|
1620
3052
|
"Reinstall Prim to restore its machine credential broker."
|
|
1621
3053
|
);
|
|
1622
|
-
await new Promise((
|
|
3054
|
+
await new Promise((resolve4, reject) => {
|
|
1623
3055
|
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
1624
3056
|
detached: true,
|
|
1625
3057
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
@@ -1634,7 +3066,7 @@ async function ensureBroker(options) {
|
|
|
1634
3066
|
if (error) child.kill();
|
|
1635
3067
|
if (child.connected) child.disconnect();
|
|
1636
3068
|
child.unref();
|
|
1637
|
-
error ? reject(error) :
|
|
3069
|
+
error ? reject(error) : resolve4();
|
|
1638
3070
|
};
|
|
1639
3071
|
const abort = () => finish(
|
|
1640
3072
|
new MachineAuthError(
|
|
@@ -1816,7 +3248,7 @@ async function forwardToApi(apiUrl, data, signal, fetchImpl = fetch) {
|
|
|
1816
3248
|
}
|
|
1817
3249
|
async function credentialResult(apiUrl, data, signal) {
|
|
1818
3250
|
try {
|
|
1819
|
-
const current = cachedMachineCredential();
|
|
3251
|
+
const current = cachedMachineCredential({ localEnvironment: true });
|
|
1820
3252
|
const force = data.force === true && (!current || data.observedTokenHash === tokenHash(current.accessToken));
|
|
1821
3253
|
const credential = await acquireMachineCredential(
|
|
1822
3254
|
{ force, signal },
|
|
@@ -1914,7 +3346,7 @@ async function startMachineBroker() {
|
|
|
1914
3346
|
const directory = primConfigDirectory();
|
|
1915
3347
|
const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
|
|
1916
3348
|
const path = descriptorPath(directory, environment.generation);
|
|
1917
|
-
const nonce =
|
|
3349
|
+
const nonce = randomBytes4(32).toString("hex");
|
|
1918
3350
|
const server = createBrokerServer({
|
|
1919
3351
|
environment,
|
|
1920
3352
|
apiUrl,
|
|
@@ -1925,14 +3357,14 @@ async function startMachineBroker() {
|
|
|
1925
3357
|
clearTimeout(idle);
|
|
1926
3358
|
server.closeAllConnections();
|
|
1927
3359
|
server.close();
|
|
1928
|
-
if (readDescriptor(path)?.nonce === nonce)
|
|
3360
|
+
if (readDescriptor(path)?.nonce === nonce) rmSync7(path, { force: true });
|
|
1929
3361
|
};
|
|
1930
3362
|
const idle = setTimeout(close, IDLE_MS);
|
|
1931
3363
|
process.once("SIGTERM", close);
|
|
1932
3364
|
process.once("SIGINT", close);
|
|
1933
|
-
await new Promise((
|
|
3365
|
+
await new Promise((resolve4, reject) => {
|
|
1934
3366
|
server.once("error", reject);
|
|
1935
|
-
server.listen(0, "127.0.0.1",
|
|
3367
|
+
server.listen(0, "127.0.0.1", resolve4);
|
|
1936
3368
|
});
|
|
1937
3369
|
const address = server.address();
|
|
1938
3370
|
if (!address || typeof address === "string") throw new Error("Invalid broker address");
|
|
@@ -1943,27 +3375,27 @@ async function startMachineBroker() {
|
|
|
1943
3375
|
}
|
|
1944
3376
|
|
|
1945
3377
|
// src/daemon/principal.ts
|
|
1946
|
-
import { createHash as
|
|
3378
|
+
import { createHash as createHash8 } from "crypto";
|
|
1947
3379
|
|
|
1948
3380
|
// src/lib/credentials.ts
|
|
1949
|
-
import { createHash as
|
|
1950
|
-
import { readFileSync as
|
|
1951
|
-
import { join as
|
|
3381
|
+
import { createHash as createHash7 } from "crypto";
|
|
3382
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
3383
|
+
import { join as join11 } from "path";
|
|
1952
3384
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
1953
|
-
var TOKEN_FILE_PATH =
|
|
1954
|
-
var REFRESH_TOKEN_PATH =
|
|
1955
|
-
var TOKEN_EXPIRES_PATH =
|
|
1956
|
-
var TERMINAL_REFRESH_PATH =
|
|
1957
|
-
var CREDENTIAL_METADATA_PATH =
|
|
1958
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
1959
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
1960
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3385
|
+
var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
|
|
3386
|
+
var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
|
|
3387
|
+
var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
|
|
3388
|
+
var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3389
|
+
var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3390
|
+
var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
|
|
3391
|
+
var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3392
|
+
var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
|
|
1961
3393
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
1962
3394
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
1963
3395
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
1964
3396
|
function readTrimmed(path) {
|
|
1965
3397
|
try {
|
|
1966
|
-
const value =
|
|
3398
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
1967
3399
|
return value || void 0;
|
|
1968
3400
|
} catch {
|
|
1969
3401
|
return void 0;
|
|
@@ -1985,22 +3417,22 @@ function resolveAuthCredential(options = {}) {
|
|
|
1985
3417
|
);
|
|
1986
3418
|
if (metadata.state === "legacy_broker") {
|
|
1987
3419
|
if (metadata.metadata) {
|
|
1988
|
-
const
|
|
1989
|
-
if (!
|
|
3420
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3421
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
1990
3422
|
return void 0;
|
|
1991
3423
|
}
|
|
1992
3424
|
}
|
|
1993
3425
|
return { token: stored, source: "token_file" };
|
|
1994
3426
|
}
|
|
1995
3427
|
if (metadata.state === "invalid") return void 0;
|
|
1996
|
-
const
|
|
1997
|
-
if (!
|
|
3428
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3429
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
1998
3430
|
return void 0;
|
|
1999
3431
|
}
|
|
2000
3432
|
return { token: stored, source: "token_file" };
|
|
2001
3433
|
}
|
|
2002
3434
|
function credentialFingerprint(value) {
|
|
2003
|
-
return
|
|
3435
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
2004
3436
|
}
|
|
2005
3437
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2006
3438
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -2020,7 +3452,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
2020
3452
|
function readBoundedCredentialJson(path) {
|
|
2021
3453
|
let raw;
|
|
2022
3454
|
try {
|
|
2023
|
-
raw =
|
|
3455
|
+
raw = readFileSync8(path, "utf8");
|
|
2024
3456
|
} catch (error) {
|
|
2025
3457
|
return error.code === "ENOENT" ? void 0 : null;
|
|
2026
3458
|
}
|
|
@@ -2097,25 +3529,25 @@ var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
|
|
|
2097
3529
|
function boundedClaim(value) {
|
|
2098
3530
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
2099
3531
|
}
|
|
2100
|
-
function
|
|
2101
|
-
return
|
|
3532
|
+
function sha2562(value) {
|
|
3533
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
2102
3534
|
}
|
|
2103
3535
|
function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
|
|
2104
3536
|
if (hasMachineConfiguration()) {
|
|
2105
3537
|
const machine = machineContext();
|
|
2106
3538
|
return machine ? `${machine.generation}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}` : void 0;
|
|
2107
3539
|
}
|
|
2108
|
-
return token ?
|
|
3540
|
+
return token ? sha2562(token) : void 0;
|
|
2109
3541
|
}
|
|
2110
3542
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
2111
3543
|
if (hasMachineConfiguration()) {
|
|
2112
3544
|
const machine = machineContext();
|
|
2113
3545
|
return machine ? {
|
|
2114
|
-
principalId:
|
|
3546
|
+
principalId: sha2562(
|
|
2115
3547
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
2116
3548
|
),
|
|
2117
3549
|
organizationId: machine.workosOrganizationId,
|
|
2118
|
-
credentialFingerprint:
|
|
3550
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
2119
3551
|
} : void 0;
|
|
2120
3552
|
}
|
|
2121
3553
|
if (!token) return void 0;
|
|
@@ -2125,9 +3557,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
2125
3557
|
if (!(subject && organizationId)) return void 0;
|
|
2126
3558
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
2127
3559
|
return {
|
|
2128
|
-
principalId:
|
|
3560
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
2129
3561
|
organizationId,
|
|
2130
|
-
credentialFingerprint:
|
|
3562
|
+
credentialFingerprint: sha2562(token)
|
|
2131
3563
|
};
|
|
2132
3564
|
}
|
|
2133
3565
|
function isDaemonPrincipal(value) {
|
|
@@ -2181,10 +3613,10 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
2181
3613
|
}
|
|
2182
3614
|
|
|
2183
3615
|
// src/daemon/server.ts
|
|
2184
|
-
import { chmodSync as
|
|
3616
|
+
import { chmodSync as chmodSync9, existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync16, unlinkSync as unlinkSync3 } from "fs";
|
|
2185
3617
|
import { createServer as createServer2 } from "net";
|
|
2186
|
-
import { join as
|
|
2187
|
-
import { fileURLToPath as
|
|
3618
|
+
import { join as join23 } from "path";
|
|
3619
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
2188
3620
|
|
|
2189
3621
|
// src/decisions/identity.ts
|
|
2190
3622
|
var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
|
|
@@ -2264,14 +3696,14 @@ function publicDecisionResponse(value) {
|
|
|
2264
3696
|
}
|
|
2265
3697
|
|
|
2266
3698
|
// src/client.ts
|
|
2267
|
-
import { createHash as
|
|
2268
|
-
import { chmodSync as
|
|
2269
|
-
import { dirname as
|
|
3699
|
+
import { createHash as createHash9 } from "crypto";
|
|
3700
|
+
import { chmodSync as chmodSync4, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
|
|
3701
|
+
import { dirname as dirname8 } from "path";
|
|
2270
3702
|
|
|
2271
3703
|
// src/daemon/client-instance-id.ts
|
|
2272
|
-
import { randomBytes as
|
|
2273
|
-
import { chmodSync as
|
|
2274
|
-
import { join as
|
|
3704
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
3705
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync9 } from "fs";
|
|
3706
|
+
import { join as join12 } from "path";
|
|
2275
3707
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
2276
3708
|
var INSTANCE_FILE_MODE = 384;
|
|
2277
3709
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -2284,17 +3716,17 @@ function isClientInstanceId(value) {
|
|
|
2284
3716
|
}
|
|
2285
3717
|
function ensurePrivateConfigDirectory(configDir) {
|
|
2286
3718
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
2287
|
-
const metadata =
|
|
3719
|
+
const metadata = lstatSync6(configDir);
|
|
2288
3720
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
2289
3721
|
throw new Error("prim config path must be a private directory");
|
|
2290
3722
|
}
|
|
2291
|
-
|
|
3723
|
+
chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
|
|
2292
3724
|
syncDirectory(configDir);
|
|
2293
3725
|
}
|
|
2294
3726
|
function readExisting(path) {
|
|
2295
3727
|
let metadata;
|
|
2296
3728
|
try {
|
|
2297
|
-
metadata =
|
|
3729
|
+
metadata = lstatSync6(path);
|
|
2298
3730
|
} catch (error) {
|
|
2299
3731
|
if (error.code === "ENOENT") {
|
|
2300
3732
|
return;
|
|
@@ -2304,11 +3736,11 @@ function readExisting(path) {
|
|
|
2304
3736
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
2305
3737
|
throw new Error("stored client instance identity is invalid");
|
|
2306
3738
|
}
|
|
2307
|
-
|
|
3739
|
+
chmodSync3(path, INSTANCE_FILE_MODE);
|
|
2308
3740
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
2309
3741
|
throw new Error("stored client instance identity is invalid");
|
|
2310
3742
|
}
|
|
2311
|
-
const raw =
|
|
3743
|
+
const raw = readFileSync9(path, "utf8");
|
|
2312
3744
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
2313
3745
|
if (raw !== value && raw !== `${value}
|
|
2314
3746
|
` || !isClientInstanceId(value)) {
|
|
@@ -2322,8 +3754,8 @@ function atomicWrite(path, value) {
|
|
|
2322
3754
|
}
|
|
2323
3755
|
async function getOrCreateClientInstanceId(options) {
|
|
2324
3756
|
const configDir = options.configDir;
|
|
2325
|
-
const path =
|
|
2326
|
-
const lockPath =
|
|
3757
|
+
const path = join12(configDir, "client_instance_id");
|
|
3758
|
+
const lockPath = join12(configDir, "client-instance.lock");
|
|
2327
3759
|
ensurePrivateConfigDirectory(configDir);
|
|
2328
3760
|
return withFileLock(
|
|
2329
3761
|
lockPath,
|
|
@@ -2332,7 +3764,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
2332
3764
|
if (existing !== void 0) {
|
|
2333
3765
|
return existing;
|
|
2334
3766
|
}
|
|
2335
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
3767
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
2336
3768
|
"base64url"
|
|
2337
3769
|
)}`;
|
|
2338
3770
|
if (!isClientInstanceId(generated)) {
|
|
@@ -2367,60 +3799,18 @@ async function ingestUploaderHeaders() {
|
|
|
2367
3799
|
return headers;
|
|
2368
3800
|
}
|
|
2369
3801
|
|
|
2370
|
-
// src/lib/terminal-safe.ts
|
|
2371
|
-
function replaceIsolatedSurrogates(value) {
|
|
2372
|
-
let out = "";
|
|
2373
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
2374
|
-
const unit = value.charCodeAt(index);
|
|
2375
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
2376
|
-
const next = value.charCodeAt(index + 1);
|
|
2377
|
-
if (next >= 56320 && next <= 57343) {
|
|
2378
|
-
out += value[index] + value[index + 1];
|
|
2379
|
-
index += 1;
|
|
2380
|
-
} else {
|
|
2381
|
-
out += "\uFFFD";
|
|
2382
|
-
}
|
|
2383
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
2384
|
-
out += "\uFFFD";
|
|
2385
|
-
} else {
|
|
2386
|
-
out += value[index];
|
|
2387
|
-
}
|
|
2388
|
-
}
|
|
2389
|
-
return out;
|
|
2390
|
-
}
|
|
2391
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
2392
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2393
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2394
|
-
point === 1564 || // Arabic letter mark
|
|
2395
|
-
point === 6158 || // Mongolian vowel separator
|
|
2396
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2397
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2398
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2399
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2400
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
2401
|
-
point >= 917504 && point <= 917631;
|
|
2402
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
2403
|
-
}
|
|
2404
|
-
function terminalSafeText(value) {
|
|
2405
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2406
|
-
}
|
|
2407
|
-
function terminalSafeLine(value) {
|
|
2408
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2409
|
-
}
|
|
2410
|
-
var stripControlChars = terminalSafeText;
|
|
2411
|
-
|
|
2412
3802
|
// src/client.ts
|
|
2413
3803
|
var CONFIG_DIR_MODE = 448;
|
|
2414
3804
|
var CREDENTIAL_FILE_MODE = 384;
|
|
2415
3805
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
2416
|
-
var
|
|
3806
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
2417
3807
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
2418
3808
|
function authExpiredMessage() {
|
|
2419
3809
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
2420
3810
|
}
|
|
2421
3811
|
function readTrimmed2(path) {
|
|
2422
3812
|
try {
|
|
2423
|
-
const value =
|
|
3813
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
2424
3814
|
return value || void 0;
|
|
2425
3815
|
} catch {
|
|
2426
3816
|
return void 0;
|
|
@@ -2430,23 +3820,23 @@ function getSiteUrl() {
|
|
|
2430
3820
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
2431
3821
|
}
|
|
2432
3822
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
2433
|
-
return primApiUrl?.trim() ||
|
|
3823
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
2434
3824
|
}
|
|
2435
3825
|
function expiresAtFor(token, expiresIn) {
|
|
2436
3826
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
2437
3827
|
}
|
|
2438
3828
|
function ensureConfigDirectory() {
|
|
2439
|
-
const directory =
|
|
2440
|
-
|
|
2441
|
-
|
|
3829
|
+
const directory = dirname8(TOKEN_FILE_PATH);
|
|
3830
|
+
mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
3831
|
+
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
2442
3832
|
}
|
|
2443
3833
|
function atomicWrite2(path, content) {
|
|
2444
3834
|
ensureConfigDirectory();
|
|
2445
3835
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
2446
3836
|
}
|
|
2447
3837
|
function removeCredentialFile(path) {
|
|
2448
|
-
if (!
|
|
2449
|
-
|
|
3838
|
+
if (!existsSync6(path)) return false;
|
|
3839
|
+
rmSync8(path, { force: true });
|
|
2450
3840
|
return true;
|
|
2451
3841
|
}
|
|
2452
3842
|
function getTokenExpiresAt() {
|
|
@@ -2461,23 +3851,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
2461
3851
|
const expiresAt = getTokenExpiresAt();
|
|
2462
3852
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
2463
3853
|
}
|
|
2464
|
-
function refreshFingerprint(
|
|
2465
|
-
return
|
|
3854
|
+
function refreshFingerprint(refreshToken3) {
|
|
3855
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
2466
3856
|
}
|
|
2467
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
3857
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
2468
3858
|
return {
|
|
2469
3859
|
version: 1,
|
|
2470
3860
|
family: "legacy_broker",
|
|
2471
3861
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2472
|
-
refreshTokenHash: refreshFingerprint(
|
|
3862
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2473
3863
|
};
|
|
2474
3864
|
}
|
|
2475
|
-
function credentialFamilyMetadata(accessToken,
|
|
3865
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
2476
3866
|
const hashes = {
|
|
2477
3867
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
2478
|
-
refreshTokenHash: refreshFingerprint(
|
|
3868
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
2479
3869
|
};
|
|
2480
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
3870
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
2481
3871
|
}
|
|
2482
3872
|
function writeCredentialMigrationSentinel() {
|
|
2483
3873
|
atomicWrite2(
|
|
@@ -2489,11 +3879,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
2489
3879
|
`
|
|
2490
3880
|
);
|
|
2491
3881
|
}
|
|
2492
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
2493
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
3882
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
3883
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
2494
3884
|
return { state: "invalid" };
|
|
2495
3885
|
}
|
|
2496
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3886
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2497
3887
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
2498
3888
|
return { state: "invalid" };
|
|
2499
3889
|
}
|
|
@@ -2510,17 +3900,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
2510
3900
|
const metadata = readStoredCredentialMetadata();
|
|
2511
3901
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
2512
3902
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
2513
|
-
const
|
|
2514
|
-
if (!(accessToken &&
|
|
2515
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
3903
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
3904
|
+
if (!(accessToken && refreshToken3)) return;
|
|
3905
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
2516
3906
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2517
3907
|
`);
|
|
2518
3908
|
}
|
|
2519
3909
|
function terminalFingerprint() {
|
|
2520
3910
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
2521
3911
|
}
|
|
2522
|
-
function writeTerminalFingerprint(
|
|
2523
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
3912
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
3913
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
2524
3914
|
`);
|
|
2525
3915
|
}
|
|
2526
3916
|
function clearTerminalFingerprint() {
|
|
@@ -2529,20 +3919,20 @@ function clearTerminalFingerprint() {
|
|
|
2529
3919
|
function isSessionEnded() {
|
|
2530
3920
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
2531
3921
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
2532
|
-
const
|
|
3922
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
2533
3923
|
const ended = terminalFingerprint();
|
|
2534
|
-
return Boolean(
|
|
3924
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
2535
3925
|
}
|
|
2536
3926
|
function withCredentialLock(operation, options = {}) {
|
|
2537
3927
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
2538
3928
|
}
|
|
2539
3929
|
function commitCredentialsUnlocked(credentials) {
|
|
2540
3930
|
const accessToken = credentials.accessToken.trim();
|
|
2541
|
-
const
|
|
2542
|
-
if (!accessToken || !
|
|
3931
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
3932
|
+
if (!accessToken || !refreshToken3) {
|
|
2543
3933
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
2544
3934
|
}
|
|
2545
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
3935
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
2546
3936
|
if (credentials.metadata !== void 0) {
|
|
2547
3937
|
preserveMarkerlessLegacyGeneration();
|
|
2548
3938
|
writeCredentialMigrationSentinel();
|
|
@@ -2550,10 +3940,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
2550
3940
|
`);
|
|
2551
3941
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
2552
3942
|
`);
|
|
2553
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3943
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2554
3944
|
`);
|
|
2555
3945
|
} else {
|
|
2556
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
3946
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
2557
3947
|
`);
|
|
2558
3948
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
2559
3949
|
`);
|
|
@@ -2590,15 +3980,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
2590
3980
|
`
|
|
2591
3981
|
);
|
|
2592
3982
|
}
|
|
2593
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
3983
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
2594
3984
|
const current = readStoredCredentialMetadata();
|
|
2595
3985
|
if (expected.state === "legacy_broker") {
|
|
2596
3986
|
if (current.state !== "legacy_broker") return false;
|
|
2597
3987
|
if (!expected.metadata) return current.metadata === void 0;
|
|
2598
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3988
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2599
3989
|
}
|
|
2600
3990
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
2601
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
3991
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
2602
3992
|
}
|
|
2603
3993
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
2604
3994
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -2767,7 +4157,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
2767
4157
|
);
|
|
2768
4158
|
}
|
|
2769
4159
|
var _refreshInFlight;
|
|
2770
|
-
function
|
|
4160
|
+
function refreshToken2(options = {}) {
|
|
2771
4161
|
if (hasMachineConfiguration())
|
|
2772
4162
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
2773
4163
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -2905,7 +4295,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
2905
4295
|
if (response.status === 401)
|
|
2906
4296
|
throw new HttpError(
|
|
2907
4297
|
401,
|
|
2908
|
-
selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
4298
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
2909
4299
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
2910
4300
|
)
|
|
2911
4301
|
);
|
|
@@ -2926,7 +4316,7 @@ async function request2(method, path, body, options) {
|
|
|
2926
4316
|
let refreshAttempted = false;
|
|
2927
4317
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2928
4318
|
refreshAttempted = true;
|
|
2929
|
-
const token = await
|
|
4319
|
+
const token = await refreshToken2({
|
|
2930
4320
|
signal: options?.signal,
|
|
2931
4321
|
quiet: options?.quietRefresh
|
|
2932
4322
|
});
|
|
@@ -2945,7 +4335,7 @@ async function request2(method, path, body, options) {
|
|
|
2945
4335
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
2946
4336
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
2947
4337
|
refreshAttempted = true;
|
|
2948
|
-
retryToken = await
|
|
4338
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
2949
4339
|
}
|
|
2950
4340
|
if (retryToken) {
|
|
2951
4341
|
_cachedCredential = {
|
|
@@ -2969,7 +4359,7 @@ async function getPinnedClient(options = {}) {
|
|
|
2969
4359
|
const siteUrl = getSiteUrl();
|
|
2970
4360
|
let credential = selectedCredential();
|
|
2971
4361
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
2972
|
-
const token2 = await
|
|
4362
|
+
const token2 = await refreshToken2({
|
|
2973
4363
|
signal: options.signal,
|
|
2974
4364
|
quiet: options.quietRefresh
|
|
2975
4365
|
});
|
|
@@ -2987,66 +4377,66 @@ async function getPinnedClient(options = {}) {
|
|
|
2987
4377
|
}
|
|
2988
4378
|
|
|
2989
4379
|
// src/flusher.ts
|
|
2990
|
-
import { createReadStream, renameSync as
|
|
2991
|
-
import { dirname as
|
|
4380
|
+
import { createReadStream, renameSync as renameSync4, statSync as statSync3, unlinkSync } from "fs";
|
|
4381
|
+
import { dirname as dirname12, join as join19 } from "path";
|
|
2992
4382
|
|
|
2993
4383
|
// src/dead-letter.ts
|
|
2994
|
-
import { createHash as
|
|
4384
|
+
import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
|
|
2995
4385
|
import {
|
|
2996
|
-
constants as
|
|
2997
|
-
chmodSync as
|
|
4386
|
+
constants as constants3,
|
|
4387
|
+
chmodSync as chmodSync5,
|
|
2998
4388
|
closeSync as closeSync2,
|
|
2999
|
-
existsSync as
|
|
4389
|
+
existsSync as existsSync7,
|
|
3000
4390
|
fchmodSync as fchmodSync2,
|
|
3001
4391
|
fsyncSync as fsyncSync2,
|
|
3002
|
-
mkdirSync as
|
|
4392
|
+
mkdirSync as mkdirSync6,
|
|
3003
4393
|
openSync as openSync2,
|
|
3004
|
-
renameSync as
|
|
3005
|
-
rmSync as
|
|
3006
|
-
writeFileSync as
|
|
4394
|
+
renameSync as renameSync3,
|
|
4395
|
+
rmSync as rmSync9,
|
|
4396
|
+
writeFileSync as writeFileSync5
|
|
3007
4397
|
} from "fs";
|
|
3008
|
-
import { dirname as
|
|
4398
|
+
import { dirname as dirname9, join as join14 } from "path";
|
|
3009
4399
|
var DIRECTORY_MODE2 = 448;
|
|
3010
4400
|
var FILE_MODE2 = 384;
|
|
3011
4401
|
var DEAD_LETTER_DIRNAME = "dead-letter";
|
|
3012
4402
|
function deadLetterDirectoryForRotation(flushingPath) {
|
|
3013
|
-
return
|
|
4403
|
+
return join14(dirname9(flushingPath), DEAD_LETTER_DIRNAME);
|
|
3014
4404
|
}
|
|
3015
4405
|
function deadLetterPathForRawLine(flushingPath, rawLine) {
|
|
3016
|
-
const quarantineId =
|
|
3017
|
-
return
|
|
4406
|
+
const quarantineId = createHash10("sha256").update(rawLine).digest("hex");
|
|
4407
|
+
return join14(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
|
|
3018
4408
|
}
|
|
3019
4409
|
function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
|
|
3020
4410
|
const directory = deadLetterDirectoryForRotation(flushingPath);
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
persistDirectory(
|
|
4411
|
+
mkdirSync6(directory, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
4412
|
+
chmodSync5(directory, DIRECTORY_MODE2);
|
|
4413
|
+
persistDirectory(dirname9(directory));
|
|
3024
4414
|
return directory;
|
|
3025
4415
|
}
|
|
3026
4416
|
function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
|
|
3027
|
-
if (
|
|
4417
|
+
if (existsSync7(path)) {
|
|
3028
4418
|
persistDirectory(directory);
|
|
3029
4419
|
return;
|
|
3030
4420
|
}
|
|
3031
|
-
const temporaryPath =
|
|
4421
|
+
const temporaryPath = join14(
|
|
3032
4422
|
directory,
|
|
3033
|
-
`.${quarantineId}.${String(process.pid)}.${
|
|
4423
|
+
`.${quarantineId}.${String(process.pid)}.${randomBytes6(8).toString("hex")}.tmp`
|
|
3034
4424
|
);
|
|
3035
|
-
const flags =
|
|
4425
|
+
const flags = constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW;
|
|
3036
4426
|
try {
|
|
3037
4427
|
const fd = openSync2(temporaryPath, flags, FILE_MODE2);
|
|
3038
4428
|
try {
|
|
3039
4429
|
fchmodSync2(fd, FILE_MODE2);
|
|
3040
|
-
|
|
4430
|
+
writeFileSync5(fd, `${JSON.stringify(record)}
|
|
3041
4431
|
`, "utf8");
|
|
3042
4432
|
fsyncSync2(fd);
|
|
3043
4433
|
} finally {
|
|
3044
4434
|
closeSync2(fd);
|
|
3045
4435
|
}
|
|
3046
|
-
|
|
4436
|
+
renameSync3(temporaryPath, path);
|
|
3047
4437
|
persistDirectory(directory);
|
|
3048
4438
|
} finally {
|
|
3049
|
-
|
|
4439
|
+
rmSync9(temporaryPath, { force: true });
|
|
3050
4440
|
}
|
|
3051
4441
|
}
|
|
3052
4442
|
function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
|
|
@@ -3055,12 +4445,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
|
|
|
3055
4445
|
const serializedMove = JSON.stringify(move);
|
|
3056
4446
|
const record = {
|
|
3057
4447
|
version: 1,
|
|
3058
|
-
quarantineId:
|
|
4448
|
+
quarantineId: createHash10("sha256").update(serializedMove).digest("hex"),
|
|
3059
4449
|
quarantinedAt: now(),
|
|
3060
4450
|
reason,
|
|
3061
4451
|
move
|
|
3062
4452
|
};
|
|
3063
|
-
const path =
|
|
4453
|
+
const path = join14(directory, `${record.quarantineId}.json`);
|
|
3064
4454
|
persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
|
|
3065
4455
|
return record;
|
|
3066
4456
|
}
|
|
@@ -3071,7 +4461,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
3071
4461
|
const record = {
|
|
3072
4462
|
version: 1,
|
|
3073
4463
|
recordKind: "raw_line_v1",
|
|
3074
|
-
quarantineId:
|
|
4464
|
+
quarantineId: createHash10("sha256").update(bytes).digest("hex"),
|
|
3075
4465
|
quarantinedAt: now(),
|
|
3076
4466
|
reason: "invalid_move",
|
|
3077
4467
|
rawLineEncoding: "base64",
|
|
@@ -3090,14 +4480,14 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
3090
4480
|
|
|
3091
4481
|
// src/drain-progress.ts
|
|
3092
4482
|
import {
|
|
3093
|
-
chmodSync as
|
|
3094
|
-
existsSync as
|
|
3095
|
-
readFileSync as
|
|
3096
|
-
readdirSync as
|
|
3097
|
-
rmSync as
|
|
4483
|
+
chmodSync as chmodSync6,
|
|
4484
|
+
existsSync as existsSync8,
|
|
4485
|
+
readFileSync as readFileSync11,
|
|
4486
|
+
readdirSync as readdirSync3,
|
|
4487
|
+
rmSync as rmSync10,
|
|
3098
4488
|
rmdirSync
|
|
3099
4489
|
} from "fs";
|
|
3100
|
-
import { basename as
|
|
4490
|
+
import { basename as basename3, dirname as dirname10, join as join15 } from "path";
|
|
3101
4491
|
var DIRECTORY_MODE3 = 448;
|
|
3102
4492
|
var FILE_MODE3 = 384;
|
|
3103
4493
|
var DRAIN_PROGRESS_DIRNAME = "drain-progress";
|
|
@@ -3106,10 +4496,10 @@ function rotationIdentity(stat) {
|
|
|
3106
4496
|
return { size: stat.size, ino: stat.ino, dev: stat.dev };
|
|
3107
4497
|
}
|
|
3108
4498
|
function drainProgressDirectory(flushingPath) {
|
|
3109
|
-
return
|
|
4499
|
+
return join15(dirname10(flushingPath), DRAIN_PROGRESS_DIRNAME);
|
|
3110
4500
|
}
|
|
3111
4501
|
function drainProgressPath(flushingPath) {
|
|
3112
|
-
return
|
|
4502
|
+
return join15(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
|
|
3113
4503
|
}
|
|
3114
4504
|
function isByteCount(value) {
|
|
3115
4505
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
@@ -3117,7 +4507,7 @@ function isByteCount(value) {
|
|
|
3117
4507
|
function drainResumeOffset(flushingPath, rotation) {
|
|
3118
4508
|
let parsed;
|
|
3119
4509
|
try {
|
|
3120
|
-
parsed = JSON.parse(
|
|
4510
|
+
parsed = JSON.parse(readFileSync11(drainProgressPath(flushingPath), "utf8"));
|
|
3121
4511
|
} catch {
|
|
3122
4512
|
return 0;
|
|
3123
4513
|
}
|
|
@@ -3133,7 +4523,7 @@ function drainResumeOffset(flushingPath, rotation) {
|
|
|
3133
4523
|
function writeDrainCheckpoint(flushingPath, checkpoint) {
|
|
3134
4524
|
const directory = drainProgressDirectory(flushingPath);
|
|
3135
4525
|
ensureDurableDirectory(directory, DIRECTORY_MODE3);
|
|
3136
|
-
|
|
4526
|
+
chmodSync6(directory, DIRECTORY_MODE3);
|
|
3137
4527
|
atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
|
|
3138
4528
|
`, {
|
|
3139
4529
|
mode: FILE_MODE3
|
|
@@ -3150,24 +4540,24 @@ function removeEmptyDirectory(directory) {
|
|
|
3150
4540
|
}
|
|
3151
4541
|
}
|
|
3152
4542
|
function removeDrainCheckpoint(flushingPath) {
|
|
3153
|
-
|
|
4543
|
+
rmSync10(drainProgressPath(flushingPath), { force: true });
|
|
3154
4544
|
removeEmptyDirectory(drainProgressDirectory(flushingPath));
|
|
3155
4545
|
}
|
|
3156
4546
|
function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
3157
|
-
const directory =
|
|
4547
|
+
const directory = join15(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
|
|
3158
4548
|
let names;
|
|
3159
4549
|
try {
|
|
3160
|
-
names =
|
|
4550
|
+
names = readdirSync3(directory);
|
|
3161
4551
|
} catch {
|
|
3162
4552
|
return;
|
|
3163
4553
|
}
|
|
3164
4554
|
for (const name of names) {
|
|
3165
4555
|
const rotation = CHECKPOINT_NAME.exec(name)?.[1];
|
|
3166
|
-
if (rotation === void 0 ||
|
|
4556
|
+
if (rotation === void 0 || existsSync8(join15(bucketDirectory, rotation))) {
|
|
3167
4557
|
continue;
|
|
3168
4558
|
}
|
|
3169
4559
|
try {
|
|
3170
|
-
|
|
4560
|
+
rmSync10(join15(directory, name), { force: true });
|
|
3171
4561
|
} catch {
|
|
3172
4562
|
}
|
|
3173
4563
|
}
|
|
@@ -29864,38 +31254,38 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
29864
31254
|
|
|
29865
31255
|
// src/lib/activation.ts
|
|
29866
31256
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
29867
|
-
import { existsSync as
|
|
31257
|
+
import { existsSync as existsSync10, readFileSync as readFileSync13 } from "fs";
|
|
29868
31258
|
import { homedir as homedir2 } from "os";
|
|
29869
|
-
import { join as
|
|
31259
|
+
import { join as join17 } from "path";
|
|
29870
31260
|
|
|
29871
31261
|
// src/lib/cloud-prepared.ts
|
|
29872
|
-
import { existsSync as
|
|
29873
|
-
import { join as
|
|
31262
|
+
import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync12, rmSync as rmSync11, writeFileSync as writeFileSync6 } from "fs";
|
|
31263
|
+
import { join as join16 } from "path";
|
|
29874
31264
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
29875
31265
|
function cloudPreparedPath(env = process.env) {
|
|
29876
|
-
return
|
|
31266
|
+
return join16(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
29877
31267
|
}
|
|
29878
31268
|
function isPreparedCloudSession(env = process.env) {
|
|
29879
31269
|
if (!isClaudeCloudSession(env)) return false;
|
|
29880
31270
|
try {
|
|
29881
|
-
return
|
|
31271
|
+
return existsSync9(cloudPreparedPath(env));
|
|
29882
31272
|
} catch {
|
|
29883
31273
|
return false;
|
|
29884
31274
|
}
|
|
29885
31275
|
}
|
|
29886
31276
|
|
|
29887
31277
|
// src/lib/demo-pause.ts
|
|
29888
|
-
import { execFileSync as
|
|
31278
|
+
import { execFileSync as execFileSync3 } from "child_process";
|
|
29889
31279
|
var DEMO_PAUSE_MS = 30 * 6e4;
|
|
29890
31280
|
var PAUSE_KEY = "prim.demoPause";
|
|
29891
|
-
var
|
|
29892
|
-
function
|
|
31281
|
+
var GIT_TIMEOUT_MS3 = 1e3;
|
|
31282
|
+
function git2(cwd, args) {
|
|
29893
31283
|
try {
|
|
29894
|
-
return
|
|
31284
|
+
return execFileSync3("git", args, {
|
|
29895
31285
|
cwd,
|
|
29896
31286
|
encoding: "utf-8",
|
|
29897
31287
|
stdio: ["ignore", "pipe", "ignore"],
|
|
29898
|
-
timeout:
|
|
31288
|
+
timeout: GIT_TIMEOUT_MS3
|
|
29899
31289
|
});
|
|
29900
31290
|
} catch {
|
|
29901
31291
|
return void 0;
|
|
@@ -29903,10 +31293,10 @@ function git(cwd, args) {
|
|
|
29903
31293
|
}
|
|
29904
31294
|
function setLocal(cwd, key, value) {
|
|
29905
31295
|
try {
|
|
29906
|
-
|
|
31296
|
+
execFileSync3(
|
|
29907
31297
|
"git",
|
|
29908
31298
|
value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
|
|
29909
|
-
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout:
|
|
31299
|
+
{ cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS3 }
|
|
29910
31300
|
);
|
|
29911
31301
|
} catch (error) {
|
|
29912
31302
|
if (value !== null || error.status !== 5) throw error;
|
|
@@ -29920,7 +31310,7 @@ function parsePause(value) {
|
|
|
29920
31310
|
function readCaptureConfig(cwd) {
|
|
29921
31311
|
let active;
|
|
29922
31312
|
let pause;
|
|
29923
|
-
const out =
|
|
31313
|
+
const out = git2(cwd, ["config", "--get-regexp", "^prim\\.(active|demopause)$"]) ?? "";
|
|
29924
31314
|
for (const line of out.split("\n")) {
|
|
29925
31315
|
const space = line.indexOf(" ");
|
|
29926
31316
|
const key = line.slice(0, space).toLowerCase();
|
|
@@ -29945,121 +31335,13 @@ function healDemoPause(cwd, pause, options = {}) {
|
|
|
29945
31335
|
}
|
|
29946
31336
|
}
|
|
29947
31337
|
|
|
29948
|
-
// src/lib/git.ts
|
|
29949
|
-
import { execFileSync as execFileSync3 } from "child_process";
|
|
29950
|
-
import { createHash as createHash8 } from "crypto";
|
|
29951
|
-
import { lstatSync as lstatSync5, readFileSync as readFileSync11, realpathSync } from "fs";
|
|
29952
|
-
import { basename as basename3, dirname as dirname8, isAbsolute as isAbsolute3, join as join13, relative, resolve as resolve2, sep } from "path";
|
|
29953
|
-
var GIT_TIMEOUT_MS2 = 1e3;
|
|
29954
|
-
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
29955
|
-
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
29956
|
-
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
29957
|
-
function gitToplevel(cwd) {
|
|
29958
|
-
try {
|
|
29959
|
-
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
29960
|
-
cwd,
|
|
29961
|
-
encoding: "utf-8",
|
|
29962
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29963
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29964
|
-
}).trim();
|
|
29965
|
-
} catch {
|
|
29966
|
-
return null;
|
|
29967
|
-
}
|
|
29968
|
-
}
|
|
29969
|
-
function gitValue(cwd, args) {
|
|
29970
|
-
try {
|
|
29971
|
-
const value = execFileSync3("git", args, {
|
|
29972
|
-
cwd,
|
|
29973
|
-
encoding: "utf-8",
|
|
29974
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
29975
|
-
timeout: GIT_TIMEOUT_MS2
|
|
29976
|
-
}).trim();
|
|
29977
|
-
return value || void 0;
|
|
29978
|
-
} catch {
|
|
29979
|
-
return void 0;
|
|
29980
|
-
}
|
|
29981
|
-
}
|
|
29982
|
-
function parseGithubRepositoryName(path) {
|
|
29983
|
-
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
29984
|
-
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
29985
|
-
return null;
|
|
29986
|
-
}
|
|
29987
|
-
return `${parts[0]}/${parts[1]}`;
|
|
29988
|
-
}
|
|
29989
|
-
function githubRepositoryFromRemote(remote) {
|
|
29990
|
-
if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
|
|
29991
|
-
const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
|
|
29992
|
-
remote
|
|
29993
|
-
);
|
|
29994
|
-
const path = match?.[1] ?? match?.[2];
|
|
29995
|
-
return path ? parseGithubRepositoryName(path) : null;
|
|
29996
|
-
}
|
|
29997
|
-
function checkoutSettingsText(repoRoot) {
|
|
29998
|
-
const path = join13(repoRoot, ".claude", "settings.json");
|
|
29999
|
-
try {
|
|
30000
|
-
if (!lstatSync5(join13(repoRoot, ".claude")).isDirectory()) return null;
|
|
30001
|
-
const stat = lstatSync5(path);
|
|
30002
|
-
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
30003
|
-
return readFileSync11(path, "utf8");
|
|
30004
|
-
} catch {
|
|
30005
|
-
return null;
|
|
30006
|
-
}
|
|
30007
|
-
}
|
|
30008
|
-
function checkoutDeclaration(repoRoot, name) {
|
|
30009
|
-
const text = checkoutSettingsText(repoRoot);
|
|
30010
|
-
if (text === null) return null;
|
|
30011
|
-
let parsed;
|
|
30012
|
-
try {
|
|
30013
|
-
parsed = JSON.parse(text);
|
|
30014
|
-
} catch {
|
|
30015
|
-
return null;
|
|
30016
|
-
}
|
|
30017
|
-
const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
|
|
30018
|
-
const value = typeof env === "object" && env !== null ? env[name] : void 0;
|
|
30019
|
-
return typeof value === "string" ? value : null;
|
|
30020
|
-
}
|
|
30021
|
-
function declaredGithubRepository(repoRoot) {
|
|
30022
|
-
const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
|
|
30023
|
-
return value === null ? null : parseGithubRepositoryName(value.trim());
|
|
30024
|
-
}
|
|
30025
|
-
function githubRepositoryFullName(cwd) {
|
|
30026
|
-
const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
|
|
30027
|
-
if (remote) {
|
|
30028
|
-
const fromOrigin = githubRepositoryFromRemote(remote);
|
|
30029
|
-
if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
|
|
30030
|
-
}
|
|
30031
|
-
const root = gitToplevel(cwd);
|
|
30032
|
-
return root ? declaredGithubRepository(root) : null;
|
|
30033
|
-
}
|
|
30034
|
-
function normalizeOriginRemote(remote) {
|
|
30035
|
-
const value = remote.trim();
|
|
30036
|
-
if (!value) return void 0;
|
|
30037
|
-
const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
|
|
30038
|
-
if (scp?.host && scp.path) {
|
|
30039
|
-
const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30040
|
-
return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
|
|
30041
|
-
}
|
|
30042
|
-
try {
|
|
30043
|
-
const url = new URL(value);
|
|
30044
|
-
url.username = "";
|
|
30045
|
-
url.password = "";
|
|
30046
|
-
url.search = "";
|
|
30047
|
-
url.hash = "";
|
|
30048
|
-
const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
|
|
30049
|
-
if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
|
|
30050
|
-
return void 0;
|
|
30051
|
-
} catch {
|
|
30052
|
-
return void 0;
|
|
30053
|
-
}
|
|
30054
|
-
}
|
|
30055
|
-
|
|
30056
31338
|
// src/lib/activation.ts
|
|
30057
31339
|
var PRIM_ACTIVE_KEY = "prim.active";
|
|
30058
31340
|
var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
|
|
30059
31341
|
var PRIM_REPO_SYNC_ID_KEY = "prim.repoSyncId";
|
|
30060
31342
|
var PRIM_REPO_SYNC_REPOSITORY_KEY = "prim.repoSyncRepository";
|
|
30061
31343
|
var PRIM_REPO_BINDING_STATE_KEY = "prim.repoBindingState";
|
|
30062
|
-
var
|
|
31344
|
+
var GIT_TIMEOUT_MS4 = 1e3;
|
|
30063
31345
|
var REPO_SYNC_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
30064
31346
|
var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
|
|
30065
31347
|
var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
|
|
@@ -30069,7 +31351,7 @@ function repoActiveFlag(cwd, strict = false) {
|
|
|
30069
31351
|
cwd,
|
|
30070
31352
|
encoding: "utf-8",
|
|
30071
31353
|
stdio: ["ignore", "pipe", "ignore"],
|
|
30072
|
-
timeout:
|
|
31354
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30073
31355
|
}).trim();
|
|
30074
31356
|
if (value === "true") return "true";
|
|
30075
31357
|
if (value === "false") return "false";
|
|
@@ -30090,7 +31372,7 @@ function localGitConfigValue(cwd, key) {
|
|
|
30090
31372
|
cwd,
|
|
30091
31373
|
encoding: "utf-8",
|
|
30092
31374
|
stdio: ["ignore", "pipe", "ignore"],
|
|
30093
|
-
timeout:
|
|
31375
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30094
31376
|
}).trim();
|
|
30095
31377
|
return value || void 0;
|
|
30096
31378
|
} catch {
|
|
@@ -30101,7 +31383,7 @@ function setLocalGitConfigValue(cwd, key, value) {
|
|
|
30101
31383
|
execFileSync4("git", ["config", "--local", key, value], {
|
|
30102
31384
|
cwd,
|
|
30103
31385
|
stdio: ["ignore", "ignore", "pipe"],
|
|
30104
|
-
timeout:
|
|
31386
|
+
timeout: GIT_TIMEOUT_MS4
|
|
30105
31387
|
});
|
|
30106
31388
|
}
|
|
30107
31389
|
function repoSyncId(cwd) {
|
|
@@ -30122,10 +31404,10 @@ function repositoryBindingState(cwd) {
|
|
|
30122
31404
|
function projectPrimInstallAt(root) {
|
|
30123
31405
|
if (root === null || root === homedir2()) return false;
|
|
30124
31406
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
30125
|
-
const path =
|
|
30126
|
-
if (
|
|
31407
|
+
const path = join17(root, rel);
|
|
31408
|
+
if (existsSync10(path)) {
|
|
30127
31409
|
try {
|
|
30128
|
-
const content =
|
|
31410
|
+
const content = readFileSync13(path, "utf-8");
|
|
30129
31411
|
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
30130
31412
|
} catch {
|
|
30131
31413
|
}
|
|
@@ -30534,17 +31816,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
|
|
|
30534
31816
|
import {
|
|
30535
31817
|
appendFileSync,
|
|
30536
31818
|
closeSync as closeSync3,
|
|
30537
|
-
existsSync as
|
|
31819
|
+
existsSync as existsSync11,
|
|
30538
31820
|
fstatSync,
|
|
30539
|
-
mkdirSync as
|
|
31821
|
+
mkdirSync as mkdirSync8,
|
|
30540
31822
|
openSync as openSync3,
|
|
30541
31823
|
opendirSync,
|
|
30542
|
-
readFileSync as
|
|
31824
|
+
readFileSync as readFileSync14,
|
|
30543
31825
|
readSync,
|
|
30544
|
-
readdirSync as
|
|
31826
|
+
readdirSync as readdirSync4
|
|
30545
31827
|
} from "fs";
|
|
30546
|
-
import { dirname as
|
|
30547
|
-
var JOURNAL_DIR =
|
|
31828
|
+
import { dirname as dirname11, join as join18 } from "path";
|
|
31829
|
+
var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
|
|
30548
31830
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
30549
31831
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
30550
31832
|
var PENDING_STATS_MAX_FILES = 128;
|
|
@@ -30556,7 +31838,7 @@ function envSlug(apiUrl) {
|
|
|
30556
31838
|
return slug;
|
|
30557
31839
|
}
|
|
30558
31840
|
function currentEnvDir() {
|
|
30559
|
-
return
|
|
31841
|
+
return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
30560
31842
|
}
|
|
30561
31843
|
function parseMoves(content) {
|
|
30562
31844
|
const moves = [];
|
|
@@ -30574,15 +31856,15 @@ function parseMoves(content) {
|
|
|
30574
31856
|
function listBuckets() {
|
|
30575
31857
|
const out = [];
|
|
30576
31858
|
const envDir = currentEnvDir();
|
|
30577
|
-
if (!
|
|
31859
|
+
if (!existsSync11(envDir)) {
|
|
30578
31860
|
return out;
|
|
30579
31861
|
}
|
|
30580
|
-
for (const entry of
|
|
31862
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
30581
31863
|
if (!entry.isDirectory()) {
|
|
30582
31864
|
continue;
|
|
30583
31865
|
}
|
|
30584
|
-
const path =
|
|
30585
|
-
if (
|
|
31866
|
+
const path = join18(envDir, entry.name, JOURNAL_BASENAME);
|
|
31867
|
+
if (existsSync11(path)) {
|
|
30586
31868
|
out.push({ bucket: entry.name, path });
|
|
30587
31869
|
}
|
|
30588
31870
|
}
|
|
@@ -30644,7 +31926,7 @@ function parseFlushingPid(name) {
|
|
|
30644
31926
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
30645
31927
|
}
|
|
30646
31928
|
function listFlushingInDir(dir, bucket, options = {}) {
|
|
30647
|
-
if (!
|
|
31929
|
+
if (!existsSync11(dir)) {
|
|
30648
31930
|
return [];
|
|
30649
31931
|
}
|
|
30650
31932
|
const out = [];
|
|
@@ -30658,7 +31940,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
30658
31940
|
entry = entries.readSync();
|
|
30659
31941
|
continue;
|
|
30660
31942
|
}
|
|
30661
|
-
const path =
|
|
31943
|
+
const path = join18(dir, entry.name);
|
|
30662
31944
|
let sample;
|
|
30663
31945
|
try {
|
|
30664
31946
|
sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
|
|
@@ -30685,18 +31967,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
30685
31967
|
}
|
|
30686
31968
|
function listFlushing(options = {}) {
|
|
30687
31969
|
const envDir = currentEnvDir();
|
|
30688
|
-
if (!
|
|
31970
|
+
if (!existsSync11(envDir)) {
|
|
30689
31971
|
return [];
|
|
30690
31972
|
}
|
|
30691
31973
|
const out = [];
|
|
30692
31974
|
let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
|
|
30693
31975
|
const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
|
|
30694
|
-
for (const entry of
|
|
31976
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
30695
31977
|
if (out.length >= maxFiles) {
|
|
30696
31978
|
break;
|
|
30697
31979
|
}
|
|
30698
31980
|
if (entry.isDirectory()) {
|
|
30699
|
-
const found = listFlushingInDir(
|
|
31981
|
+
const found = listFlushingInDir(join18(envDir, entry.name), entry.name, {
|
|
30700
31982
|
sampleBytes: remainingBytes,
|
|
30701
31983
|
maxFiles: maxFiles - out.length
|
|
30702
31984
|
});
|
|
@@ -30711,12 +31993,12 @@ function listFlushing(options = {}) {
|
|
|
30711
31993
|
}
|
|
30712
31994
|
function sweepOrphanedDrainProgress() {
|
|
30713
31995
|
const envDir = currentEnvDir();
|
|
30714
|
-
if (!
|
|
31996
|
+
if (!existsSync11(envDir)) {
|
|
30715
31997
|
return;
|
|
30716
31998
|
}
|
|
30717
|
-
for (const entry of
|
|
31999
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
30718
32000
|
if (entry.isDirectory()) {
|
|
30719
|
-
sweepOrphanedDrainCheckpoints(
|
|
32001
|
+
sweepOrphanedDrainCheckpoints(join18(envDir, entry.name));
|
|
30720
32002
|
}
|
|
30721
32003
|
}
|
|
30722
32004
|
}
|
|
@@ -30869,7 +32151,7 @@ async function* rawJournalLines(input, offset) {
|
|
|
30869
32151
|
}
|
|
30870
32152
|
var drainProgressWarned = false;
|
|
30871
32153
|
async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
30872
|
-
const rotation = rotationIdentity(
|
|
32154
|
+
const rotation = rotationIdentity(statSync3(flushingPath));
|
|
30873
32155
|
const resumeAt = drainResumeOffset(flushingPath, rotation);
|
|
30874
32156
|
const recordProgress = (end) => {
|
|
30875
32157
|
if (end === void 0 || end >= rotation.size) {
|
|
@@ -30996,7 +32278,7 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
|
30996
32278
|
async function drainPath(path, client2, binding, onProgress) {
|
|
30997
32279
|
const tmpPath = `${path}.flushing.${String(Date.now())}.${String(process.pid)}`;
|
|
30998
32280
|
try {
|
|
30999
|
-
|
|
32281
|
+
renameSync4(path, tmpPath);
|
|
31000
32282
|
} catch (err) {
|
|
31001
32283
|
if (err.code === "ENOENT") {
|
|
31002
32284
|
return { flushed: 0, quarantined: 0 };
|
|
@@ -31044,12 +32326,12 @@ async function recoverOrphans(candidates, options) {
|
|
|
31044
32326
|
if (summary.failedBuckets.has(file.bucket)) {
|
|
31045
32327
|
continue;
|
|
31046
32328
|
}
|
|
31047
|
-
const { counts, failure } = await settleDrain((onProgress) => drain(file.path, onProgress));
|
|
32329
|
+
const { counts, failure: failure2 } = await settleDrain((onProgress) => drain(file.path, onProgress));
|
|
31048
32330
|
summary.flushed += counts.flushed;
|
|
31049
32331
|
summary.quarantined += counts.quarantined;
|
|
31050
|
-
if (
|
|
32332
|
+
if (failure2) {
|
|
31051
32333
|
summary.failedDrainFlushed += counts.flushed;
|
|
31052
|
-
summary.errors.push(
|
|
32334
|
+
summary.errors.push(failure2.error);
|
|
31053
32335
|
summary.failedBuckets.add(file.bucket);
|
|
31054
32336
|
}
|
|
31055
32337
|
}
|
|
@@ -31108,14 +32390,14 @@ async function flushOnce() {
|
|
|
31108
32390
|
if (recovered.failedBuckets.has(bucket)) {
|
|
31109
32391
|
continue;
|
|
31110
32392
|
}
|
|
31111
|
-
const { counts, failure } = await settleDrain(
|
|
32393
|
+
const { counts, failure: failure2 } = await settleDrain(
|
|
31112
32394
|
(onProgress) => drainPath(path, client2, binding, onProgress)
|
|
31113
32395
|
);
|
|
31114
32396
|
total += counts.flushed;
|
|
31115
32397
|
quarantined += counts.quarantined;
|
|
31116
|
-
if (
|
|
32398
|
+
if (failure2) {
|
|
31117
32399
|
failedDrainFlushed += counts.flushed;
|
|
31118
|
-
errors.push(
|
|
32400
|
+
errors.push(failure2.error);
|
|
31119
32401
|
}
|
|
31120
32402
|
}
|
|
31121
32403
|
if (errors.length > 0) {
|
|
@@ -31130,7 +32412,7 @@ async function flushOnce() {
|
|
|
31130
32412
|
return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
|
|
31131
32413
|
}
|
|
31132
32414
|
var flushInFlight;
|
|
31133
|
-
var FLUSH_LOCK_PATH =
|
|
32415
|
+
var FLUSH_LOCK_PATH = join19(dirname12(JOURNAL_DIR), ".flush.lock");
|
|
31134
32416
|
var FLUSH_LOCK_TIMEOUT_MS = 250;
|
|
31135
32417
|
function isFlushLockContended(error) {
|
|
31136
32418
|
return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
|
|
@@ -31285,8 +32567,8 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
|
|
|
31285
32567
|
var STATUSLINE_INGESTION_CACHE_TTL_MS = 3e4;
|
|
31286
32568
|
var STATUSLINE_INGESTION_CACHE_MAX_ENTRIES = 256;
|
|
31287
32569
|
var StatuslineIngestionCache = class {
|
|
31288
|
-
constructor(
|
|
31289
|
-
this.resolve =
|
|
32570
|
+
constructor(resolve4, options = {}) {
|
|
32571
|
+
this.resolve = resolve4;
|
|
31290
32572
|
this.#now = options.now ?? Date.now;
|
|
31291
32573
|
this.#ttlMs = options.ttlMs ?? STATUSLINE_INGESTION_CACHE_TTL_MS;
|
|
31292
32574
|
this.#maxEntries = options.maxEntries ?? STATUSLINE_INGESTION_CACHE_MAX_ENTRIES;
|
|
@@ -31332,8 +32614,8 @@ var StatuslineIngestionCache = class {
|
|
|
31332
32614
|
|
|
31333
32615
|
// src/daemon/client.ts
|
|
31334
32616
|
import { createConnection } from "net";
|
|
31335
|
-
import { join as
|
|
31336
|
-
var SOCK_PATH =
|
|
32617
|
+
import { join as join20 } from "path";
|
|
32618
|
+
var SOCK_PATH = join20(primConfigDirectory(), "sock");
|
|
31337
32619
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
31338
32620
|
var nextRequestId = 1;
|
|
31339
32621
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -31346,7 +32628,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
31346
32628
|
...caller ? { caller } : {}
|
|
31347
32629
|
};
|
|
31348
32630
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
31349
|
-
return new Promise((
|
|
32631
|
+
return new Promise((resolve4) => {
|
|
31350
32632
|
let settled = false;
|
|
31351
32633
|
let socket;
|
|
31352
32634
|
let buffer = Buffer.alloc(0);
|
|
@@ -31361,7 +32643,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
31361
32643
|
} catch {
|
|
31362
32644
|
}
|
|
31363
32645
|
}
|
|
31364
|
-
|
|
32646
|
+
resolve4(value);
|
|
31365
32647
|
};
|
|
31366
32648
|
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
31367
32649
|
timer.unref();
|
|
@@ -31423,7 +32705,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
31423
32705
|
}
|
|
31424
32706
|
|
|
31425
32707
|
// src/daemon/decision-digest-cache.ts
|
|
31426
|
-
import { randomBytes as
|
|
32708
|
+
import { randomBytes as randomBytes7 } from "crypto";
|
|
31427
32709
|
var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
|
|
31428
32710
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
31429
32711
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
@@ -31453,7 +32735,7 @@ function errorMessage(error) {
|
|
|
31453
32735
|
return error instanceof Error ? error.message : String(error);
|
|
31454
32736
|
}
|
|
31455
32737
|
function privatePageToken() {
|
|
31456
|
-
return
|
|
32738
|
+
return randomBytes7(16).toString("hex");
|
|
31457
32739
|
}
|
|
31458
32740
|
var DecisionDigestCache = class {
|
|
31459
32741
|
constructor(load, now = Date.now, options = {}) {
|
|
@@ -31604,8 +32886,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
|
|
|
31604
32886
|
}
|
|
31605
32887
|
|
|
31606
32888
|
// src/daemon/health.ts
|
|
31607
|
-
import { chmodSync as
|
|
31608
|
-
import { dirname as
|
|
32889
|
+
import { chmodSync as chmodSync7, existsSync as existsSync12, mkdirSync as mkdirSync9, renameSync as renameSync5, writeFileSync as writeFileSync7 } from "fs";
|
|
32890
|
+
import { dirname as dirname13, join as join21 } from "path";
|
|
31609
32891
|
var CONFIG_DIR_MODE2 = 448;
|
|
31610
32892
|
var HEALTH_FILE_MODE = 384;
|
|
31611
32893
|
var INGESTION_SLA_MS = 3e4;
|
|
@@ -31613,7 +32895,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
|
|
|
31613
32895
|
var HEARTBEAT_RETRY_CAP_MS = 3e4;
|
|
31614
32896
|
var INGESTION_RETRY_BASE_MS = 5e3;
|
|
31615
32897
|
var INGESTION_RETRY_CAP_MS = 15e3;
|
|
31616
|
-
var DAEMON_HEALTH_PATH =
|
|
32898
|
+
var DAEMON_HEALTH_PATH = join21(primConfigDirectory(), "daemon-health.json");
|
|
31617
32899
|
function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
|
|
31618
32900
|
return {
|
|
31619
32901
|
schemaVersion: 1,
|
|
@@ -31654,37 +32936,37 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
|
|
|
31654
32936
|
return retryDelayMs(consecutiveFailures, INGESTION_RETRY_CAP_MS, random);
|
|
31655
32937
|
}
|
|
31656
32938
|
function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
31657
|
-
const dir =
|
|
31658
|
-
if (!
|
|
31659
|
-
|
|
32939
|
+
const dir = dirname13(path);
|
|
32940
|
+
if (!existsSync12(dir)) {
|
|
32941
|
+
mkdirSync9(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
|
|
31660
32942
|
}
|
|
31661
|
-
const tmp =
|
|
31662
|
-
|
|
32943
|
+
const tmp = join21(dir, `.${process.pid}.daemon-health.tmp`);
|
|
32944
|
+
writeFileSync7(tmp, `${JSON.stringify(state, null, 2)}
|
|
31663
32945
|
`, { mode: HEALTH_FILE_MODE });
|
|
31664
|
-
|
|
31665
|
-
|
|
32946
|
+
chmodSync7(tmp, HEALTH_FILE_MODE);
|
|
32947
|
+
renameSync5(tmp, path);
|
|
31666
32948
|
}
|
|
31667
32949
|
|
|
31668
32950
|
// src/daemon/instance-lock.ts
|
|
31669
32951
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
31670
32952
|
import {
|
|
31671
|
-
chmodSync as
|
|
31672
|
-
existsSync as
|
|
31673
|
-
mkdirSync as
|
|
31674
|
-
readFileSync as
|
|
31675
|
-
renameSync as
|
|
31676
|
-
rmSync as
|
|
31677
|
-
statSync as
|
|
32953
|
+
chmodSync as chmodSync8,
|
|
32954
|
+
existsSync as existsSync13,
|
|
32955
|
+
mkdirSync as mkdirSync10,
|
|
32956
|
+
readFileSync as readFileSync15,
|
|
32957
|
+
renameSync as renameSync6,
|
|
32958
|
+
rmSync as rmSync12,
|
|
32959
|
+
statSync as statSync4,
|
|
31678
32960
|
unlinkSync as unlinkSync2,
|
|
31679
|
-
writeFileSync as
|
|
32961
|
+
writeFileSync as writeFileSync8
|
|
31680
32962
|
} from "fs";
|
|
31681
|
-
import { join as
|
|
32963
|
+
import { join as join22 } from "path";
|
|
31682
32964
|
var DIR_MODE = 448;
|
|
31683
32965
|
var FILE_MODE4 = 384;
|
|
31684
32966
|
var DAEMON_STARTUP_GRACE_MS = 5e3;
|
|
31685
32967
|
function readLockRecord(path) {
|
|
31686
32968
|
try {
|
|
31687
|
-
const value = JSON.parse(
|
|
32969
|
+
const value = JSON.parse(readFileSync15(path, "utf-8"));
|
|
31688
32970
|
if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
|
|
31689
32971
|
return value;
|
|
31690
32972
|
}
|
|
@@ -31694,23 +32976,23 @@ function readLockRecord(path) {
|
|
|
31694
32976
|
}
|
|
31695
32977
|
function numericPid(path) {
|
|
31696
32978
|
try {
|
|
31697
|
-
const pid = Number(
|
|
32979
|
+
const pid = Number(readFileSync15(path, "utf-8").trim());
|
|
31698
32980
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
31699
32981
|
} catch {
|
|
31700
32982
|
return;
|
|
31701
32983
|
}
|
|
31702
32984
|
}
|
|
31703
32985
|
function readDaemonOwner(configDir) {
|
|
31704
|
-
return readLockRecord(
|
|
32986
|
+
return readLockRecord(join22(configDir, "daemon.lock", "owner.json"));
|
|
31705
32987
|
}
|
|
31706
32988
|
function readDaemonPid(configDir) {
|
|
31707
|
-
const path =
|
|
32989
|
+
const path = join22(configDir, "daemon.pid");
|
|
31708
32990
|
const pid = numericPid(path);
|
|
31709
32991
|
if (pid === void 0) {
|
|
31710
32992
|
return;
|
|
31711
32993
|
}
|
|
31712
32994
|
try {
|
|
31713
|
-
return { pid, mtimeMs:
|
|
32995
|
+
return { pid, mtimeMs: statSync4(path).mtimeMs };
|
|
31714
32996
|
} catch {
|
|
31715
32997
|
return;
|
|
31716
32998
|
}
|
|
@@ -31719,16 +33001,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31719
33001
|
const pid = opts.pid ?? process.pid;
|
|
31720
33002
|
const now = opts.now ?? Date.now();
|
|
31721
33003
|
const isAlive = opts.isAlive ?? processIsAlive;
|
|
31722
|
-
const lockDir =
|
|
31723
|
-
const ownerPath2 =
|
|
31724
|
-
const pidPath =
|
|
33004
|
+
const lockDir = join22(configDir, "daemon.lock");
|
|
33005
|
+
const ownerPath2 = join22(lockDir, "owner.json");
|
|
33006
|
+
const pidPath = join22(configDir, "daemon.pid");
|
|
31725
33007
|
const instanceId2 = randomUUID3();
|
|
31726
|
-
if (!
|
|
31727
|
-
|
|
33008
|
+
if (!existsSync13(configDir)) {
|
|
33009
|
+
mkdirSync10(configDir, { recursive: true, mode: DIR_MODE });
|
|
31728
33010
|
}
|
|
31729
33011
|
for (; ; ) {
|
|
31730
33012
|
try {
|
|
31731
|
-
|
|
33013
|
+
mkdirSync10(lockDir, { mode: DIR_MODE });
|
|
31732
33014
|
break;
|
|
31733
33015
|
} catch (err) {
|
|
31734
33016
|
if (err.code !== "EEXIST") {
|
|
@@ -31741,7 +33023,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31741
33023
|
if (!existing) {
|
|
31742
33024
|
let mtimeMs;
|
|
31743
33025
|
try {
|
|
31744
|
-
mtimeMs =
|
|
33026
|
+
mtimeMs = statSync4(lockDir).mtimeMs;
|
|
31745
33027
|
} catch (statErr) {
|
|
31746
33028
|
if (statErr.code === "ENOENT") {
|
|
31747
33029
|
continue;
|
|
@@ -31754,8 +33036,8 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31754
33036
|
}
|
|
31755
33037
|
const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
|
|
31756
33038
|
try {
|
|
31757
|
-
|
|
31758
|
-
|
|
33039
|
+
renameSync6(lockDir, stale);
|
|
33040
|
+
rmSync12(stale, { recursive: true, force: true });
|
|
31759
33041
|
} catch (renameErr) {
|
|
31760
33042
|
if (renameErr.code !== "ENOENT") {
|
|
31761
33043
|
throw renameErr;
|
|
@@ -31772,16 +33054,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
31772
33054
|
instanceId: instanceId2
|
|
31773
33055
|
};
|
|
31774
33056
|
const record = { pid, instanceId: instanceId2, startedAt: now };
|
|
31775
|
-
|
|
33057
|
+
writeFileSync8(ownerPath2, `${JSON.stringify(record)}
|
|
31776
33058
|
`, { mode: FILE_MODE4 });
|
|
31777
|
-
|
|
33059
|
+
chmodSync8(ownerPath2, FILE_MODE4);
|
|
31778
33060
|
const legacyPid = numericPid(pidPath);
|
|
31779
33061
|
if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
|
|
31780
|
-
|
|
33062
|
+
rmSync12(lockDir, { recursive: true, force: true });
|
|
31781
33063
|
throw new Error(`daemon already running (pid=${String(legacyPid)})`);
|
|
31782
33064
|
}
|
|
31783
|
-
|
|
31784
|
-
|
|
33065
|
+
writeFileSync8(pidPath, String(pid), { mode: FILE_MODE4 });
|
|
33066
|
+
chmodSync8(pidPath, FILE_MODE4);
|
|
31785
33067
|
return ownership2;
|
|
31786
33068
|
}
|
|
31787
33069
|
function ownsDaemonInstance(ownership2) {
|
|
@@ -31811,7 +33093,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
|
|
|
31811
33093
|
}
|
|
31812
33094
|
}
|
|
31813
33095
|
}
|
|
31814
|
-
|
|
33096
|
+
rmSync12(ownership2.lockDir, { recursive: true, force: true });
|
|
31815
33097
|
if (cleanupError) {
|
|
31816
33098
|
throw cleanupError;
|
|
31817
33099
|
}
|
|
@@ -31866,7 +33148,7 @@ function normalizePresenceHeartbeatResponse(value) {
|
|
|
31866
33148
|
}
|
|
31867
33149
|
|
|
31868
33150
|
// src/daemon/statusline-protocol.ts
|
|
31869
|
-
import { isAbsolute as
|
|
33151
|
+
import { isAbsolute as isAbsolute5 } from "path";
|
|
31870
33152
|
var STATUSLINE_PROTOCOL_PREFIX = Buffer.from("prim-statusline-v1\0", "utf8");
|
|
31871
33153
|
var STATUSLINE_REQUEST_MAX_BYTES = 64 * 1024;
|
|
31872
33154
|
var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
@@ -31895,7 +33177,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
31895
33177
|
try {
|
|
31896
33178
|
const cwd = utf8Decoder.decode(buffer.subarray(STATUSLINE_PROTOCOL_PREFIX.length, cwdEnd));
|
|
31897
33179
|
const primApiUrl = utf8Decoder.decode(buffer.subarray(cwdEnd + 1, apiUrlEnd));
|
|
31898
|
-
if (!cwd || !
|
|
33180
|
+
if (!cwd || !isAbsolute5(cwd)) {
|
|
31899
33181
|
return { state: "invalid" };
|
|
31900
33182
|
}
|
|
31901
33183
|
return { state: "complete", request: { cwd, primApiUrl } };
|
|
@@ -31906,7 +33188,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
31906
33188
|
|
|
31907
33189
|
// src/daemon/server.ts
|
|
31908
33190
|
var CONFIG_DIR = primConfigDirectory();
|
|
31909
|
-
var SOCK_PATH2 =
|
|
33191
|
+
var SOCK_PATH2 = join23(CONFIG_DIR, "sock");
|
|
31910
33192
|
var CONFIG_DIR_MODE3 = 448;
|
|
31911
33193
|
var SOCKET_MODE = 384;
|
|
31912
33194
|
var MAX_SOCKET_CONNECTIONS = 64;
|
|
@@ -31974,8 +33256,8 @@ function resolveRuntimeVersion() {
|
|
|
31974
33256
|
return process.env.PRIM_RUNTIME_VERSION;
|
|
31975
33257
|
}
|
|
31976
33258
|
try {
|
|
31977
|
-
const here =
|
|
31978
|
-
const pkg = JSON.parse(
|
|
33259
|
+
const here = fileURLToPath5(new URL(".", import.meta.url));
|
|
33260
|
+
const pkg = JSON.parse(readFileSync16(join23(here, "..", "..", "package.json"), "utf-8"));
|
|
31979
33261
|
return pkg.version ?? "unknown";
|
|
31980
33262
|
} catch {
|
|
31981
33263
|
return "unknown";
|
|
@@ -32014,8 +33296,8 @@ function assertCallerPrincipalMatches(caller) {
|
|
|
32014
33296
|
return credentialKey;
|
|
32015
33297
|
}
|
|
32016
33298
|
function ensureDaemonDirectoryPermissions() {
|
|
32017
|
-
|
|
32018
|
-
|
|
33299
|
+
mkdirSync11(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
|
|
33300
|
+
chmodSync9(CONFIG_DIR, CONFIG_DIR_MODE3);
|
|
32019
33301
|
}
|
|
32020
33302
|
function persistHealth() {
|
|
32021
33303
|
refreshDaemonHealth(daemonHealth, Date.now());
|
|
@@ -32101,7 +33383,7 @@ async function takeOwnership() {
|
|
|
32101
33383
|
(pid) => pid !== void 0 && processIsAlive(pid)
|
|
32102
33384
|
)
|
|
32103
33385
|
);
|
|
32104
|
-
if (
|
|
33386
|
+
if (existsSync14(SOCK_PATH2) || candidatePids.size > 0) {
|
|
32105
33387
|
const snapshot = await daemonRequest(
|
|
32106
33388
|
"status_snapshot",
|
|
32107
33389
|
{},
|
|
@@ -32246,7 +33528,7 @@ async function ensureTokenFresh() {
|
|
|
32246
33528
|
}
|
|
32247
33529
|
if (Date.now() >= expiresAt - TOKEN_REFRESH_THRESHOLD_MS) {
|
|
32248
33530
|
try {
|
|
32249
|
-
await
|
|
33531
|
+
await refreshToken2({ signal: AbortSignal.timeout(HTTP_PROXY_TIMEOUT_MS) });
|
|
32250
33532
|
} catch {
|
|
32251
33533
|
}
|
|
32252
33534
|
}
|
|
@@ -32646,7 +33928,7 @@ function startSocketServer() {
|
|
|
32646
33928
|
});
|
|
32647
33929
|
socketServer.listen(SOCK_PATH2, () => {
|
|
32648
33930
|
try {
|
|
32649
|
-
|
|
33931
|
+
chmodSync9(SOCK_PATH2, SOCKET_MODE);
|
|
32650
33932
|
} catch (err) {
|
|
32651
33933
|
shutdown(EXIT_CRASH, `[prim-daemon] failed to secure socket: ${errorMessage2(err)}`);
|
|
32652
33934
|
return;
|