@primitive.ai/prim 0.1.0-alpha.128 → 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/dist/{chunk-6QAXVFRJ.js → chunk-BVGASV3B.js} +942 -123
- package/dist/{chunk-M6KIDB5R.js → chunk-DYXCJ6WZ.js} +10 -10
- package/dist/{chunk-B3ICJZXV.js → chunk-FHDTJP2C.js} +2 -2
- package/dist/{chunk-XINFTNA2.js → chunk-HDL3UXYJ.js} +5 -5
- package/dist/{chunk-C357P37M.js → chunk-IJ3W2YBM.js} +4 -4
- package/dist/{chunk-N6PZE7HX.js → chunk-IZAEAALI.js} +2 -2
- package/dist/{chunk-PTZ6BWSU.js → chunk-KZNOT2YH.js} +2 -2
- package/dist/{chunk-P4O7L7JZ.js → chunk-L7U3G4XR.js} +2 -2
- package/dist/{chunk-EQWUCFXK.js → chunk-LBZJD2I4.js} +3 -5
- package/dist/{chunk-PRJ7P6J5.js → chunk-MMMY57UA.js} +22 -837
- package/dist/{chunk-WEGZGF3K.js → chunk-NWWTFQP2.js} +1 -1
- package/dist/{chunk-NYDM4HSS.js → chunk-QSDWWEHF.js} +2 -2
- package/dist/{chunk-3KPTVK4N.js → chunk-RAEOSDQ6.js} +1 -1
- package/dist/{chunk-E57UVUJL.js → chunk-RS5ADTDF.js} +4 -4
- package/dist/{chunk-ANMNGGTN.js → chunk-RWJ7WHTJ.js} +2 -2
- package/dist/{chunk-RDT2IV2Z.js → chunk-SJE7OWVS.js} +3 -3
- package/dist/{chunk-VLT2KGPE.js → chunk-USJ4JGDC.js} +3 -3
- package/dist/{chunk-ZCT23NBS.js → chunk-YPHDV5AS.js} +2 -2
- package/dist/{chunk-QQ3G5SXX.js → chunk-YSV43WLK.js} +1 -1
- package/dist/{chunk-4DYEBYKM.js → chunk-ZKIBD5MO.js} +2 -2
- package/dist/daemon/server.js +624 -289
- package/dist/hook-runtime/daemon/server.js +624 -289
- package/dist/hook-runtime/hooks/post-commit.js +307 -186
- package/dist/hook-runtime/hooks/post-rewrite.js +302 -181
- package/dist/hook-runtime/hooks/post-tool-use.js +490 -276
- package/dist/hook-runtime/hooks/pre-commit.js +516 -181
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +221 -7
- package/dist/hook-runtime/hooks/prim-hook.js +511 -297
- package/dist/hook-runtime/hooks/session-end.js +229 -229
- package/dist/hook-runtime/hooks/session-start.js +170 -14
- package/dist/hook-runtime/index.js +1623 -1607
- package/dist/hook-runtime/statusline-main.js +245 -124
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +15 -15
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +12 -13
- package/dist/index.js +24 -24
- package/dist/statusline-main.js +245 -124
- package/package.json +1 -1
|
@@ -54,11 +54,11 @@ var require_ucs2length = __commonJS({
|
|
|
54
54
|
|
|
55
55
|
// src/lib/machine-broker.ts
|
|
56
56
|
import { spawn } from "child_process";
|
|
57
|
-
import { createHash as
|
|
58
|
-
import { lstatSync as
|
|
57
|
+
import { createHash as createHash6, createHmac, randomBytes as randomBytes4, timingSafeEqual } from "crypto";
|
|
58
|
+
import { lstatSync as lstatSync5, readFileSync as readFileSync7, rmSync as rmSync7 } from "fs";
|
|
59
59
|
import { createServer } from "http";
|
|
60
|
-
import { basename as basename2, join as
|
|
61
|
-
import { fileURLToPath as
|
|
60
|
+
import { basename as basename2, join as join10 } from "path";
|
|
61
|
+
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
62
62
|
|
|
63
63
|
// src/lib/atomic-file.ts
|
|
64
64
|
import { randomUUID } from "crypto";
|
|
@@ -143,8 +143,48 @@ function atomicWriteFile(target, content, options = {}) {
|
|
|
143
143
|
import { existsSync, readFileSync } from "fs";
|
|
144
144
|
import { dirname as dirname2, isAbsolute, join } from "path";
|
|
145
145
|
import { fileURLToPath } from "url";
|
|
146
|
+
|
|
147
|
+
// src/lib/semver.ts
|
|
148
|
+
function parseSemver(value) {
|
|
149
|
+
if (typeof value !== "string" || value.length > 256) return;
|
|
150
|
+
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(
|
|
151
|
+
value
|
|
152
|
+
);
|
|
153
|
+
if (!match) return;
|
|
154
|
+
const prerelease = match[4]?.split(".") ?? [];
|
|
155
|
+
if (prerelease.some((part) => /^\d+$/u.test(part) && part.length > 1 && part.startsWith("0"))) {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
return { core: [BigInt(match[1]), BigInt(match[2]), BigInt(match[3])], prerelease };
|
|
159
|
+
}
|
|
160
|
+
function compareSemver(left, right) {
|
|
161
|
+
const a = parseSemver(left);
|
|
162
|
+
const b = parseSemver(right);
|
|
163
|
+
if (!a || !b) return;
|
|
164
|
+
for (let i = 0; i < a.core.length; i += 1) {
|
|
165
|
+
if (a.core[i] !== b.core[i]) return a.core[i] < b.core[i] ? -1 : 1;
|
|
166
|
+
}
|
|
167
|
+
if (a.prerelease.length === 0 || b.prerelease.length === 0) {
|
|
168
|
+
return a.prerelease.length === b.prerelease.length ? 0 : a.prerelease.length === 0 ? 1 : -1;
|
|
169
|
+
}
|
|
170
|
+
for (let i = 0; i < Math.max(a.prerelease.length, b.prerelease.length); i += 1) {
|
|
171
|
+
const x = a.prerelease[i];
|
|
172
|
+
const y = b.prerelease[i];
|
|
173
|
+
if (x === void 0 || y === void 0) return x === void 0 ? -1 : 1;
|
|
174
|
+
if (x === y) continue;
|
|
175
|
+
const xNumeric = /^\d+$/u.test(x);
|
|
176
|
+
const yNumeric = /^\d+$/u.test(y);
|
|
177
|
+
if (xNumeric && yNumeric) return BigInt(x) < BigInt(y) ? -1 : 1;
|
|
178
|
+
if (xNumeric !== yNumeric) return xNumeric ? -1 : 1;
|
|
179
|
+
return x < y ? -1 : 1;
|
|
180
|
+
}
|
|
181
|
+
return 0;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// src/lib/bin-path.ts
|
|
146
185
|
var PKG_NAME = "@primitive.ai/prim";
|
|
147
186
|
var ROOT_WALK_LIMIT = 6;
|
|
187
|
+
var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
|
|
148
188
|
var resolvedRoot;
|
|
149
189
|
function locateRoot() {
|
|
150
190
|
if (resolvedRoot !== void 0) {
|
|
@@ -285,14 +325,14 @@ function throwIfAborted(signal) {
|
|
|
285
325
|
}
|
|
286
326
|
async function defaultSleep(ms, signal) {
|
|
287
327
|
if (!signal) {
|
|
288
|
-
await new Promise((
|
|
328
|
+
await new Promise((resolve4) => setTimeout(resolve4, ms));
|
|
289
329
|
return;
|
|
290
330
|
}
|
|
291
331
|
throwIfAborted(signal);
|
|
292
|
-
await new Promise((
|
|
332
|
+
await new Promise((resolve4, reject) => {
|
|
293
333
|
const timer = setTimeout(() => {
|
|
294
334
|
signal.removeEventListener("abort", onAbort);
|
|
295
|
-
|
|
335
|
+
resolve4();
|
|
296
336
|
}, ms);
|
|
297
337
|
const onAbort = () => {
|
|
298
338
|
clearTimeout(timer);
|
|
@@ -341,7 +381,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
341
381
|
const target = new URL(url);
|
|
342
382
|
if (target.protocol !== "http:" || !["127.0.0.1", "[::1]", "localhost"].includes(target.hostname))
|
|
343
383
|
return Promise.reject(new Error(`not a loopback URL: ${url}`));
|
|
344
|
-
return new Promise((
|
|
384
|
+
return new Promise((resolve4, reject) => {
|
|
345
385
|
const outgoing = request(
|
|
346
386
|
target,
|
|
347
387
|
{ method: init.method ?? "GET", headers: init.headers, agent: false, signal: init.signal },
|
|
@@ -352,7 +392,7 @@ function loopbackFetch(url, init = {}) {
|
|
|
352
392
|
if (typeof value === "string") headers.set(name, value);
|
|
353
393
|
const status = incoming.statusCode ?? 502;
|
|
354
394
|
const body = [101, 204, 205, 304].includes(status) ? null : Readable.toWeb(incoming);
|
|
355
|
-
|
|
395
|
+
resolve4(new Response(body, { status, headers }));
|
|
356
396
|
} catch (error) {
|
|
357
397
|
incoming.destroy();
|
|
358
398
|
reject(error);
|
|
@@ -366,20 +406,337 @@ function loopbackFetch(url, init = {}) {
|
|
|
366
406
|
|
|
367
407
|
// src/lib/machine-credentials.ts
|
|
368
408
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
369
|
-
import { createHash as
|
|
409
|
+
import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
|
|
370
410
|
import {
|
|
371
|
-
chmodSync,
|
|
372
|
-
existsSync as
|
|
411
|
+
chmodSync as chmodSync2,
|
|
412
|
+
existsSync as existsSync5,
|
|
373
413
|
linkSync,
|
|
374
|
-
lstatSync as
|
|
414
|
+
lstatSync as lstatSync4,
|
|
415
|
+
mkdirSync as mkdirSync4,
|
|
416
|
+
readFileSync as readFileSync6,
|
|
417
|
+
rmSync as rmSync6,
|
|
418
|
+
writeFileSync as writeFileSync4
|
|
419
|
+
} from "fs";
|
|
420
|
+
import { createRequire as createRequire2 } from "module";
|
|
421
|
+
import { dirname as dirname7, join as join9 } from "path";
|
|
422
|
+
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
423
|
+
|
|
424
|
+
// src/lib/hook-runtime.ts
|
|
425
|
+
import { createHash, randomBytes as randomBytes2 } from "crypto";
|
|
426
|
+
import {
|
|
427
|
+
constants as constants2,
|
|
428
|
+
accessSync,
|
|
429
|
+
chmodSync,
|
|
430
|
+
copyFileSync,
|
|
431
|
+
existsSync as existsSync4,
|
|
432
|
+
lstatSync,
|
|
375
433
|
mkdirSync as mkdirSync3,
|
|
376
|
-
|
|
377
|
-
|
|
434
|
+
mkdtempSync,
|
|
435
|
+
readFileSync as readFileSync3,
|
|
436
|
+
readdirSync,
|
|
437
|
+
realpathSync,
|
|
438
|
+
renameSync as renameSync2,
|
|
439
|
+
rmSync as rmSync3,
|
|
440
|
+
statSync as statSync2,
|
|
441
|
+
utimesSync,
|
|
378
442
|
writeFileSync as writeFileSync3
|
|
379
443
|
} from "fs";
|
|
444
|
+
import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
|
|
445
|
+
|
|
446
|
+
// src/lib/git-hook-contract.ts
|
|
447
|
+
var GIT_HOOK_ENTRYPOINT_NAME = "prim-git-hook-v1";
|
|
448
|
+
var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
|
|
449
|
+
# prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
|
|
450
|
+
# Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
|
|
451
|
+
# where prim is active (git config prim.active true) and never fails the hook.
|
|
452
|
+
case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
|
|
453
|
+
prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
|
|
454
|
+
[ -x "$prim_launcher" ] || exit 0
|
|
455
|
+
[ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
|
|
456
|
+
prim_hook=\${1-}
|
|
457
|
+
if [ "$#" -gt 0 ]; then shift; fi
|
|
458
|
+
case "$prim_hook" in
|
|
459
|
+
pre-commit)
|
|
460
|
+
"$prim_launcher" prim-pre-commit "$@" || :
|
|
461
|
+
;;
|
|
462
|
+
post-commit)
|
|
463
|
+
prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
|
|
464
|
+
case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
|
|
465
|
+
case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
|
|
466
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
467
|
+
prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
|
|
468
|
+
(
|
|
469
|
+
trap '' HUP
|
|
470
|
+
trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
|
|
471
|
+
PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
|
|
472
|
+
) </dev/null >/dev/null 2>&1 &
|
|
473
|
+
;;
|
|
474
|
+
post-rewrite)
|
|
475
|
+
case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
|
|
476
|
+
prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
|
|
477
|
+
if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
|
|
478
|
+
rm -f "$prim_pairs"
|
|
479
|
+
exit 0
|
|
480
|
+
fi
|
|
481
|
+
prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
|
|
482
|
+
(
|
|
483
|
+
trap '' HUP
|
|
484
|
+
trap 'rm -f "$prim_pairs"' 0
|
|
485
|
+
PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
|
|
486
|
+
) </dev/null >/dev/null 2>&1 &
|
|
487
|
+
;;
|
|
488
|
+
esac
|
|
489
|
+
exit 0
|
|
490
|
+
`;
|
|
491
|
+
|
|
492
|
+
// src/lib/native-keyring.ts
|
|
493
|
+
import { existsSync as existsSync3 } from "fs";
|
|
380
494
|
import { createRequire } from "module";
|
|
381
|
-
import { dirname as
|
|
495
|
+
import { dirname as dirname4, join as join3 } from "path";
|
|
382
496
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
497
|
+
var require2 = createRequire(import.meta.url);
|
|
498
|
+
var KEYRING_NATIVE_FILES = ["native/keyring.cjs", "native/keyring.node"];
|
|
499
|
+
|
|
500
|
+
// src/lib/paths.ts
|
|
501
|
+
import { homedir } from "os";
|
|
502
|
+
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
503
|
+
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
504
|
+
function absolutePath(value, variable) {
|
|
505
|
+
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
506
|
+
throw new Error(`${variable} contains unsafe characters`);
|
|
507
|
+
}
|
|
508
|
+
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
509
|
+
const normalized = normalize(value);
|
|
510
|
+
return normalized === value ? value : void 0;
|
|
511
|
+
}
|
|
512
|
+
function resolvePrimConfigDirectory(options = {}) {
|
|
513
|
+
const env = options.env ?? process.env;
|
|
514
|
+
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
515
|
+
if (explicit) return { path: explicit, source: "explicit" };
|
|
516
|
+
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
517
|
+
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
518
|
+
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
519
|
+
if (!home) {
|
|
520
|
+
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
521
|
+
}
|
|
522
|
+
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
523
|
+
}
|
|
524
|
+
function primConfigDirectory(options = {}) {
|
|
525
|
+
return resolvePrimConfigDirectory(options).path;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/lib/hook-runtime.ts
|
|
529
|
+
var HOOK_RUNTIME_SCHEMA_VERSION = 1;
|
|
530
|
+
var RELEASE_PREFIX = "release-";
|
|
531
|
+
var RELEASE_NAME_RE = /^release-[0-9a-f]{64}$/u;
|
|
532
|
+
var MAX_MANIFEST_BYTES = 64 * 1024;
|
|
533
|
+
var RELEASE_GRACE_MS = 10 * 60 * 1e3;
|
|
534
|
+
var HOOK_RUNTIME_ENTRIES = {
|
|
535
|
+
// SessionStart self-healing resolves this exact CLI entry to run
|
|
536
|
+
// `daemon ensure`; it must travel with the immutable hook release.
|
|
537
|
+
prim: "dist/index.js",
|
|
538
|
+
"prim-hook": "dist/hooks/prim-hook.js",
|
|
539
|
+
"prim-pre-commit": "dist/hooks/pre-commit.js",
|
|
540
|
+
"prim-post-commit": "dist/hooks/post-commit.js",
|
|
541
|
+
"prim-post-rewrite": "dist/hooks/post-rewrite.js",
|
|
542
|
+
"prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
|
|
543
|
+
"prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
|
|
544
|
+
"prim-post-tool-use": "dist/hooks/post-tool-use.js",
|
|
545
|
+
"prim-session-start": "dist/hooks/session-start.js",
|
|
546
|
+
"prim-session-end": "dist/hooks/session-end.js",
|
|
547
|
+
"prim-daemon-server": "dist/daemon/server.js",
|
|
548
|
+
"prim-statusline": "dist/statusline-main.js"
|
|
549
|
+
};
|
|
550
|
+
var SOURCE_ENTRIES = Object.fromEntries(
|
|
551
|
+
Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
|
|
552
|
+
bin,
|
|
553
|
+
target.replace(/^dist\//u, "")
|
|
554
|
+
])
|
|
555
|
+
);
|
|
556
|
+
function hookRuntimePaths(options = {}) {
|
|
557
|
+
const env = options.env ?? process.env;
|
|
558
|
+
const configDir = primConfigDirectory({
|
|
559
|
+
...options,
|
|
560
|
+
env,
|
|
561
|
+
homeDir: options.homeDir ?? env.HOME ?? ""
|
|
562
|
+
});
|
|
563
|
+
const runtimeDir = join5(configDir, "hook-runtime");
|
|
564
|
+
return {
|
|
565
|
+
configDir,
|
|
566
|
+
launcher: join5(configDir, STABLE_HOOK_LAUNCHER_NAME),
|
|
567
|
+
gitHookEntrypoint: join5(configDir, GIT_HOOK_ENTRYPOINT_NAME),
|
|
568
|
+
runtimeDir,
|
|
569
|
+
releasesDir: join5(runtimeDir, "releases"),
|
|
570
|
+
current: join5(runtimeDir, "current"),
|
|
571
|
+
selectionLock: join5(runtimeDir, "selection.lock")
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
function sha256(path) {
|
|
575
|
+
return createHash("sha256").update(readFileSync3(path)).digest("hex");
|
|
576
|
+
}
|
|
577
|
+
function exactManifest(manifest) {
|
|
578
|
+
return `${JSON.stringify(manifest, null, 2)}
|
|
579
|
+
`;
|
|
580
|
+
}
|
|
581
|
+
function exactKeys(value, expected) {
|
|
582
|
+
const actual = Object.keys(value).sort();
|
|
583
|
+
const wanted = [...expected].sort();
|
|
584
|
+
return actual.length === wanted.length && actual.every((key, index) => key === wanted[index]);
|
|
585
|
+
}
|
|
586
|
+
function releaseId(manifest) {
|
|
587
|
+
return createHash("sha256").update(exactManifest(manifest)).digest("hex");
|
|
588
|
+
}
|
|
589
|
+
function runtimePackageJson(manifest) {
|
|
590
|
+
return `${JSON.stringify(
|
|
591
|
+
{
|
|
592
|
+
name: "@primitive.ai/prim",
|
|
593
|
+
version: manifest.version,
|
|
594
|
+
type: "module",
|
|
595
|
+
bin: HOOK_RUNTIME_ENTRIES
|
|
596
|
+
},
|
|
597
|
+
null,
|
|
598
|
+
2
|
|
599
|
+
)}
|
|
600
|
+
`;
|
|
601
|
+
}
|
|
602
|
+
function validateRelease(releaseDir, manifest) {
|
|
603
|
+
try {
|
|
604
|
+
if (!directReleaseLayout(releaseDir, manifest)) return false;
|
|
605
|
+
if (readFileSync3(join5(releaseDir, "manifest.json"), "utf8") !== exactManifest(manifest)) {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
if (readFileSync3(join5(releaseDir, "package.json"), "utf8") !== runtimePackageJson(manifest)) {
|
|
609
|
+
return false;
|
|
610
|
+
}
|
|
611
|
+
if (readFileSync3(join5(releaseDir, "node"), "utf8") !== `${manifest.nodePath}
|
|
612
|
+
`) {
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
for (const [bin, relativePath] of Object.entries(HOOK_RUNTIME_ENTRIES)) {
|
|
616
|
+
const target = join5(releaseDir, relativePath);
|
|
617
|
+
if (sha256(target) !== manifest.files[bin]) return false;
|
|
618
|
+
}
|
|
619
|
+
for (const [path, digest] of Object.entries(manifest.native ?? {})) {
|
|
620
|
+
if (sha256(join5(releaseDir, path)) !== digest) return false;
|
|
621
|
+
}
|
|
622
|
+
return true;
|
|
623
|
+
} catch {
|
|
624
|
+
return false;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
function directReleaseLayout(releaseDir, manifest) {
|
|
628
|
+
try {
|
|
629
|
+
const directories = /* @__PURE__ */ new Set([releaseDir]);
|
|
630
|
+
for (const relativePath of [
|
|
631
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
632
|
+
...Object.keys(manifest.native ?? {})
|
|
633
|
+
]) {
|
|
634
|
+
for (let directory = dirname5(relativePath); directory !== "."; directory = dirname5(directory)) {
|
|
635
|
+
directories.add(join5(releaseDir, directory));
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (![...directories].every((directory) => lstatSync(directory).isDirectory())) return false;
|
|
639
|
+
const files = [
|
|
640
|
+
"manifest.json",
|
|
641
|
+
"package.json",
|
|
642
|
+
"node",
|
|
643
|
+
...Object.values(HOOK_RUNTIME_ENTRIES),
|
|
644
|
+
...Object.keys(manifest.native ?? {})
|
|
645
|
+
];
|
|
646
|
+
const owned = /* @__PURE__ */ new Set([...directories, ...files.map((path) => join5(releaseDir, path))]);
|
|
647
|
+
if (![...directories].every(
|
|
648
|
+
(directory) => readdirSync(directory).every((name) => owned.has(join5(directory, name)))
|
|
649
|
+
))
|
|
650
|
+
return false;
|
|
651
|
+
return files.every((relativePath) => lstatSync(join5(releaseDir, relativePath)).isFile());
|
|
652
|
+
} catch {
|
|
653
|
+
return false;
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
function readReleaseManifest(releaseDir, releaseName) {
|
|
657
|
+
try {
|
|
658
|
+
const manifestPath = join5(releaseDir, "manifest.json");
|
|
659
|
+
const manifestStat = statSync2(manifestPath);
|
|
660
|
+
if (!manifestStat.isFile() || manifestStat.size > MAX_MANIFEST_BYTES) return null;
|
|
661
|
+
const raw = readFileSync3(manifestPath, "utf8");
|
|
662
|
+
const parsed = JSON.parse(raw);
|
|
663
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
664
|
+
if (!exactKeys(parsed, [
|
|
665
|
+
"schemaVersion",
|
|
666
|
+
"version",
|
|
667
|
+
"nodePath",
|
|
668
|
+
"files",
|
|
669
|
+
..."native" in parsed ? ["native"] : []
|
|
670
|
+
]))
|
|
671
|
+
return null;
|
|
672
|
+
const candidate = parsed;
|
|
673
|
+
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(
|
|
674
|
+
(digest) => typeof digest !== "string" || !/^[0-9a-f]{64}$/u.test(digest)
|
|
675
|
+
)) {
|
|
676
|
+
return null;
|
|
677
|
+
}
|
|
678
|
+
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(
|
|
679
|
+
(digest) => typeof digest !== "string" || !/^[a-f0-9]{64}$/u.test(digest)
|
|
680
|
+
)))
|
|
681
|
+
return null;
|
|
682
|
+
const manifest = candidate;
|
|
683
|
+
if (raw !== exactManifest(manifest) || releaseName !== `${RELEASE_PREFIX}${releaseId(manifest)}` || !validateRelease(releaseDir, manifest)) {
|
|
684
|
+
return null;
|
|
685
|
+
}
|
|
686
|
+
return manifest;
|
|
687
|
+
} catch {
|
|
688
|
+
return null;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
function readSelectedRelease(paths) {
|
|
692
|
+
let raw;
|
|
693
|
+
try {
|
|
694
|
+
raw = readFileSync3(paths.current, "utf8");
|
|
695
|
+
} catch (error) {
|
|
696
|
+
if (error.code === "ENOENT") return null;
|
|
697
|
+
throw error;
|
|
698
|
+
}
|
|
699
|
+
const name = raw.endsWith("\n") ? raw.slice(0, -1) : "";
|
|
700
|
+
if (`${name}
|
|
701
|
+
` !== raw || !RELEASE_NAME_RE.test(name)) {
|
|
702
|
+
throw new Error("cannot stage hook runtime: selected release is malformed");
|
|
703
|
+
}
|
|
704
|
+
const dir = join5(paths.releasesDir, name);
|
|
705
|
+
const manifest = readReleaseManifest(dir, name);
|
|
706
|
+
if (!manifest) {
|
|
707
|
+
throw new Error("cannot stage hook runtime: immutable release is corrupt");
|
|
708
|
+
}
|
|
709
|
+
return { name, dir, manifest };
|
|
710
|
+
}
|
|
711
|
+
function selectedHookRuntimeKeyringLoader(options = {}) {
|
|
712
|
+
try {
|
|
713
|
+
const selected = readSelectedRelease(hookRuntimePaths(options));
|
|
714
|
+
if (!selected?.manifest.native) return void 0;
|
|
715
|
+
const loader = join5(selected.dir, "native", "keyring.cjs");
|
|
716
|
+
return existsSync4(loader) ? loader : void 0;
|
|
717
|
+
} catch {
|
|
718
|
+
return void 0;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
|
|
722
|
+
set -eu
|
|
723
|
+
case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
|
|
724
|
+
IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
|
|
725
|
+
case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
|
|
726
|
+
prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
|
|
727
|
+
case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
|
|
728
|
+
[ "\${#prim_release_id}" -eq 64 ] || exit 69
|
|
729
|
+
prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
|
|
730
|
+
case "\${1-}" in
|
|
731
|
+
${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
|
|
732
|
+
*) exit 64 ;;
|
|
733
|
+
esac
|
|
734
|
+
shift
|
|
735
|
+
IFS= read -r prim_node < "$prim_release/node" || exit 69
|
|
736
|
+
case "$prim_node" in /*) ;; *) exit 69 ;; esac
|
|
737
|
+
[ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
|
|
738
|
+
exec "$prim_node" "$prim_entry" "$@"
|
|
739
|
+
`;
|
|
383
740
|
|
|
384
741
|
// src/lib/cloud-env.ts
|
|
385
742
|
function isClaudeCloudSession(env = process.env) {
|
|
@@ -785,23 +1142,23 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
785
1142
|
}
|
|
786
1143
|
|
|
787
1144
|
// src/lib/machine-retry.ts
|
|
788
|
-
import { createHash } from "crypto";
|
|
789
|
-
import { lstatSync, readFileSync as
|
|
790
|
-
import { join as
|
|
1145
|
+
import { createHash as createHash2 } from "crypto";
|
|
1146
|
+
import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync as readdirSync2, rmSync as rmSync4 } from "fs";
|
|
1147
|
+
import { join as join6 } from "path";
|
|
791
1148
|
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
792
1149
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
793
1150
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
794
1151
|
signal?.throwIfAborted();
|
|
795
|
-
const key =
|
|
796
|
-
const path =
|
|
1152
|
+
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1153
|
+
const path = join6(directory, `machine_retry_${key}.json`);
|
|
797
1154
|
let state = {
|
|
798
1155
|
failures: 0,
|
|
799
1156
|
retryAt: 0
|
|
800
1157
|
};
|
|
801
1158
|
try {
|
|
802
|
-
const stat =
|
|
1159
|
+
const stat = lstatSync2(path);
|
|
803
1160
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
804
|
-
const data = JSON.parse(
|
|
1161
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
805
1162
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
806
1163
|
throw new Error("Invalid retry state");
|
|
807
1164
|
state = data;
|
|
@@ -825,7 +1182,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
825
1182
|
);
|
|
826
1183
|
try {
|
|
827
1184
|
const result = await request3();
|
|
828
|
-
|
|
1185
|
+
rmSync4(path, { force: true });
|
|
829
1186
|
return result;
|
|
830
1187
|
} catch (error) {
|
|
831
1188
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -852,46 +1209,18 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
852
1209
|
}
|
|
853
1210
|
}
|
|
854
1211
|
|
|
855
|
-
// src/lib/paths.ts
|
|
856
|
-
import { homedir } from "os";
|
|
857
|
-
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
858
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
859
|
-
function absolutePath(value, variable) {
|
|
860
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
861
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
862
|
-
}
|
|
863
|
-
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
864
|
-
const normalized = normalize(value);
|
|
865
|
-
return normalized === value ? value : void 0;
|
|
866
|
-
}
|
|
867
|
-
function resolvePrimConfigDirectory(options = {}) {
|
|
868
|
-
const env = options.env ?? process.env;
|
|
869
|
-
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
870
|
-
if (explicit) return { path: explicit, source: "explicit" };
|
|
871
|
-
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
872
|
-
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
873
|
-
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
874
|
-
if (!home) {
|
|
875
|
-
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
876
|
-
}
|
|
877
|
-
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
878
|
-
}
|
|
879
|
-
function primConfigDirectory(options = {}) {
|
|
880
|
-
return resolvePrimConfigDirectory(options).path;
|
|
881
|
-
}
|
|
882
|
-
|
|
883
1212
|
// src/lib/session-identity.ts
|
|
884
1213
|
import { execFile } from "child_process";
|
|
885
|
-
import { createHash as
|
|
886
|
-
import { rmSync as
|
|
887
|
-
import { join as
|
|
1214
|
+
import { createHash as createHash4 } from "crypto";
|
|
1215
|
+
import { rmSync as rmSync5 } from "fs";
|
|
1216
|
+
import { join as join8 } from "path";
|
|
888
1217
|
import { promisify } from "util";
|
|
889
1218
|
|
|
890
1219
|
// src/lib/git.ts
|
|
891
1220
|
import { execFileSync } from "child_process";
|
|
892
|
-
import { createHash as
|
|
893
|
-
import { lstatSync as
|
|
894
|
-
import { basename, dirname as
|
|
1221
|
+
import { createHash as createHash3 } from "crypto";
|
|
1222
|
+
import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync as realpathSync2 } from "fs";
|
|
1223
|
+
import { basename, dirname as dirname6, isAbsolute as isAbsolute4, join as join7, relative, resolve as resolve2, sep } from "path";
|
|
895
1224
|
var GIT_TIMEOUT_MS = 1e3;
|
|
896
1225
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
897
1226
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
@@ -948,12 +1277,12 @@ function githubRepositoryFromRemote(remote) {
|
|
|
948
1277
|
return path ? parseGithubRepositoryName(path) : null;
|
|
949
1278
|
}
|
|
950
1279
|
function checkoutSettingsText(repoRoot) {
|
|
951
|
-
const path =
|
|
1280
|
+
const path = join7(repoRoot, ".claude", "settings.json");
|
|
952
1281
|
try {
|
|
953
|
-
if (!
|
|
954
|
-
const stat =
|
|
1282
|
+
if (!lstatSync3(join7(repoRoot, ".claude")).isDirectory()) return null;
|
|
1283
|
+
const stat = lstatSync3(path);
|
|
955
1284
|
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
956
|
-
return
|
|
1285
|
+
return readFileSync5(path, "utf8");
|
|
957
1286
|
} catch {
|
|
958
1287
|
return null;
|
|
959
1288
|
}
|
|
@@ -1149,7 +1478,7 @@ function sessionIdentityMessage(outcome) {
|
|
|
1149
1478
|
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1150
1479
|
}
|
|
1151
1480
|
function hash(value) {
|
|
1152
|
-
return
|
|
1481
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1153
1482
|
}
|
|
1154
1483
|
function sessionContext(deps) {
|
|
1155
1484
|
const env = deps.env ?? process.env;
|
|
@@ -1176,9 +1505,9 @@ function sessionContext(deps) {
|
|
|
1176
1505
|
clientId: environment.clientId,
|
|
1177
1506
|
generation: environment.generation,
|
|
1178
1507
|
sessionId,
|
|
1179
|
-
tokenPath:
|
|
1180
|
-
statePath:
|
|
1181
|
-
lockPath:
|
|
1508
|
+
tokenPath: join8(directory, `session_identity_${key}.json`),
|
|
1509
|
+
statePath: join8(directory, `session_identity_${key}.state.json`),
|
|
1510
|
+
lockPath: join8(directory, "session-identity.lock")
|
|
1182
1511
|
};
|
|
1183
1512
|
}
|
|
1184
1513
|
function readRecord(path) {
|
|
@@ -1210,7 +1539,7 @@ function readState(context) {
|
|
|
1210
1539
|
function writeToken(context, record) {
|
|
1211
1540
|
prepareMachineMetadataDirectory(context.directory);
|
|
1212
1541
|
writeMachineMetadata(context.tokenPath, record);
|
|
1213
|
-
|
|
1542
|
+
rmSync5(context.statePath, { force: true });
|
|
1214
1543
|
}
|
|
1215
1544
|
function writeState(context, state) {
|
|
1216
1545
|
try {
|
|
@@ -1388,8 +1717,8 @@ function gitDetail(stderr) {
|
|
|
1388
1717
|
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1389
1718
|
}
|
|
1390
1719
|
async function defaultSleep2(milliseconds, signal) {
|
|
1391
|
-
await new Promise((
|
|
1392
|
-
const timer = setTimeout(
|
|
1720
|
+
await new Promise((resolve4, reject) => {
|
|
1721
|
+
const timer = setTimeout(resolve4, milliseconds);
|
|
1393
1722
|
signal?.addEventListener(
|
|
1394
1723
|
"abort",
|
|
1395
1724
|
() => {
|
|
@@ -1820,7 +2149,7 @@ async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
|
1820
2149
|
return identified(refreshed.record, true);
|
|
1821
2150
|
}
|
|
1822
2151
|
if (refreshed.status === "refused") {
|
|
1823
|
-
|
|
2152
|
+
rmSync5(ctx.tokenPath, { force: true });
|
|
1824
2153
|
writeState(ctx, {
|
|
1825
2154
|
sessionId: ctx.sessionId,
|
|
1826
2155
|
status: "failed",
|
|
@@ -1964,7 +2293,7 @@ async function acquireSessionCredential(options = {}, deps = {}) {
|
|
|
1964
2293
|
function sessionScoped(deps) {
|
|
1965
2294
|
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
1966
2295
|
}
|
|
1967
|
-
var
|
|
2296
|
+
var require3 = createRequire2(import.meta.url);
|
|
1968
2297
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1969
2298
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1970
2299
|
var PROFILE_FILE = "machine_profile.json";
|
|
@@ -1977,16 +2306,16 @@ function apiUrlFor(deps) {
|
|
|
1977
2306
|
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1978
2307
|
}
|
|
1979
2308
|
function hash2(value) {
|
|
1980
|
-
return
|
|
2309
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1981
2310
|
}
|
|
1982
2311
|
function recordPath(directory, generation) {
|
|
1983
|
-
return
|
|
2312
|
+
return join9(directory, `machine_${generation}.json`);
|
|
1984
2313
|
}
|
|
1985
2314
|
function storageKey(directory, generation) {
|
|
1986
2315
|
return `${hash2(directory)}:${generation}`;
|
|
1987
2316
|
}
|
|
1988
2317
|
function environmentContextPath(deps, clientId) {
|
|
1989
|
-
return
|
|
2318
|
+
return join9(
|
|
1990
2319
|
configurationDirectory(deps),
|
|
1991
2320
|
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1992
2321
|
);
|
|
@@ -2046,22 +2375,28 @@ function readEnvironmentContext(environment, deps) {
|
|
|
2046
2375
|
return void 0;
|
|
2047
2376
|
}
|
|
2048
2377
|
}
|
|
2049
|
-
function
|
|
2050
|
-
let directory =
|
|
2378
|
+
function keyringLoaderPath(start, options = {}) {
|
|
2379
|
+
let directory = start;
|
|
2051
2380
|
for (let depth = 0; depth < 5; depth++) {
|
|
2052
|
-
const loader =
|
|
2053
|
-
if (
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2381
|
+
const loader = join9(directory, "native", "keyring.cjs");
|
|
2382
|
+
if (existsSync5(loader)) return loader;
|
|
2383
|
+
directory = dirname7(directory);
|
|
2384
|
+
}
|
|
2385
|
+
try {
|
|
2386
|
+
createRequire2(join9(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
2387
|
+
return void 0;
|
|
2388
|
+
} catch {
|
|
2389
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
2058
2390
|
}
|
|
2059
|
-
|
|
2391
|
+
}
|
|
2392
|
+
function keyringEntry(key) {
|
|
2393
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath3(import.meta.url)));
|
|
2394
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
2060
2395
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
2061
2396
|
}
|
|
2062
2397
|
function protectPath(path, directory) {
|
|
2063
2398
|
if (process.platform !== "win32") {
|
|
2064
|
-
|
|
2399
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
2065
2400
|
return;
|
|
2066
2401
|
}
|
|
2067
2402
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
@@ -2078,8 +2413,8 @@ function protectPath(path, directory) {
|
|
|
2078
2413
|
);
|
|
2079
2414
|
}
|
|
2080
2415
|
function ensureDirectory(directory) {
|
|
2081
|
-
|
|
2082
|
-
if (
|
|
2416
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
2417
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
2083
2418
|
throw new MachineAuthError(
|
|
2084
2419
|
"unsafe_storage",
|
|
2085
2420
|
"Credential directory must not be a symbolic link."
|
|
@@ -2097,14 +2432,14 @@ function readMachineMetadata(path) {
|
|
|
2097
2432
|
function readPrivate(path) {
|
|
2098
2433
|
let raw;
|
|
2099
2434
|
try {
|
|
2100
|
-
const stat =
|
|
2435
|
+
const stat = lstatSync4(path);
|
|
2101
2436
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
2102
2437
|
throw new MachineAuthError(
|
|
2103
2438
|
"unsafe_storage",
|
|
2104
2439
|
"Machine credential files must be owner-only regular files."
|
|
2105
2440
|
);
|
|
2106
2441
|
}
|
|
2107
|
-
raw =
|
|
2442
|
+
raw = readFileSync6(path, "utf8");
|
|
2108
2443
|
} catch (error) {
|
|
2109
2444
|
if (error.code === "ENOENT") return void 0;
|
|
2110
2445
|
throw error;
|
|
@@ -2149,7 +2484,7 @@ function parseProfile(value) {
|
|
|
2149
2484
|
};
|
|
2150
2485
|
}
|
|
2151
2486
|
function readMachineProfile(deps = {}) {
|
|
2152
|
-
const value = readPrivate(
|
|
2487
|
+
const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
|
|
2153
2488
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
2154
2489
|
}
|
|
2155
2490
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -2158,20 +2493,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
2158
2493
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2159
2494
|
function networkSecretBrokerKey(deps, clientId) {
|
|
2160
2495
|
const directory = configurationDirectory(deps);
|
|
2161
|
-
const path =
|
|
2496
|
+
const path = join9(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2162
2497
|
const known = brokerKeys.get(path);
|
|
2163
2498
|
if (known) return known;
|
|
2164
2499
|
ensureDirectory(directory);
|
|
2165
2500
|
const read = () => {
|
|
2166
2501
|
try {
|
|
2167
|
-
const stat =
|
|
2502
|
+
const stat = lstatSync4(path);
|
|
2168
2503
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
2169
2504
|
throw new MachineAuthError(
|
|
2170
2505
|
"unsafe_storage",
|
|
2171
2506
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
2172
2507
|
true
|
|
2173
2508
|
);
|
|
2174
|
-
const value =
|
|
2509
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
2175
2510
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
2176
2511
|
} catch (error) {
|
|
2177
2512
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -2190,16 +2525,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
2190
2525
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
2191
2526
|
true
|
|
2192
2527
|
);
|
|
2193
|
-
const staged = `${path}.${process.pid}.${
|
|
2528
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
2194
2529
|
try {
|
|
2195
|
-
|
|
2530
|
+
writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
|
|
2196
2531
|
`, { mode: 384, flag: "wx" });
|
|
2197
2532
|
protectPath(staged, false);
|
|
2198
2533
|
linkSync(staged, path);
|
|
2199
2534
|
} catch (error) {
|
|
2200
2535
|
if (error.code !== "EEXIST") throw error;
|
|
2201
2536
|
} finally {
|
|
2202
|
-
|
|
2537
|
+
rmSync6(staged, { force: true });
|
|
2203
2538
|
}
|
|
2204
2539
|
}
|
|
2205
2540
|
const key = read()?.key;
|
|
@@ -2258,7 +2593,7 @@ function environmentCredentials(deps) {
|
|
|
2258
2593
|
}
|
|
2259
2594
|
function hasMachineConfiguration(deps = {}) {
|
|
2260
2595
|
const env = deps.env ?? process.env;
|
|
2261
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 ||
|
|
2596
|
+
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));
|
|
2262
2597
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
2263
2598
|
throw new MachineAuthError(
|
|
2264
2599
|
"conflicting_credentials",
|
|
@@ -2294,7 +2629,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
2294
2629
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2295
2630
|
if (!generation) return false;
|
|
2296
2631
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2297
|
-
return readPrivate(
|
|
2632
|
+
return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2298
2633
|
}
|
|
2299
2634
|
var environmentTerminal;
|
|
2300
2635
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -2387,7 +2722,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2387
2722
|
}
|
|
2388
2723
|
}
|
|
2389
2724
|
return withFileLock(
|
|
2390
|
-
|
|
2725
|
+
join9(directory2, "credentials.lock"),
|
|
2391
2726
|
async () => {
|
|
2392
2727
|
if (machineSessionEnded(deps))
|
|
2393
2728
|
throw new MachineAuthError(
|
|
@@ -2469,7 +2804,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2469
2804
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2470
2805
|
try {
|
|
2471
2806
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2472
|
-
|
|
2807
|
+
rmSync6(contextPath, { force: true });
|
|
2473
2808
|
} catch {
|
|
2474
2809
|
}
|
|
2475
2810
|
throw error;
|
|
@@ -2479,7 +2814,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2479
2814
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2480
2815
|
try {
|
|
2481
2816
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2482
|
-
|
|
2817
|
+
rmSync6(contextPath, { force: true });
|
|
2483
2818
|
} catch {
|
|
2484
2819
|
}
|
|
2485
2820
|
}
|
|
@@ -2493,7 +2828,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2493
2828
|
const expected = machineContext(deps);
|
|
2494
2829
|
const directory = configurationDirectory(deps);
|
|
2495
2830
|
return withFileLock(
|
|
2496
|
-
|
|
2831
|
+
join9(directory, "credentials.lock"),
|
|
2497
2832
|
async () => {
|
|
2498
2833
|
const profile = readMachineProfile(deps);
|
|
2499
2834
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2543,7 +2878,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2543
2878
|
await persistRecord(record, deps, signal);
|
|
2544
2879
|
} catch (error) {
|
|
2545
2880
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2546
|
-
writePrivate(
|
|
2881
|
+
writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
|
|
2547
2882
|
throw error;
|
|
2548
2883
|
}
|
|
2549
2884
|
}
|
|
@@ -2600,14 +2935,14 @@ var FORWARD_TIMEOUT_MS = 3e4;
|
|
|
2600
2935
|
var FORWARD_METHODS = ["GET", "POST", "DELETE"];
|
|
2601
2936
|
var IDLE_MS = 5 * 6e4;
|
|
2602
2937
|
function descriptorPath(directory, generation) {
|
|
2603
|
-
return
|
|
2938
|
+
return join10(directory, `machine_broker_${generation}.json`);
|
|
2604
2939
|
}
|
|
2605
2940
|
function readDescriptor(path) {
|
|
2606
2941
|
try {
|
|
2607
|
-
const stat =
|
|
2942
|
+
const stat = lstatSync5(path);
|
|
2608
2943
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
2609
2944
|
return void 0;
|
|
2610
|
-
const data = JSON.parse(
|
|
2945
|
+
const data = JSON.parse(readFileSync7(path, "utf8"));
|
|
2611
2946
|
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;
|
|
2612
2947
|
} catch {
|
|
2613
2948
|
return void 0;
|
|
@@ -2620,7 +2955,7 @@ function matches(left, right) {
|
|
|
2620
2955
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
2621
2956
|
}
|
|
2622
2957
|
function tokenHash(token) {
|
|
2623
|
-
return token ?
|
|
2958
|
+
return token ? createHash6("sha256").update(token).digest("hex") : void 0;
|
|
2624
2959
|
}
|
|
2625
2960
|
async function brokerRequest(descriptor, environment, options) {
|
|
2626
2961
|
const body = JSON.stringify({
|
|
@@ -2697,7 +3032,7 @@ async function acquireBrokerCredential(options) {
|
|
|
2697
3032
|
async function ensureBroker(options) {
|
|
2698
3033
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2699
3034
|
return withFileLock(
|
|
2700
|
-
|
|
3035
|
+
join10(options.directory, "machine-broker.lock"),
|
|
2701
3036
|
async () => {
|
|
2702
3037
|
const current = readDescriptor(path);
|
|
2703
3038
|
if (current) {
|
|
@@ -2710,14 +3045,14 @@ async function ensureBroker(options) {
|
|
|
2710
3045
|
options.signal.throwIfAborted();
|
|
2711
3046
|
}
|
|
2712
3047
|
}
|
|
2713
|
-
const bundled =
|
|
3048
|
+
const bundled = fileURLToPath4(import.meta.url);
|
|
2714
3049
|
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
2715
3050
|
if (!entry)
|
|
2716
3051
|
throw new MachineAuthError(
|
|
2717
3052
|
"broker_unavailable",
|
|
2718
3053
|
"Reinstall Prim to restore its machine credential broker."
|
|
2719
3054
|
);
|
|
2720
|
-
await new Promise((
|
|
3055
|
+
await new Promise((resolve4, reject) => {
|
|
2721
3056
|
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
2722
3057
|
detached: true,
|
|
2723
3058
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
@@ -2732,7 +3067,7 @@ async function ensureBroker(options) {
|
|
|
2732
3067
|
if (error) child.kill();
|
|
2733
3068
|
if (child.connected) child.disconnect();
|
|
2734
3069
|
child.unref();
|
|
2735
|
-
error ? reject(error) :
|
|
3070
|
+
error ? reject(error) : resolve4();
|
|
2736
3071
|
};
|
|
2737
3072
|
const abort = () => finish(
|
|
2738
3073
|
new MachineAuthError(
|
|
@@ -3012,7 +3347,7 @@ async function startMachineBroker() {
|
|
|
3012
3347
|
const directory = primConfigDirectory();
|
|
3013
3348
|
const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
|
|
3014
3349
|
const path = descriptorPath(directory, environment.generation);
|
|
3015
|
-
const nonce =
|
|
3350
|
+
const nonce = randomBytes4(32).toString("hex");
|
|
3016
3351
|
const server = createBrokerServer({
|
|
3017
3352
|
environment,
|
|
3018
3353
|
apiUrl,
|
|
@@ -3023,14 +3358,14 @@ async function startMachineBroker() {
|
|
|
3023
3358
|
clearTimeout(idle);
|
|
3024
3359
|
server.closeAllConnections();
|
|
3025
3360
|
server.close();
|
|
3026
|
-
if (readDescriptor(path)?.nonce === nonce)
|
|
3361
|
+
if (readDescriptor(path)?.nonce === nonce) rmSync7(path, { force: true });
|
|
3027
3362
|
};
|
|
3028
3363
|
const idle = setTimeout(close, IDLE_MS);
|
|
3029
3364
|
process.once("SIGTERM", close);
|
|
3030
3365
|
process.once("SIGINT", close);
|
|
3031
|
-
await new Promise((
|
|
3366
|
+
await new Promise((resolve4, reject) => {
|
|
3032
3367
|
server.once("error", reject);
|
|
3033
|
-
server.listen(0, "127.0.0.1",
|
|
3368
|
+
server.listen(0, "127.0.0.1", resolve4);
|
|
3034
3369
|
});
|
|
3035
3370
|
const address = server.address();
|
|
3036
3371
|
if (!address || typeof address === "string") throw new Error("Invalid broker address");
|
|
@@ -3041,27 +3376,27 @@ async function startMachineBroker() {
|
|
|
3041
3376
|
}
|
|
3042
3377
|
|
|
3043
3378
|
// src/daemon/principal.ts
|
|
3044
|
-
import { createHash as
|
|
3379
|
+
import { createHash as createHash8 } from "crypto";
|
|
3045
3380
|
|
|
3046
3381
|
// src/lib/credentials.ts
|
|
3047
|
-
import { createHash as
|
|
3048
|
-
import { readFileSync as
|
|
3049
|
-
import { join as
|
|
3382
|
+
import { createHash as createHash7 } from "crypto";
|
|
3383
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
3384
|
+
import { join as join11 } from "path";
|
|
3050
3385
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
3051
|
-
var TOKEN_FILE_PATH =
|
|
3052
|
-
var REFRESH_TOKEN_PATH =
|
|
3053
|
-
var TOKEN_EXPIRES_PATH =
|
|
3054
|
-
var TERMINAL_REFRESH_PATH =
|
|
3055
|
-
var CREDENTIAL_METADATA_PATH =
|
|
3056
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
3057
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
3058
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3386
|
+
var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
|
|
3387
|
+
var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
|
|
3388
|
+
var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
|
|
3389
|
+
var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3390
|
+
var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3391
|
+
var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
|
|
3392
|
+
var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3393
|
+
var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
|
|
3059
3394
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
3060
3395
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
3061
3396
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
3062
3397
|
function readTrimmed(path) {
|
|
3063
3398
|
try {
|
|
3064
|
-
const value =
|
|
3399
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
3065
3400
|
return value || void 0;
|
|
3066
3401
|
} catch {
|
|
3067
3402
|
return void 0;
|
|
@@ -3098,7 +3433,7 @@ function resolveAuthCredential(options = {}) {
|
|
|
3098
3433
|
return { token: stored, source: "token_file" };
|
|
3099
3434
|
}
|
|
3100
3435
|
function credentialFingerprint(value) {
|
|
3101
|
-
return
|
|
3436
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
3102
3437
|
}
|
|
3103
3438
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
3104
3439
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -3118,7 +3453,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
3118
3453
|
function readBoundedCredentialJson(path) {
|
|
3119
3454
|
let raw;
|
|
3120
3455
|
try {
|
|
3121
|
-
raw =
|
|
3456
|
+
raw = readFileSync8(path, "utf8");
|
|
3122
3457
|
} catch (error) {
|
|
3123
3458
|
return error.code === "ENOENT" ? void 0 : null;
|
|
3124
3459
|
}
|
|
@@ -3195,25 +3530,25 @@ var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
|
|
|
3195
3530
|
function boundedClaim(value) {
|
|
3196
3531
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
3197
3532
|
}
|
|
3198
|
-
function
|
|
3199
|
-
return
|
|
3533
|
+
function sha2562(value) {
|
|
3534
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
3200
3535
|
}
|
|
3201
3536
|
function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
|
|
3202
3537
|
if (hasMachineConfiguration()) {
|
|
3203
3538
|
const machine = machineContext();
|
|
3204
3539
|
return machine ? `${machine.generation}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}` : void 0;
|
|
3205
3540
|
}
|
|
3206
|
-
return token ?
|
|
3541
|
+
return token ? sha2562(token) : void 0;
|
|
3207
3542
|
}
|
|
3208
3543
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
3209
3544
|
if (hasMachineConfiguration()) {
|
|
3210
3545
|
const machine = machineContext();
|
|
3211
3546
|
return machine ? {
|
|
3212
|
-
principalId:
|
|
3547
|
+
principalId: sha2562(
|
|
3213
3548
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
3214
3549
|
),
|
|
3215
3550
|
organizationId: machine.workosOrganizationId,
|
|
3216
|
-
credentialFingerprint:
|
|
3551
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
3217
3552
|
} : void 0;
|
|
3218
3553
|
}
|
|
3219
3554
|
if (!token) return void 0;
|
|
@@ -3223,9 +3558,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
3223
3558
|
if (!(subject && organizationId)) return void 0;
|
|
3224
3559
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
3225
3560
|
return {
|
|
3226
|
-
principalId:
|
|
3561
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
3227
3562
|
organizationId,
|
|
3228
|
-
credentialFingerprint:
|
|
3563
|
+
credentialFingerprint: sha2562(token)
|
|
3229
3564
|
};
|
|
3230
3565
|
}
|
|
3231
3566
|
function isDaemonPrincipal(value) {
|
|
@@ -3279,10 +3614,10 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
3279
3614
|
}
|
|
3280
3615
|
|
|
3281
3616
|
// src/daemon/server.ts
|
|
3282
|
-
import { chmodSync as
|
|
3617
|
+
import { chmodSync as chmodSync9, existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync16, unlinkSync as unlinkSync3 } from "fs";
|
|
3283
3618
|
import { createServer as createServer2 } from "net";
|
|
3284
|
-
import { join as
|
|
3285
|
-
import { fileURLToPath as
|
|
3619
|
+
import { join as join23 } from "path";
|
|
3620
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3286
3621
|
|
|
3287
3622
|
// src/decisions/identity.ts
|
|
3288
3623
|
var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
|
|
@@ -3362,14 +3697,14 @@ function publicDecisionResponse(value) {
|
|
|
3362
3697
|
}
|
|
3363
3698
|
|
|
3364
3699
|
// src/client.ts
|
|
3365
|
-
import { createHash as
|
|
3366
|
-
import { chmodSync as
|
|
3367
|
-
import { dirname as
|
|
3700
|
+
import { createHash as createHash9 } from "crypto";
|
|
3701
|
+
import { chmodSync as chmodSync4, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
|
|
3702
|
+
import { dirname as dirname8 } from "path";
|
|
3368
3703
|
|
|
3369
3704
|
// src/daemon/client-instance-id.ts
|
|
3370
|
-
import { randomBytes as
|
|
3371
|
-
import { chmodSync as
|
|
3372
|
-
import { join as
|
|
3705
|
+
import { randomBytes as randomBytes5 } from "crypto";
|
|
3706
|
+
import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync9 } from "fs";
|
|
3707
|
+
import { join as join12 } from "path";
|
|
3373
3708
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
3374
3709
|
var INSTANCE_FILE_MODE = 384;
|
|
3375
3710
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -3382,17 +3717,17 @@ function isClientInstanceId(value) {
|
|
|
3382
3717
|
}
|
|
3383
3718
|
function ensurePrivateConfigDirectory(configDir) {
|
|
3384
3719
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
3385
|
-
const metadata =
|
|
3720
|
+
const metadata = lstatSync6(configDir);
|
|
3386
3721
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
3387
3722
|
throw new Error("prim config path must be a private directory");
|
|
3388
3723
|
}
|
|
3389
|
-
|
|
3724
|
+
chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
|
|
3390
3725
|
syncDirectory(configDir);
|
|
3391
3726
|
}
|
|
3392
3727
|
function readExisting(path) {
|
|
3393
3728
|
let metadata;
|
|
3394
3729
|
try {
|
|
3395
|
-
metadata =
|
|
3730
|
+
metadata = lstatSync6(path);
|
|
3396
3731
|
} catch (error) {
|
|
3397
3732
|
if (error.code === "ENOENT") {
|
|
3398
3733
|
return;
|
|
@@ -3402,11 +3737,11 @@ function readExisting(path) {
|
|
|
3402
3737
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
3403
3738
|
throw new Error("stored client instance identity is invalid");
|
|
3404
3739
|
}
|
|
3405
|
-
|
|
3740
|
+
chmodSync3(path, INSTANCE_FILE_MODE);
|
|
3406
3741
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
3407
3742
|
throw new Error("stored client instance identity is invalid");
|
|
3408
3743
|
}
|
|
3409
|
-
const raw =
|
|
3744
|
+
const raw = readFileSync9(path, "utf8");
|
|
3410
3745
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
3411
3746
|
if (raw !== value && raw !== `${value}
|
|
3412
3747
|
` || !isClientInstanceId(value)) {
|
|
@@ -3420,8 +3755,8 @@ function atomicWrite(path, value) {
|
|
|
3420
3755
|
}
|
|
3421
3756
|
async function getOrCreateClientInstanceId(options) {
|
|
3422
3757
|
const configDir = options.configDir;
|
|
3423
|
-
const path =
|
|
3424
|
-
const lockPath =
|
|
3758
|
+
const path = join12(configDir, "client_instance_id");
|
|
3759
|
+
const lockPath = join12(configDir, "client-instance.lock");
|
|
3425
3760
|
ensurePrivateConfigDirectory(configDir);
|
|
3426
3761
|
return withFileLock(
|
|
3427
3762
|
lockPath,
|
|
@@ -3430,7 +3765,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
3430
3765
|
if (existing !== void 0) {
|
|
3431
3766
|
return existing;
|
|
3432
3767
|
}
|
|
3433
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
3768
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
3434
3769
|
"base64url"
|
|
3435
3770
|
)}`;
|
|
3436
3771
|
if (!isClientInstanceId(generated)) {
|
|
@@ -3476,7 +3811,7 @@ function authExpiredMessage() {
|
|
|
3476
3811
|
}
|
|
3477
3812
|
function readTrimmed2(path) {
|
|
3478
3813
|
try {
|
|
3479
|
-
const value =
|
|
3814
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
3480
3815
|
return value || void 0;
|
|
3481
3816
|
} catch {
|
|
3482
3817
|
return void 0;
|
|
@@ -3492,17 +3827,17 @@ function expiresAtFor(token, expiresIn) {
|
|
|
3492
3827
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
3493
3828
|
}
|
|
3494
3829
|
function ensureConfigDirectory() {
|
|
3495
|
-
const directory =
|
|
3496
|
-
|
|
3497
|
-
|
|
3830
|
+
const directory = dirname8(TOKEN_FILE_PATH);
|
|
3831
|
+
mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
3832
|
+
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
3498
3833
|
}
|
|
3499
3834
|
function atomicWrite2(path, content) {
|
|
3500
3835
|
ensureConfigDirectory();
|
|
3501
3836
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
3502
3837
|
}
|
|
3503
3838
|
function removeCredentialFile(path) {
|
|
3504
|
-
if (!
|
|
3505
|
-
|
|
3839
|
+
if (!existsSync6(path)) return false;
|
|
3840
|
+
rmSync8(path, { force: true });
|
|
3506
3841
|
return true;
|
|
3507
3842
|
}
|
|
3508
3843
|
function getTokenExpiresAt() {
|
|
@@ -3518,7 +3853,7 @@ function isTokenExpiringSoon(credential) {
|
|
|
3518
3853
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
3519
3854
|
}
|
|
3520
3855
|
function refreshFingerprint(refreshToken3) {
|
|
3521
|
-
return
|
|
3856
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
3522
3857
|
}
|
|
3523
3858
|
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
3524
3859
|
return {
|
|
@@ -4043,66 +4378,66 @@ async function getPinnedClient(options = {}) {
|
|
|
4043
4378
|
}
|
|
4044
4379
|
|
|
4045
4380
|
// src/flusher.ts
|
|
4046
|
-
import { createReadStream, renameSync as
|
|
4047
|
-
import { dirname as
|
|
4381
|
+
import { createReadStream, renameSync as renameSync4, statSync as statSync3, unlinkSync } from "fs";
|
|
4382
|
+
import { dirname as dirname12, join as join19 } from "path";
|
|
4048
4383
|
|
|
4049
4384
|
// src/dead-letter.ts
|
|
4050
|
-
import { createHash as
|
|
4385
|
+
import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
|
|
4051
4386
|
import {
|
|
4052
|
-
constants as
|
|
4053
|
-
chmodSync as
|
|
4387
|
+
constants as constants3,
|
|
4388
|
+
chmodSync as chmodSync5,
|
|
4054
4389
|
closeSync as closeSync2,
|
|
4055
|
-
existsSync as
|
|
4390
|
+
existsSync as existsSync7,
|
|
4056
4391
|
fchmodSync as fchmodSync2,
|
|
4057
4392
|
fsyncSync as fsyncSync2,
|
|
4058
|
-
mkdirSync as
|
|
4393
|
+
mkdirSync as mkdirSync6,
|
|
4059
4394
|
openSync as openSync2,
|
|
4060
|
-
renameSync as
|
|
4061
|
-
rmSync as
|
|
4062
|
-
writeFileSync as
|
|
4395
|
+
renameSync as renameSync3,
|
|
4396
|
+
rmSync as rmSync9,
|
|
4397
|
+
writeFileSync as writeFileSync5
|
|
4063
4398
|
} from "fs";
|
|
4064
|
-
import { dirname as
|
|
4399
|
+
import { dirname as dirname9, join as join14 } from "path";
|
|
4065
4400
|
var DIRECTORY_MODE2 = 448;
|
|
4066
4401
|
var FILE_MODE2 = 384;
|
|
4067
4402
|
var DEAD_LETTER_DIRNAME = "dead-letter";
|
|
4068
4403
|
function deadLetterDirectoryForRotation(flushingPath) {
|
|
4069
|
-
return
|
|
4404
|
+
return join14(dirname9(flushingPath), DEAD_LETTER_DIRNAME);
|
|
4070
4405
|
}
|
|
4071
4406
|
function deadLetterPathForRawLine(flushingPath, rawLine) {
|
|
4072
|
-
const quarantineId =
|
|
4073
|
-
return
|
|
4407
|
+
const quarantineId = createHash10("sha256").update(rawLine).digest("hex");
|
|
4408
|
+
return join14(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
|
|
4074
4409
|
}
|
|
4075
4410
|
function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
|
|
4076
4411
|
const directory = deadLetterDirectoryForRotation(flushingPath);
|
|
4077
|
-
|
|
4078
|
-
|
|
4079
|
-
persistDirectory(
|
|
4412
|
+
mkdirSync6(directory, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
4413
|
+
chmodSync5(directory, DIRECTORY_MODE2);
|
|
4414
|
+
persistDirectory(dirname9(directory));
|
|
4080
4415
|
return directory;
|
|
4081
4416
|
}
|
|
4082
4417
|
function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
|
|
4083
|
-
if (
|
|
4418
|
+
if (existsSync7(path)) {
|
|
4084
4419
|
persistDirectory(directory);
|
|
4085
4420
|
return;
|
|
4086
4421
|
}
|
|
4087
|
-
const temporaryPath =
|
|
4422
|
+
const temporaryPath = join14(
|
|
4088
4423
|
directory,
|
|
4089
|
-
`.${quarantineId}.${String(process.pid)}.${
|
|
4424
|
+
`.${quarantineId}.${String(process.pid)}.${randomBytes6(8).toString("hex")}.tmp`
|
|
4090
4425
|
);
|
|
4091
|
-
const flags =
|
|
4426
|
+
const flags = constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW;
|
|
4092
4427
|
try {
|
|
4093
4428
|
const fd = openSync2(temporaryPath, flags, FILE_MODE2);
|
|
4094
4429
|
try {
|
|
4095
4430
|
fchmodSync2(fd, FILE_MODE2);
|
|
4096
|
-
|
|
4431
|
+
writeFileSync5(fd, `${JSON.stringify(record)}
|
|
4097
4432
|
`, "utf8");
|
|
4098
4433
|
fsyncSync2(fd);
|
|
4099
4434
|
} finally {
|
|
4100
4435
|
closeSync2(fd);
|
|
4101
4436
|
}
|
|
4102
|
-
|
|
4437
|
+
renameSync3(temporaryPath, path);
|
|
4103
4438
|
persistDirectory(directory);
|
|
4104
4439
|
} finally {
|
|
4105
|
-
|
|
4440
|
+
rmSync9(temporaryPath, { force: true });
|
|
4106
4441
|
}
|
|
4107
4442
|
}
|
|
4108
4443
|
function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
|
|
@@ -4111,12 +4446,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
|
|
|
4111
4446
|
const serializedMove = JSON.stringify(move);
|
|
4112
4447
|
const record = {
|
|
4113
4448
|
version: 1,
|
|
4114
|
-
quarantineId:
|
|
4449
|
+
quarantineId: createHash10("sha256").update(serializedMove).digest("hex"),
|
|
4115
4450
|
quarantinedAt: now(),
|
|
4116
4451
|
reason,
|
|
4117
4452
|
move
|
|
4118
4453
|
};
|
|
4119
|
-
const path =
|
|
4454
|
+
const path = join14(directory, `${record.quarantineId}.json`);
|
|
4120
4455
|
persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
|
|
4121
4456
|
return record;
|
|
4122
4457
|
}
|
|
@@ -4127,7 +4462,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
4127
4462
|
const record = {
|
|
4128
4463
|
version: 1,
|
|
4129
4464
|
recordKind: "raw_line_v1",
|
|
4130
|
-
quarantineId:
|
|
4465
|
+
quarantineId: createHash10("sha256").update(bytes).digest("hex"),
|
|
4131
4466
|
quarantinedAt: now(),
|
|
4132
4467
|
reason: "invalid_move",
|
|
4133
4468
|
rawLineEncoding: "base64",
|
|
@@ -4146,14 +4481,14 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
4146
4481
|
|
|
4147
4482
|
// src/drain-progress.ts
|
|
4148
4483
|
import {
|
|
4149
|
-
chmodSync as
|
|
4150
|
-
existsSync as
|
|
4151
|
-
readFileSync as
|
|
4152
|
-
readdirSync as
|
|
4153
|
-
rmSync as
|
|
4484
|
+
chmodSync as chmodSync6,
|
|
4485
|
+
existsSync as existsSync8,
|
|
4486
|
+
readFileSync as readFileSync11,
|
|
4487
|
+
readdirSync as readdirSync3,
|
|
4488
|
+
rmSync as rmSync10,
|
|
4154
4489
|
rmdirSync
|
|
4155
4490
|
} from "fs";
|
|
4156
|
-
import { basename as basename3, dirname as
|
|
4491
|
+
import { basename as basename3, dirname as dirname10, join as join15 } from "path";
|
|
4157
4492
|
var DIRECTORY_MODE3 = 448;
|
|
4158
4493
|
var FILE_MODE3 = 384;
|
|
4159
4494
|
var DRAIN_PROGRESS_DIRNAME = "drain-progress";
|
|
@@ -4162,10 +4497,10 @@ function rotationIdentity(stat) {
|
|
|
4162
4497
|
return { size: stat.size, ino: stat.ino, dev: stat.dev };
|
|
4163
4498
|
}
|
|
4164
4499
|
function drainProgressDirectory(flushingPath) {
|
|
4165
|
-
return
|
|
4500
|
+
return join15(dirname10(flushingPath), DRAIN_PROGRESS_DIRNAME);
|
|
4166
4501
|
}
|
|
4167
4502
|
function drainProgressPath(flushingPath) {
|
|
4168
|
-
return
|
|
4503
|
+
return join15(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
|
|
4169
4504
|
}
|
|
4170
4505
|
function isByteCount(value) {
|
|
4171
4506
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
@@ -4173,7 +4508,7 @@ function isByteCount(value) {
|
|
|
4173
4508
|
function drainResumeOffset(flushingPath, rotation) {
|
|
4174
4509
|
let parsed;
|
|
4175
4510
|
try {
|
|
4176
|
-
parsed = JSON.parse(
|
|
4511
|
+
parsed = JSON.parse(readFileSync11(drainProgressPath(flushingPath), "utf8"));
|
|
4177
4512
|
} catch {
|
|
4178
4513
|
return 0;
|
|
4179
4514
|
}
|
|
@@ -4189,7 +4524,7 @@ function drainResumeOffset(flushingPath, rotation) {
|
|
|
4189
4524
|
function writeDrainCheckpoint(flushingPath, checkpoint) {
|
|
4190
4525
|
const directory = drainProgressDirectory(flushingPath);
|
|
4191
4526
|
ensureDurableDirectory(directory, DIRECTORY_MODE3);
|
|
4192
|
-
|
|
4527
|
+
chmodSync6(directory, DIRECTORY_MODE3);
|
|
4193
4528
|
atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
|
|
4194
4529
|
`, {
|
|
4195
4530
|
mode: FILE_MODE3
|
|
@@ -4206,24 +4541,24 @@ function removeEmptyDirectory(directory) {
|
|
|
4206
4541
|
}
|
|
4207
4542
|
}
|
|
4208
4543
|
function removeDrainCheckpoint(flushingPath) {
|
|
4209
|
-
|
|
4544
|
+
rmSync10(drainProgressPath(flushingPath), { force: true });
|
|
4210
4545
|
removeEmptyDirectory(drainProgressDirectory(flushingPath));
|
|
4211
4546
|
}
|
|
4212
4547
|
function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
4213
|
-
const directory =
|
|
4548
|
+
const directory = join15(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
|
|
4214
4549
|
let names;
|
|
4215
4550
|
try {
|
|
4216
|
-
names =
|
|
4551
|
+
names = readdirSync3(directory);
|
|
4217
4552
|
} catch {
|
|
4218
4553
|
return;
|
|
4219
4554
|
}
|
|
4220
4555
|
for (const name of names) {
|
|
4221
4556
|
const rotation = CHECKPOINT_NAME.exec(name)?.[1];
|
|
4222
|
-
if (rotation === void 0 ||
|
|
4557
|
+
if (rotation === void 0 || existsSync8(join15(bucketDirectory, rotation))) {
|
|
4223
4558
|
continue;
|
|
4224
4559
|
}
|
|
4225
4560
|
try {
|
|
4226
|
-
|
|
4561
|
+
rmSync10(join15(directory, name), { force: true });
|
|
4227
4562
|
} catch {
|
|
4228
4563
|
}
|
|
4229
4564
|
}
|
|
@@ -30920,21 +31255,21 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
30920
31255
|
|
|
30921
31256
|
// src/lib/activation.ts
|
|
30922
31257
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
30923
|
-
import { existsSync as
|
|
31258
|
+
import { existsSync as existsSync10, readFileSync as readFileSync13 } from "fs";
|
|
30924
31259
|
import { homedir as homedir2 } from "os";
|
|
30925
|
-
import { join as
|
|
31260
|
+
import { join as join17 } from "path";
|
|
30926
31261
|
|
|
30927
31262
|
// src/lib/cloud-prepared.ts
|
|
30928
|
-
import { existsSync as
|
|
30929
|
-
import { join as
|
|
31263
|
+
import { existsSync as existsSync9, mkdirSync as mkdirSync7, readFileSync as readFileSync12, rmSync as rmSync11, writeFileSync as writeFileSync6 } from "fs";
|
|
31264
|
+
import { join as join16 } from "path";
|
|
30930
31265
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
30931
31266
|
function cloudPreparedPath(env = process.env) {
|
|
30932
|
-
return
|
|
31267
|
+
return join16(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
30933
31268
|
}
|
|
30934
31269
|
function isPreparedCloudSession(env = process.env) {
|
|
30935
31270
|
if (!isClaudeCloudSession(env)) return false;
|
|
30936
31271
|
try {
|
|
30937
|
-
return
|
|
31272
|
+
return existsSync9(cloudPreparedPath(env));
|
|
30938
31273
|
} catch {
|
|
30939
31274
|
return false;
|
|
30940
31275
|
}
|
|
@@ -31070,10 +31405,10 @@ function repositoryBindingState(cwd) {
|
|
|
31070
31405
|
function projectPrimInstallAt(root) {
|
|
31071
31406
|
if (root === null || root === homedir2()) return false;
|
|
31072
31407
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
31073
|
-
const path =
|
|
31074
|
-
if (
|
|
31408
|
+
const path = join17(root, rel);
|
|
31409
|
+
if (existsSync10(path)) {
|
|
31075
31410
|
try {
|
|
31076
|
-
const content =
|
|
31411
|
+
const content = readFileSync13(path, "utf-8");
|
|
31077
31412
|
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
31078
31413
|
} catch {
|
|
31079
31414
|
}
|
|
@@ -31482,17 +31817,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
|
|
|
31482
31817
|
import {
|
|
31483
31818
|
appendFileSync,
|
|
31484
31819
|
closeSync as closeSync3,
|
|
31485
|
-
existsSync as
|
|
31820
|
+
existsSync as existsSync11,
|
|
31486
31821
|
fstatSync,
|
|
31487
|
-
mkdirSync as
|
|
31822
|
+
mkdirSync as mkdirSync8,
|
|
31488
31823
|
openSync as openSync3,
|
|
31489
31824
|
opendirSync,
|
|
31490
|
-
readFileSync as
|
|
31825
|
+
readFileSync as readFileSync14,
|
|
31491
31826
|
readSync,
|
|
31492
|
-
readdirSync as
|
|
31827
|
+
readdirSync as readdirSync4
|
|
31493
31828
|
} from "fs";
|
|
31494
|
-
import { dirname as
|
|
31495
|
-
var JOURNAL_DIR =
|
|
31829
|
+
import { dirname as dirname11, join as join18 } from "path";
|
|
31830
|
+
var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
|
|
31496
31831
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
31497
31832
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
31498
31833
|
var PENDING_STATS_MAX_FILES = 128;
|
|
@@ -31504,7 +31839,7 @@ function envSlug(apiUrl) {
|
|
|
31504
31839
|
return slug;
|
|
31505
31840
|
}
|
|
31506
31841
|
function currentEnvDir() {
|
|
31507
|
-
return
|
|
31842
|
+
return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
31508
31843
|
}
|
|
31509
31844
|
function parseMoves(content) {
|
|
31510
31845
|
const moves = [];
|
|
@@ -31522,15 +31857,15 @@ function parseMoves(content) {
|
|
|
31522
31857
|
function listBuckets() {
|
|
31523
31858
|
const out = [];
|
|
31524
31859
|
const envDir = currentEnvDir();
|
|
31525
|
-
if (!
|
|
31860
|
+
if (!existsSync11(envDir)) {
|
|
31526
31861
|
return out;
|
|
31527
31862
|
}
|
|
31528
|
-
for (const entry of
|
|
31863
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31529
31864
|
if (!entry.isDirectory()) {
|
|
31530
31865
|
continue;
|
|
31531
31866
|
}
|
|
31532
|
-
const path =
|
|
31533
|
-
if (
|
|
31867
|
+
const path = join18(envDir, entry.name, JOURNAL_BASENAME);
|
|
31868
|
+
if (existsSync11(path)) {
|
|
31534
31869
|
out.push({ bucket: entry.name, path });
|
|
31535
31870
|
}
|
|
31536
31871
|
}
|
|
@@ -31592,7 +31927,7 @@ function parseFlushingPid(name) {
|
|
|
31592
31927
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
31593
31928
|
}
|
|
31594
31929
|
function listFlushingInDir(dir, bucket, options = {}) {
|
|
31595
|
-
if (!
|
|
31930
|
+
if (!existsSync11(dir)) {
|
|
31596
31931
|
return [];
|
|
31597
31932
|
}
|
|
31598
31933
|
const out = [];
|
|
@@ -31606,7 +31941,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
31606
31941
|
entry = entries.readSync();
|
|
31607
31942
|
continue;
|
|
31608
31943
|
}
|
|
31609
|
-
const path =
|
|
31944
|
+
const path = join18(dir, entry.name);
|
|
31610
31945
|
let sample;
|
|
31611
31946
|
try {
|
|
31612
31947
|
sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
|
|
@@ -31633,18 +31968,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
31633
31968
|
}
|
|
31634
31969
|
function listFlushing(options = {}) {
|
|
31635
31970
|
const envDir = currentEnvDir();
|
|
31636
|
-
if (!
|
|
31971
|
+
if (!existsSync11(envDir)) {
|
|
31637
31972
|
return [];
|
|
31638
31973
|
}
|
|
31639
31974
|
const out = [];
|
|
31640
31975
|
let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
|
|
31641
31976
|
const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
|
|
31642
|
-
for (const entry of
|
|
31977
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31643
31978
|
if (out.length >= maxFiles) {
|
|
31644
31979
|
break;
|
|
31645
31980
|
}
|
|
31646
31981
|
if (entry.isDirectory()) {
|
|
31647
|
-
const found = listFlushingInDir(
|
|
31982
|
+
const found = listFlushingInDir(join18(envDir, entry.name), entry.name, {
|
|
31648
31983
|
sampleBytes: remainingBytes,
|
|
31649
31984
|
maxFiles: maxFiles - out.length
|
|
31650
31985
|
});
|
|
@@ -31659,12 +31994,12 @@ function listFlushing(options = {}) {
|
|
|
31659
31994
|
}
|
|
31660
31995
|
function sweepOrphanedDrainProgress() {
|
|
31661
31996
|
const envDir = currentEnvDir();
|
|
31662
|
-
if (!
|
|
31997
|
+
if (!existsSync11(envDir)) {
|
|
31663
31998
|
return;
|
|
31664
31999
|
}
|
|
31665
|
-
for (const entry of
|
|
32000
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31666
32001
|
if (entry.isDirectory()) {
|
|
31667
|
-
sweepOrphanedDrainCheckpoints(
|
|
32002
|
+
sweepOrphanedDrainCheckpoints(join18(envDir, entry.name));
|
|
31668
32003
|
}
|
|
31669
32004
|
}
|
|
31670
32005
|
}
|
|
@@ -31817,7 +32152,7 @@ async function* rawJournalLines(input, offset) {
|
|
|
31817
32152
|
}
|
|
31818
32153
|
var drainProgressWarned = false;
|
|
31819
32154
|
async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
31820
|
-
const rotation = rotationIdentity(
|
|
32155
|
+
const rotation = rotationIdentity(statSync3(flushingPath));
|
|
31821
32156
|
const resumeAt = drainResumeOffset(flushingPath, rotation);
|
|
31822
32157
|
const recordProgress = (end) => {
|
|
31823
32158
|
if (end === void 0 || end >= rotation.size) {
|
|
@@ -31944,7 +32279,7 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
|
31944
32279
|
async function drainPath(path, client2, binding, onProgress) {
|
|
31945
32280
|
const tmpPath = `${path}.flushing.${String(Date.now())}.${String(process.pid)}`;
|
|
31946
32281
|
try {
|
|
31947
|
-
|
|
32282
|
+
renameSync4(path, tmpPath);
|
|
31948
32283
|
} catch (err) {
|
|
31949
32284
|
if (err.code === "ENOENT") {
|
|
31950
32285
|
return { flushed: 0, quarantined: 0 };
|
|
@@ -32078,7 +32413,7 @@ async function flushOnce() {
|
|
|
32078
32413
|
return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
|
|
32079
32414
|
}
|
|
32080
32415
|
var flushInFlight;
|
|
32081
|
-
var FLUSH_LOCK_PATH =
|
|
32416
|
+
var FLUSH_LOCK_PATH = join19(dirname12(JOURNAL_DIR), ".flush.lock");
|
|
32082
32417
|
var FLUSH_LOCK_TIMEOUT_MS = 250;
|
|
32083
32418
|
function isFlushLockContended(error) {
|
|
32084
32419
|
return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
|
|
@@ -32233,8 +32568,8 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
|
|
|
32233
32568
|
var STATUSLINE_INGESTION_CACHE_TTL_MS = 3e4;
|
|
32234
32569
|
var STATUSLINE_INGESTION_CACHE_MAX_ENTRIES = 256;
|
|
32235
32570
|
var StatuslineIngestionCache = class {
|
|
32236
|
-
constructor(
|
|
32237
|
-
this.resolve =
|
|
32571
|
+
constructor(resolve4, options = {}) {
|
|
32572
|
+
this.resolve = resolve4;
|
|
32238
32573
|
this.#now = options.now ?? Date.now;
|
|
32239
32574
|
this.#ttlMs = options.ttlMs ?? STATUSLINE_INGESTION_CACHE_TTL_MS;
|
|
32240
32575
|
this.#maxEntries = options.maxEntries ?? STATUSLINE_INGESTION_CACHE_MAX_ENTRIES;
|
|
@@ -32280,8 +32615,8 @@ var StatuslineIngestionCache = class {
|
|
|
32280
32615
|
|
|
32281
32616
|
// src/daemon/client.ts
|
|
32282
32617
|
import { createConnection } from "net";
|
|
32283
|
-
import { join as
|
|
32284
|
-
var SOCK_PATH =
|
|
32618
|
+
import { join as join20 } from "path";
|
|
32619
|
+
var SOCK_PATH = join20(primConfigDirectory(), "sock");
|
|
32285
32620
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
32286
32621
|
var nextRequestId = 1;
|
|
32287
32622
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -32294,7 +32629,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32294
32629
|
...caller ? { caller } : {}
|
|
32295
32630
|
};
|
|
32296
32631
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
32297
|
-
return new Promise((
|
|
32632
|
+
return new Promise((resolve4) => {
|
|
32298
32633
|
let settled = false;
|
|
32299
32634
|
let socket;
|
|
32300
32635
|
let buffer = Buffer.alloc(0);
|
|
@@ -32309,7 +32644,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32309
32644
|
} catch {
|
|
32310
32645
|
}
|
|
32311
32646
|
}
|
|
32312
|
-
|
|
32647
|
+
resolve4(value);
|
|
32313
32648
|
};
|
|
32314
32649
|
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
32315
32650
|
timer.unref();
|
|
@@ -32371,7 +32706,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32371
32706
|
}
|
|
32372
32707
|
|
|
32373
32708
|
// src/daemon/decision-digest-cache.ts
|
|
32374
|
-
import { randomBytes as
|
|
32709
|
+
import { randomBytes as randomBytes7 } from "crypto";
|
|
32375
32710
|
var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
|
|
32376
32711
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
32377
32712
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
@@ -32401,7 +32736,7 @@ function errorMessage(error) {
|
|
|
32401
32736
|
return error instanceof Error ? error.message : String(error);
|
|
32402
32737
|
}
|
|
32403
32738
|
function privatePageToken() {
|
|
32404
|
-
return
|
|
32739
|
+
return randomBytes7(16).toString("hex");
|
|
32405
32740
|
}
|
|
32406
32741
|
var DecisionDigestCache = class {
|
|
32407
32742
|
constructor(load, now = Date.now, options = {}) {
|
|
@@ -32552,8 +32887,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
|
|
|
32552
32887
|
}
|
|
32553
32888
|
|
|
32554
32889
|
// src/daemon/health.ts
|
|
32555
|
-
import { chmodSync as
|
|
32556
|
-
import { dirname as
|
|
32890
|
+
import { chmodSync as chmodSync7, existsSync as existsSync12, mkdirSync as mkdirSync9, renameSync as renameSync5, writeFileSync as writeFileSync7 } from "fs";
|
|
32891
|
+
import { dirname as dirname13, join as join21 } from "path";
|
|
32557
32892
|
var CONFIG_DIR_MODE2 = 448;
|
|
32558
32893
|
var HEALTH_FILE_MODE = 384;
|
|
32559
32894
|
var INGESTION_SLA_MS = 3e4;
|
|
@@ -32561,7 +32896,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
|
|
|
32561
32896
|
var HEARTBEAT_RETRY_CAP_MS = 3e4;
|
|
32562
32897
|
var INGESTION_RETRY_BASE_MS = 5e3;
|
|
32563
32898
|
var INGESTION_RETRY_CAP_MS = 15e3;
|
|
32564
|
-
var DAEMON_HEALTH_PATH =
|
|
32899
|
+
var DAEMON_HEALTH_PATH = join21(primConfigDirectory(), "daemon-health.json");
|
|
32565
32900
|
function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
|
|
32566
32901
|
return {
|
|
32567
32902
|
schemaVersion: 1,
|
|
@@ -32602,37 +32937,37 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
|
|
|
32602
32937
|
return retryDelayMs(consecutiveFailures, INGESTION_RETRY_CAP_MS, random);
|
|
32603
32938
|
}
|
|
32604
32939
|
function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
32605
|
-
const dir =
|
|
32606
|
-
if (!
|
|
32607
|
-
|
|
32940
|
+
const dir = dirname13(path);
|
|
32941
|
+
if (!existsSync12(dir)) {
|
|
32942
|
+
mkdirSync9(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
|
|
32608
32943
|
}
|
|
32609
|
-
const tmp =
|
|
32610
|
-
|
|
32944
|
+
const tmp = join21(dir, `.${process.pid}.daemon-health.tmp`);
|
|
32945
|
+
writeFileSync7(tmp, `${JSON.stringify(state, null, 2)}
|
|
32611
32946
|
`, { mode: HEALTH_FILE_MODE });
|
|
32612
|
-
|
|
32613
|
-
|
|
32947
|
+
chmodSync7(tmp, HEALTH_FILE_MODE);
|
|
32948
|
+
renameSync5(tmp, path);
|
|
32614
32949
|
}
|
|
32615
32950
|
|
|
32616
32951
|
// src/daemon/instance-lock.ts
|
|
32617
32952
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
32618
32953
|
import {
|
|
32619
|
-
chmodSync as
|
|
32620
|
-
existsSync as
|
|
32621
|
-
mkdirSync as
|
|
32622
|
-
readFileSync as
|
|
32623
|
-
renameSync as
|
|
32624
|
-
rmSync as
|
|
32625
|
-
statSync as
|
|
32954
|
+
chmodSync as chmodSync8,
|
|
32955
|
+
existsSync as existsSync13,
|
|
32956
|
+
mkdirSync as mkdirSync10,
|
|
32957
|
+
readFileSync as readFileSync15,
|
|
32958
|
+
renameSync as renameSync6,
|
|
32959
|
+
rmSync as rmSync12,
|
|
32960
|
+
statSync as statSync4,
|
|
32626
32961
|
unlinkSync as unlinkSync2,
|
|
32627
|
-
writeFileSync as
|
|
32962
|
+
writeFileSync as writeFileSync8
|
|
32628
32963
|
} from "fs";
|
|
32629
|
-
import { join as
|
|
32964
|
+
import { join as join22 } from "path";
|
|
32630
32965
|
var DIR_MODE = 448;
|
|
32631
32966
|
var FILE_MODE4 = 384;
|
|
32632
32967
|
var DAEMON_STARTUP_GRACE_MS = 5e3;
|
|
32633
32968
|
function readLockRecord(path) {
|
|
32634
32969
|
try {
|
|
32635
|
-
const value = JSON.parse(
|
|
32970
|
+
const value = JSON.parse(readFileSync15(path, "utf-8"));
|
|
32636
32971
|
if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
|
|
32637
32972
|
return value;
|
|
32638
32973
|
}
|
|
@@ -32642,23 +32977,23 @@ function readLockRecord(path) {
|
|
|
32642
32977
|
}
|
|
32643
32978
|
function numericPid(path) {
|
|
32644
32979
|
try {
|
|
32645
|
-
const pid = Number(
|
|
32980
|
+
const pid = Number(readFileSync15(path, "utf-8").trim());
|
|
32646
32981
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
32647
32982
|
} catch {
|
|
32648
32983
|
return;
|
|
32649
32984
|
}
|
|
32650
32985
|
}
|
|
32651
32986
|
function readDaemonOwner(configDir) {
|
|
32652
|
-
return readLockRecord(
|
|
32987
|
+
return readLockRecord(join22(configDir, "daemon.lock", "owner.json"));
|
|
32653
32988
|
}
|
|
32654
32989
|
function readDaemonPid(configDir) {
|
|
32655
|
-
const path =
|
|
32990
|
+
const path = join22(configDir, "daemon.pid");
|
|
32656
32991
|
const pid = numericPid(path);
|
|
32657
32992
|
if (pid === void 0) {
|
|
32658
32993
|
return;
|
|
32659
32994
|
}
|
|
32660
32995
|
try {
|
|
32661
|
-
return { pid, mtimeMs:
|
|
32996
|
+
return { pid, mtimeMs: statSync4(path).mtimeMs };
|
|
32662
32997
|
} catch {
|
|
32663
32998
|
return;
|
|
32664
32999
|
}
|
|
@@ -32667,16 +33002,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32667
33002
|
const pid = opts.pid ?? process.pid;
|
|
32668
33003
|
const now = opts.now ?? Date.now();
|
|
32669
33004
|
const isAlive = opts.isAlive ?? processIsAlive;
|
|
32670
|
-
const lockDir =
|
|
32671
|
-
const ownerPath2 =
|
|
32672
|
-
const pidPath =
|
|
33005
|
+
const lockDir = join22(configDir, "daemon.lock");
|
|
33006
|
+
const ownerPath2 = join22(lockDir, "owner.json");
|
|
33007
|
+
const pidPath = join22(configDir, "daemon.pid");
|
|
32673
33008
|
const instanceId2 = randomUUID3();
|
|
32674
|
-
if (!
|
|
32675
|
-
|
|
33009
|
+
if (!existsSync13(configDir)) {
|
|
33010
|
+
mkdirSync10(configDir, { recursive: true, mode: DIR_MODE });
|
|
32676
33011
|
}
|
|
32677
33012
|
for (; ; ) {
|
|
32678
33013
|
try {
|
|
32679
|
-
|
|
33014
|
+
mkdirSync10(lockDir, { mode: DIR_MODE });
|
|
32680
33015
|
break;
|
|
32681
33016
|
} catch (err) {
|
|
32682
33017
|
if (err.code !== "EEXIST") {
|
|
@@ -32689,7 +33024,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32689
33024
|
if (!existing) {
|
|
32690
33025
|
let mtimeMs;
|
|
32691
33026
|
try {
|
|
32692
|
-
mtimeMs =
|
|
33027
|
+
mtimeMs = statSync4(lockDir).mtimeMs;
|
|
32693
33028
|
} catch (statErr) {
|
|
32694
33029
|
if (statErr.code === "ENOENT") {
|
|
32695
33030
|
continue;
|
|
@@ -32702,8 +33037,8 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32702
33037
|
}
|
|
32703
33038
|
const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
|
|
32704
33039
|
try {
|
|
32705
|
-
|
|
32706
|
-
|
|
33040
|
+
renameSync6(lockDir, stale);
|
|
33041
|
+
rmSync12(stale, { recursive: true, force: true });
|
|
32707
33042
|
} catch (renameErr) {
|
|
32708
33043
|
if (renameErr.code !== "ENOENT") {
|
|
32709
33044
|
throw renameErr;
|
|
@@ -32720,16 +33055,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32720
33055
|
instanceId: instanceId2
|
|
32721
33056
|
};
|
|
32722
33057
|
const record = { pid, instanceId: instanceId2, startedAt: now };
|
|
32723
|
-
|
|
33058
|
+
writeFileSync8(ownerPath2, `${JSON.stringify(record)}
|
|
32724
33059
|
`, { mode: FILE_MODE4 });
|
|
32725
|
-
|
|
33060
|
+
chmodSync8(ownerPath2, FILE_MODE4);
|
|
32726
33061
|
const legacyPid = numericPid(pidPath);
|
|
32727
33062
|
if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
|
|
32728
|
-
|
|
33063
|
+
rmSync12(lockDir, { recursive: true, force: true });
|
|
32729
33064
|
throw new Error(`daemon already running (pid=${String(legacyPid)})`);
|
|
32730
33065
|
}
|
|
32731
|
-
|
|
32732
|
-
|
|
33066
|
+
writeFileSync8(pidPath, String(pid), { mode: FILE_MODE4 });
|
|
33067
|
+
chmodSync8(pidPath, FILE_MODE4);
|
|
32733
33068
|
return ownership2;
|
|
32734
33069
|
}
|
|
32735
33070
|
function ownsDaemonInstance(ownership2) {
|
|
@@ -32759,7 +33094,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
|
|
|
32759
33094
|
}
|
|
32760
33095
|
}
|
|
32761
33096
|
}
|
|
32762
|
-
|
|
33097
|
+
rmSync12(ownership2.lockDir, { recursive: true, force: true });
|
|
32763
33098
|
if (cleanupError) {
|
|
32764
33099
|
throw cleanupError;
|
|
32765
33100
|
}
|
|
@@ -32814,7 +33149,7 @@ function normalizePresenceHeartbeatResponse(value) {
|
|
|
32814
33149
|
}
|
|
32815
33150
|
|
|
32816
33151
|
// src/daemon/statusline-protocol.ts
|
|
32817
|
-
import { isAbsolute as
|
|
33152
|
+
import { isAbsolute as isAbsolute5 } from "path";
|
|
32818
33153
|
var STATUSLINE_PROTOCOL_PREFIX = Buffer.from("prim-statusline-v1\0", "utf8");
|
|
32819
33154
|
var STATUSLINE_REQUEST_MAX_BYTES = 64 * 1024;
|
|
32820
33155
|
var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
@@ -32843,7 +33178,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
32843
33178
|
try {
|
|
32844
33179
|
const cwd = utf8Decoder.decode(buffer.subarray(STATUSLINE_PROTOCOL_PREFIX.length, cwdEnd));
|
|
32845
33180
|
const primApiUrl = utf8Decoder.decode(buffer.subarray(cwdEnd + 1, apiUrlEnd));
|
|
32846
|
-
if (!cwd || !
|
|
33181
|
+
if (!cwd || !isAbsolute5(cwd)) {
|
|
32847
33182
|
return { state: "invalid" };
|
|
32848
33183
|
}
|
|
32849
33184
|
return { state: "complete", request: { cwd, primApiUrl } };
|
|
@@ -32854,7 +33189,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
32854
33189
|
|
|
32855
33190
|
// src/daemon/server.ts
|
|
32856
33191
|
var CONFIG_DIR = primConfigDirectory();
|
|
32857
|
-
var SOCK_PATH2 =
|
|
33192
|
+
var SOCK_PATH2 = join23(CONFIG_DIR, "sock");
|
|
32858
33193
|
var CONFIG_DIR_MODE3 = 448;
|
|
32859
33194
|
var SOCKET_MODE = 384;
|
|
32860
33195
|
var MAX_SOCKET_CONNECTIONS = 64;
|
|
@@ -32922,8 +33257,8 @@ function resolveRuntimeVersion() {
|
|
|
32922
33257
|
return process.env.PRIM_RUNTIME_VERSION;
|
|
32923
33258
|
}
|
|
32924
33259
|
try {
|
|
32925
|
-
const here =
|
|
32926
|
-
const pkg = JSON.parse(
|
|
33260
|
+
const here = fileURLToPath5(new URL(".", import.meta.url));
|
|
33261
|
+
const pkg = JSON.parse(readFileSync16(join23(here, "..", "..", "package.json"), "utf-8"));
|
|
32927
33262
|
return pkg.version ?? "unknown";
|
|
32928
33263
|
} catch {
|
|
32929
33264
|
return "unknown";
|
|
@@ -32962,8 +33297,8 @@ function assertCallerPrincipalMatches(caller) {
|
|
|
32962
33297
|
return credentialKey;
|
|
32963
33298
|
}
|
|
32964
33299
|
function ensureDaemonDirectoryPermissions() {
|
|
32965
|
-
|
|
32966
|
-
|
|
33300
|
+
mkdirSync11(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
|
|
33301
|
+
chmodSync9(CONFIG_DIR, CONFIG_DIR_MODE3);
|
|
32967
33302
|
}
|
|
32968
33303
|
function persistHealth() {
|
|
32969
33304
|
refreshDaemonHealth(daemonHealth, Date.now());
|
|
@@ -33049,7 +33384,7 @@ async function takeOwnership() {
|
|
|
33049
33384
|
(pid) => pid !== void 0 && processIsAlive(pid)
|
|
33050
33385
|
)
|
|
33051
33386
|
);
|
|
33052
|
-
if (
|
|
33387
|
+
if (existsSync14(SOCK_PATH2) || candidatePids.size > 0) {
|
|
33053
33388
|
const snapshot = await daemonRequest(
|
|
33054
33389
|
"status_snapshot",
|
|
33055
33390
|
{},
|
|
@@ -33594,7 +33929,7 @@ function startSocketServer() {
|
|
|
33594
33929
|
});
|
|
33595
33930
|
socketServer.listen(SOCK_PATH2, () => {
|
|
33596
33931
|
try {
|
|
33597
|
-
|
|
33932
|
+
chmodSync9(SOCK_PATH2, SOCKET_MODE);
|
|
33598
33933
|
} catch (err) {
|
|
33599
33934
|
shutdown(EXIT_CRASH, `[prim-daemon] failed to secure socket: ${errorMessage2(err)}`);
|
|
33600
33935
|
return;
|