@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
@@ -1,19 +1,21 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/commands/statusline.ts
4
- import { readFileSync as readFileSync12 } from "fs";
5
- import { dirname as dirname7, resolve as resolve3 } from "path";
6
- import { fileURLToPath as fileURLToPath4 } from "url";
4
+ import { readFileSync as readFileSync13 } from "fs";
5
+ import { dirname as dirname9, resolve as resolve4 } from "path";
6
+ import { fileURLToPath as fileURLToPath5 } from "url";
7
7
 
8
8
  // src/lib/cloud-env.ts
9
9
  function isClaudeCloudSession(env = process.env) {
10
10
  return env.CLAUDE_CODE_REMOTE === "true";
11
11
  }
12
+ 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';
13
+ 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}.`;
12
14
 
13
15
  // src/client.ts
14
- import { createHash as createHash5 } from "crypto";
15
- import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
16
- import { dirname as dirname5 } from "path";
16
+ import { createHash as createHash8 } from "crypto";
17
+ import { chmodSync as chmodSync4, existsSync as existsSync6, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8 } from "fs";
18
+ import { dirname as dirname8 } from "path";
17
19
 
18
20
  // src/lib/atomic-file.ts
19
21
  import { randomUUID } from "crypto";
@@ -31,26 +33,26 @@ import {
31
33
  import { dirname } from "path";
32
34
 
33
35
  // src/lib/credentials.ts
34
- import { createHash as createHash4 } from "crypto";
35
- import { readFileSync as readFileSync6 } from "fs";
36
- import { join as join7 } from "path";
36
+ import { createHash as createHash7 } from "crypto";
37
+ import { readFileSync as readFileSync8 } from "fs";
38
+ import { join as join11 } from "path";
37
39
 
38
40
  // src/lib/machine-credentials.ts
39
- import { execFileSync } from "child_process";
40
- import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
41
+ import { execFileSync as execFileSync2 } from "child_process";
42
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
41
43
  import {
42
- chmodSync,
43
- existsSync as existsSync3,
44
+ chmodSync as chmodSync2,
45
+ existsSync as existsSync5,
44
46
  linkSync,
45
- lstatSync as lstatSync3,
46
- mkdirSync as mkdirSync3,
47
- readFileSync as readFileSync5,
48
- rmSync as rmSync5,
49
- writeFileSync as writeFileSync3
47
+ lstatSync as lstatSync5,
48
+ mkdirSync as mkdirSync4,
49
+ readFileSync as readFileSync7,
50
+ rmSync as rmSync7,
51
+ writeFileSync as writeFileSync4
50
52
  } from "fs";
51
- import { createRequire } from "module";
52
- import { dirname as dirname4, join as join6 } from "path";
53
- import { fileURLToPath as fileURLToPath3 } from "url";
53
+ import { createRequire as createRequire2 } from "module";
54
+ import { dirname as dirname7, join as join10 } from "path";
55
+ import { fileURLToPath as fileURLToPath4 } from "url";
54
56
 
55
57
  // src/lib/file-lock.ts
56
58
  import { randomBytes } from "crypto";
@@ -58,13 +60,27 @@ import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, s
58
60
  import { dirname as dirname2, join } from "path";
59
61
  var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
60
62
 
61
- // src/lib/machine-broker.ts
62
- import { spawn } from "child_process";
63
- import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
64
- import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
65
- import { createServer } from "http";
66
- import { basename, join as join4 } from "path";
67
- import { fileURLToPath as fileURLToPath2 } from "url";
63
+ // src/lib/hook-runtime.ts
64
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
65
+ import {
66
+ constants as constants2,
67
+ accessSync,
68
+ chmodSync,
69
+ copyFileSync,
70
+ existsSync as existsSync4,
71
+ lstatSync,
72
+ mkdirSync as mkdirSync3,
73
+ mkdtempSync,
74
+ readFileSync as readFileSync3,
75
+ readdirSync,
76
+ realpathSync,
77
+ renameSync as renameSync2,
78
+ rmSync as rmSync3,
79
+ statSync as statSync2,
80
+ utimesSync,
81
+ writeFileSync as writeFileSync3
82
+ } from "fs";
83
+ import { delimiter, dirname as dirname5, isAbsolute as isAbsolute3, join as join5, resolve } from "path";
68
84
 
69
85
  // src/lib/bin-path.ts
70
86
  import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
@@ -72,6 +88,7 @@ import { dirname as dirname3, isAbsolute, join as join2 } from "path";
72
88
  import { fileURLToPath } from "url";
73
89
  var PKG_NAME = "@primitive.ai/prim";
74
90
  var ROOT_WALK_LIMIT = 6;
91
+ var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
75
92
  var resolvedRoot;
76
93
  function locateRoot() {
77
94
  if (resolvedRoot !== void 0) {
@@ -110,6 +127,140 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
110
127
  "fi; fi; "
111
128
  ].join("");
112
129
 
130
+ // src/lib/git-hook-contract.ts
131
+ var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
132
+ # prim git hook entrypoint v1 \u2014 managed by prim; do not edit.
133
+ # Run by the "# >>> prim <hook> hook >>>" block in a Git hook file. Acts only
134
+ # where prim is active (git config prim.active true) and never fails the hook.
135
+ case "$0" in */*) prim_dir=\${0%/*} ;; *) exit 0 ;; esac
136
+ prim_launcher="$prim_dir/${STABLE_HOOK_LAUNCHER_NAME}"
137
+ [ -x "$prim_launcher" ] || exit 0
138
+ [ "$(git config --get prim.active 2>/dev/null)" = "true" ] || exit 0
139
+ prim_hook=\${1-}
140
+ if [ "$#" -gt 0 ]; then shift; fi
141
+ case "$prim_hook" in
142
+ pre-commit)
143
+ "$prim_launcher" prim-pre-commit "$@" || :
144
+ ;;
145
+ post-commit)
146
+ prim_sha=$(git rev-parse --verify HEAD 2>/dev/null) || exit 0
147
+ case "$prim_sha" in *[!0-9a-f]* | "") exit 0 ;; esac
148
+ case "\${#prim_sha}" in 40 | 64) ;; *) exit 0 ;; esac
149
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
150
+ prim_observed=$(mktemp "\${TMPDIR:-/tmp}/prim-post-commit-observed.XXXXXXXX" 2>/dev/null) || prim_observed=
151
+ (
152
+ trap '' HUP
153
+ trap 'if [ -n "$prim_observed" ]; then rm -f "$prim_observed"; fi' 0
154
+ PRIM_COMMIT_SHA=$prim_sha PRIM_COMMIT_BRANCH=$prim_branch PRIM_COMMIT_OBSERVED_FILE=$prim_observed "$prim_launcher" prim-post-commit
155
+ ) </dev/null >/dev/null 2>&1 &
156
+ ;;
157
+ post-rewrite)
158
+ case "\${1-}" in amend | rebase) prim_source=$1 ;; *) exit 0 ;; esac
159
+ prim_pairs=$(mktemp "\${TMPDIR:-/tmp}/prim-post-rewrite-pairs.XXXXXXXX" 2>/dev/null) || exit 0
160
+ if ! chmod 600 "$prim_pairs" 2>/dev/null || ! cat >"$prim_pairs"; then
161
+ rm -f "$prim_pairs"
162
+ exit 0
163
+ fi
164
+ prim_branch=$(git symbolic-ref --quiet --short HEAD 2>/dev/null) || prim_branch=
165
+ (
166
+ trap '' HUP
167
+ trap 'rm -f "$prim_pairs"' 0
168
+ PRIM_REWRITE_SOURCE=$prim_source PRIM_REWRITE_BRANCH=$prim_branch PRIM_REWRITE_PAIRS_FILE=$prim_pairs "$prim_launcher" prim-post-rewrite
169
+ ) </dev/null >/dev/null 2>&1 &
170
+ ;;
171
+ esac
172
+ exit 0
173
+ `;
174
+
175
+ // src/lib/native-keyring.ts
176
+ import { existsSync as existsSync3 } from "fs";
177
+ import { createRequire } from "module";
178
+ import { dirname as dirname4, join as join3 } from "path";
179
+ import { fileURLToPath as fileURLToPath2 } from "url";
180
+ var require2 = createRequire(import.meta.url);
181
+
182
+ // src/lib/paths.ts
183
+ import { homedir } from "os";
184
+ import { isAbsolute as isAbsolute2, join as join4, normalize } from "path";
185
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
186
+ function absolutePath(value, variable) {
187
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
188
+ throw new Error(`${variable} contains unsafe characters`);
189
+ }
190
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
191
+ const normalized = normalize(value);
192
+ return normalized === value ? value : void 0;
193
+ }
194
+ function resolvePrimConfigDirectory(options = {}) {
195
+ const env = options.env ?? process.env;
196
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
197
+ if (explicit) return { path: explicit, source: "explicit" };
198
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
199
+ if (xdgConfigHome) return { path: join4(xdgConfigHome, "prim"), source: "xdg" };
200
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
201
+ if (!home) {
202
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
203
+ }
204
+ return { path: join4(home, ".config", "prim"), source: "default" };
205
+ }
206
+ function primConfigDirectory(options = {}) {
207
+ return resolvePrimConfigDirectory(options).path;
208
+ }
209
+
210
+ // src/lib/hook-runtime.ts
211
+ var RELEASE_PREFIX = "release-";
212
+ var MAX_MANIFEST_BYTES = 64 * 1024;
213
+ var RELEASE_GRACE_MS = 10 * 60 * 1e3;
214
+ var HOOK_RUNTIME_ENTRIES = {
215
+ // SessionStart self-healing resolves this exact CLI entry to run
216
+ // `daemon ensure`; it must travel with the immutable hook release.
217
+ prim: "dist/index.js",
218
+ "prim-hook": "dist/hooks/prim-hook.js",
219
+ "prim-pre-commit": "dist/hooks/pre-commit.js",
220
+ "prim-post-commit": "dist/hooks/post-commit.js",
221
+ "prim-post-rewrite": "dist/hooks/post-rewrite.js",
222
+ "prim-pre-tool-use-worker": "dist/hooks/pre-tool-use-worker.js",
223
+ "prim-pre-tool-use": "dist/hooks/pre-tool-use.js",
224
+ "prim-post-tool-use": "dist/hooks/post-tool-use.js",
225
+ "prim-session-start": "dist/hooks/session-start.js",
226
+ "prim-session-end": "dist/hooks/session-end.js",
227
+ "prim-daemon-server": "dist/daemon/server.js",
228
+ "prim-statusline": "dist/statusline-main.js"
229
+ };
230
+ var SOURCE_ENTRIES = Object.fromEntries(
231
+ Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, target]) => [
232
+ bin,
233
+ target.replace(/^dist\//u, "")
234
+ ])
235
+ );
236
+ var STABLE_HOOK_LAUNCHER_CONTENT = `#!/bin/sh
237
+ set -eu
238
+ case "$0" in */*) prim_launcher_dir=\${0%/*} ;; *) exit 78 ;; esac
239
+ IFS= read -r prim_release_name < "$prim_launcher_dir/hook-runtime/current" || exit 69
240
+ case "$prim_release_name" in ${RELEASE_PREFIX}*) ;; *) exit 69 ;; esac
241
+ prim_release_id=\${prim_release_name#${RELEASE_PREFIX}}
242
+ case "$prim_release_id" in *[!0-9a-f]*|"") exit 69 ;; esac
243
+ [ "\${#prim_release_id}" -eq 64 ] || exit 69
244
+ prim_release="$prim_launcher_dir/hook-runtime/releases/$prim_release_name"
245
+ case "\${1-}" in
246
+ ${Object.entries(HOOK_RUNTIME_ENTRIES).map(([bin, entry]) => ` ${bin}) prim_entry="$prim_release/${entry}" ;;`).join("\n")}
247
+ *) exit 64 ;;
248
+ esac
249
+ shift
250
+ IFS= read -r prim_node < "$prim_release/node" || exit 69
251
+ case "$prim_node" in /*) ;; *) exit 69 ;; esac
252
+ [ -x "$prim_node" ] && [ -f "$prim_entry" ] || exit 69
253
+ exec "$prim_node" "$prim_entry" "$@"
254
+ `;
255
+
256
+ // src/lib/machine-broker.ts
257
+ import { spawn } from "child_process";
258
+ import { createHash as createHash2, createHmac, randomBytes as randomBytes3, timingSafeEqual } from "crypto";
259
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
260
+ import { createServer } from "http";
261
+ import { basename, join as join6 } from "path";
262
+ import { fileURLToPath as fileURLToPath3 } from "url";
263
+
113
264
  // src/lib/loopback-fetch.ts
