@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.129

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-HZI5PBN4.js → chunk-BVGASV3B.js} +2047 -138
  3. package/dist/{chunk-72NIZMZN.js → chunk-DYXCJ6WZ.js} +15 -10
  4. package/dist/{chunk-TNWI3JWK.js → chunk-FHDTJP2C.js} +4 -2
  5. package/dist/{chunk-C4QNBSWB.js → chunk-HDL3UXYJ.js} +8 -8
  6. package/dist/{chunk-RV3JFSMX.js → chunk-IJ3W2YBM.js} +4 -4
  7. package/dist/{chunk-O65UVJZH.js → chunk-IZAEAALI.js} +2 -2
  8. package/dist/{chunk-H74RDXKP.js → chunk-KZNOT2YH.js} +2 -2
  9. package/dist/{chunk-R4EYLEIK.js → chunk-L7U3G4XR.js} +2 -2
  10. package/dist/{chunk-MGKSZSTV.js → chunk-LBZJD2I4.js} +3 -5
  11. package/dist/{chunk-UUQT5GMO.js → chunk-MMMY57UA.js} +22 -837
  12. package/dist/{chunk-H6X52UVF.js → chunk-NWWTFQP2.js} +1 -1
  13. package/dist/{chunk-WGTUNUIS.js → chunk-QSDWWEHF.js} +5 -5
  14. package/dist/{chunk-NVDPKW7Z.js → chunk-RAEOSDQ6.js} +3 -51
  15. package/dist/{chunk-KFRGVHGB.js → chunk-RS5ADTDF.js} +6 -6
  16. package/dist/{chunk-A5VTE43F.js → chunk-RWJ7WHTJ.js} +2 -2
  17. package/dist/{chunk-VVFVENU4.js → chunk-SJE7OWVS.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-USJ4JGDC.js} +34 -34
  19. package/dist/{chunk-JCKOW45X.js → chunk-YPHDV5AS.js} +2 -2
  20. package/dist/{chunk-F3FDVHR7.js → chunk-YSV43WLK.js} +1 -1
  21. package/dist/{chunk-URYZDQFH.js → chunk-ZKIBD5MO.js} +3 -5
  22. package/dist/daemon/server.js +1769 -487
  23. package/dist/hook-runtime/daemon/server.js +1769 -487
  24. package/dist/hook-runtime/hooks/post-commit.js +611 -337
  25. package/dist/hook-runtime/hooks/post-rewrite.js +606 -332
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1841 -683
  27. package/dist/hook-runtime/hooks/pre-commit.js +1713 -434
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1308 -150
  29. package/dist/hook-runtime/hooks/prim-hook.js +1863 -705
  30. package/dist/hook-runtime/hooks/session-end.js +538 -385
  31. package/dist/hook-runtime/hooks/session-start.js +1379 -233
  32. package/dist/hook-runtime/index.js +5438 -4052
  33. package/dist/hook-runtime/statusline-main.js +547 -273
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +18 -18
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +64 -22
  42. package/dist/index.js +396 -52
  43. package/dist/statusline-main.js +547 -273
  44. package/package.json +1 -1
@@ -2,29 +2,29 @@
2
2
  import { createRequire as __primCreateRequire } from "node:module"; const require = __primCreateRequire(import.meta.url);
3
3
 
4
4
  // src/daemon/principal.ts
5
- import { createHash as createHash5 } from "crypto";
5
+ import { createHash as createHash8 } from "crypto";
6
6
 
7
7
  // src/lib/credentials.ts
8
- import { createHash as createHash4 } from "crypto";
9
- import { readFileSync as readFileSync6 } from "fs";
10
- import { join as join7 } from "path";
8
+ import { createHash as createHash7 } from "crypto";
9
+ import { readFileSync as readFileSync8 } from "fs";
10
+ import { join as join11 } from "path";
11
11
 
12
12
  // src/lib/machine-credentials.ts
13
- import { execFileSync } from "child_process";
14
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
13
+ import { execFileSync as execFileSync2 } from "child_process";
14
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
15
15
  import {
16
- chmodSync,
17
- existsSync as existsSync3,
16
+ chmodSync as chmodSync2,
17
+ existsSync as existsSync5,
18
18
  linkSync,
19
- lstatSync as lstatSync3,
20
- mkdirSync as mkdirSync3,
21
- readFileSync as readFileSync5,
22
- rmSync as rmSync5,
23
- writeFileSync as writeFileSync3
19
+ lstatSync as lstatSync5,
20
+ mkdirSync as mkdirSync4,
21
+ readFileSync as readFileSync7,
22
+ rmSync as rmSync7,
23
+ writeFileSync as writeFileSync4
24
24
  } from "fs";
25
- import { createRequire } from "module";
26
- import { dirname as dirname4, join as join6 } from "path";
27
- import { fileURLToPath as fileURLToPath3 } from "url";
25
+ import { createRequire as createRequire2 } from "module";
26
+ import { dirname as dirname7, join as join10 } from "path";
27
+ import { fileURLToPath as fileURLToPath4 } from "url";
28
28
 
29
29
  // src/lib/atomic-file.ts
30
30
  import { randomUUID } from "crypto";
@@ -47,13 +47,27 @@ import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, s
47
47
  import { dirname as dirname2, join } from "path";
48
48
  var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
49
49
 
50
- // src/lib/machine-broker.ts
51
- import { spawn } from "child_process";
52
- import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
53
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
54
- import { createServer } from "http";
55
- import { basename, join as join4 } from "path";
56
- import { fileURLToPath as fileURLToPath2 } from "url";
50
+ // src/lib/hook-runtime.ts
51
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
52
+ import {
53
+ constants as constants2,
54
+ accessSync,
55
+ chmodSync,
56
+ copyFileSync,
57
+ existsSync as existsSync4,
58
+ lstatSync,
59
+ mkdirSync as mkdirSync3,
60
+ mkdtempSync,
61
+ readFileSync as readFileSync3,
62
+ readdirSync,
63
+ realpathSync,
64
+ renameSync as renameSync2,
65
+ rmSync as rmSync3,
66
+ statSync as statSync2,
67
+ utimesSync,
68
+ writeFileSync as writeFileSync3
69
+ } from "fs";
70
+ import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
57
71
 
