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