114
265
  import { request } from "http";
115
266
  import { Readable } from "stream";
@@ -259,34 +410,6 @@ function parseMachineIdentity(value, clientId) {
259
410
  };
260
411
  }
261
412
 
262
- // src/lib/paths.ts
263
- import { homedir } from "os";
264
- import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
265
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
266
- function absolutePath(value, variable) {
267
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
268
- throw new Error(`${variable} contains unsafe characters`);
269
- }
270
- if (!value || value.trim() !== value || !isAbsolute2(value)) return;
271
- const normalized = normalize(value);
272
- return normalized === value ? value : void 0;
273
- }
274
- function resolvePrimConfigDirectory(options = {}) {
275
- const env = options.env ?? process.env;
276
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
277
- if (explicit) return { path: explicit, source: "explicit" };
278
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
279
- if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
280
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
281
- if (!home) {
282
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
283
- }
284
- return { path: join3(home, ".config", "prim"), source: "default" };
285
- }
286
- function primConfigDirectory(options = {}) {
287
- return resolvePrimConfigDirectory(options).path;
288
- }
289
-
290
413
  // src/lib/machine-broker.ts
291
414
  var MAX_RESPONSE_BYTES = 96 * 1024;
292
415
  var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
@@ -295,29 +418,322 @@ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
295
418
  var IDLE_MS = 5 * 6e4;
