@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
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 as basename2, 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);
|
|
@@ -365,20 +405,337 @@ function loopbackFetch(url, init = {}) {
|
|
|
365
405
|
|
|
366
406
|
// src/lib/machine-credentials.ts
|
|
367
407
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
368
|
-
import { createHash as
|
|
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
|
|
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) {
|
|
@@ -784,23 +1141,23 @@ async function verifyInjectedMachineIdentity(apiUrl, clientId, signal, fetchImpl
|
|
|
784
1141
|
}
|
|
785
1142
|
|
|
786
1143
|
// src/lib/machine-retry.ts
|
|
787
|
-
import { createHash } from "crypto";
|
|
788
|
-
import { lstatSync, readFileSync as
|
|
789
|
-
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";
|
|
790
1147
|
var SERVER_WAIT_PREFIX = "The sign-in service asked prim to wait";
|
|
791
1148
|
var MAX_SERVER_WAIT_MS = 15 * 6e4;
|
|
792
1149
|
async function withMachineCooldown(directory, apiUrl, clientId, signal, request3) {
|
|
793
1150
|
signal?.throwIfAborted();
|
|
794
|
-
const key =
|
|
795
|
-
const path =
|
|
1151
|
+
const key = createHash2("sha256").update(`${apiUrl}\0${clientId}`).digest("hex");
|
|
1152
|
+
const path = join6(directory, `machine_retry_${key}.json`);
|
|
796
1153
|
let state = {
|
|
797
1154
|
failures: 0,
|
|
798
1155
|
retryAt: 0
|
|
799
1156
|
};
|
|
800
1157
|
try {
|
|
801
|
-
const stat =
|
|
1158
|
+
const stat = lstatSync2(path);
|
|
802
1159
|
if (!stat.isFile() || stat.size > 1024) throw new Error("Invalid retry state");
|
|
803
|
-
const data = JSON.parse(
|
|
1160
|
+
const data = JSON.parse(readFileSync4(path, "utf8"));
|
|
804
1161
|
if (!Number.isSafeInteger(data.failures) || data.failures < 0 || data.failures > 16 || !Number.isSafeInteger(data.retryAt) || data.retryAt < 0)
|
|
805
1162
|
throw new Error("Invalid retry state");
|
|
806
1163
|
state = data;
|
|
@@ -824,7 +1181,7 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
824
1181
|
);
|
|
825
1182
|
try {
|
|
826
1183
|
const result = await request3();
|
|
827
|
-
|
|
1184
|
+
rmSync4(path, { force: true });
|
|
828
1185
|
return result;
|
|
829
1186
|
} catch (error) {
|
|
830
1187
|
if (!signal?.aborted && error instanceof MachineAuthError && [
|
|
@@ -851,46 +1208,18 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
851
1208
|
}
|
|
852
1209
|
}
|
|
853
1210
|
|
|
854
|
-
// src/lib/paths.ts
|
|
855
|
-
import { homedir } from "os";
|
|
856
|
-
import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
|
|
857
|
-
var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
|
|
858
|
-
function absolutePath(value, variable) {
|
|
859
|
-
if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
|
|
860
|
-
throw new Error(`${variable} contains unsafe characters`);
|
|
861
|
-
}
|
|
862
|
-
if (!value || value.trim() !== value || !isAbsolute2(value)) return;
|
|
863
|
-
const normalized = normalize(value);
|
|
864
|
-
return normalized === value ? value : void 0;
|
|
865
|
-
}
|
|
866
|
-
function resolvePrimConfigDirectory(options = {}) {
|
|
867
|
-
const env = options.env ?? process.env;
|
|
868
|
-
const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
|
|
869
|
-
if (explicit) return { path: explicit, source: "explicit" };
|
|
870
|
-
const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
|
|
871
|
-
if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
|
|
872
|
-
const home = absolutePath(options.homeDir ?? homedir(), "HOME");
|
|
873
|
-
if (!home) {
|
|
874
|
-
throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
|
|
875
|
-
}
|
|
876
|
-
return { path: join4(home, ".config", "prim"), source: "default" };
|
|
877
|
-
}
|
|
878
|
-
function primConfigDirectory(options = {}) {
|
|
879
|
-
return resolvePrimConfigDirectory(options).path;
|
|
880
|
-
}
|
|
881
|
-
|
|
882
1211
|
// src/lib/session-identity.ts
|
|
883
1212
|
import { execFile } from "child_process";
|
|
884
|
-
import { createHash as
|
|
885
|
-
import { rmSync as
|
|
886
|
-
import { join as
|
|
1213
|
+
import { createHash as createHash4 } from "crypto";
|
|
1214
|
+
import { rmSync as rmSync5 } from "fs";
|
|
1215
|
+
import { join as join8 } from "path";
|
|
887
1216
|
import { promisify } from "util";
|
|
888
1217
|
|
|
889
1218
|
// src/lib/git.ts
|
|
890
1219
|
import { execFileSync } from "child_process";
|
|
891
|
-
import { createHash as
|
|
892
|
-
import { lstatSync as
|
|
893
|
-
import { basename, dirname as
|
|
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";
|
|
894
1223
|
var GIT_TIMEOUT_MS = 1e3;
|
|
895
1224
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
896
1225
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
@@ -947,12 +1276,12 @@ function githubRepositoryFromRemote(remote) {
|
|
|
947
1276
|
return path ? parseGithubRepositoryName(path) : null;
|
|
948
1277
|
}
|
|
949
1278
|
function checkoutSettingsText(repoRoot) {
|
|
950
|
-
const path =
|
|
1279
|
+
const path = join7(repoRoot, ".claude", "settings.json");
|
|
951
1280
|
try {
|
|
952
|
-
if (!
|
|
953
|
-
const stat =
|
|
1281
|
+
if (!lstatSync3(join7(repoRoot, ".claude")).isDirectory()) return null;
|
|
1282
|
+
const stat = lstatSync3(path);
|
|
954
1283
|
if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
|
|
955
|
-
return
|
|
1284
|
+
return readFileSync5(path, "utf8");
|
|
956
1285
|
} catch {
|
|
957
1286
|
return null;
|
|
958
1287
|
}
|
|
@@ -1148,7 +1477,7 @@ function sessionIdentityMessage(outcome) {
|
|
|
1148
1477
|
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
1149
1478
|
}
|
|
1150
1479
|
function hash(value) {
|
|
1151
|
-
return
|
|
1480
|
+
return createHash4("sha256").update(value).digest("hex");
|
|
1152
1481
|
}
|
|
1153
1482
|
function sessionContext(deps) {
|
|
1154
1483
|
const env = deps.env ?? process.env;
|
|
@@ -1175,9 +1504,9 @@ function sessionContext(deps) {
|
|
|
1175
1504
|
clientId: environment.clientId,
|
|
1176
1505
|
generation: environment.generation,
|
|
1177
1506
|
sessionId,
|
|
1178
|
-
tokenPath:
|
|
1179
|
-
statePath:
|
|
1180
|
-
lockPath:
|
|
1507
|
+
tokenPath: join8(directory, `session_identity_${key}.json`),
|
|
1508
|
+
statePath: join8(directory, `session_identity_${key}.state.json`),
|
|
1509
|
+
lockPath: join8(directory, "session-identity.lock")
|
|
1181
1510
|
};
|
|
1182
1511
|
}
|
|
1183
1512
|
function readRecord(path) {
|
|
@@ -1209,7 +1538,7 @@ function readState(context) {
|
|
|
1209
1538
|
function writeToken(context, record) {
|
|
1210
1539
|
prepareMachineMetadataDirectory(context.directory);
|
|
1211
1540
|
writeMachineMetadata(context.tokenPath, record);
|
|
1212
|
-
|
|
1541
|
+
rmSync5(context.statePath, { force: true });
|
|
1213
1542
|
}
|
|
1214
1543
|
function writeState(context, state) {
|
|
1215
1544
|
try {
|
|
@@ -1387,8 +1716,8 @@ function gitDetail(stderr) {
|
|
|
1387
1716
|
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
1388
1717
|
}
|
|
1389
1718
|
async function defaultSleep2(milliseconds, signal) {
|
|
1390
|
-
await new Promise((
|
|
1391
|
-
const timer = setTimeout(
|
|
1719
|
+
await new Promise((resolve4, reject) => {
|
|
1720
|
+
const timer = setTimeout(resolve4, milliseconds);
|
|
1392
1721
|
signal?.addEventListener(
|
|
1393
1722
|
"abort",
|
|
1394
1723
|
() => {
|
|
@@ -1819,7 +2148,7 @@ async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
|
1819
2148
|
return identified(refreshed.record, true);
|
|
1820
2149
|
}
|
|
1821
2150
|
if (refreshed.status === "refused") {
|
|
1822
|
-
|
|
2151
|
+
rmSync5(ctx.tokenPath, { force: true });
|
|
1823
2152
|
writeState(ctx, {
|
|
1824
2153
|
sessionId: ctx.sessionId,
|
|
1825
2154
|
status: "failed",
|
|
@@ -1963,7 +2292,7 @@ async function acquireSessionCredential(options = {}, deps = {}) {
|
|
|
1963
2292
|
function sessionScoped(deps) {
|
|
1964
2293
|
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
1965
2294
|
}
|
|
1966
|
-
var
|
|
2295
|
+
var require3 = createRequire2(import.meta.url);
|
|
1967
2296
|
var SERVICE = "ai.primitive.prim.machine";
|
|
1968
2297
|
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
1969
2298
|
var PROFILE_FILE = "machine_profile.json";
|
|
@@ -1976,16 +2305,16 @@ function apiUrlFor(deps) {
|
|
|
1976
2305
|
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
1977
2306
|
}
|
|
1978
2307
|
function hash2(value) {
|
|
1979
|
-
return
|
|
2308
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
1980
2309
|
}
|
|
1981
2310
|
function recordPath(directory, generation) {
|
|
1982
|
-
return
|
|
2311
|
+
return join9(directory, `machine_${generation}.json`);
|
|
1983
2312
|
}
|
|
1984
2313
|
function storageKey(directory, generation) {
|
|
1985
2314
|
return `${hash2(directory)}:${generation}`;
|
|
1986
2315
|
}
|
|
1987
2316
|
function environmentContextPath(deps, clientId) {
|
|
1988
|
-
return
|
|
2317
|
+
return join9(
|
|
1989
2318
|
configurationDirectory(deps),
|
|
1990
2319
|
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
1991
2320
|
);
|
|
@@ -2045,22 +2374,28 @@ function readEnvironmentContext(environment, deps) {
|
|
|
2045
2374
|
return void 0;
|
|
2046
2375
|
}
|
|
2047
2376
|
}
|
|
2048
|
-
function
|
|
2049
|
-
let directory =
|
|
2377
|
+
function keyringLoaderPath(start, options = {}) {
|
|
2378
|
+
let directory = start;
|
|
2050
2379
|
for (let depth = 0; depth < 5; depth++) {
|
|
2051
|
-
const loader =
|
|
2052
|
-
if (
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2380
|
+
const loader = join9(directory, "native", "keyring.cjs");
|
|
2381
|
+
if (existsSync5(loader)) return loader;
|
|
2382
|
+
directory = dirname7(directory);
|
|
2383
|
+
}
|
|
2384
|
+
try {
|
|
2385
|
+
createRequire2(join9(start, "noop.js")).resolve("@napi-rs/keyring");
|
|
2386
|
+
return void 0;
|
|
2387
|
+
} catch {
|
|
2388
|
+
return selectedHookRuntimeKeyringLoader(options);
|
|
2057
2389
|
}
|
|
2058
|
-
|
|
2390
|
+
}
|
|
2391
|
+
function keyringEntry(key) {
|
|
2392
|
+
const loader = keyringLoaderPath(dirname7(fileURLToPath3(import.meta.url)));
|
|
2393
|
+
const module = require3(loader ?? "@napi-rs/keyring");
|
|
2059
2394
|
return new module.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
2060
2395
|
}
|
|
2061
2396
|
function protectPath(path, directory) {
|
|
2062
2397
|
if (process.platform !== "win32") {
|
|
2063
|
-
|
|
2398
|
+
chmodSync2(path, directory ? 448 : 384);
|
|
2064
2399
|
return;
|
|
2065
2400
|
}
|
|
2066
2401
|
const encodedPath = Buffer.from(path).toString("base64");
|
|
@@ -2077,8 +2412,8 @@ function protectPath(path, directory) {
|
|
|
2077
2412
|
);
|
|
2078
2413
|
}
|
|
2079
2414
|
function ensureDirectory(directory) {
|
|
2080
|
-
|
|
2081
|
-
if (
|
|
2415
|
+
mkdirSync4(directory, { recursive: true, mode: 448 });
|
|
2416
|
+
if (lstatSync4(directory).isSymbolicLink())
|
|
2082
2417
|
throw new MachineAuthError(
|
|
2083
2418
|
"unsafe_storage",
|
|
2084
2419
|
"Credential directory must not be a symbolic link."
|
|
@@ -2096,14 +2431,14 @@ function readMachineMetadata(path) {
|
|
|
2096
2431
|
function readPrivate(path) {
|
|
2097
2432
|
let raw;
|
|
2098
2433
|
try {
|
|
2099
|
-
const stat =
|
|
2434
|
+
const stat = lstatSync4(path);
|
|
2100
2435
|
if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
|
|
2101
2436
|
throw new MachineAuthError(
|
|
2102
2437
|
"unsafe_storage",
|
|
2103
2438
|
"Machine credential files must be owner-only regular files."
|
|
2104
2439
|
);
|
|
2105
2440
|
}
|
|
2106
|
-
raw =
|
|
2441
|
+
raw = readFileSync6(path, "utf8");
|
|
2107
2442
|
} catch (error) {
|
|
2108
2443
|
if (error.code === "ENOENT") return void 0;
|
|
2109
2444
|
throw error;
|
|
@@ -2148,7 +2483,7 @@ function parseProfile(value) {
|
|
|
2148
2483
|
};
|
|
2149
2484
|
}
|
|
2150
2485
|
function readMachineProfile(deps = {}) {
|
|
2151
|
-
const value = readPrivate(
|
|
2486
|
+
const value = readPrivate(join9(configurationDirectory(deps), PROFILE_FILE));
|
|
2152
2487
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
2153
2488
|
}
|
|
2154
2489
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -2157,20 +2492,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
2157
2492
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2158
2493
|
function networkSecretBrokerKey(deps, clientId) {
|
|
2159
2494
|
const directory = configurationDirectory(deps);
|
|
2160
|
-
const path =
|
|
2495
|
+
const path = join9(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2161
2496
|
const known = brokerKeys.get(path);
|
|
2162
2497
|
if (known) return known;
|
|
2163
2498
|
ensureDirectory(directory);
|
|
2164
2499
|
const read = () => {
|
|
2165
2500
|
try {
|
|
2166
|
-
const stat =
|
|
2501
|
+
const stat = lstatSync4(path);
|
|
2167
2502
|
if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
|
|
2168
2503
|
throw new MachineAuthError(
|
|
2169
2504
|
"unsafe_storage",
|
|
2170
2505
|
`The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
|
|
2171
2506
|
true
|
|
2172
2507
|
);
|
|
2173
|
-
const value =
|
|
2508
|
+
const value = readFileSync6(path, "utf8").trim();
|
|
2174
2509
|
return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
|
|
2175
2510
|
} catch (error) {
|
|
2176
2511
|
if (error.code === "ENOENT") return void 0;
|
|
@@ -2189,16 +2524,16 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
2189
2524
|
`The machine broker key at ${path} is damaged. Delete it and retry.`,
|
|
2190
2525
|
true
|
|
2191
2526
|
);
|
|
2192
|
-
const staged = `${path}.${process.pid}.${
|
|
2527
|
+
const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
|
|
2193
2528
|
try {
|
|
2194
|
-
|
|
2529
|
+
writeFileSync4(staged, `${randomBytes3(32).toString("hex")}
|
|
2195
2530
|
`, { mode: 384, flag: "wx" });
|
|
2196
2531
|
protectPath(staged, false);
|
|
2197
2532
|
linkSync(staged, path);
|
|
2198
2533
|
} catch (error) {
|
|
2199
2534
|
if (error.code !== "EEXIST") throw error;
|
|
2200
2535
|
} finally {
|
|
2201
|
-
|
|
2536
|
+
rmSync6(staged, { force: true });
|
|
2202
2537
|
}
|
|
2203
2538
|
}
|
|
2204
2539
|
const key = read()?.key;
|
|
@@ -2257,7 +2592,7 @@ function environmentCredentials(deps) {
|
|
|
2257
2592
|
}
|
|
2258
2593
|
function hasMachineConfiguration(deps = {}) {
|
|
2259
2594
|
const env = deps.env ?? process.env;
|
|
2260
|
-
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));
|
|
2261
2596
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
2262
2597
|
throw new MachineAuthError(
|
|
2263
2598
|
"conflicting_credentials",
|
|
@@ -2293,7 +2628,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
2293
2628
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2294
2629
|
if (!generation) return false;
|
|
2295
2630
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2296
|
-
return readPrivate(
|
|
2631
|
+
return readPrivate(join9(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2297
2632
|
}
|
|
2298
2633
|
var environmentTerminal;
|
|
2299
2634
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -2386,7 +2721,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2386
2721
|
}
|
|
2387
2722
|
}
|
|
2388
2723
|
return withFileLock(
|
|
2389
|
-
|
|
2724
|
+
join9(directory2, "credentials.lock"),
|
|
2390
2725
|
async () => {
|
|
2391
2726
|
if (machineSessionEnded(deps))
|
|
2392
2727
|
throw new MachineAuthError(
|
|
@@ -2468,7 +2803,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2468
2803
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2469
2804
|
try {
|
|
2470
2805
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2471
|
-
|
|
2806
|
+
rmSync6(contextPath, { force: true });
|
|
2472
2807
|
} catch {
|
|
2473
2808
|
}
|
|
2474
2809
|
throw error;
|
|
@@ -2478,7 +2813,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2478
2813
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2479
2814
|
try {
|
|
2480
2815
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2481
|
-
|
|
2816
|
+
rmSync6(contextPath, { force: true });
|
|
2482
2817
|
} catch {
|
|
2483
2818
|
}
|
|
2484
2819
|
}
|
|
@@ -2492,7 +2827,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2492
2827
|
const expected = machineContext(deps);
|
|
2493
2828
|
const directory = configurationDirectory(deps);
|
|
2494
2829
|
return withFileLock(
|
|
2495
|
-
|
|
2830
|
+
join9(directory, "credentials.lock"),
|
|
2496
2831
|
async () => {
|
|
2497
2832
|
const profile = readMachineProfile(deps);
|
|
2498
2833
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2542,7 +2877,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2542
2877
|
await persistRecord(record, deps, signal);
|
|
2543
2878
|
} catch (error) {
|
|
2544
2879
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2545
|
-
writePrivate(
|
|
2880
|
+
writePrivate(join9(directory, "machine_terminal.json"), profile.generation);
|
|
2546
2881
|
throw error;
|
|
2547
2882
|
}
|
|
2548
2883
|
}
|
|
@@ -2599,14 +2934,14 @@ var FORWARD_TIMEOUT_MS = 3e4;
|
|
|
2599
2934
|
var FORWARD_METHODS = ["GET", "POST", "DELETE"];
|
|
2600
2935
|
var IDLE_MS = 5 * 6e4;
|
|
2601
2936
|
function descriptorPath(directory, generation) {
|
|
2602
|
-
return
|
|
2937
|
+
return join10(directory, `machine_broker_${generation}.json`);
|
|
2603
2938
|
}
|
|
2604
2939
|
function readDescriptor(path) {
|
|
2605
2940
|
try {
|
|
2606
|
-
const stat =
|
|
2941
|
+
const stat = lstatSync5(path);
|
|
2607
2942
|
if (!stat.isFile() || stat.size > 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
2608
2943
|
return void 0;
|
|
2609
|
-
const data = JSON.parse(
|
|
2944
|
+
const data = JSON.parse(readFileSync7(path, "utf8"));
|
|
2610
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;
|
|
2611
2946
|
} catch {
|
|
2612
2947
|
return void 0;
|
|
@@ -2619,7 +2954,7 @@ function matches(left, right) {
|
|
|
2619
2954
|
return typeof right === "string" && /^[a-f0-9]{64}$/u.test(right) && timingSafeEqual(Buffer.from(left, "hex"), Buffer.from(right, "hex"));
|
|
2620
2955
|
}
|
|
2621
2956
|
function tokenHash(token) {
|
|
2622
|
-
return token ?
|
|
2957
|
+
return token ? createHash6("sha256").update(token).digest("hex") : void 0;
|
|
2623
2958
|
}
|
|
2624
2959
|
async function brokerRequest(descriptor, environment, options) {
|
|
2625
2960
|
const body = JSON.stringify({
|
|
@@ -2696,7 +3031,7 @@ async function acquireBrokerCredential(options) {
|
|
|
2696
3031
|
async function ensureBroker(options) {
|
|
2697
3032
|
const path = descriptorPath(options.directory, options.environment.generation);
|
|
2698
3033
|
return withFileLock(
|
|
2699
|
-
|
|
3034
|
+
join10(options.directory, "machine-broker.lock"),
|
|
2700
3035
|
async () => {
|
|
2701
3036
|
const current = readDescriptor(path);
|
|
2702
3037
|
if (current) {
|
|
@@ -2709,14 +3044,14 @@ async function ensureBroker(options) {
|
|
|
2709
3044
|
options.signal.throwIfAborted();
|
|
2710
3045
|
}
|
|
2711
3046
|
}
|
|
2712
|
-
const bundled =
|
|
3047
|
+
const bundled = fileURLToPath4(import.meta.url);
|
|
2713
3048
|
const entry = basename2(bundled) === "prim-daemon-server" ? bundled : binFile("prim-daemon-server");
|
|
2714
3049
|
if (!entry)
|
|
2715
3050
|
throw new MachineAuthError(
|
|
2716
3051
|
"broker_unavailable",
|
|
2717
3052
|
"Reinstall Prim to restore its machine credential broker."
|
|
2718
3053
|
);
|
|
2719
|
-
await new Promise((
|
|
3054
|
+
await new Promise((resolve4, reject) => {
|
|
2720
3055
|
const child = spawn(process.execPath, [entry, "--machine-token-broker"], {
|
|
2721
3056
|
detached: true,
|
|
2722
3057
|
stdio: ["ignore", "ignore", "ignore", "ipc"],
|
|
@@ -2731,7 +3066,7 @@ async function ensureBroker(options) {
|
|
|
2731
3066
|
if (error) child.kill();
|
|
2732
3067
|
if (child.connected) child.disconnect();
|
|
2733
3068
|
child.unref();
|
|
2734
|
-
error ? reject(error) :
|
|
3069
|
+
error ? reject(error) : resolve4();
|
|
2735
3070
|
};
|
|
2736
3071
|
const abort = () => finish(
|
|
2737
3072
|
new MachineAuthError(
|
|
@@ -3011,7 +3346,7 @@ async function startMachineBroker() {
|
|
|
3011
3346
|
const directory = primConfigDirectory();
|
|
3012
3347
|
const apiUrl = machineApiUrl(process.env.PRIM_API_URL || "https://api.getprimitive.ai");
|
|
3013
3348
|
const path = descriptorPath(directory, environment.generation);
|
|
3014
|
-
const nonce =
|
|
3349
|
+
const nonce = randomBytes4(32).toString("hex");
|
|
3015
3350
|
const server = createBrokerServer({
|
|
3016
3351
|
environment,
|
|
3017
3352
|
apiUrl,
|
|
@@ -3022,14 +3357,14 @@ async function startMachineBroker() {
|
|
|
3022
3357
|
clearTimeout(idle);
|
|
3023
3358
|
server.closeAllConnections();
|
|
3024
3359
|
server.close();
|
|
3025
|
-
if (readDescriptor(path)?.nonce === nonce)
|
|
3360
|
+
if (readDescriptor(path)?.nonce === nonce) rmSync7(path, { force: true });
|
|
3026
3361
|
};
|
|
3027
3362
|
const idle = setTimeout(close, IDLE_MS);
|
|
3028
3363
|
process.once("SIGTERM", close);
|
|
3029
3364
|
process.once("SIGINT", close);
|
|
3030
|
-
await new Promise((
|
|
3365
|
+
await new Promise((resolve4, reject) => {
|
|
3031
3366
|
server.once("error", reject);
|
|
3032
|
-
server.listen(0, "127.0.0.1",
|
|
3367
|
+
server.listen(0, "127.0.0.1", resolve4);
|
|
3033
3368
|
});
|
|
3034
3369
|
const address = server.address();
|
|
3035
3370
|
if (!address || typeof address === "string") throw new Error("Invalid broker address");
|
|
@@ -3040,27 +3375,27 @@ async function startMachineBroker() {
|
|
|
3040
3375
|
}
|
|
3041
3376
|
|
|
3042
3377
|
// src/daemon/principal.ts
|
|
3043
|
-
import { createHash as
|
|
3378
|
+
import { createHash as createHash8 } from "crypto";
|
|
3044
3379
|
|
|
3045
3380
|
// src/lib/credentials.ts
|
|
3046
|
-
import { createHash as
|
|
3047
|
-
import { readFileSync as
|
|
3048
|
-
import { join as
|
|
3381
|
+
import { createHash as createHash7 } from "crypto";
|
|
3382
|
+
import { readFileSync as readFileSync8 } from "fs";
|
|
3383
|
+
import { join as join11 } from "path";
|
|
3049
3384
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
3050
|
-
var TOKEN_FILE_PATH =
|
|
3051
|
-
var REFRESH_TOKEN_PATH =
|
|
3052
|
-
var TOKEN_EXPIRES_PATH =
|
|
3053
|
-
var TERMINAL_REFRESH_PATH =
|
|
3054
|
-
var CREDENTIAL_METADATA_PATH =
|
|
3055
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
3056
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
3057
|
-
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");
|
|
3058
3393
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
3059
3394
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
3060
3395
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
3061
3396
|
function readTrimmed(path) {
|
|
3062
3397
|
try {
|
|
3063
|
-
const value =
|
|
3398
|
+
const value = readFileSync8(path, "utf8").trim();
|
|
3064
3399
|
return value || void 0;
|
|
3065
3400
|
} catch {
|
|
3066
3401
|
return void 0;
|
|
@@ -3097,7 +3432,7 @@ function resolveAuthCredential(options = {}) {
|
|
|
3097
3432
|
return { token: stored, source: "token_file" };
|
|
3098
3433
|
}
|
|
3099
3434
|
function credentialFingerprint(value) {
|
|
3100
|
-
return
|
|
3435
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
3101
3436
|
}
|
|
3102
3437
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
3103
3438
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -3117,7 +3452,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
|
|
|
3117
3452
|
function readBoundedCredentialJson(path) {
|
|
3118
3453
|
let raw;
|
|
3119
3454
|
try {
|
|
3120
|
-
raw =
|
|
3455
|
+
raw = readFileSync8(path, "utf8");
|
|
3121
3456
|
} catch (error) {
|
|
3122
3457
|
return error.code === "ENOENT" ? void 0 : null;
|
|
3123
3458
|
}
|
|
@@ -3194,25 +3529,25 @@ var SHA256_HEX_PATTERN = /^[a-f0-9]{64}$/;
|
|
|
3194
3529
|
function boundedClaim(value) {
|
|
3195
3530
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
3196
3531
|
}
|
|
3197
|
-
function
|
|
3198
|
-
return
|
|
3532
|
+
function sha2562(value) {
|
|
3533
|
+
return createHash8("sha256").update(value).digest("hex");
|
|
3199
3534
|
}
|
|
3200
3535
|
function resolveDaemonCredentialKey(token = resolveAuthCredential()?.token) {
|
|
3201
3536
|
if (hasMachineConfiguration()) {
|
|
3202
3537
|
const machine = machineContext();
|
|
3203
3538
|
return machine ? `${machine.generation}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}` : void 0;
|
|
3204
3539
|
}
|
|
3205
|
-
return token ?
|
|
3540
|
+
return token ? sha2562(token) : void 0;
|
|
3206
3541
|
}
|
|
3207
3542
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
3208
3543
|
if (hasMachineConfiguration()) {
|
|
3209
3544
|
const machine = machineContext();
|
|
3210
3545
|
return machine ? {
|
|
3211
|
-
principalId:
|
|
3546
|
+
principalId: sha2562(
|
|
3212
3547
|
`${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
|
|
3213
3548
|
),
|
|
3214
3549
|
organizationId: machine.workosOrganizationId,
|
|
3215
|
-
credentialFingerprint:
|
|
3550
|
+
credentialFingerprint: sha2562(machine.generation)
|
|
3216
3551
|
} : void 0;
|
|
3217
3552
|
}
|
|
3218
3553
|
if (!token) return void 0;
|
|
@@ -3222,9 +3557,9 @@ function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
|
3222
3557
|
if (!(subject && organizationId)) return void 0;
|
|
3223
3558
|
const issuer = boundedClaim(payload?.iss) ?? "unknown-issuer";
|
|
3224
3559
|
return {
|
|
3225
|
-
principalId:
|
|
3560
|
+
principalId: sha2562(`${issuer}\0${subject}`),
|
|
3226
3561
|
organizationId,
|
|
3227
|
-
credentialFingerprint:
|
|
3562
|
+
credentialFingerprint: sha2562(token)
|
|
3228
3563
|
};
|
|
3229
3564
|
}
|
|
3230
3565
|
function isDaemonPrincipal(value) {
|
|
@@ -3278,10 +3613,10 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
3278
3613
|
}
|
|
3279
3614
|
|
|
3280
3615
|
// src/daemon/server.ts
|
|
3281
|
-
import { chmodSync as
|
|
3616
|
+
import { chmodSync as chmodSync9, existsSync as existsSync14, mkdirSync as mkdirSync11, readFileSync as readFileSync16, unlinkSync as unlinkSync3 } from "fs";
|
|
3282
3617
|
import { createServer as createServer2 } from "net";
|
|
3283
|
-
import { join as
|
|
3284
|
-
import { fileURLToPath as
|
|
3618
|
+
import { join as join23 } from "path";
|
|
3619
|
+
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
3285
3620
|
|
|
3286
3621
|
// src/decisions/identity.ts
|
|
3287
3622
|
var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
|
|
@@ -3361,14 +3696,14 @@ function publicDecisionResponse(value) {
|
|
|
3361
3696
|
}
|
|
3362
3697
|
|
|
3363
3698
|
// src/client.ts
|
|
3364
|
-
import { createHash as
|
|
3365
|
-
import { chmodSync as
|
|
3366
|
-
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";
|
|
3367
3702
|
|
|
3368
3703
|
// src/daemon/client-instance-id.ts
|
|
3369
|
-
import { randomBytes as
|
|
3370
|
-
import { chmodSync as
|
|
3371
|
-
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";
|
|
3372
3707
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
3373
3708
|
var INSTANCE_FILE_MODE = 384;
|
|
3374
3709
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -3381,17 +3716,17 @@ function isClientInstanceId(value) {
|
|
|
3381
3716
|
}
|
|
3382
3717
|
function ensurePrivateConfigDirectory(configDir) {
|
|
3383
3718
|
ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
|
|
3384
|
-
const metadata =
|
|
3719
|
+
const metadata = lstatSync6(configDir);
|
|
3385
3720
|
if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
|
|
3386
3721
|
throw new Error("prim config path must be a private directory");
|
|
3387
3722
|
}
|
|
3388
|
-
|
|
3723
|
+
chmodSync3(configDir, CONFIG_DIRECTORY_MODE);
|
|
3389
3724
|
syncDirectory(configDir);
|
|
3390
3725
|
}
|
|
3391
3726
|
function readExisting(path) {
|
|
3392
3727
|
let metadata;
|
|
3393
3728
|
try {
|
|
3394
|
-
metadata =
|
|
3729
|
+
metadata = lstatSync6(path);
|
|
3395
3730
|
} catch (error) {
|
|
3396
3731
|
if (error.code === "ENOENT") {
|
|
3397
3732
|
return;
|
|
@@ -3401,11 +3736,11 @@ function readExisting(path) {
|
|
|
3401
3736
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
3402
3737
|
throw new Error("stored client instance identity is invalid");
|
|
3403
3738
|
}
|
|
3404
|
-
|
|
3739
|
+
chmodSync3(path, INSTANCE_FILE_MODE);
|
|
3405
3740
|
if (metadata.size > MAX_STORED_BYTES) {
|
|
3406
3741
|
throw new Error("stored client instance identity is invalid");
|
|
3407
3742
|
}
|
|
3408
|
-
const raw =
|
|
3743
|
+
const raw = readFileSync9(path, "utf8");
|
|
3409
3744
|
const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
|
|
3410
3745
|
if (raw !== value && raw !== `${value}
|
|
3411
3746
|
` || !isClientInstanceId(value)) {
|
|
@@ -3419,8 +3754,8 @@ function atomicWrite(path, value) {
|
|
|
3419
3754
|
}
|
|
3420
3755
|
async function getOrCreateClientInstanceId(options) {
|
|
3421
3756
|
const configDir = options.configDir;
|
|
3422
|
-
const path =
|
|
3423
|
-
const lockPath =
|
|
3757
|
+
const path = join12(configDir, "client_instance_id");
|
|
3758
|
+
const lockPath = join12(configDir, "client-instance.lock");
|
|
3424
3759
|
ensurePrivateConfigDirectory(configDir);
|
|
3425
3760
|
return withFileLock(
|
|
3426
3761
|
lockPath,
|
|
@@ -3429,7 +3764,7 @@ async function getOrCreateClientInstanceId(options) {
|
|
|
3429
3764
|
if (existing !== void 0) {
|
|
3430
3765
|
return existing;
|
|
3431
3766
|
}
|
|
3432
|
-
const generated = `${INSTANCE_PREFIX}${
|
|
3767
|
+
const generated = `${INSTANCE_PREFIX}${randomBytes5(INSTANCE_ENTROPY_BYTES).toString(
|
|
3433
3768
|
"base64url"
|
|
3434
3769
|
)}`;
|
|
3435
3770
|
if (!isClientInstanceId(generated)) {
|
|
@@ -3475,7 +3810,7 @@ function authExpiredMessage() {
|
|
|
3475
3810
|
}
|
|
3476
3811
|
function readTrimmed2(path) {
|
|
3477
3812
|
try {
|
|
3478
|
-
const value =
|
|
3813
|
+
const value = readFileSync10(path, "utf8").trim();
|
|
3479
3814
|
return value || void 0;
|
|
3480
3815
|
} catch {
|
|
3481
3816
|
return void 0;
|
|
@@ -3491,17 +3826,17 @@ function expiresAtFor(token, expiresIn) {
|
|
|
3491
3826
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
3492
3827
|
}
|
|
3493
3828
|
function ensureConfigDirectory() {
|
|
3494
|
-
const directory =
|
|
3495
|
-
|
|
3496
|
-
|
|
3829
|
+
const directory = dirname8(TOKEN_FILE_PATH);
|
|
3830
|
+
mkdirSync5(directory, { recursive: true, mode: CONFIG_DIR_MODE });
|
|
3831
|
+
chmodSync4(directory, CONFIG_DIR_MODE);
|
|
3497
3832
|
}
|
|
3498
3833
|
function atomicWrite2(path, content) {
|
|
3499
3834
|
ensureConfigDirectory();
|
|
3500
3835
|
atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
|
|
3501
3836
|
}
|
|
3502
3837
|
function removeCredentialFile(path) {
|
|
3503
|
-
if (!
|
|
3504
|
-
|
|
3838
|
+
if (!existsSync6(path)) return false;
|
|
3839
|
+
rmSync8(path, { force: true });
|
|
3505
3840
|
return true;
|
|
3506
3841
|
}
|
|
3507
3842
|
function getTokenExpiresAt() {
|
|
@@ -3517,7 +3852,7 @@ function isTokenExpiringSoon(credential) {
|
|
|
3517
3852
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
3518
3853
|
}
|
|
3519
3854
|
function refreshFingerprint(refreshToken3) {
|
|
3520
|
-
return
|
|
3855
|
+
return createHash9("sha256").update(refreshToken3).digest("hex");
|
|
3521
3856
|
}
|
|
3522
3857
|
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
3523
3858
|
return {
|
|
@@ -4042,66 +4377,66 @@ async function getPinnedClient(options = {}) {
|
|
|
4042
4377
|
}
|
|
4043
4378
|
|
|
4044
4379
|
// src/flusher.ts
|
|
4045
|
-
import { createReadStream, renameSync as
|
|
4046
|
-
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";
|
|
4047
4382
|
|
|
4048
4383
|
// src/dead-letter.ts
|
|
4049
|
-
import { createHash as
|
|
4384
|
+
import { createHash as createHash10, randomBytes as randomBytes6 } from "crypto";
|
|
4050
4385
|
import {
|
|
4051
|
-
constants as
|
|
4052
|
-
chmodSync as
|
|
4386
|
+
constants as constants3,
|
|
4387
|
+
chmodSync as chmodSync5,
|
|
4053
4388
|
closeSync as closeSync2,
|
|
4054
|
-
existsSync as
|
|
4389
|
+
existsSync as existsSync7,
|
|
4055
4390
|
fchmodSync as fchmodSync2,
|
|
4056
4391
|
fsyncSync as fsyncSync2,
|
|
4057
|
-
mkdirSync as
|
|
4392
|
+
mkdirSync as mkdirSync6,
|
|
4058
4393
|
openSync as openSync2,
|
|
4059
|
-
renameSync as
|
|
4060
|
-
rmSync as
|
|
4061
|
-
writeFileSync as
|
|
4394
|
+
renameSync as renameSync3,
|
|
4395
|
+
rmSync as rmSync9,
|
|
4396
|
+
writeFileSync as writeFileSync5
|
|
4062
4397
|
} from "fs";
|
|
4063
|
-
import { dirname as
|
|
4398
|
+
import { dirname as dirname9, join as join14 } from "path";
|
|
4064
4399
|
var DIRECTORY_MODE2 = 448;
|
|
4065
4400
|
var FILE_MODE2 = 384;
|
|
4066
4401
|
var DEAD_LETTER_DIRNAME = "dead-letter";
|
|
4067
4402
|
function deadLetterDirectoryForRotation(flushingPath) {
|
|
4068
|
-
return
|
|
4403
|
+
return join14(dirname9(flushingPath), DEAD_LETTER_DIRNAME);
|
|
4069
4404
|
}
|
|
4070
4405
|
function deadLetterPathForRawLine(flushingPath, rawLine) {
|
|
4071
|
-
const quarantineId =
|
|
4072
|
-
return
|
|
4406
|
+
const quarantineId = createHash10("sha256").update(rawLine).digest("hex");
|
|
4407
|
+
return join14(deadLetterDirectoryForRotation(flushingPath), `raw-${quarantineId}.json`);
|
|
4073
4408
|
}
|
|
4074
4409
|
function ensureDeadLetterDirectory(flushingPath, persistDirectory) {
|
|
4075
4410
|
const directory = deadLetterDirectoryForRotation(flushingPath);
|
|
4076
|
-
|
|
4077
|
-
|
|
4078
|
-
persistDirectory(
|
|
4411
|
+
mkdirSync6(directory, { recursive: true, mode: DIRECTORY_MODE2 });
|
|
4412
|
+
chmodSync5(directory, DIRECTORY_MODE2);
|
|
4413
|
+
persistDirectory(dirname9(directory));
|
|
4079
4414
|
return directory;
|
|
4080
4415
|
}
|
|
4081
4416
|
function persistDeadLetter(directory, path, quarantineId, record, persistDirectory) {
|
|
4082
|
-
if (
|
|
4417
|
+
if (existsSync7(path)) {
|
|
4083
4418
|
persistDirectory(directory);
|
|
4084
4419
|
return;
|
|
4085
4420
|
}
|
|
4086
|
-
const temporaryPath =
|
|
4421
|
+
const temporaryPath = join14(
|
|
4087
4422
|
directory,
|
|
4088
|
-
`.${quarantineId}.${String(process.pid)}.${
|
|
4423
|
+
`.${quarantineId}.${String(process.pid)}.${randomBytes6(8).toString("hex")}.tmp`
|
|
4089
4424
|
);
|
|
4090
|
-
const flags =
|
|
4425
|
+
const flags = constants3.O_CREAT | constants3.O_EXCL | constants3.O_WRONLY | constants3.O_NOFOLLOW;
|
|
4091
4426
|
try {
|
|
4092
4427
|
const fd = openSync2(temporaryPath, flags, FILE_MODE2);
|
|
4093
4428
|
try {
|
|
4094
4429
|
fchmodSync2(fd, FILE_MODE2);
|
|
4095
|
-
|
|
4430
|
+
writeFileSync5(fd, `${JSON.stringify(record)}
|
|
4096
4431
|
`, "utf8");
|
|
4097
4432
|
fsyncSync2(fd);
|
|
4098
4433
|
} finally {
|
|
4099
4434
|
closeSync2(fd);
|
|
4100
4435
|
}
|
|
4101
|
-
|
|
4436
|
+
renameSync3(temporaryPath, path);
|
|
4102
4437
|
persistDirectory(directory);
|
|
4103
4438
|
} finally {
|
|
4104
|
-
|
|
4439
|
+
rmSync9(temporaryPath, { force: true });
|
|
4105
4440
|
}
|
|
4106
4441
|
}
|
|
4107
4442
|
function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}) {
|
|
@@ -4110,12 +4445,12 @@ function quarantineMove(flushingPath, move, reason, now = Date.now, options = {}
|
|
|
4110
4445
|
const serializedMove = JSON.stringify(move);
|
|
4111
4446
|
const record = {
|
|
4112
4447
|
version: 1,
|
|
4113
|
-
quarantineId:
|
|
4448
|
+
quarantineId: createHash10("sha256").update(serializedMove).digest("hex"),
|
|
4114
4449
|
quarantinedAt: now(),
|
|
4115
4450
|
reason,
|
|
4116
4451
|
move
|
|
4117
4452
|
};
|
|
4118
|
-
const path =
|
|
4453
|
+
const path = join14(directory, `${record.quarantineId}.json`);
|
|
4119
4454
|
persistDeadLetter(directory, path, record.quarantineId, record, persistDirectory);
|
|
4120
4455
|
return record;
|
|
4121
4456
|
}
|
|
@@ -4126,7 +4461,7 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
4126
4461
|
const record = {
|
|
4127
4462
|
version: 1,
|
|
4128
4463
|
recordKind: "raw_line_v1",
|
|
4129
|
-
quarantineId:
|
|
4464
|
+
quarantineId: createHash10("sha256").update(bytes).digest("hex"),
|
|
4130
4465
|
quarantinedAt: now(),
|
|
4131
4466
|
reason: "invalid_move",
|
|
4132
4467
|
rawLineEncoding: "base64",
|
|
@@ -4145,14 +4480,14 @@ function quarantineRawLine(flushingPath, rawLine, now = Date.now, options = {})
|
|
|
4145
4480
|
|
|
4146
4481
|
// src/drain-progress.ts
|
|
4147
4482
|
import {
|
|
4148
|
-
chmodSync as
|
|
4149
|
-
existsSync as
|
|
4150
|
-
readFileSync as
|
|
4151
|
-
readdirSync as
|
|
4152
|
-
rmSync as
|
|
4483
|
+
chmodSync as chmodSync6,
|
|
4484
|
+
existsSync as existsSync8,
|
|
4485
|
+
readFileSync as readFileSync11,
|
|
4486
|
+
readdirSync as readdirSync3,
|
|
4487
|
+
rmSync as rmSync10,
|
|
4153
4488
|
rmdirSync
|
|
4154
4489
|
} from "fs";
|
|
4155
|
-
import { basename as basename3, dirname as
|
|
4490
|
+
import { basename as basename3, dirname as dirname10, join as join15 } from "path";
|
|
4156
4491
|
var DIRECTORY_MODE3 = 448;
|
|
4157
4492
|
var FILE_MODE3 = 384;
|
|
4158
4493
|
var DRAIN_PROGRESS_DIRNAME = "drain-progress";
|
|
@@ -4161,10 +4496,10 @@ function rotationIdentity(stat) {
|
|
|
4161
4496
|
return { size: stat.size, ino: stat.ino, dev: stat.dev };
|
|
4162
4497
|
}
|
|
4163
4498
|
function drainProgressDirectory(flushingPath) {
|
|
4164
|
-
return
|
|
4499
|
+
return join15(dirname10(flushingPath), DRAIN_PROGRESS_DIRNAME);
|
|
4165
4500
|
}
|
|
4166
4501
|
function drainProgressPath(flushingPath) {
|
|
4167
|
-
return
|
|
4502
|
+
return join15(drainProgressDirectory(flushingPath), `${basename3(flushingPath)}.json`);
|
|
4168
4503
|
}
|
|
4169
4504
|
function isByteCount(value) {
|
|
4170
4505
|
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
@@ -4172,7 +4507,7 @@ function isByteCount(value) {
|
|
|
4172
4507
|
function drainResumeOffset(flushingPath, rotation) {
|
|
4173
4508
|
let parsed;
|
|
4174
4509
|
try {
|
|
4175
|
-
parsed = JSON.parse(
|
|
4510
|
+
parsed = JSON.parse(readFileSync11(drainProgressPath(flushingPath), "utf8"));
|
|
4176
4511
|
} catch {
|
|
4177
4512
|
return 0;
|
|
4178
4513
|
}
|
|
@@ -4188,7 +4523,7 @@ function drainResumeOffset(flushingPath, rotation) {
|
|
|
4188
4523
|
function writeDrainCheckpoint(flushingPath, checkpoint) {
|
|
4189
4524
|
const directory = drainProgressDirectory(flushingPath);
|
|
4190
4525
|
ensureDurableDirectory(directory, DIRECTORY_MODE3);
|
|
4191
|
-
|
|
4526
|
+
chmodSync6(directory, DIRECTORY_MODE3);
|
|
4192
4527
|
atomicWriteFile(drainProgressPath(flushingPath), `${JSON.stringify(checkpoint)}
|
|
4193
4528
|
`, {
|
|
4194
4529
|
mode: FILE_MODE3
|
|
@@ -4205,24 +4540,24 @@ function removeEmptyDirectory(directory) {
|
|
|
4205
4540
|
}
|
|
4206
4541
|
}
|
|
4207
4542
|
function removeDrainCheckpoint(flushingPath) {
|
|
4208
|
-
|
|
4543
|
+
rmSync10(drainProgressPath(flushingPath), { force: true });
|
|
4209
4544
|
removeEmptyDirectory(drainProgressDirectory(flushingPath));
|
|
4210
4545
|
}
|
|
4211
4546
|
function sweepOrphanedDrainCheckpoints(bucketDirectory) {
|
|
4212
|
-
const directory =
|
|
4547
|
+
const directory = join15(bucketDirectory, DRAIN_PROGRESS_DIRNAME);
|
|
4213
4548
|
let names;
|
|
4214
4549
|
try {
|
|
4215
|
-
names =
|
|
4550
|
+
names = readdirSync3(directory);
|
|
4216
4551
|
} catch {
|
|
4217
4552
|
return;
|
|
4218
4553
|
}
|
|
4219
4554
|
for (const name of names) {
|
|
4220
4555
|
const rotation = CHECKPOINT_NAME.exec(name)?.[1];
|
|
4221
|
-
if (rotation === void 0 ||
|
|
4556
|
+
if (rotation === void 0 || existsSync8(join15(bucketDirectory, rotation))) {
|
|
4222
4557
|
continue;
|
|
4223
4558
|
}
|
|
4224
4559
|
try {
|
|
4225
|
-
|
|
4560
|
+
rmSync10(join15(directory, name), { force: true });
|
|
4226
4561
|
} catch {
|
|
4227
4562
|
}
|
|
4228
4563
|
}
|
|
@@ -30919,21 +31254,21 @@ validate84.evaluated = { "props": true, "dynamicProps": false, "dynamicItems": f
|
|
|
30919
31254
|
|
|
30920
31255
|
// src/lib/activation.ts
|
|
30921
31256
|
import { execFileSync as execFileSync4 } from "child_process";
|
|
30922
|
-
import { existsSync as
|
|
31257
|
+
import { existsSync as existsSync10, readFileSync as readFileSync13 } from "fs";
|
|
30923
31258
|
import { homedir as homedir2 } from "os";
|
|
30924
|
-
import { join as
|
|
31259
|
+
import { join as join17 } from "path";
|
|
30925
31260
|
|
|
30926
31261
|
// src/lib/cloud-prepared.ts
|
|
30927
|
-
import { existsSync as
|
|
30928
|
-
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";
|
|
30929
31264
|
var CLOUD_PREPARED_MARKER = "cloud-prepared";
|
|
30930
31265
|
function cloudPreparedPath(env = process.env) {
|
|
30931
|
-
return
|
|
31266
|
+
return join16(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
|
|
30932
31267
|
}
|
|
30933
31268
|
function isPreparedCloudSession(env = process.env) {
|
|
30934
31269
|
if (!isClaudeCloudSession(env)) return false;
|
|
30935
31270
|
try {
|
|
30936
|
-
return
|
|
31271
|
+
return existsSync9(cloudPreparedPath(env));
|
|
30937
31272
|
} catch {
|
|
30938
31273
|
return false;
|
|
30939
31274
|
}
|
|
@@ -31069,10 +31404,10 @@ function repositoryBindingState(cwd) {
|
|
|
31069
31404
|
function projectPrimInstallAt(root) {
|
|
31070
31405
|
if (root === null || root === homedir2()) return false;
|
|
31071
31406
|
for (const rel of PROJECT_INSTALL_FILES) {
|
|
31072
|
-
const path =
|
|
31073
|
-
if (
|
|
31407
|
+
const path = join17(root, rel);
|
|
31408
|
+
if (existsSync10(path)) {
|
|
31074
31409
|
try {
|
|
31075
|
-
const content =
|
|
31410
|
+
const content = readFileSync13(path, "utf-8");
|
|
31076
31411
|
if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
|
|
31077
31412
|
} catch {
|
|
31078
31413
|
}
|
|
@@ -31481,17 +31816,17 @@ async function inspectJournalDelivery(buckets, options = {}) {
|
|
|
31481
31816
|
import {
|
|
31482
31817
|
appendFileSync,
|
|
31483
31818
|
closeSync as closeSync3,
|
|
31484
|
-
existsSync as
|
|
31819
|
+
existsSync as existsSync11,
|
|
31485
31820
|
fstatSync,
|
|
31486
|
-
mkdirSync as
|
|
31821
|
+
mkdirSync as mkdirSync8,
|
|
31487
31822
|
openSync as openSync3,
|
|
31488
31823
|
opendirSync,
|
|
31489
|
-
readFileSync as
|
|
31824
|
+
readFileSync as readFileSync14,
|
|
31490
31825
|
readSync,
|
|
31491
|
-
readdirSync as
|
|
31826
|
+
readdirSync as readdirSync4
|
|
31492
31827
|
} from "fs";
|
|
31493
|
-
import { dirname as
|
|
31494
|
-
var JOURNAL_DIR =
|
|
31828
|
+
import { dirname as dirname11, join as join18 } from "path";
|
|
31829
|
+
var JOURNAL_DIR = join18(primConfigDirectory(), "moves");
|
|
31495
31830
|
var JOURNAL_BASENAME = "journal.ndjson";
|
|
31496
31831
|
var JOURNAL_STATS_SAMPLE_BYTES = 64 * 1024;
|
|
31497
31832
|
var PENDING_STATS_MAX_FILES = 128;
|
|
@@ -31503,7 +31838,7 @@ function envSlug(apiUrl) {
|
|
|
31503
31838
|
return slug;
|
|
31504
31839
|
}
|
|
31505
31840
|
function currentEnvDir() {
|
|
31506
|
-
return
|
|
31841
|
+
return join18(JOURNAL_DIR, envSlug(getSiteUrl()));
|
|
31507
31842
|
}
|
|
31508
31843
|
function parseMoves(content) {
|
|
31509
31844
|
const moves = [];
|
|
@@ -31521,15 +31856,15 @@ function parseMoves(content) {
|
|
|
31521
31856
|
function listBuckets() {
|
|
31522
31857
|
const out = [];
|
|
31523
31858
|
const envDir = currentEnvDir();
|
|
31524
|
-
if (!
|
|
31859
|
+
if (!existsSync11(envDir)) {
|
|
31525
31860
|
return out;
|
|
31526
31861
|
}
|
|
31527
|
-
for (const entry of
|
|
31862
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31528
31863
|
if (!entry.isDirectory()) {
|
|
31529
31864
|
continue;
|
|
31530
31865
|
}
|
|
31531
|
-
const path =
|
|
31532
|
-
if (
|
|
31866
|
+
const path = join18(envDir, entry.name, JOURNAL_BASENAME);
|
|
31867
|
+
if (existsSync11(path)) {
|
|
31533
31868
|
out.push({ bucket: entry.name, path });
|
|
31534
31869
|
}
|
|
31535
31870
|
}
|
|
@@ -31591,7 +31926,7 @@ function parseFlushingPid(name) {
|
|
|
31591
31926
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
31592
31927
|
}
|
|
31593
31928
|
function listFlushingInDir(dir, bucket, options = {}) {
|
|
31594
|
-
if (!
|
|
31929
|
+
if (!existsSync11(dir)) {
|
|
31595
31930
|
return [];
|
|
31596
31931
|
}
|
|
31597
31932
|
const out = [];
|
|
@@ -31605,7 +31940,7 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
31605
31940
|
entry = entries.readSync();
|
|
31606
31941
|
continue;
|
|
31607
31942
|
}
|
|
31608
|
-
const path =
|
|
31943
|
+
const path = join18(dir, entry.name);
|
|
31609
31944
|
let sample;
|
|
31610
31945
|
try {
|
|
31611
31946
|
sample = sampleJournalFile(path, remainingBytes, { fromDrainCheckpoint: true });
|
|
@@ -31632,18 +31967,18 @@ function listFlushingInDir(dir, bucket, options = {}) {
|
|
|
31632
31967
|
}
|
|
31633
31968
|
function listFlushing(options = {}) {
|
|
31634
31969
|
const envDir = currentEnvDir();
|
|
31635
|
-
if (!
|
|
31970
|
+
if (!existsSync11(envDir)) {
|
|
31636
31971
|
return [];
|
|
31637
31972
|
}
|
|
31638
31973
|
const out = [];
|
|
31639
31974
|
let remainingBytes = options.sampleBytes ?? JOURNAL_STATS_SAMPLE_BYTES;
|
|
31640
31975
|
const maxFiles = options.maxFiles ?? Number.POSITIVE_INFINITY;
|
|
31641
|
-
for (const entry of
|
|
31976
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31642
31977
|
if (out.length >= maxFiles) {
|
|
31643
31978
|
break;
|
|
31644
31979
|
}
|
|
31645
31980
|
if (entry.isDirectory()) {
|
|
31646
|
-
const found = listFlushingInDir(
|
|
31981
|
+
const found = listFlushingInDir(join18(envDir, entry.name), entry.name, {
|
|
31647
31982
|
sampleBytes: remainingBytes,
|
|
31648
31983
|
maxFiles: maxFiles - out.length
|
|
31649
31984
|
});
|
|
@@ -31658,12 +31993,12 @@ function listFlushing(options = {}) {
|
|
|
31658
31993
|
}
|
|
31659
31994
|
function sweepOrphanedDrainProgress() {
|
|
31660
31995
|
const envDir = currentEnvDir();
|
|
31661
|
-
if (!
|
|
31996
|
+
if (!existsSync11(envDir)) {
|
|
31662
31997
|
return;
|
|
31663
31998
|
}
|
|
31664
|
-
for (const entry of
|
|
31999
|
+
for (const entry of readdirSync4(envDir, { withFileTypes: true })) {
|
|
31665
32000
|
if (entry.isDirectory()) {
|
|
31666
|
-
sweepOrphanedDrainCheckpoints(
|
|
32001
|
+
sweepOrphanedDrainCheckpoints(join18(envDir, entry.name));
|
|
31667
32002
|
}
|
|
31668
32003
|
}
|
|
31669
32004
|
}
|
|
@@ -31816,7 +32151,7 @@ async function* rawJournalLines(input, offset) {
|
|
|
31816
32151
|
}
|
|
31817
32152
|
var drainProgressWarned = false;
|
|
31818
32153
|
async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
31819
|
-
const rotation = rotationIdentity(
|
|
32154
|
+
const rotation = rotationIdentity(statSync3(flushingPath));
|
|
31820
32155
|
const resumeAt = drainResumeOffset(flushingPath, rotation);
|
|
31821
32156
|
const recordProgress = (end) => {
|
|
31822
32157
|
if (end === void 0 || end >= rotation.size) {
|
|
@@ -31943,7 +32278,7 @@ async function drainFlushingPath(flushingPath, client2, binding, options = {}) {
|
|
|
31943
32278
|
async function drainPath(path, client2, binding, onProgress) {
|
|
31944
32279
|
const tmpPath = `${path}.flushing.${String(Date.now())}.${String(process.pid)}`;
|
|
31945
32280
|
try {
|
|
31946
|
-
|
|
32281
|
+
renameSync4(path, tmpPath);
|
|
31947
32282
|
} catch (err) {
|
|
31948
32283
|
if (err.code === "ENOENT") {
|
|
31949
32284
|
return { flushed: 0, quarantined: 0 };
|
|
@@ -32077,7 +32412,7 @@ async function flushOnce() {
|
|
|
32077
32412
|
return inspection.retainedBuckets.length > 0 ? { flushed: total, quarantined, retained: inspection.retainedBuckets } : { flushed: total, quarantined };
|
|
32078
32413
|
}
|
|
32079
32414
|
var flushInFlight;
|
|
32080
|
-
var FLUSH_LOCK_PATH =
|
|
32415
|
+
var FLUSH_LOCK_PATH = join19(dirname12(JOURNAL_DIR), ".flush.lock");
|
|
32081
32416
|
var FLUSH_LOCK_TIMEOUT_MS = 250;
|
|
32082
32417
|
function isFlushLockContended(error) {
|
|
32083
32418
|
return error instanceof Error && error.message.startsWith("timed out waiting for file lock");
|
|
@@ -32232,8 +32567,8 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
|
|
|
32232
32567
|
var STATUSLINE_INGESTION_CACHE_TTL_MS = 3e4;
|
|
32233
32568
|
var STATUSLINE_INGESTION_CACHE_MAX_ENTRIES = 256;
|
|
32234
32569
|
var StatuslineIngestionCache = class {
|
|
32235
|
-
constructor(
|
|
32236
|
-
this.resolve =
|
|
32570
|
+
constructor(resolve4, options = {}) {
|
|
32571
|
+
this.resolve = resolve4;
|
|
32237
32572
|
this.#now = options.now ?? Date.now;
|
|
32238
32573
|
this.#ttlMs = options.ttlMs ?? STATUSLINE_INGESTION_CACHE_TTL_MS;
|
|
32239
32574
|
this.#maxEntries = options.maxEntries ?? STATUSLINE_INGESTION_CACHE_MAX_ENTRIES;
|
|
@@ -32279,8 +32614,8 @@ var StatuslineIngestionCache = class {
|
|
|
32279
32614
|
|
|
32280
32615
|
// src/daemon/client.ts
|
|
32281
32616
|
import { createConnection } from "net";
|
|
32282
|
-
import { join as
|
|
32283
|
-
var SOCK_PATH =
|
|
32617
|
+
import { join as join20 } from "path";
|
|
32618
|
+
var SOCK_PATH = join20(primConfigDirectory(), "sock");
|
|
32284
32619
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
32285
32620
|
var nextRequestId = 1;
|
|
32286
32621
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -32293,7 +32628,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32293
32628
|
...caller ? { caller } : {}
|
|
32294
32629
|
};
|
|
32295
32630
|
const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
|
|
32296
|
-
return new Promise((
|
|
32631
|
+
return new Promise((resolve4) => {
|
|
32297
32632
|
let settled = false;
|
|
32298
32633
|
let socket;
|
|
32299
32634
|
let buffer = Buffer.alloc(0);
|
|
@@ -32308,7 +32643,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32308
32643
|
} catch {
|
|
32309
32644
|
}
|
|
32310
32645
|
}
|
|
32311
|
-
|
|
32646
|
+
resolve4(value);
|
|
32312
32647
|
};
|
|
32313
32648
|
const timer = setTimeout(() => settle(null), timeoutMs);
|
|
32314
32649
|
timer.unref();
|
|
@@ -32370,7 +32705,7 @@ function daemonRequest(method, params = {}, opts = {}) {
|
|
|
32370
32705
|
}
|
|
32371
32706
|
|
|
32372
32707
|
// src/daemon/decision-digest-cache.ts
|
|
32373
|
-
import { randomBytes as
|
|
32708
|
+
import { randomBytes as randomBytes7 } from "crypto";
|
|
32374
32709
|
var DECISION_DIGEST_CACHE_WARMING = "daemon Decision cache warming";
|
|
32375
32710
|
var DECISION_DIGEST_CACHE_LIMIT = 100;
|
|
32376
32711
|
var DECISION_DIGEST_CACHE_WINDOW = "24h";
|
|
@@ -32400,7 +32735,7 @@ function errorMessage(error) {
|
|
|
32400
32735
|
return error instanceof Error ? error.message : String(error);
|
|
32401
32736
|
}
|
|
32402
32737
|
function privatePageToken() {
|
|
32403
|
-
return
|
|
32738
|
+
return randomBytes7(16).toString("hex");
|
|
32404
32739
|
}
|
|
32405
32740
|
var DecisionDigestCache = class {
|
|
32406
32741
|
constructor(load, now = Date.now, options = {}) {
|
|
@@ -32551,8 +32886,8 @@ function assertCallerEnvMatches(callerEnv, boundEnv) {
|
|
|
32551
32886
|
}
|
|
32552
32887
|
|
|
32553
32888
|
// src/daemon/health.ts
|
|
32554
|
-
import { chmodSync as
|
|
32555
|
-
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";
|
|
32556
32891
|
var CONFIG_DIR_MODE2 = 448;
|
|
32557
32892
|
var HEALTH_FILE_MODE = 384;
|
|
32558
32893
|
var INGESTION_SLA_MS = 3e4;
|
|
@@ -32560,7 +32895,7 @@ var HEARTBEAT_FRESH_MS = 9e4;
|
|
|
32560
32895
|
var HEARTBEAT_RETRY_CAP_MS = 3e4;
|
|
32561
32896
|
var INGESTION_RETRY_BASE_MS = 5e3;
|
|
32562
32897
|
var INGESTION_RETRY_CAP_MS = 15e3;
|
|
32563
|
-
var DAEMON_HEALTH_PATH =
|
|
32898
|
+
var DAEMON_HEALTH_PATH = join21(primConfigDirectory(), "daemon-health.json");
|
|
32564
32899
|
function createDaemonHealthState(version, pid, startedAt2, siteUrl) {
|
|
32565
32900
|
return {
|
|
32566
32901
|
schemaVersion: 1,
|
|
@@ -32601,37 +32936,37 @@ function ingestionRetryDelayMs(consecutiveFailures, random = Math.random) {
|
|
|
32601
32936
|
return retryDelayMs(consecutiveFailures, INGESTION_RETRY_CAP_MS, random);
|
|
32602
32937
|
}
|
|
32603
32938
|
function writeDaemonHealthState(state, path = DAEMON_HEALTH_PATH) {
|
|
32604
|
-
const dir =
|
|
32605
|
-
if (!
|
|
32606
|
-
|
|
32939
|
+
const dir = dirname13(path);
|
|
32940
|
+
if (!existsSync12(dir)) {
|
|
32941
|
+
mkdirSync9(dir, { recursive: true, mode: CONFIG_DIR_MODE2 });
|
|
32607
32942
|
}
|
|
32608
|
-
const tmp =
|
|
32609
|
-
|
|
32943
|
+
const tmp = join21(dir, `.${process.pid}.daemon-health.tmp`);
|
|
32944
|
+
writeFileSync7(tmp, `${JSON.stringify(state, null, 2)}
|
|
32610
32945
|
`, { mode: HEALTH_FILE_MODE });
|
|
32611
|
-
|
|
32612
|
-
|
|
32946
|
+
chmodSync7(tmp, HEALTH_FILE_MODE);
|
|
32947
|
+
renameSync5(tmp, path);
|
|
32613
32948
|
}
|
|
32614
32949
|
|
|
32615
32950
|
// src/daemon/instance-lock.ts
|
|
32616
32951
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
32617
32952
|
import {
|
|
32618
|
-
chmodSync as
|
|
32619
|
-
existsSync as
|
|
32620
|
-
mkdirSync as
|
|
32621
|
-
readFileSync as
|
|
32622
|
-
renameSync as
|
|
32623
|
-
rmSync as
|
|
32624
|
-
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,
|
|
32625
32960
|
unlinkSync as unlinkSync2,
|
|
32626
|
-
writeFileSync as
|
|
32961
|
+
writeFileSync as writeFileSync8
|
|
32627
32962
|
} from "fs";
|
|
32628
|
-
import { join as
|
|
32963
|
+
import { join as join22 } from "path";
|
|
32629
32964
|
var DIR_MODE = 448;
|
|
32630
32965
|
var FILE_MODE4 = 384;
|
|
32631
32966
|
var DAEMON_STARTUP_GRACE_MS = 5e3;
|
|
32632
32967
|
function readLockRecord(path) {
|
|
32633
32968
|
try {
|
|
32634
|
-
const value = JSON.parse(
|
|
32969
|
+
const value = JSON.parse(readFileSync15(path, "utf-8"));
|
|
32635
32970
|
if (Number.isSafeInteger(value.pid) && value.pid > 0 && typeof value.instanceId === "string" && typeof value.startedAt === "number") {
|
|
32636
32971
|
return value;
|
|
32637
32972
|
}
|
|
@@ -32641,23 +32976,23 @@ function readLockRecord(path) {
|
|
|
32641
32976
|
}
|
|
32642
32977
|
function numericPid(path) {
|
|
32643
32978
|
try {
|
|
32644
|
-
const pid = Number(
|
|
32979
|
+
const pid = Number(readFileSync15(path, "utf-8").trim());
|
|
32645
32980
|
return Number.isSafeInteger(pid) && pid > 0 ? pid : void 0;
|
|
32646
32981
|
} catch {
|
|
32647
32982
|
return;
|
|
32648
32983
|
}
|
|
32649
32984
|
}
|
|
32650
32985
|
function readDaemonOwner(configDir) {
|
|
32651
|
-
return readLockRecord(
|
|
32986
|
+
return readLockRecord(join22(configDir, "daemon.lock", "owner.json"));
|
|
32652
32987
|
}
|
|
32653
32988
|
function readDaemonPid(configDir) {
|
|
32654
|
-
const path =
|
|
32989
|
+
const path = join22(configDir, "daemon.pid");
|
|
32655
32990
|
const pid = numericPid(path);
|
|
32656
32991
|
if (pid === void 0) {
|
|
32657
32992
|
return;
|
|
32658
32993
|
}
|
|
32659
32994
|
try {
|
|
32660
|
-
return { pid, mtimeMs:
|
|
32995
|
+
return { pid, mtimeMs: statSync4(path).mtimeMs };
|
|
32661
32996
|
} catch {
|
|
32662
32997
|
return;
|
|
32663
32998
|
}
|
|
@@ -32666,16 +33001,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32666
33001
|
const pid = opts.pid ?? process.pid;
|
|
32667
33002
|
const now = opts.now ?? Date.now();
|
|
32668
33003
|
const isAlive = opts.isAlive ?? processIsAlive;
|
|
32669
|
-
const lockDir =
|
|
32670
|
-
const ownerPath2 =
|
|
32671
|
-
const pidPath =
|
|
33004
|
+
const lockDir = join22(configDir, "daemon.lock");
|
|
33005
|
+
const ownerPath2 = join22(lockDir, "owner.json");
|
|
33006
|
+
const pidPath = join22(configDir, "daemon.pid");
|
|
32672
33007
|
const instanceId2 = randomUUID3();
|
|
32673
|
-
if (!
|
|
32674
|
-
|
|
33008
|
+
if (!existsSync13(configDir)) {
|
|
33009
|
+
mkdirSync10(configDir, { recursive: true, mode: DIR_MODE });
|
|
32675
33010
|
}
|
|
32676
33011
|
for (; ; ) {
|
|
32677
33012
|
try {
|
|
32678
|
-
|
|
33013
|
+
mkdirSync10(lockDir, { mode: DIR_MODE });
|
|
32679
33014
|
break;
|
|
32680
33015
|
} catch (err) {
|
|
32681
33016
|
if (err.code !== "EEXIST") {
|
|
@@ -32688,7 +33023,7 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32688
33023
|
if (!existing) {
|
|
32689
33024
|
let mtimeMs;
|
|
32690
33025
|
try {
|
|
32691
|
-
mtimeMs =
|
|
33026
|
+
mtimeMs = statSync4(lockDir).mtimeMs;
|
|
32692
33027
|
} catch (statErr) {
|
|
32693
33028
|
if (statErr.code === "ENOENT") {
|
|
32694
33029
|
continue;
|
|
@@ -32701,8 +33036,8 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32701
33036
|
}
|
|
32702
33037
|
const stale = `${lockDir}.stale.${String(pid)}.${instanceId2}`;
|
|
32703
33038
|
try {
|
|
32704
|
-
|
|
32705
|
-
|
|
33039
|
+
renameSync6(lockDir, stale);
|
|
33040
|
+
rmSync12(stale, { recursive: true, force: true });
|
|
32706
33041
|
} catch (renameErr) {
|
|
32707
33042
|
if (renameErr.code !== "ENOENT") {
|
|
32708
33043
|
throw renameErr;
|
|
@@ -32719,16 +33054,16 @@ function acquireDaemonOwnership(configDir, opts = {}) {
|
|
|
32719
33054
|
instanceId: instanceId2
|
|
32720
33055
|
};
|
|
32721
33056
|
const record = { pid, instanceId: instanceId2, startedAt: now };
|
|
32722
|
-
|
|
33057
|
+
writeFileSync8(ownerPath2, `${JSON.stringify(record)}
|
|
32723
33058
|
`, { mode: FILE_MODE4 });
|
|
32724
|
-
|
|
33059
|
+
chmodSync8(ownerPath2, FILE_MODE4);
|
|
32725
33060
|
const legacyPid = numericPid(pidPath);
|
|
32726
33061
|
if (legacyPid !== void 0 && legacyPid !== pid && isAlive(legacyPid)) {
|
|
32727
|
-
|
|
33062
|
+
rmSync12(lockDir, { recursive: true, force: true });
|
|
32728
33063
|
throw new Error(`daemon already running (pid=${String(legacyPid)})`);
|
|
32729
33064
|
}
|
|
32730
|
-
|
|
32731
|
-
|
|
33065
|
+
writeFileSync8(pidPath, String(pid), { mode: FILE_MODE4 });
|
|
33066
|
+
chmodSync8(pidPath, FILE_MODE4);
|
|
32732
33067
|
return ownership2;
|
|
32733
33068
|
}
|
|
32734
33069
|
function ownsDaemonInstance(ownership2) {
|
|
@@ -32758,7 +33093,7 @@ function releaseDaemonOwnership(ownership2, socketPath) {
|
|
|
32758
33093
|
}
|
|
32759
33094
|
}
|
|
32760
33095
|
}
|
|
32761
|
-
|
|
33096
|
+
rmSync12(ownership2.lockDir, { recursive: true, force: true });
|
|
32762
33097
|
if (cleanupError) {
|
|
32763
33098
|
throw cleanupError;
|
|
32764
33099
|
}
|
|
@@ -32813,7 +33148,7 @@ function normalizePresenceHeartbeatResponse(value) {
|
|
|
32813
33148
|
}
|
|
32814
33149
|
|
|
32815
33150
|
// src/daemon/statusline-protocol.ts
|
|
32816
|
-
import { isAbsolute as
|
|
33151
|
+
import { isAbsolute as isAbsolute5 } from "path";
|
|
32817
33152
|
var STATUSLINE_PROTOCOL_PREFIX = Buffer.from("prim-statusline-v1\0", "utf8");
|
|
32818
33153
|
var STATUSLINE_REQUEST_MAX_BYTES = 64 * 1024;
|
|
32819
33154
|
var utf8Decoder = new TextDecoder("utf-8", { fatal: true });
|
|
@@ -32842,7 +33177,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
32842
33177
|
try {
|
|
32843
33178
|
const cwd = utf8Decoder.decode(buffer.subarray(STATUSLINE_PROTOCOL_PREFIX.length, cwdEnd));
|
|
32844
33179
|
const primApiUrl = utf8Decoder.decode(buffer.subarray(cwdEnd + 1, apiUrlEnd));
|
|
32845
|
-
if (!cwd || !
|
|
33180
|
+
if (!cwd || !isAbsolute5(cwd)) {
|
|
32846
33181
|
return { state: "invalid" };
|
|
32847
33182
|
}
|
|
32848
33183
|
return { state: "complete", request: { cwd, primApiUrl } };
|
|
@@ -32853,7 +33188,7 @@ function parseStatuslineRequest(buffer) {
|
|
|
32853
33188
|
|
|
32854
33189
|
// src/daemon/server.ts
|
|
32855
33190
|
var CONFIG_DIR = primConfigDirectory();
|
|
32856
|
-
var SOCK_PATH2 =
|
|
33191
|
+
var SOCK_PATH2 = join23(CONFIG_DIR, "sock");
|
|
32857
33192
|
var CONFIG_DIR_MODE3 = 448;
|
|
32858
33193
|
var SOCKET_MODE = 384;
|
|
32859
33194
|
var MAX_SOCKET_CONNECTIONS = 64;
|
|
@@ -32921,8 +33256,8 @@ function resolveRuntimeVersion() {
|
|
|
32921
33256
|
return process.env.PRIM_RUNTIME_VERSION;
|
|
32922
33257
|
}
|
|
32923
33258
|
try {
|
|
32924
|
-
const here =
|
|
32925
|
-
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"));
|
|
32926
33261
|
return pkg.version ?? "unknown";
|
|
32927
33262
|
} catch {
|
|
32928
33263
|
return "unknown";
|
|
@@ -32961,8 +33296,8 @@ function assertCallerPrincipalMatches(caller) {
|
|
|
32961
33296
|
return credentialKey;
|
|
32962
33297
|
}
|
|
32963
33298
|
function ensureDaemonDirectoryPermissions() {
|
|
32964
|
-
|
|
32965
|
-
|
|
33299
|
+
mkdirSync11(CONFIG_DIR, { recursive: true, mode: CONFIG_DIR_MODE3 });
|
|
33300
|
+
chmodSync9(CONFIG_DIR, CONFIG_DIR_MODE3);
|
|
32966
33301
|
}
|
|
32967
33302
|
function persistHealth() {
|
|
32968
33303
|
refreshDaemonHealth(daemonHealth, Date.now());
|
|
@@ -33048,7 +33383,7 @@ async function takeOwnership() {
|
|
|
33048
33383
|
(pid) => pid !== void 0 && processIsAlive(pid)
|
|
33049
33384
|
)
|
|
33050
33385
|
);
|
|
33051
|
-
if (
|
|
33386
|
+
if (existsSync14(SOCK_PATH2) || candidatePids.size > 0) {
|
|
33052
33387
|
const snapshot = await daemonRequest(
|
|
33053
33388
|
"status_snapshot",
|
|
33054
33389
|
{},
|
|
@@ -33593,7 +33928,7 @@ function startSocketServer() {
|
|
|
33593
33928
|
});
|
|
33594
33929
|
socketServer.listen(SOCK_PATH2, () => {
|
|
33595
33930
|
try {
|
|
33596
|
-
|
|
33931
|
+
chmodSync9(SOCK_PATH2, SOCKET_MODE);
|
|
33597
33932
|
} catch (err) {
|
|
33598
33933
|
shutdown(EXIT_CRASH, `[prim-daemon] failed to secure socket: ${errorMessage2(err)}`);
|
|
33599
33934
|
return;
|