58
72
  // src/lib/bin-path.ts
59
73
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
@@ -94,6 +108,140 @@ function detachedHookShimCommand(bin, args = "") {
94
108
  return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
95
109
  }
96
110
 
111
+ // src/lib/git-hook-contract.ts
112
+ var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
113
+ # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
114
+ # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
115
+ # where prim is active (git config prim.active true) and never fails the hook.
116
+ case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
117
+ prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
118
+ [ -x "$prim_launcher" ] || exit 0
119
+ [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
120
+ prim_hook=\${1-}
121
+ if [ "$#" -gt 0 ]; then shift; fi
122
+ case "$prim_hook" in
123
+ pre-commit)
124
+ "$prim_launcher" prim-pre-commit "$@" || :
125
+ ;;
126
+ post-commit)
127
+ prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
128
+ case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
129
+ case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
130
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
131
+ prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
132
+ (
133
+ trap '' HUP
134
+ trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
135
+ PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
136
+ ) </dev/null >/dev/null 2>&1 &
137
+ ;;
138
+ post-rewrite)
139
+ case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
140
+ prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
141
+ if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
142
+ rm -f "$prim_pairs"
143
+ exit 0
144
+ fi
145
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
146
+ (
147
+ trap '' HUP
148
+ trap 'rm -f "$prim_pairs"' 0
149
+ PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
150
+ ) </dev/null >/dev/null 2>&1 &
151
+ ;;
152
+ esac
153
+ exit 0
154
+ `;
155
+
156
+ // src/lib/native-keyring.ts
157
+ import { existsSync as existsSync3 } from "fs";
158
+ import { createRequire } from "module";
159
+ import { dirname as dirname4, join as join3 } from "path";
160
+ import { fileURLToPath as fileURLToPath2 } from "url";
161
+ var require2 = createRequire(import.meta.url);
162
+
163
+ // src/lib/paths.ts
164
+ import { homedir } from "os";
165
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
166
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
167
+ function absolutePath(value, variable) {
168
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
169
+ throw new Error(`${variable} contains unsafe characters`);
170
+ }
171
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
172
+ const normalized = normalize(value);
173
+ return normalized === value ? value : void 0;
174
+ }
175
+ function resolvePrimConfigDirectory(options = {}) {
176
+ const env = options.env ?? process.env;
177
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
178
+ if (explicit) return { path: explicit, source: "explicit" };
179
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
180
+ if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
181
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
182
+ if (!home) {
183
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
184
+ }
185
+ return { path: join4(home, ".config", "prim"), source: "default" };
186
+ }
187
+ function primConfigDirectory(options = {}) {
188
+ return resolvePrimConfigDirectory(options).path;
189
+ }
190
+
191
+ // src/lib/hook-runtime.ts
192
+ var RELEASE_PREFIX = "release-";
193
+ var MAX_MANIFEST_BYTES = 64 * 1024;
194
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
195
+ var HOOK_RUNTIME_ENTRIES = {
196
+ // SessionStart self-healing resolves this exact CLI entry to run
197
+ // `daemon ensure`; it must travel with the immutable hook release.
198
+ prim: "dist/index.js",
199
+ "prim-hook": "dist/hooks/prim-hook.js",
200
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
201
+ "prim-post-commit": "dist/hooks/post-commit.js",
202
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
203
+ "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
204
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
205
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
206
+ "prim-session-start": "dist/hooks/session-start.js",
207
+ "prim-session-end": "dist/hooks/session-end.js",
208
+ "prim-daemon-server": "dist/daemon/server.js",
209
+ "prim-statusline": "dist/statusline-main.js"
210
+ };
211
+ var SOURCE_ENTRIES = Object.fromEntries(
212
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
213
+ bin,
214
+ target.replace(/^dist\//u, "")
215
+ ])
216
+ );
217
+ var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
218
+ set -eu
219
+ case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
220
+ IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
221
+ case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
222
+ prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
223
+ case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
224
+ [ "\${#prim_release_id}" -eq 64 ] || exit 69
225
+ prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
226
+ case "\${1-}" in
227
+ ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
228
+ *) exit 64 ;;
229
+ esac
230
+ shift
231
+ IFS= read -r prim_node < "$prim_release/node" || exit 69
232
+ case "$prim_node" in /*) ;; *) exit 69 ;; esac
233
+ [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
234
+ exec "$prim_node" "$prim_entry" "$@"
235
+ `;
236
+
237
+ // src/lib/machine-broker.ts
238
+ import { spawn } from "child_process";
239
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
240
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
241
+ import { createServer } from "http";
242
+ import { basename, join as join6 } from "path";
243
+ import { fileURLToPath as fileURLToPath3 } from "url";
244
+
97
245
  // src/lib/loopback-fetch.ts
98
246
  import { request } from "http";
99
247
  import { Readable } from "stream";
@@ -102,6 +250,8 @@ import { Readable } from "stream";
102
250
  function isClaudeCloudSession(env = process.env) {
103
251
  return env.CLAUDE_CODE_REMOTE === "true";
104
252
  }
253
+ var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
254
+ var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
105
255
 
106
256
  // src/lib/workos-connect.ts
107
257
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -248,34 +398,6 @@ function parseMachineIdentity(value, clientId) {
248
398
  };
249
399
  }
250
400
 
251
- // src/lib/paths.ts
252
- import { homedir } from "os";
253
- import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
254
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
255
- function absolutePath(value, variable) {
256
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
257
- throw new Error(`${variable} contains unsafe characters`);
258
- }
259
- if (!value || value.trim() !== value || !isAbsolute2(value)) return;
260
- const normalized = normalize(value);
261
- return normalized === value ? value : void 0;
262
- }
263
- function resolvePrimConfigDirectory(options = {}) {
264
- const env = options.env ?? process.env;
265
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
266
- if (explicit) return { path: explicit, source: "explicit" };
267
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
268
- if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
269
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
270
- if (!home) {
271
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
272
- }
273
- return { path: join3(home, ".config", "prim"), source: "default" };
274
- }
275
- function primConfigDirectory(options = {}) {
276
- return resolvePrimConfigDirectory(options).path;
277
- }
278
-
279
401
  // src/lib/machine-broker.ts