296
419
 
297
420
  // src/lib/machine-retry.ts
298
- import { createHash as createHash2 } from "crypto";
299
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
300
- import { join as join5 } from "path";
421
+ import { createHash as createHash3 } from "crypto";
422
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, readdirSync as readdirSync2, rmSync as rmSync5 } from "fs";
423
+ import { join as join7 } from "path";
301
424
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
302
425
 
303
- // src/lib/machine-credentials.ts
304
- var require2 = createRequire(import.meta.url);
426
+ // src/lib/session-identity.ts
427
+ import { execFile } from "child_process";
428
+ import { createHash as createHash5 } from "crypto";
429
+ import { rmSync as rmSync6 } from "fs";
430
+ import { join as join9 } from "path";
431
+ import { promisify } from "util";
432
+
433
+ // src/lib/git.ts
434
+ import { execFileSync } from "child_process";
435
+ import { createHash as createHash4 } from "crypto";
436
+ import { lstatSync as lstatSync4, readFileSync as readFileSync6, realpathSync as realpathSync2 } from "fs";
437
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute4, join as join8, relative, resolve as resolve2, sep } from "path";
438
+ var GIT_TIMEOUT_MS = 1e3;
439
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
440
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
441
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
442
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
443
+ function gitChildEnvironment(env = process.env) {
444
+ return Object.fromEntries(
445
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
446
+ );
447
+ }
448
+ function gitToplevel(cwd) {
449
+ try {
450
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
451
+ cwd,
452
+ encoding: "utf-8",
453
+ stdio: ["ignore", "pipe", "ignore"],
454
+ timeout: GIT_TIMEOUT_MS,
455
+ env: gitChildEnvironment()
456
+ }).trim();
457
+ } catch {
458
+ return null;
459
+ }
460
+ }
461
+ function gitValue(cwd, args) {
462
+ try {
463
+ const value = execFileSync("git", args, {
464
+ cwd,
465
+ encoding: "utf-8",
466
+ stdio: ["ignore", "pipe", "ignore"],
467
+ timeout: GIT_TIMEOUT_MS,
468
+ env: gitChildEnvironment()
469
+ }).trim();
470
+ return value || void 0;
471
+ } catch {
472
+ return void 0;
473
+ }
474
+ }
475
+ function parseGithubRepositoryName(path) {
476
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
477
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
478
+ return null;
479
+ }
480
+ return `${parts[0]}/${parts[1]}`;
481
+ }
482
+ function githubRepositoryFromRemote(remote) {
483
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
484
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
485
+ remote
486
+ );
487
+ const path = match?.[1] ?? match?.[2];
488
+ return path ? parseGithubRepositoryName(path) : null;
489
+ }
490
+ function checkoutSettingsText(repoRoot) {
491
+ const path = join8(repoRoot, ".claude", "settings.json");
492
+ try {
493
+ if (!lstatSync4(join8(repoRoot, ".claude")).isDirectory()) return null;
494
+ const stat = lstatSync4(path);
495
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
496
+ return readFileSync6(path, "utf8");
497
+ } catch {
498
+ return null;
499
+ }
500
+ }
501
+ function checkoutDeclaration(repoRoot, name) {
502
+ const text = checkoutSettingsText(repoRoot);
503
+ if (text === null) return null;
504
+ let parsed;
505
+ try {
506
+ parsed = JSON.parse(text);
507
+ } catch {
508
+ return null;
509
+ }
510
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
511
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
512
+ return typeof value === "string" ? value : null;
513
+ }
514
+ function declaredGithubRepository(repoRoot) {
515
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
516
+ return value === null ? null : parseGithubRepositoryName(value.trim());
517
+ }
518
+ function githubRepositoryFullName(cwd) {
519
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
520
+ if (remote) {
521
+ const fromOrigin = githubRepositoryFromRemote(remote);
522
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
523
+ }
524
+ const root = gitToplevel(cwd);
525
+ return root ? declaredGithubRepository(root) : null;
526
+ }
527
+ function normalizeOriginRemote(remote) {
528
+ const value = remote.trim();
529
+ if (!value) return void 0;
530
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
531
+ if (scp?.host && scp.path) {
532
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
533
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
534
+ }
535
+ try {
536
+ const url = new URL(value);
537
+ url.username = "";
538
+ url.password = "";
539
+ url.search = "";
540
+ url.hash = "";
541
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
542
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
543
+ return void 0;
544
+ } catch {
545
+ return void 0;
546
+ }
547
+ }
548
+
549
+ // src/lib/terminal-safe.ts
550
+ function replaceIsolatedSurrogates(value) {
551
+ let out = "";
552
+ for (let index = 0; index < value.length; index += 1) {
553
+ const unit = value.charCodeAt(index);
554
+ if (unit >= 55296 && unit <= 56319) {
555
+ const next = value.charCodeAt(index + 1);
556
+ if (next >= 56320 && next <= 57343) {
557
+ out += value[index] + value[index + 1];
558
+ index += 1;
559
+ } else {
560
+ out += "\uFFFD";
561
+ }
562
+ } else if (unit >= 56320 && unit <= 57343) {
563
+ out += "\uFFFD";
564
+ } else {
565
+ out += value[index];
566
+ }
567
+ }
568
+ return out;
569
+ }
570
+ function isUnsafeTerminalCodePoint(point) {
571
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
572
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
573
+ point === 1564 || // Arabic letter mark
574
+ point === 6158 || // Mongolian vowel separator
575
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
576
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
577
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
578
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
579
+ point === 65279 || // zero-width no-break space / BOM
580
+ point >= 917504 && point <= 917631;
581
+ return c0OrC1 || bidiOrZeroWidth;
582
+ }
583
+ function terminalSafeText(value) {
584
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
585
+ }
586
+ var stripControlChars = terminalSafeText;
587
+
588
+ // src/lib/session-identity.ts
589
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
590
+ var SESSION_IDENTITY_VALUE = "session";
591
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
592
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
593
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
305
594
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
595
+ var RENEW_BEFORE_MS = 6e4;
596
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
597
+ var RESPONSE_MAX_BYTES = 64 * 1024;
598
+ function sessionIdentityRequested(env = process.env) {
599
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
600
+ }
601
+ function sessionIdentityMode(deps = {}) {
602
+ const env = deps.env ?? process.env;
603
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
604
+ }
605
+ function failure(code, cause, remedy) {
606
+ return { status: "failed", code, cause, remedy };
607
+ }
608
+ var NEW_SESSION_REMEDY = "start a new cloud session";
609
+ var SESSION_REVOKED = failure(
610
+ "session_revoked",
611
+ "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",
612
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
613
+ );
614
+ var CHALLENGE_WINDOW_PASSED = failure(
615
+ "challenge_expired",
616
+ "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)",
617
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
618
+ );
619
+ var CHALLENGE_GONE = failure(
620
+ "challenge_not_found",
621
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
622
+ NEW_SESSION_REMEDY
623
+ );
624
+ function hash(value) {
625
+ return createHash5("sha256").update(value).digest("hex");
626
+ }
627
+ function sessionContext(deps) {
628
+ const env = deps.env ?? process.env;
629
+ const environment = environmentCredentials(deps);
630
+ if (!environment)
631
+ return failure(
632
+ "environment_credential_missing",
633
+ "the cloud environment has no environment credential",
634
+ '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'
635
+ );
636
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
637
+ if (!sessionId || !SESSION_ID.test(sessionId))
638
+ return failure(
639
+ "session_id_missing",
640
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
641
+ NEW_SESSION_REMEDY
642
+ );
643
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
644
+ const directory = deps.directory ?? primConfigDirectory({ env });
645
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
646
+ return {
647
+ directory,
648
+ apiUrl,
649
+ clientId: environment.clientId,
650
+ generation: environment.generation,
651
+ sessionId,
652
+ tokenPath: join9(directory, `session_identity_${key}.json`),
653
+ statePath: join9(directory, `session_identity_${key}.state.json`),
654
+ lockPath: join9(directory, "session-identity.lock")
655
+ };
656
+ }
657
+ function readRecord(path) {
658
+ try {
659
+ const value = readMachineMetadata(path);
660
+ return value === void 0 ? void 0 : machineRecord(value);
661
+ } catch {
662
+ return void 0;
663
+ }
664
+ }
665
+ function finiteNumber(value) {
666
+ return typeof value === "number" && Number.isFinite(value);
667
+ }
668
+ function readToken(context) {
669
+ const data = readRecord(context.tokenPath);
670
+ 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))
671
+ return void 0;
672
+ const identity = data.identity;
673
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
674
+ return void 0;
675
+ return data;
676
+ }
677
+ function tokenValid(record, now = Date.now()) {
678
+ return now < record.expiresAt - RENEW_BEFORE_MS;
679
+ }
680
+ function toCredential(record) {
681
+ return {
682
+ issuer: record.issuer,
683
+ audience: record.audience,
684
+ ...record.identity,
685
+ accessToken: record.accessToken,
686
+ expiresAt: record.expiresAt,
687
+ apiUrl: record.apiUrl,
688
+ generation: record.generation,
689
+ storage: "environment",
690
+ session: {
691
+ userId: record.userId,
692
+ displayName: record.displayName,
693
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
694
+ refreshAfter: record.refreshAfter
695
+ }
696
+ };
697
+ }
698
+ function cachedSessionCredential(deps = {}) {
699
+ if (!sessionIdentityMode(deps)) return void 0;
700
+ let context;
701
+ try {
702
+ context = sessionContext(deps);
703
+ } catch {
704
+ return void 0;
705
+ }
706
+ if ("status" in context) return void 0;
707
+ const record = readToken(context);
708
+ return record && tokenValid(record) ? toCredential(record) : void 0;
709
+ }
710
+ var SERVER_CONTRACT_FAILURE = failure(
711
+ "server_contract",
712
+ "Primitive's answer did not identify the linked member",
713
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
714
+ );
715
+
716
+ // src/lib/machine-credentials.ts
717
+ function sessionScoped(deps) {
718
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
719
+ }
720
+ var require3 = createRequire2(import.meta.url);
721
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
306
722
  var PROFILE_FILE = "machine_profile.json";
