@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128

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 (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
@@ -2,19 +2,28 @@
2
2
  import { createRequire as __primCreateRequire } from "node:module"; const require = __primCreateRequire(import.meta.url);
3
3
 
4
4
  // src/daemon/principal.ts
5
- import { createHash as createHash5 } from "crypto";
5
+ import { createHash as createHash7 } from "crypto";
6
6
 
7
7
  // src/lib/credentials.ts
8
- import { createHash as createHash4 } from "crypto";
9
- import { readFileSync as readFileSync6 } from "fs";
10
- import { join as join7 } from "path";
8
+ import { createHash as createHash6 } from "crypto";
9
+ import { readFileSync as readFileSync7 } from "fs";
10
+ import { join as join9 } from "path";
11
11
 
12
12
  // src/lib/machine-credentials.ts
13
- import { execFileSync } from "child_process";
14
- import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
15
- import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
13
+ import { execFileSync as execFileSync2 } from "child_process";
14
+ import { createHash as createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
15
+ import {
16
+ chmodSync,
17
+ existsSync as existsSync3,
18
+ linkSync,
19
+ lstatSync as lstatSync4,
20
+ mkdirSync as mkdirSync3,
21
+ readFileSync as readFileSync6,
22
+ rmSync as rmSync6,
23
+ writeFileSync as writeFileSync3
24
+ } from "fs";
16
25
  import { createRequire } from "module";
17
- import { dirname as dirname4, join as join6 } from "path";
26
+ import { dirname as dirname5, join as join8 } from "path";
18
27
  import { fileURLToPath as fileURLToPath3 } from "url";
19
28
 
20
29
  // src/lib/atomic-file.ts
@@ -64,6 +73,7 @@ var PRIM_CONFIG_SHELL_RESOLVER = [
64
73
  'else prim_home=${HOME:-}; prim_absolute "$prim_home" || exit 78; case "$prim_home" in /) prim_config=/.config/prim ;; *) prim_config="$prim_home/.config/prim" ;; esac; ',
65
74
  "fi; fi; "
66
75
  ].join("");
76
+ var LAUNCHER_EXEC = 'exec "$prim_launcher" "$@"';
67
77
  function stableHookCommand(bin, args = "") {
68
78
  if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
69
79
  throw new Error("invalid stable hook command");
@@ -75,7 +85,7 @@ function stableHookCommand(bin, args = "") {
75
85
  `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
76
86
  PRIM_CONFIG_SHELL_RESOLVER,
77
87
  `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
78
- 'exec "$prim_launcher" "$@"'
88
+ LAUNCHER_EXEC
79
89
  ].join("");
80
90
  const suffix = args ? ` ${args}` : "";
81
91
  return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
@@ -84,6 +94,17 @@ function detachedHookShimCommand(bin, args = "") {
84
94
  return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
85
95
  }
86
96
 
97
+ // src/lib/loopback-fetch.ts
98
+ import { request } from "http";
99
+ import { Readable } from "stream";
100
+
101
+ // src/lib/cloud-env.ts
102
+ function isClaudeCloudSession(env = process.env) {
103
+ return env.CLAUDE_CODE_REMOTE === "true";
104
+ }
105
+ 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';
106
+ 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}.`;
107
+
87
108
  // src/lib/workos-connect.ts
88
109
  var DISCOVERY_MAX_BYTES = 16 * 1024;
89
110
  var WORKOS_CONNECT_RESPONSE_MAX_BYTES = 64 * 1024;
@@ -259,31 +280,331 @@ function primConfigDirectory(options = {}) {
259
280
 
260
281
  // src/lib/machine-broker.ts
261
282
  var MAX_RESPONSE_BYTES = 96 * 1024;
283
+ var MAX_FORWARD_REQUEST_BYTES = 12 * 1024 * 1024;
284
+ var MAX_API_RESPONSE_BYTES = 8 * 1024 * 1024;
285
+ var MAX_FORWARD_RESPONSE_BYTES = 36 * 1024 * 1024;
262
286
  var IDLE_MS = 5 * 6e4;
263
287
 
264
288
  // src/lib/machine-retry.ts
265
289
  import { createHash as createHash2 } from "crypto";
266
- import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
290
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rmSync as rmSync4 } from "fs";
267
291
  import { join as join5 } from "path";
292
+ var MAX_SERVER_WAIT_MS = 15 * 6e4;
293
+
294
+ // src/lib/session-identity.ts
295
+ import { execFile } from "child_process";
296
+ import { createHash as createHash4 } from "crypto";
297
+ import { rmSync as rmSync5 } from "fs";
298
+ import { join as join7 } from "path";
299
+ import { promisify } from "util";
300
+
301
+ // src/lib/git.ts
302
+ import { execFileSync } from "child_process";
303
+ import { createHash as createHash3 } from "crypto";
304
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
305
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
306
+ var GIT_TIMEOUT_MS = 1e3;
307
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
308
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
309
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
310
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
311
+ function gitChildEnvironment(env = process.env) {
312
+ return Object.fromEntries(
313
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
314
+ );
315
+ }
316
+ function gitToplevel(cwd) {
317
+ try {
318
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
319
+ cwd,
320
+ encoding: "utf-8",
321
+ stdio: ["ignore", "pipe", "ignore"],
322
+ timeout: GIT_TIMEOUT_MS,
323
+ env: gitChildEnvironment()
324
+ }).trim();
325
+ } catch {
326
+ return null;
327
+ }
328
+ }
329
+ function gitValue(cwd, args) {
330
+ try {
331
+ const value = execFileSync("git", args, {
332
+ cwd,
333
+ encoding: "utf-8",
334
+ stdio: ["ignore", "pipe", "ignore"],
335
+ timeout: GIT_TIMEOUT_MS,
336
+ env: gitChildEnvironment()
337
+ }).trim();
338
+ return value || void 0;
339
+ } catch {
340
+ return void 0;
341
+ }
342
+ }
343
+ function parseGithubRepositoryName(path) {
344
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
345
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
346
+ return null;
347
+ }
348
+ return `${parts[0]}/${parts[1]}`;
349
+ }
350
+ function githubRepositoryFromRemote(remote) {
351
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
352
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
353
+ remote
354
+ );
355
+ const path = match?.[1] ?? match?.[2];
356
+ return path ? parseGithubRepositoryName(path) : null;
357
+ }
358
+ function checkoutSettingsText(repoRoot) {
359
+ const path = join6(repoRoot, ".claude", "settings.json");
360
+ try {
361
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
362
+ const stat = lstatSync3(path);
363
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
364
+ return readFileSync5(path, "utf8");
365
+ } catch {
366
+ return null;
367
+ }
368
+ }
369
+ function checkoutDeclaration(repoRoot, name) {
370
+ const text = checkoutSettingsText(repoRoot);
371
+ if (text === null) return null;
372
+ let parsed;
373
+ try {
374
+ parsed = JSON.parse(text);
375
+ } catch {
376
+ return null;
377
+ }
378
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
379
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
380
+ return typeof value === "string" ? value : null;
381
+ }
382
+ function declaredGithubRepository(repoRoot) {
383
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
384
+ return value === null ? null : parseGithubRepositoryName(value.trim());
385
+ }
386
+ function githubRepositoryFullName(cwd) {
387
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
388
+ if (remote) {
389
+ const fromOrigin = githubRepositoryFromRemote(remote);
390
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
391
+ }
392
+ const root = gitToplevel(cwd);
393
+ return root ? declaredGithubRepository(root) : null;
394
+ }
395
+ function normalizeOriginRemote(remote) {
396
+ const value = remote.trim();
397
+ if (!value) return void 0;
398
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
399
+ if (scp?.host && scp.path) {
400
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
401
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
402
+ }
403
+ try {
404
+ const url = new URL(value);
405
+ url.username = "";
406
+ url.password = "";
407
+ url.search = "";
408
+ url.hash = "";
409
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
410
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
411
+ return void 0;
412
+ } catch {
413
+ return void 0;
414
+ }
415
+ }
416
+ function opaqueRepoKey(source, value) {
417
+ return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
418
+ }
419
+ function resolveRepositoryContext(cwd = process.cwd()) {
420
+ const top = gitToplevel(cwd);
421
+ if (!top) return null;
422
+ let repoRoot;
423
+ try {
424
+ repoRoot = realpathSync.native(top);
425
+ } catch {
426
+ repoRoot = resolve(top);
427
+ }
428
+ const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
429
+ const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
430
+ const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
431
+ if (normalizedOrigin) {
432
+ return {
433
+ repoRoot,
434
+ repoKey: opaqueRepoKey("origin", normalizedOrigin),
435
+ identitySource: "origin",
436
+ repoFullName
437
+ };
438
+ }
439
+ if (repoFullName) {
440
+ return {
441
+ repoRoot,
442
+ repoKey: opaqueRepoKey("origin", `github.com/${repoFullName}`),
443
+ identitySource: "declared",
444
+ repoFullName
445
+ };
446
+ }
447
+ const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
448
+ if (roots && roots.length > 0) {
449
+ return {
450
+ repoRoot,
451
+ repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
452
+ identitySource: "root_commit",
453
+ repoFullName
454
+ };
455
+ }
456
+ return { repoRoot, repoFullName };
457
+ }
458
+
459
+ // src/lib/session-identity.ts
460
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
461
+ var SESSION_IDENTITY_VALUE = "session";
462
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
463
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
464
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
465
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
466
+ var RENEW_BEFORE_MS = 6e4;
467
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
468
+ var RESPONSE_MAX_BYTES = 64 * 1024;
469
+ function sessionIdentityRequested(env = process.env) {
470
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
471
+ }
472
+ function sessionIdentityMode(deps = {}) {
473
+ const env = deps.env ?? process.env;
474
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
475
+ }
476
+ function failure(code, cause, remedy) {
477
+ return { status: "failed", code, cause, remedy };
478
+ }
479
+ var NEW_SESSION_REMEDY = "start a new cloud session";
480
+ var SESSION_REVOKED = failure(
481
+ "session_revoked",
482
+ "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",
483
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
484
+ );
485
+ var CHALLENGE_WINDOW_PASSED = failure(
486
+ "challenge_expired",
487
+ "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)",
488
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
489
+ );
490
+ var CHALLENGE_GONE = failure(
491
+ "challenge_not_found",
492
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
493
+ NEW_SESSION_REMEDY
494
+ );
495
+ function hash(value) {
496
+ return createHash4("sha256").update(value).digest("hex");
497
+ }
498
+ function sessionContext(deps) {
499
+ const env = deps.env ?? process.env;
500
+ const environment = environmentCredentials(deps);
501
+ if (!environment)
502
+ return failure(
503
+ "environment_credential_missing",
504
+ "the cloud environment has no environment credential",
505
+ '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'
506
+ );
507
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
508
+ if (!sessionId || !SESSION_ID.test(sessionId))
509
+ return failure(
510
+ "session_id_missing",
511
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
512
+ NEW_SESSION_REMEDY
513
+ );
514
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
515
+ const directory = deps.directory ?? primConfigDirectory({ env });
516
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
517
+ return {
518
+ directory,
519
+ apiUrl,
520
+ clientId: environment.clientId,
521
+ generation: environment.generation,
522
+ sessionId,
523
+ tokenPath: join7(directory, `session_identity_${key}.json`),
524
+ statePath: join7(directory, `session_identity_${key}.state.json`),
525
+ lockPath: join7(directory, "session-identity.lock")
526
+ };
527
+ }
528
+ function readRecord(path) {
529
+ try {
530
+ const value = readMachineMetadata(path);
531
+ return value === void 0 ? void 0 : machineRecord(value);
532
+ } catch {
533
+ return void 0;
534
+ }
535
+ }
536
+ function finiteNumber(value) {
537
+ return typeof value === "number" && Number.isFinite(value);
538
+ }
539
+ function readToken(context) {
540
+ const data = readRecord(context.tokenPath);
541
+ 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))
542
+ return void 0;
543
+ const identity = data.identity;
544
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
545
+ return void 0;
546
+ return data;
547
+ }
548
+ function tokenValid(record, now = Date.now()) {
549
+ return now < record.expiresAt - RENEW_BEFORE_MS;
550
+ }
551
+ function toCredential(record) {
552
+ return {
553
+ issuer: record.issuer,
554
+ audience: record.audience,
555
+ ...record.identity,
556
+ accessToken: record.accessToken,
557
+ expiresAt: record.expiresAt,
558
+ apiUrl: record.apiUrl,
559
+ generation: record.generation,
560
+ storage: "environment",
561
+ session: {
562
+ userId: record.userId,
563
+ displayName: record.displayName,
564
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
565
+ refreshAfter: record.refreshAfter
566
+ }
567
+ };
568
+ }
569
+ function cachedSessionCredential(deps = {}) {
570
+ if (!sessionIdentityMode(deps)) return void 0;
571
+ let context;
572
+ try {
573
+ context = sessionContext(deps);
574
+ } catch {
575
+ return void 0;
576
+ }
577
+ if ("status" in context) return void 0;
578
+ const record = readToken(context);
579
+ return record && tokenValid(record) ? toCredential(record) : void 0;
580
+ }
581
+ var SERVER_CONTRACT_FAILURE = failure(
582
+ "server_contract",
583
+ "Primitive's answer did not identify the linked member",
584
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
585
+ );
268
586
 
269
587
  // src/lib/machine-credentials.ts
588
+ function sessionScoped(deps) {
589
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
590
+ }
270
591
  var require2 = createRequire(import.meta.url);
271
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
592
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
272
593
  var PROFILE_FILE = "machine_profile.json";
273
594
  var cached;
274
595
  function configurationDirectory(deps) {
275
596
  return deps.directory ?? primConfigDirectory({ env: deps.env });
276
597
  }
277
598
  function apiUrlFor(deps) {
278
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
599
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
279
600
  }
280
- function hash(value) {
281
- return createHash3("sha256").update(value).digest("hex");
601
+ function hash2(value) {
602
+ return createHash5("sha256").update(value).digest("hex");
282
603
  }
283
604
  function environmentContextPath(deps, clientId) {
284
- return join6(
605
+ return join8(
285
606
  configurationDirectory(deps),
286
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
607
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
287
608
  );
288
609
  }
289
610
  function readEnvironmentContext(environment, deps) {
@@ -307,17 +628,47 @@ function readEnvironmentContext(environment, deps) {
307
628
  return void 0;
308
629
  }
309
630
  }
631
+ function protectPath(path, directory) {
632
+ if (process.platform !== "win32") {
633
+ chmodSync(path, directory ? 448 : 384);
634
+ return;
635
+ }
636
+ const encodedPath = Buffer.from(path).toString("base64");
637
+ 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)`;
638
+ execFileSync2(
639
+ "powershell.exe",
640
+ [
641
+ "-NoProfile",
642
+ "-NonInteractive",
643
+ "-EncodedCommand",
644
+ Buffer.from(script, "utf16le").toString("base64")
645
+ ],
646
+ { stdio: "pipe", encoding: "utf8", windowsHide: true }
647
+ );
648
+ }
649
+ function ensureDirectory(directory) {
650
+ mkdirSync3(directory, { recursive: true, mode: 448 });
651
+ if (lstatSync4(directory).isSymbolicLink())
652
+ throw new MachineAuthError(
653
+ "unsafe_storage",
654
+ "Credential directory must not be a symbolic link."
655
+ );
656
+ protectPath(directory, true);
657
+ }
658
+ function readMachineMetadata(path) {
659
+ return readPrivate(path);
660
+ }
310
661
  function readPrivate(path) {
311
662
  let raw;
312
663
  try {
313
- const stat = lstatSync3(path);
664
+ const stat = lstatSync4(path);
314
665
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
315
666
  throw new MachineAuthError(
316
667
  "unsafe_storage",
317
668
  "Machine credential files must be owner-only regular files."
318
669
  );
319
670
  }
320
- raw = readFileSync5(path, "utf8");
671
+ raw = readFileSync6(path, "utf8");
321
672
  } catch (error) {
322
673
  if (error.code === "ENOENT") return void 0;
323
674
  throw error;
@@ -362,13 +713,101 @@ function parseProfile(value) {
362
713
  };
363
714
  }
364
715
  function readMachineProfile(deps = {}) {
365
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
716
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
366
717
  return value === void 0 ? void 0 : parseProfile(value);
367
718
  }
719
+ var NETWORK_SECRET_AUTH = "network-secret";
720
+ var NETWORK_TOKEN_AUTH = "network-token";
721
+ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
722
+ var brokerKeys = /* @__PURE__ */ new Map();
723
+ function networkSecretBrokerKey(deps, clientId) {
724
+ const directory = configurationDirectory(deps);
725
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
726
+ const known = brokerKeys.get(path);
727
+ if (known) return known;
728
+ ensureDirectory(directory);
729
+ const read = () => {
730
+ try {
731
+ const stat = lstatSync4(path);
732
+ if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
733
+ throw new MachineAuthError(
734
+ "unsafe_storage",
735
+ `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
736
+ true
737
+ );
738
+ const value = readFileSync6(path, "utf8").trim();
739
+ return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
740
+ } catch (error) {
741
+ if (error.code === "ENOENT") return void 0;
742
+ throw error;
743
+ }
744
+ };
745
+ for (let attempt = 0; attempt < 2; attempt += 1) {
746
+ const existing = read();
747
+ if (existing?.key) {
748
+ brokerKeys.set(path, existing.key);
749
+ return existing.key;
750
+ }
751
+ if (existing)
752
+ throw new MachineAuthError(
753
+ "unsafe_storage",
754
+ `The machine broker key at ${path} is damaged. Delete it and retry.`,
755
+ true
756
+ );
757
+ const staged = `${path}.${process.pid}.${randomBytes3(6).toString("hex")}`;
758
+ try {
759
+ writeFileSync3(staged, `${randomBytes3(32).toString("hex")}
760
+ `, { mode: 384, flag: "wx" });
761
+ protectPath(staged, false);
762
+ linkSync(staged, path);
763
+ } catch (error) {
764
+ if (error.code !== "EEXIST") throw error;
765
+ } finally {
766
+ rmSync6(staged, { force: true });
767
+ }
768
+ }
769
+ const key = read()?.key;
770
+ if (!key)
771
+ throw new MachineAuthError("unsafe_storage", "The machine broker key is unreadable.", true);
772
+ brokerKeys.set(path, key);
773
+ return key;
774
+ }
368
775
  function environmentCredentials(deps) {
369
776
  const env = deps.env ?? process.env;
370
- const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
371
- if (clientId === void 0 && clientSecret === void 0) return void 0;
777
+ const {
778
+ PRIM_M2M_CLIENT_ID: clientId,
779
+ PRIM_M2M_CLIENT_SECRET: clientSecret,
780
+ PRIM_M2M_CLIENT_AUTH: auth
781
+ } = env;
782
+ if (clientId === void 0 && clientSecret === void 0 && auth === void 0) return void 0;
783
+ if (auth !== void 0 && auth !== NETWORK_SECRET_AUTH && auth !== NETWORK_TOKEN_AUTH)
784
+ throw new MachineAuthError(
785
+ "incomplete_machine_credentials",
786
+ `PRIM_M2M_CLIENT_AUTH accepts ${NETWORK_SECRET_AUTH} or ${NETWORK_TOKEN_AUTH}.`
787
+ );
788
+ if (auth !== void 0) {
789
+ if (!clientId || !/^client_[\w-]+$/u.test(clientId))
790
+ throw new MachineAuthError(
791
+ "incomplete_machine_credentials",
792
+ `Set PRIM_M2M_CLIENT_ID with PRIM_M2M_CLIENT_AUTH=${auth}.`
793
+ );
794
+ if (clientSecret !== void 0)
795
+ throw new MachineAuthError(
796
+ "conflicting_credentials",
797
+ `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
798
+ );
799
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
800
+ const credentials = {
801
+ clientId,
802
+ generation,
803
+ ...auth === NETWORK_TOKEN_AUTH ? { tokenInjection: "network" } : { secretInjection: "network" }
804
+ };
805
+ Object.defineProperty(credentials, "clientSecret", {
806
+ enumerable: true,
807
+ get: () => networkSecretBrokerKey(deps, clientId)
808
+ });
809
+ return credentials;
810
+ }
372
811
  if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
373
812
  throw new MachineAuthError(
374
813
  "incomplete_machine_credentials",
@@ -378,12 +817,12 @@ function environmentCredentials(deps) {
378
817
  return {
379
818
  clientId,
380
819
  clientSecret,
381
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
820
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
382
821
  };
383
822
  }
384
823
  function hasMachineConfiguration(deps = {}) {
385
824
  const env = deps.env ?? process.env;
386
- const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
825
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync3(join8(configurationDirectory(deps), PROFILE_FILE));
387
826
  if (configured && env.PRIM_TOKEN?.trim()) {
388
827
  throw new MachineAuthError(
389
828
  "conflicting_credentials",
@@ -395,6 +834,7 @@ function hasMachineConfiguration(deps = {}) {
395
834
  }
396
835
  function machineContext(deps = {}) {
397
836
  if (!hasMachineConfiguration(deps)) return void 0;
837
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
398
838
  const environment = environmentCredentials(deps);
399
839
  if (environment) {
400
840
  if (environmentTerminal === environment.generation) return void 0;
@@ -409,6 +849,7 @@ function machineContext(deps = {}) {
409
849
  return profile;
410
850
  }
411
851
  function cachedMachineCredential(deps = {}) {
852
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
412
853
  const context = machineContext(deps);
413
854
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
414
855
  }
@@ -416,20 +857,20 @@ var environmentTerminal;
416
857
 
417
858
  // src/lib/credentials.ts
418
859
  var CONFIG_DIRECTORY = primConfigDirectory();
419
- var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
420
- var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
421
- var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
422
- var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
423
- var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
424
- var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
425
- var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
426
- var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
860
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
861
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
862
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
863
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
864
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
865
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
866
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
867
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
427
868
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
428
869
  var CREDENTIAL_MIGRATION_VERSION = 1;
429
870
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
430
871
  function readTrimmed(path) {
431
872
  try {
432
- const value = readFileSync6(path, "utf8").trim();
873
+ const value = readFileSync7(path, "utf8").trim();
433
874
  return value || void 0;
434
875
  } catch {
435
876
  return void 0;
@@ -438,7 +879,7 @@ function readTrimmed(path) {
438
879
  function resolveAuthCredential(options = {}) {
439
880
  if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
440
881
  const machine = cachedMachineCredential({ env: options.env });
441
- return machine ? { token: machine.accessToken, source: "machine" } : void 0;
882
+ return machine?.accessToken ? { token: machine.accessToken, source: "machine" } : void 0;
442
883
  }
443
884
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
444
885
  if (envToken) return { token: envToken, source: "environment" };
@@ -466,7 +907,7 @@ function resolveAuthCredential(options = {}) {
466
907
  return { token: stored, source: "token_file" };
467
908
  }
468
909
  function credentialFingerprint(value) {
469
- return createHash4("sha256").update(value).digest("hex");
910
+ return createHash6("sha256").update(value).digest("hex");
470
911
  }
471
912
  function parseLegacyBrokerCredentialMetadata(value) {
472
913
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -486,7 +927,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
486
927
  function readBoundedCredentialJson(path) {
487
928
  let raw;
488
929
  try {
489
- raw = readFileSync6(path, "utf8");
930
+ raw = readFileSync7(path, "utf8");
490
931
  } catch (error) {
491
932
  return error.code === "ENOENT" ? void 0 : null;
492
933
  }
@@ -559,7 +1000,7 @@ function boundedClaim(value) {
559
1000
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
560
1001
  }
561
1002
  function sha256(value) {
562
- return createHash5("sha256").update(value).digest("hex");
1003
+ return createHash7("sha256").update(value).digest("hex");
563
1004
  }
564
1005
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
565
1006
  if (hasMachineConfiguration()) {
@@ -610,14 +1051,14 @@ function parseDaemonResponseEnvelope(value) {
610
1051
 
611
1052
  // src/daemon/client.ts
612
1053
  import { createConnection } from "net";
613
- import { join as join8 } from "path";
614
- var SOCK_PATH = join8(primConfigDirectory(), "sock");
1054
+ import { join as join10 } from "path";
1055
+ var SOCK_PATH = join10(primConfigDirectory(), "sock");
615
1056
  var DEFAULT_TIMEOUT_MS = 250;
616
1057
  var nextRequestId = 1;
617
1058
  function daemonRequest(method, params = {}, opts = {}) {
618
1059
  const id = nextRequestId++;
619
1060
  const caller = resolveDaemonPrincipal();
620
- const request = {
1061
+ const request2 = {
621
1062
  id,
622
1063
  method,
623
1064
  params,
@@ -656,7 +1097,7 @@ function daemonRequest(method, params = {}, opts = {}) {
656
1097
  });
657
1098
  socket.on("connect", () => {
658
1099
  try {
659
- socket?.write(`${JSON.stringify(request)}
1100
+ socket?.write(`${JSON.stringify(request2)}
660
1101
  `);
661
1102
  } catch {
662
1103
  clearTimeout(timer);
@@ -702,22 +1143,38 @@ function daemonRequest(method, params = {}, opts = {}) {
702
1143
 
703
1144
  // src/lib/activation.ts
704
1145
  import { execFileSync as execFileSync4 } from "child_process";
705
- import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
1146
+ import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
706
1147
  import { homedir as homedir2 } from "os";
707
- import { join as join9 } from "path";
1148
+ import { join as join12 } from "path";
1149
+
1150
+ // src/lib/cloud-prepared.ts
1151
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync7, writeFileSync as writeFileSync4 } from "fs";
1152
+ import { join as join11 } from "path";
1153
+ var CLOUD_PREPARED_MARKER = "cloud-prepared";
1154
+ function cloudPreparedPath(env = process.env) {
1155
+ return join11(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1156
+ }
1157
+ function isPreparedCloudSession(env = process.env) {
1158
+ if (!isClaudeCloudSession(env)) return false;
1159
+ try {
1160
+ return existsSync4(cloudPreparedPath(env));
1161
+ } catch {
1162
+ return false;
1163
+ }
1164
+ }
708
1165
 
709
1166
  // src/lib/demo-pause.ts
710
- import { execFileSync as execFileSync2 } from "child_process";
1167
+ import { execFileSync as execFileSync3 } from "child_process";
711
1168
  var DEMO_PAUSE_MS = 30 * 6e4;
712
1169
  var PAUSE_KEY = "prim.demoPause";
713
- var GIT_TIMEOUT_MS = 1e3;
1170
+ var GIT_TIMEOUT_MS2 = 1e3;
714
1171
  function git(cwd, args) {
715
1172
  try {
716
- return execFileSync2("git", args, {
1173
+ return execFileSync3("git", args, {
717
1174
  cwd,
718
1175
  encoding: "utf-8",
719
1176
  stdio: ["ignore", "pipe", "ignore"],
720
- timeout: GIT_TIMEOUT_MS
1177
+ timeout: GIT_TIMEOUT_MS2
721
1178
  });
722
1179
  } catch {
723
1180
  return void 0;
@@ -725,10 +1182,10 @@ function git(cwd, args) {
725
1182
  }
726
1183
  function setLocal(cwd, key, value) {
727
1184
  try {
728
- execFileSync2(
1185
+ execFileSync3(
729
1186
  "git",
730
1187
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
731
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1188
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
732
1189
  );
733
1190
  } catch (error) {
734
1191
  if (value !== null || error.status !== 5) throw error;
@@ -767,111 +1224,9 @@ function healDemoPause(cwd, pause, options = {}) {
767
1224
  }
768
1225
  }
769
1226
 
770
- // src/lib/git.ts
771
- import { execFileSync as execFileSync3 } from "child_process";
772
- import { createHash as createHash6 } from "crypto";
773
- import { lstatSync as lstatSync4, realpathSync } from "fs";
774
- import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve, sep } from "path";
775
- var GIT_TIMEOUT_MS2 = 1e3;
776
- var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
777
- var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
778
- function gitToplevel(cwd) {
779
- try {
780
- return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
781
- cwd,
782
- encoding: "utf-8",
783
- stdio: ["ignore", "pipe", "ignore"],
784
- timeout: GIT_TIMEOUT_MS2
785
- }).trim();
786
- } catch {
787
- return null;
788
- }
789
- }
790
- function gitValue(cwd, args) {
791
- try {
792
- const value = execFileSync3("git", args, {
793
- cwd,
794
- encoding: "utf-8",
795
- stdio: ["ignore", "pipe", "ignore"],
796
- timeout: GIT_TIMEOUT_MS2
797
- }).trim();
798
- return value || void 0;
799
- } catch {
800
- return void 0;
801
- }
802
- }
803
- function githubRepositoryFullName(cwd) {
804
- const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
805
- if (!remote || [...remote].some((char) => char < " " || char === "\x7F")) return null;
806
- const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
807
- remote
808
- );
809
- const path = match?.[1] ?? match?.[2];
810
- if (!path) return null;
811
- const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
812
- if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
813
- return null;
814
- }
815
- return `${parts[0]}/${parts[1]}`;
816
- }
817
- function normalizeOriginRemote(remote) {
818
- const value = remote.trim();
819
- if (!value) return void 0;
820
- const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
821
- if (scp?.host && scp.path) {
822
- const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
823
- return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
824
- }
825
- try {
826
- const url = new URL(value);
827
- url.username = "";
828
- url.password = "";
829
- url.search = "";
830
- url.hash = "";
831
- const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
832
- if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
833
- return void 0;
834
- } catch {
835
- return void 0;
836
- }
837
- }
838
- function opaqueRepoKey(source, value) {
839
- return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
840
- }
841
- function resolveRepositoryContext(cwd = process.cwd()) {
842
- const top = gitToplevel(cwd);
843
- if (!top) return null;
844
- let repoRoot;
845
- try {
846
- repoRoot = realpathSync.native(top);
847
- } catch {
848
- repoRoot = resolve(top);
849
- }
850
- const origin = gitValue(repoRoot, ["config", "--get", "remote.origin.url"]);
851
- const repoFullName = githubRepositoryFullName(repoRoot) ?? void 0;
852
- const normalizedOrigin = origin ? normalizeOriginRemote(origin) : void 0;
853
- if (normalizedOrigin) {
854
- return {
855
- repoRoot,
856
- repoKey: opaqueRepoKey("origin", normalizedOrigin),
857
- identitySource: "origin",
858
- repoFullName
859
- };
860
- }
861
- const roots = gitValue(repoRoot, ["rev-list", "--max-parents=0", "HEAD"])?.split(/\s+/).filter(Boolean).sort();
862
- if (roots && roots.length > 0) {
863
- return {
864
- repoRoot,
865
- repoKey: opaqueRepoKey("root_commit", roots.join("\n")),
866
- identitySource: "root_commit",
867
- repoFullName
868
- };
869
- }
870
- return { repoRoot, repoFullName };
871
- }
872
-
873
1227
  // src/lib/activation.ts
874
1228
  var PRIM_ACTIVE_KEY = "prim.active";
1229
+ var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
875
1230
  var GIT_TIMEOUT_MS3 = 1e3;
876
1231
  var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cursor/hooks.json"];
877
1232
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
@@ -893,14 +1248,13 @@ function repoActiveFlag(cwd, strict = false) {
893
1248
  return void 0;
894
1249
  }
895
1250
  }
896
- function hasProjectPrimInstall(cwd) {
897
- const root = gitToplevel(cwd);
1251
+ function projectPrimInstallAt(root) {
898
1252
  if (root === null || root === homedir2()) return false;
899
1253
  for (const rel of PROJECT_INSTALL_FILES) {
900
- const path = join9(root, rel);
901
- if (existsSync4(path)) {
1254
+ const path = join12(root, rel);
1255
+ if (existsSync5(path)) {
902
1256
  try {
903
- const content = readFileSync7(path, "utf-8");
1257
+ const content = readFileSync9(path, "utf-8");
904
1258
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
905
1259
  } catch {
906
1260
  }
@@ -908,12 +1262,27 @@ function hasProjectPrimInstall(cwd) {
908
1262
  }
909
1263
  return false;
910
1264
  }
1265
+ var UNPARSED_OPT_OUT = /"PRIM_ACTIVE"\s*:\s*"\s*false\s*"/u;
1266
+ function declaresInactiveAt(root) {
1267
+ if (root === null || root === homedir2()) return false;
1268
+ if (checkoutDeclaration(root, PRIM_ACTIVE_DECLARATION)?.trim() === "false") return true;
1269
+ const text = checkoutSettingsText(root);
1270
+ if (text === null || !UNPARSED_OPT_OUT.test(text)) return false;
1271
+ try {
1272
+ JSON.parse(text);
1273
+ return false;
1274
+ } catch {
1275
+ return true;
1276
+ }
1277
+ }
911
1278
  function isRepoActiveForCapture(cwd, options = {}) {
912
1279
  let { active: flag, pause } = readCaptureConfig(cwd);
913
1280
  if (pause && healDemoPause(cwd, pause, options)) flag = repoActiveFlag(cwd);
914
1281
  if (flag === "true") return true;
915
1282
  if (flag === "false") return false;
916
- return hasProjectPrimInstall(cwd);
1283
+ const root = gitToplevel(cwd);
1284
+ if (declaresInactiveAt(root)) return false;
1285
+ return projectPrimInstallAt(root) || isPreparedCloudSession() && root !== null;
917
1286
  }
918
1287
 
919
1288
  // src/hooks/agent.ts
@@ -927,31 +1296,31 @@ function parseAgent(argv) {
927
1296
  }
928
1297
 
929
1298
  // src/commands/cursor-install.ts
930
- import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
1299
+ import { existsSync as existsSync9, readFileSync as readFileSync12 } from "fs";
931
1300
  import { homedir as homedir4 } from "os";
932
- import { isAbsolute as isAbsolute5, join as join13 } from "path";
1301
+ import { isAbsolute as isAbsolute5, join as join16 } from "path";
933
1302
 
934
1303
  // src/lib/hook-runtime.ts
935
- import { createHash as createHash7, randomBytes as randomBytes3 } from "crypto";
1304
+ import { createHash as createHash8, randomBytes as randomBytes4 } from "crypto";
936
1305
  import {
937
1306
  constants as constants2,
938
1307
  accessSync,
939
1308
  chmodSync as chmodSync2,
940
1309
  copyFileSync,
941
- existsSync as existsSync6,
1310
+ existsSync as existsSync7,
942
1311
  lstatSync as lstatSync5,
943
- mkdirSync as mkdirSync4,
1312
+ mkdirSync as mkdirSync5,
944
1313
  mkdtempSync,
945
- readFileSync as readFileSync8,
946
- readdirSync,
1314
+ readFileSync as readFileSync10,
1315
+ readdirSync as readdirSync2,
947
1316
  realpathSync as realpathSync2,
948
1317
  renameSync as renameSync2,
949
- rmSync as rmSync6,
1318
+ rmSync as rmSync8,
950
1319
  statSync as statSync2,
951
1320
  utimesSync,
952
- writeFileSync as writeFileSync3
1321
+ writeFileSync as writeFileSync5
953
1322
  } from "fs";
954
- import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join11, resolve as resolve2 } from "path";
1323
+ import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join14, resolve as resolve2 } from "path";
955
1324
 
956
1325
  // src/lib/git-hook-contract.ts
957
1326
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -999,9 +1368,9 @@ exit 0
999
1368
  `;
1000
1369
 
1001
1370
  // src/lib/native-keyring.ts
1002
- import { existsSync as existsSync5 } from "fs";
1371
+ import { existsSync as existsSync6 } from "fs";
1003
1372
  import { createRequire as createRequire2 } from "module";
1004
- import { dirname as dirname6, join as join10 } from "path";
1373
+ import { dirname as dirname6, join as join13 } from "path";
1005
1374
  import { fileURLToPath as fileURLToPath4 } from "url";
1006
1375
  var require3 = createRequire2(import.meta.url);
1007
1376
 
@@ -1055,9 +1424,9 @@ exec "$prim_node" "$prim_entry" "$@"
1055
1424
  import { execFileSync as execFileSync5 } from "child_process";
1056
1425
 
1057
1426
  // src/commands/claude-install.ts
1058
- import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
1427
+ import { existsSync as existsSync8, lstatSync as lstatSync6, readFileSync as readFileSync11 } from "fs";
1059
1428
  import { homedir as homedir3 } from "os";
1060
- import { join as join12 } from "path";
1429
+ import { join as join15 } from "path";
1061
1430
  var CAPTURE_BIN = "prim-hook";
1062
1431
  var GATE_BIN = "prim-pre-tool-use";
1063
1432
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -1066,7 +1435,7 @@ var SESSION_END_BIN = "prim-session-end";
1066
1435
  var STATUSLINE_BIN = "prim-statusline";
1067
1436
  var STATUSLINE_ARGS = "";
1068
1437
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
1069
- var USER_SCOPE_PATH = join12(homedir3(), ".claude", "settings.json");
1438
+ var USER_SCOPE_PATH = join15(homedir3(), ".claude", "settings.json");
1070
1439
  function projectRoot() {
1071
1440
  return gitToplevel() ?? process.cwd();
1072
1441
  }
@@ -1146,20 +1515,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
1146
1515
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
1147
1516
  if (explicit && isAbsolute5(explicit)) return explicit;
1148
1517
  const xdg = env.XDG_CONFIG_HOME?.trim();
1149
- if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join13(xdg, "cursor");
1150
- return join13(home, ".cursor");
1518
+ if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join16(xdg, "cursor");
1519
+ return join16(home, ".cursor");
1151
1520
  }
1152
1521
  function cursorHooksPath(scope, root = projectRoot()) {
1153
- return scope === "user" ? join13(cursorConfigDirectory(), "hooks.json") : join13(root, ".cursor", "hooks.json");
1522
+ return scope === "user" ? join16(cursorConfigDirectory(), "hooks.json") : join16(root, ".cursor", "hooks.json");
1154
1523
  }
1155
1524
  function plainObject(value) {
1156
1525
  return typeof value === "object" && value !== null && !Array.isArray(value);
1157
1526
  }
1158
1527
  function readCursorHooks(path) {
1159
- if (!existsSync8(path)) return {};
1528
+ if (!existsSync9(path)) return {};
1160
1529
  let parsed;
1161
1530
  try {
1162
- parsed = JSON.parse(readFileSync10(path, "utf8"));
1531
+ parsed = JSON.parse(readFileSync12(path, "utf8"));
1163
1532
  } catch {
1164
1533
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
1165
1534
  }
@@ -1302,7 +1671,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1302
1671
  }
1303
1672
 
1304
1673
  // src/hooks/normalize.ts
1305
- import { createHash as createHash8 } from "crypto";
1674
+ import { createHash as createHash9 } from "crypto";
1306
1675
  import { realpathSync as realpathSync3 } from "fs";
1307
1676
  import { isAbsolute as isAbsolute6, resolve as resolve3 } from "path";
1308
1677
  var HERMES_EVENT_MAP = {
@@ -1347,7 +1716,7 @@ function requiredId(value, field) {
1347
1716
  }
1348
1717
  function cursorToolUseId(value) {
1349
1718
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
1350
- return `cursor:tool:v1:${createHash8("sha256").update(value).digest("hex")}`;
1719
+ return `cursor:tool:v1:${createHash9("sha256").update(value).digest("hex")}`;
1351
1720
  }
1352
1721
  function workspaceCandidates(value) {
1353
1722
  if (!Array.isArray(value)) return [];
@@ -1444,7 +1813,7 @@ function normalizeEnvelope(parsed, agent) {
1444
1813
  ]);
1445
1814
  return {
1446
1815
  ...parsed,
1447
- tool_use_id: `codex:fallback:v1:${createHash8("sha256").update(stableToolIdentity).digest("hex")}`
1816
+ tool_use_id: `codex:fallback:v1:${createHash9("sha256").update(stableToolIdentity).digest("hex")}`
1448
1817
  };
1449
1818
  }
1450
1819
  return parsed;