280
402
  var MAX_RESPONSE_BYTES = 96 * 1024;
281
403
  var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
@@ -284,29 +406,325 @@ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
284
406
  var IDLE_MS = 5 * 6e4;
285
407
 
286
408
  // src/lib/machine-retry.ts
287
- import { createHash as createHash2 } from "crypto";
288
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
289
- import { join as join5 } from "path";
409
+ import { createHash as createHash3 } from "crypto";
410
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
411
+ import { join as join7 } from "path";
290
412
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
291
413
 
292
- // src/lib/machine-credentials.ts
293
- var require2 = createRequire(import.meta.url);
414
+ // src/lib/session-identity.ts
415
+ import { execFile } from "child_process";
416
+ import { createHash as createHash5 } from "crypto";
417
+ import { rmSync as rmSync6 } from "fs";
418
+ import { join as join9 } from "path";
419
+ import { promisify } from "util";
420
+
421
+ // src/lib/git.ts
422
+ import { execFileSync } from "child_process";
423
+ import { createHash as createHash4 } from "crypto";
424
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
425
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
426
+ var GIT_TIMEOUT_MS = 1e3;
427
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
428
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
429
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
430
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
431
+ function gitChildEnvironment(env = process.env) {
432
+ return Object.fromEntries(
433
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
434
+ );
435
+ }
436
+ function gitToplevel(cwd) {
437
+ try {
438
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
439
+ cwd,
440
+ encoding: "utf-8",
441
+ stdio: ["ignore", "pipe", "ignore"],
442
+ timeout: GIT_TIMEOUT_MS,
443
+ env: gitChildEnvironment()
444
+ }).trim();
445
+ } catch {
446
+ return null;
447
+ }
448
+ }
449
+ function gitValue(cwd, args) {
450
+ try {
451
+ const value = execFileSync("git", args, {
452
+ cwd,
453
+ encoding: "utf-8",
454
+ stdio: ["ignore", "pipe", "ignore"],
455
+ timeout: GIT_TIMEOUT_MS,
456
+ env: gitChildEnvironment()
457
+ }).trim();
458
+ return value || void 0;
459
+ } catch {
460
+ return void 0;
461
+ }
462
+ }
463
+ function parseGithubRepositoryName(path) {
464
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
465
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
466
+ return null;
467
+ }
468
+ return `${parts[0]}/${parts[1]}`;
469
+ }
470
+ function githubRepositoryFromRemote(remote) {
471
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
472
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
473
+ remote
474
+ );
475
+ const path = match?.[1] ?? match?.[2];
476
+ return path ? parseGithubRepositoryName(path) : null;
477
+ }
478
+ function checkoutSettingsText(repoRoot) {
479
+ const path = join8(repoRoot, ".claude", "settings.json");
480
+ try {
481
+ if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
482
+ const stat = lstatSync4(path);
483
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
484
+ return readFileSync6(path, "utf8");
485
+ } catch {
486
+ return null;
487
+ }
488
+ }
489
+ function checkoutDeclaration(repoRoot, name) {
490
+ const text = checkoutSettingsText(repoRoot);
491
+ if (text === null) return null;
492
+ let parsed;
493
+ try {
494
+ parsed = JSON.parse(text);
495
+ } catch {
496
+ return null;
497
+ }
498
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
499
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
500
+ return typeof value === "string" ? value : null;
501
+ }
502
+ function declaredGithubRepository(repoRoot) {
503
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
504
+ return value === null ? null : parseGithubRepositoryName(value.trim());
505
+ }
506
+ function githubRepositoryFullName(cwd) {
507
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
508
+ if (remote) {
509
+ const fromOrigin = githubRepositoryFromRemote(remote);
510
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
511
+ }
512
+ const root = gitToplevel(cwd);
513
+ return root ? declaredGithubRepository(root) : null;
514
+ }
515
+ function normalizeOriginRemote(remote) {
516
+ const value = remote.trim();
517
+ if (!value) return void 0;
518
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
519
+ if (scp?.host && scp.path) {
520
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
521
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
522
+ }
523
+ try {
524
+ const url = new URL(value);
525
+ url.username = "";
526
+ url.password = "";
527
+ url.search = "";
528
+ url.hash = "";
529
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
530
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
531
+ return void 0;
532
+ } catch {
533
+ return void 0;
534
+ }
535
+ }
536
+ function opaqueRepoKey(source, value) {
537
+ return `repo_v1_${createHash4("sha256").update(`${source}\0${value}`).digest("hex")}`;
538
+ }
539
+ function resolveRepositoryContext(cwd = process.cwd()) {
540
+ const top = gitToplevel(cwd);
541
+ if (!top) return null;
542
+ let repoRoot;
543
+ try {
544
+ repoRoot = realpathSync2.native(top);
545
+ } catch {
546
+ repoRoot = resolve2(top);
547
+ }
548
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
549
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
550
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
551
+ if (normalizedOrigin) {
552
+ return {
553
+ repoRoot,
554
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
555
+ identitySource: "origin",
556
+ repoFullName
557
+ };
558
+ }
559
+ if (repoFullName) {
560
+ return {
561
+ repoRoot,
562
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
563
+ identitySource: "declared",
564
+ repoFullName
565
+ };
566
+ }
567
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
568
+ if (roots && roots.length > 0) {
569
+ return {
570
+ repoRoot,
571
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
572
+ identitySource: "root_commit",
573
+ repoFullName
574
+ };
575
+ }
576
+ return { repoRoot, repoFullName };
577
+ }
578
+
579
+ // src/lib/session-identity.ts
580
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
581
+ var SESSION_IDENTITY_VALUE = "session";
582
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
583
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
584
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
294
585
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
586
+ var RENEW_BEFORE_MS = 6e4;
587
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
588
+ var RESPONSE_MAX_BYTES = 64 * 1024;
589
+ function sessionIdentityRequested(env = process.env) {
590
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
591
+ }
592
+ function sessionIdentityMode(deps = {}) {
593
+ const env = deps.env ?? process.env;
594
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
595
+ }
596
+ function failure(code, cause, remedy) {
597
+ return { status: "failed", code, cause, remedy };
598
+ }
599
+ var NEW_SESSION_REMEDY = "start a new cloud session";
600
+ var SESSION_REVOKED = failure(
601
+ "session_revoked",
602
+ "Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
603
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
604
+ );
605
+ var CHALLENGE_WINDOW_PASSED = failure(
606
+ "challenge_expired",
607
+ "this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
608
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
609
+ );
610
+ var CHALLENGE_GONE = failure(
611
+ "challenge_not_found",
612
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
613
+ NEW_SESSION_REMEDY
614
+ );
615
+ function hash(value) {
616
+ return createHash5("sha256").update(value).digest("hex");
617
+ }
618
+ function sessionContext(deps) {
619
+ const env = deps.env ?? process.env;
620
+ const environment = environmentCredentials(deps);
621
+ if (!environment)
622
+ return failure(
623
+ "environment_credential_missing",
624
+ "the cloud environment has no environment credential",
625
+ 'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
626
+ );
627
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
628
+ if (!sessionId || !SESSION_ID.test(sessionId))
629
+ return failure(
630
+ "session_id_missing",
631
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
632
+ NEW_SESSION_REMEDY
633
+ );
634
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
635
+ const directory = deps.directory ?? primConfigDirectory({ env });
636
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
637
+ return {
638
+ directory,
639
+ apiUrl,
640
+ clientId: environment.clientId,
641
+ generation: environment.generation,
642
+ sessionId,
643
+ tokenPath: join9(directory, `session_identity_${key}.json`),
644
+ statePath: join9(directory, `session_identity_${key}.state.json`),
645
+ lockPath: join9(directory, "session-identity.lock")
646
+ };
647
+ }
648
+ function readRecord(path) {
649
+ try {
650
+ const value = readMachineMetadata(path);
651
+ return value === void 0 ? void 0 : machineRecord(value);
652
+ } catch {
653
+ return void 0;
654
+ }
655
+ }
656
+ function finiteNumber(value) {
657
+ return typeof value === "number" && Number.isFinite(value);
658
+ }
659
+ function readToken(context) {
660
+ const data = readRecord(context.tokenPath);
661
+ if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
662
+ return void 0;
663
+ const identity = data.identity;
664
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
665
+ return void 0;
666
+ return data;
667
+ }
668
+ function tokenValid(record, now = Date.now()) {
669
+ return now < record.expiresAt - RENEW_BEFORE_MS;
670
+ }
671
+ function toCredential(record) {
672
+ return {
673
+ issuer: record.issuer,
674
+ audience: record.audience,
675
+ ...record.identity,
676
+ accessToken: record.accessToken,
677
+ expiresAt: record.expiresAt,
678
+ apiUrl: record.apiUrl,
679
+ generation: record.generation,
680
+ storage: "environment",
681
+ session: {
682
+ userId: record.userId,
683
+ displayName: record.displayName,
684
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
685
+ refreshAfter: record.refreshAfter
686
+ }
687
+ };
688
+ }
689
+ function cachedSessionCredential(deps = {}) {
690
+ if (!sessionIdentityMode(deps)) return void 0;
691
+ let context;
692
+ try {
693
+ context = sessionContext(deps);
694
+ } catch {
695
+ return void 0;
696
+ }
697
+ if ("status" in context) return void 0;
698
+ const record = readToken(context);
699
+ return record && tokenValid(record) ? toCredential(record) : void 0;
700
+ }
701
+ var SERVER_CONTRACT_FAILURE = failure(
702
+ "server_contract",
703
+ "Primitive's answer did not identify the linked member",
704
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
705
+ );
706
+
707
+ // src/lib/machine-credentials.ts
708
+ function sessionScoped(deps) {
709
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
710
+ }
711
+ var require3 = createRequire2(import.meta.url);
712
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
295
713
  var PROFILE_FILE = "machine_profile.json";