307
723
  var cached;
308
724
  function configurationDirectory(deps) {
309
725
  return deps.directory ?? primConfigDirectory({ env: deps.env });
310
726
  }
311
727
  function apiUrlFor(deps) {
312
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
728
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
313
729
  }
314
- function hash(value) {
315
- return createHash3("sha256").update(value).digest("hex");
730
+ function hash2(value) {
731
+ return createHash6("sha256").update(value).digest("hex");
316
732
  }
317
733
  function environmentContextPath(deps, clientId) {
318
- return join6(
734
+ return join10(
319
735
  configurationDirectory(deps),
320
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
736
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
321
737
  );
322
738
  }
323
739
  function readEnvironmentContext(environment, deps) {
@@ -343,12 +759,12 @@ function readEnvironmentContext(environment, deps) {
343
759
  }
344
760
  function protectPath(path, directory) {
345
761
  if (process.platform !== "win32") {
346
- chmodSync(path, directory ? 448 : 384);
762
+ chmodSync2(path, directory ? 448 : 384);
347
763
  return;
348
764
  }
349
765
  const encodedPath = Buffer.from(path).toString("base64");
350
766
  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)`;
351
- execFileSync(
767
+ execFileSync2(
352
768
  "powershell.exe",
353
769
  [
354
770
  "-NoProfile",
@@ -360,25 +776,28 @@ function protectPath(path, directory) {
360
776
  );
361
777
  }
362
778
  function ensureDirectory(directory) {
363
- mkdirSync3(directory, { recursive: true, mode: 448 });
364
- if (lstatSync3(directory).isSymbolicLink())
779
+ mkdirSync4(directory, { recursive: true, mode: 448 });
780
+ if (lstatSync5(directory).isSymbolicLink())
365
781
  throw new MachineAuthError(
366
782
  "unsafe_storage",
367
783
  "Credential directory must not be a symbolic link."
368
784
  );
369
785
  protectPath(directory, true);
370
786
  }
787
+ function readMachineMetadata(path) {
788
+ return readPrivate(path);
789
+ }
371
790
  function readPrivate(path) {
372
791
  let raw;
373
792
  try {
374
- const stat = lstatSync3(path);
793
+ const stat = lstatSync5(path);
375
794
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
376
795
  throw new MachineAuthError(
377
796
  "unsafe_storage",
378
797
  "Machine credential files must be owner-only regular files."
379
798
  );
380
799
  }
381
- raw = readFileSync5(path, "utf8");
800
+ raw = readFileSync7(path, "utf8");
382
801
  } catch (error) {
383
802
  if (error.code === "ENOENT") return void 0;
384
803
  throw error;
@@ -423,7 +842,7 @@ function parseProfile(value) {
423
842
  };
424
843
  }
425
844
  function readMachineProfile(deps = {}) {
426
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
845
+ const value = readPrivate(join10(configurationDirectory(deps), PROFILE_FILE));
427
846
  return value === void 0 ? void 0 : parseProfile(value);
428
847
  }
429
848
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -432,20 +851,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
432
851
  var brokerKeys = /* @__PURE__ */ new Map();
433
852
  function networkSecretBrokerKey(deps, clientId) {
434
853
  const directory = configurationDirectory(deps);
435
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
854
+ const path = join10(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
436
855
  const known = brokerKeys.get(path);
437
856
  if (known) return known;
438
857
  ensureDirectory(directory);
439
858
  const read = () => {
440
859
  try {
441
- const stat = lstatSync3(path);
860
+ const stat = lstatSync5(path);
442
861
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
443
862
  throw new MachineAuthError(
444
863
  "unsafe_storage",
445
864
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
446
865
  true
447
866
  );
448
- const value = readFileSync5(path, "utf8").trim();
867
+ const value = readFileSync7(path, "utf8").trim();
449
868
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
450
869
  } catch (error) {
451
870
  if (error.code === "ENOENT") return void 0;
@@ -464,16 +883,16 @@ function networkSecretBrokerKey(deps, clientId) {
464
883
  `The machine broker key at ${path} is damaged. Delete it and retry.`,
465
884
  true
466
885
  );
467
- const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
886
+ const staged = `${path}.${process.pid}.${randomBytes4(6).toString("hex")}`;
468
887
  try {
469
- writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
888
+ writeFileSync4(staged, `${randomBytes4(32).toString("hex")}
470
889
  `, { mode: 384, flag: "wx" });
471
890
  protectPath(staged, false);
472
891
  linkSync(staged, path);
473
892
  } catch (error) {
474
893
  if (error.code !== "EEXIST") throw error;
475
894
  } finally {
476
- rmSync5(staged, { force: true });
895
+ rmSync7(staged, { force: true });
477
896
  }
478
897
  }
479
898
  const key = read()?.key;
@@ -506,7 +925,7 @@ function environmentCredentials(deps) {
506
925
  "conflicting_credentials",
507
926
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
508
927
  );
509
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
928
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
510
929
  const credentials = {
511
930
  clientId,
512
931
  generation,
@@ -527,12 +946,12 @@ function environmentCredentials(deps) {
527
946
  return {
528
947
  clientId,
529
948
  clientSecret,
530
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
949
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
531
950
  };
532
951
  }
533
952
  function hasMachineConfiguration(deps = {}) {
534
953
  const env = deps.env ?? process.env;
535
- 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));
954
+ 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));
536
955
  if (configured && env.PRIM_TOKEN?.trim()) {
537
956
  throw new MachineAuthError(
538
957
  "conflicting_credentials",
@@ -544,6 +963,7 @@ function hasMachineConfiguration(deps = {}) {
544
963
  }
545
964
  function machineContext(deps = {}) {
546
965
  if (!hasMachineConfiguration(deps)) return void 0;
966
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
547
967
  const environment = environmentCredentials(deps);
548
968
  if (environment) {
549
969
  if (environmentTerminal === environment.generation) return void 0;
@@ -558,6 +978,7 @@ function machineContext(deps = {}) {
558
978
  return profile;
559
979
  }
560
980
  function cachedMachineCredential(deps = {}) {
981
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
561
982
  const context = machineContext(deps);
562
983
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
563
984
  }
@@ -565,20 +986,20 @@ var environmentTerminal;
565
986
 
566
987
  // src/lib/credentials.ts
567
988
  var CONFIG_DIRECTORY = primConfigDirectory();
568
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
569
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
570
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
571
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
572
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
573
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
574
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
575
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
989
+ var TOKEN_FILE_PATH = join11(CONFIG_DIRECTORY, "token");
990
+ var REFRESH_TOKEN_PATH = join11(CONFIG_DIRECTORY, "refresh_token");
991
+ var TOKEN_EXPIRES_PATH = join11(CONFIG_DIRECTORY, "token_expires_at");
992
+ var TERMINAL_REFRESH_PATH = join11(CONFIG_DIRECTORY, "refresh_terminal");
993
+ var CREDENTIAL_METADATA_PATH = join11(CONFIG_DIRECTORY, "credential_metadata.json");
994
+ var CREDENTIAL_FAMILY_PATH = join11(CONFIG_DIRECTORY, "credential_family.json");
995
+ var CREDENTIAL_MIGRATION_PATH = join11(CONFIG_DIRECTORY, "credential_migration.json");
996
+ var CREDENTIAL_LOCK_PATH = join11(CONFIG_DIRECTORY, "credentials.lock");
576
997
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
577
998
  var CREDENTIAL_MIGRATION_VERSION = 1;
578
999
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
579
1000
  function readTrimmed(path) {
580
1001
  try {
581
- const value = readFileSync6(path, "utf8").trim();
1002
+ const value = readFileSync8(path, "utf8").trim();
582
1003
  return value || void 0;
583
1004
  } catch {
584
1005
  return void 0;
@@ -615,7 +1036,7 @@ function resolveAuthCredential(options = {}) {
615
1036
  return { token: stored, source: "token_file" };
616
1037
  }
617
1038
  function credentialFingerprint(value) {
618
- return createHash4("sha256").update(value).digest("hex");
1039
+ return createHash7("sha256").update(value).digest("hex");
619
1040
  }
620
1041
  function parseLegacyBrokerCredentialMetadata(value) {
621
1042
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -635,7 +1056,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
635
1056
  function readBoundedCredentialJson(path) {
636
1057
  let raw;
637
1058
  try {
638
- raw = readFileSync6(path, "utf8");
1059
+ raw = readFileSync8(path, "utf8");
639
1060
  } catch (error) {
640
1061
  return error.code === "ENOENT" ? void 0 : null;
641
1062
  }
@@ -703,9 +1124,9 @@ function decodeJwtPayload(token) {
703
1124
  }
704
1125
 
705
1126
  // src/daemon/client-instance-id.ts
706
- import { randomBytes as randomBytes4 } from "crypto";
707
- import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
708
- import { join as join8 } from "path";
1127
+ import { randomBytes as randomBytes5 } from "crypto";
1128
+ import { chmodSync as chmodSync3, lstatSync as lstatSync6, readFileSync as readFileSync9 } from "fs";
1129
+ import { join as join12 } from "path";
709
1130
  var INSTANCE_BODY_CHARS = 43;
710
1131
  var INSTANCE_PREFIX = "pci_";
711
1132
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -713,63 +1134,24 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
713
1134
  // src/lib/ingest-uploader.ts
714
1135
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
715
1136
 
716
- // src/lib/terminal-safe.ts
717
- function replaceIsolatedSurrogates(value) {
718
- let out = "";
719
- for (let index = 0; index < value.length; index += 1) {
720
- const unit = value.charCodeAt(index);
721
- if (unit >= 55296 && unit <= 56319) {
722
- const next = value.charCodeAt(index + 1);
723
- if (next >= 56320 && next <= 57343) {
724
- out += value[index] + value[index + 1];
725
- index += 1;
726
- } else {
727
- out += "\uFFFD";
728
- }
729
- } else if (unit >= 56320 && unit <= 57343) {
730
- out += "\uFFFD";
731
- } else {
732
- out += value[index];
733
- }
734
- }
735
- return out;
736
- }
737
- function isUnsafeTerminalCodePoint(point) {
738
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
739
- const bidiOrZeroWidth = point === 173 || // soft hyphen
740
- point === 1564 || // Arabic letter mark
741
- point === 6158 || // Mongolian vowel separator
742
- point >= 8203 && point <= 8207 || // zero-width + directional marks
743
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
744
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
745
- point >= 65529 && point <= 65531 || // interlinear annotation controls
746
- point === 65279 || // zero-width no-break space / BOM
747
- point >= 917504 && point <= 917631;
748
- return c0OrC1 || bidiOrZeroWidth;
749
- }
750
- function terminalSafeText(value) {
751
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
752
- }
753
- var stripControlChars = terminalSafeText;
754
-
755
1137
  // src/client.ts
756
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1138
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
757
1139
  function getSiteUrl() {
758
1140
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
759
1141
  }
760
1142
  function getSiteUrlForEnvironment(primApiUrl) {
761
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1143
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
762
1144
  }
763
1145
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
764
1146
 
765
1147
  // src/daemon/principal.ts
766
- import { createHash as createHash6 } from "crypto";
1148
+ import { createHash as createHash9 } from "crypto";
767
1149
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
768
1150
  function boundedClaim(value) {
769
1151
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
770
1152
  }
771
1153
  function sha256(value) {
772
- return createHash6("sha256").update(value).digest("hex");
1154
+ return createHash9("sha256").update(value).digest("hex");
773
1155
  }
774
1156
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
775
1157
  if (hasMachineConfiguration()) {
@@ -820,8 +1202,8 @@ function parseDaemonResponseEnvelope(value) {
820
1202
 
821
1203
  // src/daemon/client.ts
822
1204
  import { createConnection } from "net";
823
- import { join as join10 } from "path";
824
- var SOCK_PATH = join10(primConfigDirectory(), "sock");
1205
+ import { join as join14 } from "path";
1206
+ var SOCK_PATH = join14(primConfigDirectory(), "sock");
825
1207
  var DEFAULT_TIMEOUT_MS = 250;
826
1208
  var nextRequestId = 1;
827
1209
  function daemonRequest(method, params = {}, opts = {}) {
@@ -834,7 +1216,7 @@ function daemonRequest(method, params = {}, opts = {}) {
834
1216
  ...caller ? { caller } : {}
835
1217
  };
836
1218
  const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;
837
- return new Promise((resolve4) => {
1219
+ return new Promise((resolve5) => {
838
1220
  let settled = false;
839
1221
  let socket;
840
1222
  let buffer = Buffer.alloc(0);
@@ -849,7 +1231,7 @@ function daemonRequest(method, params = {}, opts = {}) {
849
1231
  } catch {
850
1232
  }
851
1233
  }
852
- resolve4(value);
1234
+ resolve5(value);
853
1235
  };
854
1236
  const timer = setTimeout(() => settle(null), timeoutMs);
855
1237
  timer.unref();
@@ -912,38 +1294,38 @@ function daemonRequest(method, params = {}, opts = {}) {
912
1294
 
913
1295
  // src/lib/activation.ts
914
1296
  import { execFileSync as execFileSync4 } from "child_process";
915
- import { existsSync as existsSync6, readFileSync as readFileSync11 } from "fs";
1297
+ import { existsSync as existsSync8, readFileSync as readFileSync12 } from "fs";
916
1298
  import { homedir as homedir2 } from "os";
917
- import { join as join13 } from "path";
1299
+ import { join as join16 } from "path";
918
1300
 
919
1301
  // src/lib/cloud-prepared.ts
920
- import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync9, rmSync as rmSync7, writeFileSync as writeFileSync4 } from "fs";
921
- import { join as join11 } from "path";
1302
+ import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync11, rmSync as rmSync9, writeFileSync as writeFileSync5 } from "fs";
1303
+ import { join as join15 } from "path";
922
1304
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
923
1305
  function cloudPreparedPath(env = process.env) {
924
- return join11(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1306
+ return join15(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
925
1307
  }
926
1308
  function isPreparedCloudSession(env = process.env) {
927
1309
  if (!isClaudeCloudSession(env)) return false;
928
1310
  try {
929
- return existsSync5(cloudPreparedPath(env));
1311
+ return existsSync7(cloudPreparedPath(env));
930
1312
  } catch {
931
1313
  return false;
932
1314
  }
933
1315
  }
934
1316
 
935
1317
  // src/lib/demo-pause.ts
936
- import { execFileSync as execFileSync2 } from "child_process";
1318
+ import { execFileSync as execFileSync3 } from "child_process";
937
1319
  var DEMO_PAUSE_MS = 30 * 6e4;
938
1320
  var PAUSE_KEY = "prim.demoPause";
939
- var GIT_TIMEOUT_MS = 1e3;
1321
+ var GIT_TIMEOUT_MS2 = 1e3;
940
1322
  function git(cwd, args) {
941
1323
  try {
942
- return execFileSync2("git", args, {
1324
+ return execFileSync3("git", args, {
943
1325
  cwd,
944
1326
  encoding: "utf-8",
945
1327
  stdio: ["ignore", "pipe", "ignore"],
946
- timeout: GIT_TIMEOUT_MS
1328
+ timeout: GIT_TIMEOUT_MS2
947
1329
  });
948
1330
  } catch {
949
1331
  return void 0;
@@ -951,10 +1333,10 @@ function git(cwd, args) {
951
1333
  }
952
1334
  function setLocal(cwd, key, value) {
953
1335
  try {
954
- execFileSync2(
1336
+ execFileSync3(
955
1337
  "git",
956
1338
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
957
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1339
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
958
1340
  );
959
1341
  } catch (error) {
960
1342
  if (value !== null || error.status !== 5) throw error;
@@ -993,114 +1375,6 @@ function healDemoPause(cwd, pause, options = {}) {
993
1375
  }
994
1376
  }
995
1377
 
996
- // src/lib/git.ts
997
- import { execFileSync as execFileSync3 } from "child_process";
998
- import { createHash as createHash7 } from "crypto";
999
- import { lstatSync as lstatSync5, readFileSync as readFileSync10, realpathSync } from "fs";
1000
- import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, join as join12, relative, resolve as resolve2, sep } from "path";
1001
- var GIT_TIMEOUT_MS2 = 1e3;
1002
- var MAX_SETTINGS_BYTES = 1024 * 1024;
1003
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
1004
- var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
1005
- function gitToplevel(cwd) {
1006
- try {
1007
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
1008
- cwd,
1009
- encoding: "utf-8",
1010
- stdio: ["ignore", "pipe", "ignore"],
1011
- timeout: GIT_TIMEOUT_MS2
1012
- }).trim();
1013
- } catch {
1014
- return null;
1015
- }
1016
- }
1017
- function gitValue(cwd, args) {
1018
- try {
1019
- const value = execFileSync3("git", args, {
1020
- cwd,
1021
- encoding: "utf-8",
1022
- stdio: ["ignore", "pipe", "ignore"],
1023
- timeout: GIT_TIMEOUT_MS2
1024
- }).trim();
1025
- return value || void 0;
1026
- } catch {
1027
- return void 0;
1028
- }
1029
- }
1030
- function parseGithubRepositoryName(path) {
1031
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
1032
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
1033
- return null;
1034
- }
1035
- return `${parts[0]}/${parts[1]}`;
1036
- }
1037
- function githubRepositoryFromRemote(remote) {
1038
- if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
1039
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
1040
- remote
1041
- );
1042
- const path = match?.[1] ?? match?.[2];
1043
- return path ? parseGithubRepositoryName(path) : null;
1044
- }
1045
- function checkoutSettingsText(repoRoot) {
1046
- const path = join12(repoRoot, ".claude", "settings.json");
1047
- try {
1048
- if (!lstatSync5(join12(repoRoot, ".claude")).isDirectory()) return null;
1049
- const stat = lstatSync5(path);
1050
- if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
1051
- return readFileSync10(path, "utf8");
1052
- } catch {
1053
- return null;
1054
- }
1055
- }
1056
- function checkoutDeclaration(repoRoot, name) {
1057
- const text = checkoutSettingsText(repoRoot);
1058
- if (text === null) return null;
1059
- let parsed;
1060
- try {
1061
- parsed = JSON.parse(text);
1062
- } catch {
1063
- return null;
1064
- }
1065
- const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
1066
- const value = typeof env === "object" && env !== null ? env[name] : void 0;
1067
- return typeof value === "string" ? value : null;
1068
- }
1069
- function declaredGithubRepository(repoRoot) {
1070
- const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
1071
- return value === null ? null : parseGithubRepositoryName(value.trim());
1072
- }
1073
- function githubRepositoryFullName(cwd) {
1074
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
1075
- if (remote) {
1076
- const fromOrigin = githubRepositoryFromRemote(remote);
1077
- if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
1078
- }
1079
- const root = gitToplevel(cwd);
1080
- return root ? declaredGithubRepository(root) : null;
1081
- }
1082
- function normalizeOriginRemote(remote) {
1083
- const value = remote.trim();
1084
- if (!value) return void 0;
1085
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
1086
- if (scp?.host && scp.path) {
1087
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1088
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
1089
- }
1090
- try {
1091
- const url = new URL(value);
1092
- url.username = "";
1093
- url.password = "";
1094
- url.search = "";
1095
- url.hash = "";
1096
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
1097
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
1098
- return void 0;
1099
- } catch {
1100
- return void 0;
1101
- }
1102
- }
1103
-
1104
1378
  // src/lib/activation.ts
1105
1379
  var PRIM_ACTIVE_KEY = "prim.active";
1106
1380
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1163,10 +1437,10 @@ function repositoryBindingState(cwd) {
1163
1437
  function projectPrimInstallAt(root) {
1164
1438
  if (root === null || root === homedir2()) return false;
1165
1439
  for (const rel of PROJECT_INSTALL_FILES) {
1166
- const path = join13(root, rel);
1167
- if (existsSync6(path)) {
1440
+ const path = join16(root, rel);
1441
+ if (existsSync8(path)) {
1168
1442
  try {
1169
- const content = readFileSync11(path, "utf-8");
1443
+ const content = readFileSync12(path, "utf-8");
1170
1444
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
1171
1445
  } catch {
1172
1446
  }
@@ -1329,17 +1603,17 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
1329
1603
  var STATUSLINE_TIMEOUT_MS = 200;
1330
1604
  function readPackageVersion() {
1331
1605
  try {
1332
- const here = dirname7(fileURLToPath4(import.meta.url));
1606
+ const here = dirname9(fileURLToPath5(import.meta.url));
1333
1607
  const candidates = [
1334
1608
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
1335
1609
  // Keep resolving it while those legacy launchers transition to schema v3.
1336
- resolve3(here, "manifest.json"),
1337
- resolve3(here, "../../package.json"),
1338
- resolve3(here, "../package.json")
1610
+ resolve4(here, "manifest.json"),
1611
+ resolve4(here, "../../package.json"),
1612
+ resolve4(here, "../package.json")
1339
1613
  ];
1340
1614
  for (const path of candidates) {
1341
1615
  try {
1342
- const pkg = JSON.parse(readFileSync12(path, "utf-8"));
1616
+ const pkg = JSON.parse(readFileSync13(path, "utf-8"));
1343
1617
  if (pkg.version) {
1344
1618
  return pkg.version;
1345
1619
  }
@@ -1381,7 +1655,7 @@ async function renderStatusline(cwd = process.cwd()) {
1381
1655
  // src/hooks/hook-stdin.ts
1382
1656
  var DEFAULT_MAX_BYTES = 1024 * 1024;
1383
1657
  function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1384
- return new Promise((resolve4, reject) => {
1658
+ return new Promise((resolve5, reject) => {
1385
1659
  const chunks = [];
1386
1660
  let bytes = 0;
1387
1661
  let settled = false;
@@ -1393,7 +1667,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1393
1667
  process.stdin.removeAllListeners("end");
1394
1668
  process.stdin.removeAllListeners("error");
1395
1669
  if (error) reject(error);
1396
- else resolve4(Buffer.concat(chunks, bytes).toString("utf-8"));
1670
+ else resolve5(Buffer.concat(chunks, bytes).toString("utf-8"));
1397
1671
  };
1398
1672
  const timer = setTimeout(() => finish(new Error("stdin read timeout")), timeoutMs);
1399
1673
  process.stdin.on("data", (chunk) => {