296
714
  var cached;
297
715
  function configurationDirectory(deps) {
298
716
  return deps.directory ?? primConfigDirectory({ env: deps.env });
299
717
  }
300
718
  function apiUrlFor(deps) {
301
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
719
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
302
720
  }
303
- function hash(value) {
304
- return createHash3("sha256").update(value).digest("hex");
721
+ function hash2(value) {
722
+ return createHash6("sha256").update(value).digest("hex");
305
723
  }
306
724
  function environmentContextPath(deps, clientId) {
307
- return join6(
725
+ return join10(
308
726
  configurationDirectory(deps),
309
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
727
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
310
728
  );
311
729
  }
312
730
  function readEnvironmentContext(environment, deps) {
@@ -332,12 +750,12 @@ function readEnvironmentContext(environment, deps) {
332
750
  }
333
751
  function protectPath(path, directory) {
334
752
  if (process.platform !== "win32") {
335
- chmodSync(path, directory ? 448 : 384);
753
+ chmodSync2(path, directory ? 448 : 384);
336
754
  return;
337
755
  }
338
756
  const encodedPath = Buffer.from(path).toString("base64");
339
757
  const script = `$ErrorActionPreference = 'Stop'; $p = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encodedPath}')); $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User; $acl = [System.Security.AccessControl.${directory ? "DirectorySecurity" : "FileSecurity"}]::new(); $acl.SetOwner($sid); $acl.SetAccessRuleProtection($true, $false); $rule = [System.Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', '${directory ? "ContainerInherit, ObjectInherit" : "None"}', 'None', 'Allow'); $acl.AddAccessRule($rule); [System.IO.${directory ? "Directory" : "File"}]::SetAccessControl($p, $acl)`;
340
- execFileSync(
758
+ execFileSync2(
341
759
  "powershell.exe",
342
760
  [
343
761
  "-NoProfile",
@@ -349,25 +767,28 @@ function protectPath(path, directory) {
349
767
  );
350
768
  }
351
769
  function ensureDirectory(directory) {
352
- mkdirSync3(directory, { recursive: true, mode: 448 });
353
- if (lstatSync3(directory).isSymbolicLink())
770
+ mkdirSync4(directory, { recursive: true, mode: 448 });
771
+ if (lstatSync5(directory).isSymbolicLink())
354
772
  throw new MachineAuthError(
355
773
  "unsafe_storage",
356
774
  "Credential directory must not be a symbolic link."
357
775
  );
358
776
  protectPath(directory, true);
359
777
  }
778
+ function readMachineMetadata(path) {
779
+ return readPrivate(path);
780
+ }
360
781
  function readPrivate(path) {
361
782
  let raw;
362
783
  try {
363
- const stat = lstatSync3(path);
784
+ const stat = lstatSync5(path);
364
785
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
365
786
  throw new MachineAuthError(
366
787
  "unsafe_storage",
367
788
  "Machine credential files must be owner-only regular files."
368
789
  );
369
790
  }
370
- raw = readFileSync5(path, "utf8");
791
+ raw = readFileSync7(path, "utf8");
371
792
  } catch (error) {
372
793
  if (error.code === "ENOENT") return void 0;
373
794
  throw error;
@@ -412,7 +833,7 @@ function parseProfile(value) {
412
833
  };
413
834
  }
414
835
  function readMachineProfile(deps = {}) {
415
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
836
+ const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
416
837
  return value === void 0 ? void 0 : parseProfile(value);
417
838
  }
418
839
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -421,20 +842,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
421
842
  var brokerKeys = /* @__PURE__ */ new Map();
422
843
  function networkSecretBrokerKey(deps, clientId) {
423
844
  const directory = configurationDirectory(deps);
424
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
845
+ const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
425
846
  const known = brokerKeys.get(path);
426
847
  if (known) return known;
427
848
  ensureDirectory(directory);
428
849
  const read = () => {
429
850
  try {
430
- const stat = lstatSync3(path);
851
+ const stat = lstatSync5(path);
431
852
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
432
853
  throw new MachineAuthError(
433
854
  "unsafe_storage",
434
855
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
435
856
  true
436
857
  );
437
- const value = readFileSync5(path, "utf8").trim();
858
+ const value = readFileSync7(path, "utf8").trim();
438
859
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
439
860
  } catch (error) {
440
861
  if (error.code === "ENOENT") return void 0;
@@ -453,16 +874,16 @@ function networkSecretBrokerKey(deps, clientId) {
453
874
  `The machine broker key at ${path} is damaged. Delete it and retry.`,
454
875
  true
455
876
  );
456
- const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
877
+ const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
457
878
  try {
458
- writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
879
+ writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
459
880
  `, { mode: 384, flag: "wx" });
460
881
  protectPath(staged, false);
461
882
  linkSync(staged, path);
462
883
  } catch (error) {
463
884
  if (error.code !== "EEXIST") throw error;
464
885
  } finally {
465
- rmSync5(staged, { force: true });
886
+ rmSync7(staged, { force: true });
466
887
  }
467
888
  }
468
889
  const key = read()?.key;
@@ -495,7 +916,7 @@ function environmentCredentials(deps) {
495
916
  "conflicting_credentials",
496
917
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
497
918
  );
498
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
919
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
499
920
  const credentials = {
500
921
  clientId,
501
922
  generation,
@@ -516,12 +937,12 @@ function environmentCredentials(deps) {
516
937
  return {
517
938
  clientId,
518
939
  clientSecret,
519
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
940
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
520
941
  };
521
942
  }
522
943
  function hasMachineConfiguration(deps = {}) {
523
944
  const env = deps.env ?? process.env;
524
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
945
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync5(join10(configurationDirectory(deps), PROFILE_FILE));
525
946
  if (configured && env.PRIM_TOKEN?.trim()) {
526
947
  throw new MachineAuthError(
527
948
  "conflicting_credentials",
@@ -533,6 +954,7 @@ function hasMachineConfiguration(deps = {}) {
533
954
  }
534
955
  function machineContext(deps = {}) {
535
956
  if (!hasMachineConfiguration(deps)) return void 0;
957
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
536
958
  const environment = environmentCredentials(deps);
537
959
  if (environment) {
538
960
  if (environmentTerminal === environment.generation) return void 0;
@@ -547,6 +969,7 @@ function machineContext(deps = {}) {
547
969
  return profile;
548
970
  }
549
971
  function cachedMachineCredential(deps = {}) {
972
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
550
973
  const context = machineContext(deps);
551
974
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
552
975
  }
@@ -554,20 +977,20 @@ var environmentTerminal;
554
977
 
555
978
  // src/lib/credentials.ts
556
979
  var CONFIG_DIRECTORY = primConfigDirectory();
557
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
558
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
559
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
560
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
561
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
562
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
563
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
564
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
980
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
981
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
982
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
983
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
984
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
985
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
986
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
987
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
565
988
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
566
989
  var CREDENTIAL_MIGRATION_VERSION = 1;
567
990
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
568
991
  function readTrimmed(path) {
569
992
  try {
570
- const value = readFileSync6(path, "utf8").trim();
993
+ const value = readFileSync8(path, "utf8").trim();
571
994
  return value || void 0;
572
995
  } catch {
573
996
  return void 0;
@@ -604,7 +1027,7 @@ function resolveAuthCredential(options = {}) {
604
1027
  return { token: stored, source: "token_file" };
605
1028
  }
606
1029
  function credentialFingerprint(value) {
607
- return createHash4("sha256").update(value).digest("hex");
1030
+ return createHash7("sha256").update(value).digest("hex");
608
1031
  }
609
1032
  function parseLegacyBrokerCredentialMetadata(value) {
610
1033
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -624,7 +1047,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
624
1047
  function readBoundedCredentialJson(path) {
625
1048
  let raw;
626
1049
  try {
627
- raw = readFileSync6(path, "utf8");
1050
+ raw = readFileSync8(path, "utf8");
628
1051
  } catch (error) {
629
1052
  return error.code === "ENOENT" ? void 0 : null;
630
1053
  }
@@ -697,7 +1120,7 @@ function boundedClaim(value) {
697
1120
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
698
1121
  }
699
1122
  function sha256(value) {
700
- return createHash5("sha256").update(value).digest("hex");
1123
+ return createHash8("sha256").update(value).digest("hex");
701
1124
  }
702
1125
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
703
1126
  if (hasMachineConfiguration()) {
@@ -748,8 +1171,8 @@ function parseDaemonResponseEnvelope(value) {
748
1171
 
749
1172
  // src/daemon/client.ts
750
1173
  import { createConnection } from "net";
751
- import { join as join8 } from "path";
752
- var SOCK_PATH = join8(primConfigDirectory(), "sock");
1174
+ import { join as join12 } from "path";
1175
+ var SOCK_PATH = join12(primConfigDirectory(), "sock");
753
1176
  var DEFAULT_TIMEOUT_MS = 250;
754
1177
  var nextRequestId = 1;
755
1178
  function daemonRequest(method, params = {}, opts = {}) {
@@ -840,38 +1263,38 @@ function daemonRequest(method, params = {}, opts = {}) {
840
1263
 
841
1264
  // src/lib/activation.ts
842
1265
  import { execFileSync as execFileSync4 } from "child_process";
843
- import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
1266
+ import { existsSync as existsSync7, readFileSync as readFileSync10 } from "fs";
844
1267
  import { homedir as homedir2 } from "os";
845
- import { join as join11 } from "path";
1268
+ import { join as join14 } from "path";
846
1269
 
847
1270
  // src/lib/cloud-prepared.ts
848
- import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync7, rmSync as rmSync6, writeFileSync as writeFileSync4 } from "fs";
849
- import { join as join9 } from "path";
1271
+ import { existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync8, writeFileSync as writeFileSync5 } from "fs";
1272
+ import { join as join13 } from "path";
850
1273
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
851
1274
  function cloudPreparedPath(env = process.env) {
852
- return join9(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1275
+ return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
853
1276
  }
854
1277
  function isPreparedCloudSession(env = process.env) {
855
1278
  if (!isClaudeCloudSession(env)) return false;
856
1279
  try {
857
- return existsSync4(cloudPreparedPath(env));
1280
+ return existsSync6(cloudPreparedPath(env));
858
1281
  } catch {
859
1282
  return false;
860
1283
  }
861
1284
  }
862
1285
 
863
1286
  // src/lib/demo-pause.ts
864
- import { execFileSync as execFileSync2 } from "child_process";
1287
+ import { execFileSync as execFileSync3 } from "child_process";
865
1288
  var DEMO_PAUSE_MS = 30 * 6e4;
866
1289
  var PAUSE_KEY = "prim.demoPause";
867
- var GIT_TIMEOUT_MS = 1e3;
1290
+ var GIT_TIMEOUT_MS2 = 1e3;
868
1291
  function git(cwd, args) {
869
1292
  try {
870
- return execFileSync2("git", args, {
1293
+ return execFileSync3("git", args, {
871
1294
  cwd,
872
1295
  encoding: "utf-8",
873
1296
  stdio: ["ignore", "pipe", "ignore"],
874
- timeout: GIT_TIMEOUT_MS
1297
+ timeout: GIT_TIMEOUT_MS2
875
1298
  });
876
1299
  } catch {
877
1300
  return void 0;
@@ -879,10 +1302,10 @@ function git(cwd, args) {
879
1302
  }
880
1303
  function setLocal(cwd, key, value) {
881
1304
  try {
882
- execFileSync2(
1305
+ execFileSync3(
883
1306
  "git",
884
1307
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
885
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1308
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
886
1309
  );
887
1310
  } catch (error) {
888
1311
  if (value !== null || error.status !== 5) throw error;
@@ -921,156 +1344,6 @@ function healDemoPause(cwd, pause, options = {}) {
921
1344
  }
922
1345
  }
923
1346
 
924
- // src/lib/git.ts
925
- import { execFileSync as execFileSync3 } from "child_process";
926
- import { createHash as createHash6 } from "crypto";
927
- import { lstatSync as lstatSync4, readFileSync as readFileSync8, realpathSync } from "fs";
928
- import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute3, join as join10, relative, resolve, sep } from "path";
929
- var GIT_TIMEOUT_MS2 = 1e3;
930
- var MAX_SETTINGS_BYTES = 1024 * 1024;
931
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
932
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
933
- function gitToplevel(cwd) {
934
- try {
935
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
936
- cwd,
937
- encoding: "utf-8",
938
- stdio: ["ignore", "pipe", "ignore"],
939
- timeout: GIT_TIMEOUT_MS2
940
- }).trim();
941
- } catch {
942
- return null;
943
- }
944
- }
945
- function gitValue(cwd, args) {
946
- try {
947
- const value = execFileSync3("git", args, {
948
- cwd,
949
- encoding: "utf-8",
950
- stdio: ["ignore", "pipe", "ignore"],
951
- timeout: GIT_TIMEOUT_MS2
952
- }).trim();
953
- return value || void 0;
954
- } catch {
955
- return void 0;
956
- }
957
- }
958
- function parseGithubRepositoryName(path) {
959
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
960
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
961
- return null;
962
- }
963
- return `${parts[0]}/${parts[1]}`;
964
- }
965
- function githubRepositoryFromRemote(remote) {
966
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
967
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
968
- remote
969
- );
970
- const path = match?.[1] ?? match?.[2];
971
- return path ? parseGithubRepositoryName(path) : null;
972
- }
973
- function checkoutSettingsText(repoRoot) {
974
- const path = join10(repoRoot, ".claude", "settings.json");
975
- try {
976
- if (!lstatSync4(join10(repoRoot, ".claude")).isDirectory()) return null;
977
- const stat = lstatSync4(path);
978
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
979
- return readFileSync8(path, "utf8");
980
- } catch {
981
- return null;
982
- }
983
- }
984
- function checkoutDeclaration(repoRoot, name) {
985
- const text = checkoutSettingsText(repoRoot);
986
- if (text === null) return null;
987
- let parsed;
988
- try {
989
- parsed = JSON.parse(text);
990
- } catch {
991
- return null;
992
- }
993
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
994
- const value = typeof env === "object" && env !== null ? env[name] : void 0;
995
- return typeof value === "string" ? value : null;
996
- }
997
- function declaredGithubRepository(repoRoot) {
998
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
999
- return value === null ? null : parseGithubRepositoryName(value.trim());
1000
- }
1001
- function githubRepositoryFullName(cwd) {
1002
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1003
- if (remote) {
1004
- const fromOrigin = githubRepositoryFromRemote(remote);
1005
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1006
- }
1007
- const root = gitToplevel(cwd);
1008
- return root ? declaredGithubRepository(root) : null;
1009
- }
1010
- function normalizeOriginRemote(remote) {
1011
- const value = remote.trim();
1012
- if (!value) return void 0;
1013
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1014
- if (scp?.host && scp.path) {
1015
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1016
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1017
- }
1018
- try {
1019
- const url = new URL(value);
1020
- url.username = "";
1021
- url.password = "";
1022
- url.search = "";
1023
- url.hash = "";
1024
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1025
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1026
- return void 0;
1027
- } catch {
1028
- return void 0;
1029
- }
1030
- }
1031
- function opaqueRepoKey(source, value) {
1032
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
1033
- }
1034
- function resolveRepositoryContext(cwd = process.cwd()) {
1035
- const top = gitToplevel(cwd);
1036
- if (!top) return null;
1037
- let repoRoot;
1038
- try {
1039
- repoRoot = realpathSync.native(top);
1040
- } catch {
1041
- repoRoot = resolve(top);
1042
- }
1043
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
1044
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
1045
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
1046
- if (normalizedOrigin) {
1047
- return {
1048
- repoRoot,
1049
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
1050
- identitySource: "origin",
1051
- repoFullName
1052
- };
1053
- }
1054
- if (repoFullName) {
1055
- return {
1056
- repoRoot,
1057
- repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
1058
- identitySource: "declared",
1059
- repoFullName
1060
- };
1061
- }
1062
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
1063
- if (roots && roots.length > 0) {
1064
- return {
1065
- repoRoot,
1066
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
1067
- identitySource: "root_commit",
1068
- repoFullName
1069
- };
1070
- }
1071
- return { repoRoot, repoFullName };
1072
- }
1073
-
1074
1347
  // src/lib/activation.ts
1075
1348
  var PRIM_ACTIVE_KEY = "prim.active";
1076
1349
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1098,10 +1371,10 @@ function repoActiveFlag(cwd, strict = false) {
1098
1371
  function projectPrimInstallAt(root) {
1099
1372
  if (root === null || root === homedir2()) return false;
1100
1373
  for (const rel of PROJECT_INSTALL_FILES) {
1101
- const path = join11(root, rel);
1102
- if (existsSync5(path)) {
1374
+ const path = join14(root, rel);
1375
+ if (existsSync7(path)) {
1103
1376
  try {
1104
- const content = readFileSync9(path, "utf-8");
1377
+ const content = readFileSync10(path, "utf-8");
1105
1378
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
1106
1379
  } catch {
1107
1380
  }
@@ -1145,127 +1418,7 @@ function parseAgent(argv) {
1145
1418
  // src/commands/cursor-install.ts
1146
1419
  import { existsSync as existsSync9, readFileSync as readFileSync12 } from "fs";
1147
1420
  import { homedir as homedir4 } from "os";
1148
- import { isAbsolute as isAbsolute5, join as join15 } from "path";
1149
-
1150
- // src/lib/hook-runtime.ts
1151
- import { createHash as createHash7, randomBytes as randomBytes4 } from "crypto";
1152
- import {
1153
- constants as constants2,
1154
- accessSync,
1155
- chmodSync as chmodSync2,
1156
- copyFileSync,
1157
- existsSync as existsSync7,
1158
- lstatSync as lstatSync5,
1159
- mkdirSync as mkdirSync5,
1160
- mkdtempSync,
1161
- readFileSync as readFileSync10,
1162
- readdirSync as readdirSync2,
1163
- realpathSync as realpathSync2,
1164
- renameSync as renameSync2,
1165
- rmSync as rmSync7,
1166
- statSync as statSync2,
1167
- utimesSync,
1168
- writeFileSync as writeFileSync5
1169
- } from "fs";
1170
- import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join13, resolve as resolve2 } from "path";
1171
-
1172
- // src/lib/git-hook-contract.ts
1173
- var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
1174
- # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
1175
- # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
1176
- # where prim is active (git config prim.active true) and never fails the hook.
1177
- case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
1178
- prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
1179
- [ -x "$prim_launcher" ] || exit 0
1180
- [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
1181
- prim_hook=\${1-}
1182
- if [ "$#" -gt 0 ]; then shift; fi
1183
- case "$prim_hook" in
1184
- pre-commit)
1185
- "$prim_launcher" prim-pre-commit "$@" || :
1186
- ;;
1187
- post-commit)
1188
- prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
1189
- case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
1190
- case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
1191
- prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
1192
- prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
1193
- (
1194
- trap '' HUP
1195
- trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
1196
- PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
1197
- ) </dev/null >/dev/null 2>&1 &
1198
- ;;
1199
- post-rewrite)
1200
- case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
1201
- prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
1202
- if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
1203
- rm -f "$prim_pairs"
1204
- exit 0
1205
- fi
1206
- prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
1207
- (
1208
- trap '' HUP
1209
- trap 'rm -f "$prim_pairs"' 0
1210
- PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
1211
- ) </dev/null >/dev/null 2>&1 &
1212
- ;;
1213
- esac
1214
- exit 0
1215
- `;
1216
-
1217
- // src/lib/native-keyring.ts
1218
- import { existsSync as existsSync6 } from "fs";
1219
- import { createRequire as createRequire2 } from "module";
1220
- import { dirname as dirname6, join as join12 } from "path";
1221
- import { fileURLToPath as fileURLToPath4 } from "url";
1222
- var require3 = createRequire2(import.meta.url);
1223
-
1224
- // src/lib/hook-runtime.ts
1225
- var RELEASE_PREFIX = "release-";
1226
- var MAX_MANIFEST_BYTES = 64 * 1024;
1227
- var RELEASE_GRACE_MS = 10 * 60 * 1e3;
1228
- var HOOK_RUNTIME_ENTRIES = {
1229
- // SessionStart self-healing resolves this exact CLI entry to run
1230
- // `daemon ensure`; it must travel with the immutable hook release.
1231
- prim: "dist/index.js",
1232
- "prim-hook": "dist/hooks/prim-hook.js",
1233
- "prim-pre-commit": "dist/hooks/pre-commit.js",
1234
- "prim-post-commit": "dist/hooks/post-commit.js",
1235
- "prim-post-rewrite": "dist/hooks/post-rewrite.js",
1236
- "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
1237
- "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
1238
- "prim-post-tool-use": "dist/hooks/post-tool-use.js",
1239
- "prim-session-start": "dist/hooks/session-start.js",
1240
- "prim-session-end": "dist/hooks/session-end.js",
1241
- "prim-daemon-server": "dist/daemon/server.js",
1242
- "prim-statusline": "dist/statusline-main.js"
1243
- };
1244
- var SOURCE_ENTRIES = Object.fromEntries(
1245
- Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
1246
- bin,
1247
- target.replace(/^dist\//u, "")
1248
- ])
1249
- );
1250
- var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
1251
- set -eu
1252
- case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
1253
- IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
1254
- case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
1255
- prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
1256
- case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
1257
- [ "\${#prim_release_id}" -eq 64 ] || exit 69
1258
- prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
1259
- case "\${1-}" in
1260
- ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
1261
- *) exit 64 ;;
1262
- esac
1263
- shift
1264
- IFS= read -r prim_node < "$prim_release/node" || exit 69
1265
- case "$prim_node" in /*) ;; *) exit 69 ;; esac
1266
- [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
1267
- exec "$prim_node" "$prim_entry" "$@"
1268
- `;
1421
+ import { isAbsolute as isAbsolute5, join as join16 } from "path";
1269
1422
 
1270
1423
  // src/lib/preflight-host.ts
1271
1424
  import { execFileSync as execFileSync5 } from "child_process";
@@ -1273,7 +1426,7 @@ import { execFileSync as execFileSync5 } from "child_process";
1273
1426
  // src/commands/claude-install.ts
1274
1427
  import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11 } from "fs";
1275
1428
  import { homedir as homedir3 } from "os";
1276
- import { join as join14 } from "path";
1429
+ import { join as join15 } from "path";
1277
1430
  var CAPTURE_BIN = "prim-hook";
1278
1431
  var GATE_BIN = "prim-pre-tool-use";
1279
1432
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -1282,7 +1435,7 @@ var SESSION_END_BIN = "prim-session-end";
1282
1435
  var STATUSLINE_BIN = "prim-statusline";
1283
1436
  var STATUSLINE_ARGS = "";
1284
1437
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
1285
- var USER_SCOPE_PATH = join14(homedir3(), ".claude", "settings.json");
1438
+ var USER_SCOPE_PATH = join15(homedir3(), ".claude", "settings.json");
1286
1439
  function projectRoot() {
1287
1440
  return gitToplevel() ?? process.cwd();
1288
1441
  }
@@ -1362,11 +1515,11 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
1362
1515
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
1363
1516
  if (explicit && isAbsolute5(explicit)) return explicit;
1364
1517
  const xdg = env.XDG_CONFIG_HOME?.trim();
1365
- if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join15(xdg, "cursor");
1366
- return join15(home, ".cursor");
1518
+ if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join16(xdg, "cursor");
1519
+ return join16(home, ".cursor");
1367
1520
  }
1368
1521
  function cursorHooksPath(scope, root = projectRoot()) {
1369
- return scope === "user" ? join15(cursorConfigDirectory(), "hooks.json") : join15(root, ".cursor", "hooks.json");
1522
+ return scope === "user" ? join16(cursorConfigDirectory(), "hooks.json") : join16(root, ".cursor", "hooks.json");
1370
1523
  }
1371
1524
  function plainObject(value) {
1372
1525
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -1518,7 +1671,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1518
1671
  }
1519
1672
 
1520
1673
  // src/hooks/normalize.ts
1521
- import { createHash as createHash8 } from "crypto";
1674
+ import { createHash as createHash9 } from "crypto";
1522
1675
  import { realpathSync as realpathSync3 } from "fs";
1523
1676
  import { isAbsolute as isAbsolute6, resolve as resolve3 } from "path";
1524
1677
  var HERMES_EVENT_MAP = {
@@ -1563,7 +1716,7 @@ function requiredId(value, field) {
1563
1716
  }
1564
1717
  function cursorToolUseId(value) {
1565
1718
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
1566
- return `cursor:tool:v1:${createHash8("sha256").update(value).digest("hex")}`;
1719
+ return `cursor:tool:v1:${createHash9("sha256").update(value).digest("hex")}`;
1567
1720
  }
1568
1721
  function workspaceCandidates(value) {
1569
1722
  if (!Array.isArray(value)) return [];
@@ -1660,7 +1813,7 @@ function normalizeEnvelope(parsed, agent) {
1660
1813
  ]);
1661
1814
  return {
1662
1815
  ...parsed,
1663
- tool_use_id: `codex:fallback:v1:${createHash8("sha256").update(stableToolIdentity).digest("hex")}`
1816
+ tool_use_id: `codex:fallback:v1:${createHash9("sha256").update(stableToolIdentity).digest("hex")}`
1664
1817
  };
1665
1818
  }
1666
1819
  return parsed;