@primitive.ai/prim 0.1.0-alpha.127 → 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 (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
  3. package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
  4. package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
  5. package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
  6. package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
  7. package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
  8. package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
  9. package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
  10. package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
  11. package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
  12. package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
  13. package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
  14. package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
  15. package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
  16. package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
  17. package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
  19. package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
  20. package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
  21. package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
  22. package/dist/daemon/server.js +1311 -364
  23. package/dist/hook-runtime/daemon/server.js +1311 -364
  24. package/dist/hook-runtime/hooks/post-commit.js +395 -242
  25. package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
  27. package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
  29. package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
  30. package/dist/hook-runtime/hooks/session-end.js +369 -216
  31. package/dist/hook-runtime/hooks/session-start.js +1209 -219
  32. package/dist/hook-runtime/index.js +2406 -1036
  33. package/dist/hook-runtime/statusline-main.js +360 -207
  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 +63 -20
  42. package/dist/index.js +387 -43
  43. package/dist/statusline-main.js +360 -207
  44. package/package.json +1 -1
@@ -10,11 +10,13 @@ import { fileURLToPath as fileURLToPath4 } from "url";
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 createHash7 } from "crypto";
18
+ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync9, rmSync as rmSync7 } from "fs";
19
+ import { dirname as dirname6 } from "path";
18
20
 
19
21
  // src/lib/atomic-file.ts
20
22
  import { randomUUID } from "crypto";
@@ -32,25 +34,25 @@ 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 createHash6 } from "crypto";
38
+ import { readFileSync as readFileSync7 } from "fs";
39
+ import { join as join9 } 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 createHash5, randomBytes as randomBytes3, randomUUID as randomUUID2 } from "crypto";
42
44
  import {
43
45
  chmodSync,
44
46
  existsSync as existsSync3,
45
47
  linkSync,
46
- lstatSync as lstatSync3,
48
+ lstatSync as lstatSync4,
47
49
  mkdirSync as mkdirSync3,
48
- readFileSync as readFileSync5,
49
- rmSync as rmSync5,
50
+ readFileSync as readFileSync6,
51
+ rmSync as rmSync6,
50
52
  writeFileSync as writeFileSync3
51
53
  } from "fs";
52
54
  import { createRequire } from "module";
53
- import { dirname as dirname4, join as join6 } from "path";
55
+ import { dirname as dirname5, join as join8 } from "path";
54
56
  import { fileURLToPath as fileURLToPath3 } from "url";
55
57
 
56
58
  // src/lib/file-lock.ts
@@ -301,24 +303,317 @@ import { lstatSync as lstatSync2, readFileSync as readFileSync4, readdirSync, rm
301
303
  import { join as join5 } from "path";
302
304
  var MAX_SERVER_WAIT_MS = 15 * 6e4;
303
305
 
306
+ // src/lib/session-identity.ts
307
+ import { execFile } from "child_process";
308
+ import { createHash as createHash4 } from "crypto";
309
+ import { rmSync as rmSync5 } from "fs";
310
+ import { join as join7 } from "path";
311
+ import { promisify } from "util";
312
+
313
+ // src/lib/git.ts
314
+ import { execFileSync } from "child_process";
315
+ import { createHash as createHash3 } from "crypto";
316
+ import { lstatSync as lstatSync3, readFileSync as readFileSync5, realpathSync } from "fs";
317
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join6, relative, resolve, sep } from "path";
318
+ var GIT_TIMEOUT_MS = 1e3;
319
+ var MAX_SETTINGS_BYTES = 1024 * 1024;
320
+ var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
321
+ var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
322
+ var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
323
+ function gitChildEnvironment(env = process.env) {
324
+ return Object.fromEntries(
325
+ Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
326
+ );
327
+ }
328
+ function gitToplevel(cwd) {
329
+ try {
330
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], {
331
+ cwd,
332
+ encoding: "utf-8",
333
+ stdio: ["ignore", "pipe", "ignore"],
334
+ timeout: GIT_TIMEOUT_MS,
335
+ env: gitChildEnvironment()
336
+ }).trim();
337
+ } catch {
338
+ return null;
339
+ }
340
+ }
341
+ function gitValue(cwd, args) {
342
+ try {
343
+ const value = execFileSync("git", args, {
344
+ cwd,
345
+ encoding: "utf-8",
346
+ stdio: ["ignore", "pipe", "ignore"],
347
+ timeout: GIT_TIMEOUT_MS,
348
+ env: gitChildEnvironment()
349
+ }).trim();
350
+ return value || void 0;
351
+ } catch {
352
+ return void 0;
353
+ }
354
+ }
355
+ function parseGithubRepositoryName(path) {
356
+ const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
357
+ if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
358
+ return null;
359
+ }
360
+ return `${parts[0]}/${parts[1]}`;
361
+ }
362
+ function githubRepositoryFromRemote(remote) {
363
+ if ([...remote].some((char) => char < " " || char === "\x7F")) return null;
364
+ const match = /^(?:git@github\.com:([^?#]+)|(?:https|ssh):\/\/(?:[^/@]+@)?github\.com(?::\d+)?\/([^?#]+))$/i.exec(
365
+ remote
366
+ );
367
+ const path = match?.[1] ?? match?.[2];
368
+ return path ? parseGithubRepositoryName(path) : null;
369
+ }
370
+ function checkoutSettingsText(repoRoot) {
371
+ const path = join6(repoRoot, ".claude", "settings.json");
372
+ try {
373
+ if (!lstatSync3(join6(repoRoot, ".claude")).isDirectory()) return null;
374
+ const stat = lstatSync3(path);
375
+ if (!stat.isFile() || stat.size > MAX_SETTINGS_BYTES) return null;
376
+ return readFileSync5(path, "utf8");
377
+ } catch {
378
+ return null;
379
+ }
380
+ }
381
+ function checkoutDeclaration(repoRoot, name) {
382
+ const text = checkoutSettingsText(repoRoot);
383
+ if (text === null) return null;
384
+ let parsed;
385
+ try {
386
+ parsed = JSON.parse(text);
387
+ } catch {
388
+ return null;
389
+ }
390
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : void 0;
391
+ const value = typeof env === "object" && env !== null ? env[name] : void 0;
392
+ return typeof value === "string" ? value : null;
393
+ }
394
+ function declaredGithubRepository(repoRoot) {
395
+ const value = checkoutDeclaration(repoRoot, "PRIM_REPOSITORY");
396
+ return value === null ? null : parseGithubRepositoryName(value.trim());
397
+ }
398
+ function githubRepositoryFullName(cwd) {
399
+ const remote = gitValue(cwd, ["config", "--get", "remote.origin.url"]);
400
+ if (remote) {
401
+ const fromOrigin = githubRepositoryFromRemote(remote);
402
+ if (fromOrigin || normalizeOriginRemote(remote)) return fromOrigin;
403
+ }
404
+ const root = gitToplevel(cwd);
405
+ return root ? declaredGithubRepository(root) : null;
406
+ }
407
+ function normalizeOriginRemote(remote) {
408
+ const value = remote.trim();
409
+ if (!value) return void 0;
410
+ const scp = !value.includes("://") ? /^(?:[^@/\s]+@)?(?<host>[^:/\s]+):(?<path>.+)$/.exec(value)?.groups : void 0;
411
+ if (scp?.host && scp.path) {
412
+ const path = scp.path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
413
+ return path ? `${scp.host.toLowerCase()}/${path}` : void 0;
414
+ }
415
+ try {
416
+ const url = new URL(value);
417
+ url.username = "";
418
+ url.password = "";
419
+ url.search = "";
420
+ url.hash = "";
421
+ const path = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "");
422
+ if (url.host && path) return `${url.host.toLowerCase()}/${path}`;
423
+ return void 0;
424
+ } catch {
425
+ return void 0;
426
+ }
427
+ }
428
+
429
+ // src/lib/terminal-safe.ts
430
+ function replaceIsolatedSurrogates(value) {
431
+ let out = "";
432
+ for (let index = 0; index < value.length; index += 1) {
433
+ const unit = value.charCodeAt(index);
434
+ if (unit >= 55296 && unit <= 56319) {
435
+ const next = value.charCodeAt(index + 1);
436
+ if (next >= 56320 && next <= 57343) {
437
+ out += value[index] + value[index + 1];
438
+ index += 1;
439
+ } else {
440
+ out += "\uFFFD";
441
+ }
442
+ } else if (unit >= 56320 && unit <= 57343) {
443
+ out += "\uFFFD";
444
+ } else {
445
+ out += value[index];
446
+ }
447
+ }
448
+ return out;
449
+ }
450
+ function isUnsafeTerminalCodePoint(point) {
451
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
452
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
453
+ point === 1564 || // Arabic letter mark
454
+ point === 6158 || // Mongolian vowel separator
455
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
456
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
457
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
458
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
459
+ point === 65279 || // zero-width no-break space / BOM
460
+ point >= 917504 && point <= 917631;
461
+ return c0OrC1 || bidiOrZeroWidth;
462
+ }
463
+ function terminalSafeText(value) {
464
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
465
+ }
466
+ var stripControlChars = terminalSafeText;
467
+
468
+ // src/lib/session-identity.ts
469
+ var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
470
+ var SESSION_IDENTITY_VALUE = "session";
471
+ var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
472
+ var SESSION_TOKEN_PREFIX = "prim_sess_";
473
+ var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
474
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
475
+ var RENEW_BEFORE_MS = 6e4;
476
+ var BACKGROUND_RETRY_MS = 5 * 6e4;
477
+ var RESPONSE_MAX_BYTES = 64 * 1024;
478
+ function sessionIdentityRequested(env = process.env) {
479
+ return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
480
+ }
481
+ function sessionIdentityMode(deps = {}) {
482
+ const env = deps.env ?? process.env;
483
+ return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
484
+ }
485
+ function failure(code, cause, remedy) {
486
+ return { status: "failed", code, cause, remedy };
487
+ }
488
+ var NEW_SESSION_REMEDY = "start a new cloud session";
489
+ var SESSION_REVOKED = failure(
490
+ "session_revoked",
491
+ "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",
492
+ `${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
493
+ );
494
+ var CHALLENGE_WINDOW_PASSED = failure(
495
+ "challenge_expired",
496
+ "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)",
497
+ `${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
498
+ );
499
+ var CHALLENGE_GONE = failure(
500
+ "challenge_not_found",
501
+ "Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
502
+ NEW_SESSION_REMEDY
503
+ );
504
+ function hash(value) {
505
+ return createHash4("sha256").update(value).digest("hex");
506
+ }
507
+ function sessionContext(deps) {
508
+ const env = deps.env ?? process.env;
509
+ const environment = environmentCredentials(deps);
510
+ if (!environment)
511
+ return failure(
512
+ "environment_credential_missing",
513
+ "the cloud environment has no environment credential",
514
+ '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'
515
+ );
516
+ const sessionId = env[SESSION_ID_VARIABLE]?.trim();
517
+ if (!sessionId || !SESSION_ID.test(sessionId))
518
+ return failure(
519
+ "session_id_missing",
520
+ `this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
521
+ NEW_SESSION_REMEDY
522
+ );
523
+ const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
524
+ const directory = deps.directory ?? primConfigDirectory({ env });
525
+ const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
526
+ return {
527
+ directory,
528
+ apiUrl,
529
+ clientId: environment.clientId,
530
+ generation: environment.generation,
531
+ sessionId,
532
+ tokenPath: join7(directory, `session_identity_${key}.json`),
533
+ statePath: join7(directory, `session_identity_${key}.state.json`),
534
+ lockPath: join7(directory, "session-identity.lock")
535
+ };
536
+ }
537
+ function readRecord(path) {
538
+ try {
539
+ const value = readMachineMetadata(path);
540
+ return value === void 0 ? void 0 : machineRecord(value);
541
+ } catch {
542
+ return void 0;
543
+ }
544
+ }
545
+ function finiteNumber(value) {
546
+ return typeof value === "number" && Number.isFinite(value);
547
+ }
548
+ function readToken(context) {
549
+ const data = readRecord(context.tokenPath);
550
+ 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))
551
+ return void 0;
552
+ const identity = data.identity;
553
+ if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
554
+ return void 0;
555
+ return data;
556
+ }
557
+ function tokenValid(record, now = Date.now()) {
558
+ return now < record.expiresAt - RENEW_BEFORE_MS;
559
+ }
560
+ function toCredential(record) {
561
+ return {
562
+ issuer: record.issuer,
563
+ audience: record.audience,
564
+ ...record.identity,
565
+ accessToken: record.accessToken,
566
+ expiresAt: record.expiresAt,
567
+ apiUrl: record.apiUrl,
568
+ generation: record.generation,
569
+ storage: "environment",
570
+ session: {
571
+ userId: record.userId,
572
+ displayName: record.displayName,
573
+ ...record.githubLogin ? { githubLogin: record.githubLogin } : {},
574
+ refreshAfter: record.refreshAfter
575
+ }
576
+ };
577
+ }
578
+ function cachedSessionCredential(deps = {}) {
579
+ if (!sessionIdentityMode(deps)) return void 0;
580
+ let context;
581
+ try {
582
+ context = sessionContext(deps);
583
+ } catch {
584
+ return void 0;
585
+ }
586
+ if ("status" in context) return void 0;
587
+ const record = readToken(context);
588
+ return record && tokenValid(record) ? toCredential(record) : void 0;
589
+ }
590
+ var SERVER_CONTRACT_FAILURE = failure(
591
+ "server_contract",
592
+ "Primitive's answer did not identify the linked member",
593
+ "update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
594
+ );
595
+
304
596
  // src/lib/machine-credentials.ts
597
+ function sessionScoped(deps) {
598
+ return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
599
+ }
305
600
  var require2 = createRequire(import.meta.url);
306
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
601
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
307
602
  var PROFILE_FILE = "machine_profile.json";
308
603
  var cached;
309
604
  function configurationDirectory(deps) {
310
605
  return deps.directory ?? primConfigDirectory({ env: deps.env });
311
606
  }
312
607
  function apiUrlFor(deps) {
313
- return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
608
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
314
609
  }
315
- function hash(value) {
316
- return createHash3("sha256").update(value).digest("hex");
610
+ function hash2(value) {
611
+ return createHash5("sha256").update(value).digest("hex");
317
612
  }
318
613
  function environmentContextPath(deps, clientId) {
319
- return join6(
614
+ return join8(
320
615
  configurationDirectory(deps),
321
- `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
616
+ `machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
322
617
  );
323
618
  }
324
619
  function readEnvironmentContext(environment, deps) {
@@ -349,7 +644,7 @@ function protectPath(path, directory) {
349
644
  }
350
645
  const encodedPath = Buffer.from(path).toString("base64");
351
646
  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(
647
+ execFileSync2(
353
648
  "powershell.exe",
354
649
  [
355
650
  "-NoProfile",
@@ -362,24 +657,27 @@ function protectPath(path, directory) {
362
657
  }
363
658
  function ensureDirectory(directory) {
364
659
  mkdirSync3(directory, { recursive: true, mode: 448 });
365
- if (lstatSync3(directory).isSymbolicLink())
660
+ if (lstatSync4(directory).isSymbolicLink())
366
661
  throw new MachineAuthError(
367
662
  "unsafe_storage",
368
663
  "Credential directory must not be a symbolic link."
369
664
  );
370
665
  protectPath(directory, true);
371
666
  }
667
+ function readMachineMetadata(path) {
668
+ return readPrivate(path);
669
+ }
372
670
  function readPrivate(path) {
373
671
  let raw;
374
672
  try {
375
- const stat = lstatSync3(path);
673
+ const stat = lstatSync4(path);
376
674
  if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
377
675
  throw new MachineAuthError(
378
676
  "unsafe_storage",
379
677
  "Machine credential files must be owner-only regular files."
380
678
  );
381
679
  }
382
- raw = readFileSync5(path, "utf8");
680
+ raw = readFileSync6(path, "utf8");
383
681
  } catch (error) {
384
682
  if (error.code === "ENOENT") return void 0;
385
683
  throw error;
@@ -424,7 +722,7 @@ function parseProfile(value) {
424
722
  };
425
723
  }
426
724
  function readMachineProfile(deps = {}) {
427
- const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
725
+ const value = readPrivate(join8(configurationDirectory(deps), PROFILE_FILE));
428
726
  return value === void 0 ? void 0 : parseProfile(value);
429
727
  }
430
728
  var NETWORK_SECRET_AUTH = "network-secret";
@@ -433,20 +731,20 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
433
731
  var brokerKeys = /* @__PURE__ */ new Map();
434
732
  function networkSecretBrokerKey(deps, clientId) {
435
733
  const directory = configurationDirectory(deps);
436
- const path = join6(directory, `machine_network_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
734
+ const path = join8(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
437
735
  const known = brokerKeys.get(path);
438
736
  if (known) return known;
439
737
  ensureDirectory(directory);
440
738
  const read = () => {
441
739
  try {
442
- const stat = lstatSync3(path);
740
+ const stat = lstatSync4(path);
443
741
  if (!stat.isFile() || process.platform !== "win32" && ((stat.mode & 63) !== 0 || typeof process.getuid === "function" && stat.uid !== process.getuid()))
444
742
  throw new MachineAuthError(
445
743
  "unsafe_storage",
446
744
  `The machine broker key at ${path} is not an owner-only file. Delete it and retry.`,
447
745
  true
448
746
  );
449
- const value = readFileSync5(path, "utf8").trim();
747
+ const value = readFileSync6(path, "utf8").trim();
450
748
  return { key: /^[a-f0-9]{64}$/u.test(value) ? value : void 0 };
451
749
  } catch (error) {
452
750
  if (error.code === "ENOENT") return void 0;
@@ -474,7 +772,7 @@ function networkSecretBrokerKey(deps, clientId) {
474
772
  } catch (error) {
475
773
  if (error.code !== "EEXIST") throw error;
476
774
  } finally {
477
- rmSync5(staged, { force: true });
775
+ rmSync6(staged, { force: true });
478
776
  }
479
777
  }
480
778
  const key = read()?.key;
@@ -507,7 +805,7 @@ function environmentCredentials(deps) {
507
805
  "conflicting_credentials",
508
806
  `Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
509
807
  );
510
- const generation = hash(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
808
+ const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
511
809
  const credentials = {
512
810
  clientId,
513
811
  generation,
@@ -528,12 +826,12 @@ function environmentCredentials(deps) {
528
826
  return {
529
827
  clientId,
530
828
  clientSecret,
531
- generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
829
+ generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
532
830
  };
533
831
  }
534
832
  function hasMachineConfiguration(deps = {}) {
535
833
  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));
834
+ 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));
537
835
  if (configured && env.PRIM_TOKEN?.trim()) {
538
836
  throw new MachineAuthError(
539
837
  "conflicting_credentials",
@@ -545,6 +843,7 @@ function hasMachineConfiguration(deps = {}) {
545
843
  }
546
844
  function machineContext(deps = {}) {
547
845
  if (!hasMachineConfiguration(deps)) return void 0;
846
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
548
847
  const environment = environmentCredentials(deps);
549
848
  if (environment) {
550
849
  if (environmentTerminal === environment.generation) return void 0;
@@ -559,6 +858,7 @@ function machineContext(deps = {}) {
559
858
  return profile;
560
859
  }
561
860
  function cachedMachineCredential(deps = {}) {
861
+ if (sessionScoped(deps)) return cachedSessionCredential(deps);
562
862
  const context = machineContext(deps);
563
863
  return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
564
864
  }
@@ -566,20 +866,20 @@ var environmentTerminal;
566
866
 
567
867
  // src/lib/credentials.ts
568
868
  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");
869
+ var TOKEN_FILE_PATH = join9(CONFIG_DIRECTORY, "token");
870
+ var REFRESH_TOKEN_PATH = join9(CONFIG_DIRECTORY, "refresh_token");
871
+ var TOKEN_EXPIRES_PATH = join9(CONFIG_DIRECTORY, "token_expires_at");
872
+ var TERMINAL_REFRESH_PATH = join9(CONFIG_DIRECTORY, "refresh_terminal");
873
+ var CREDENTIAL_METADATA_PATH = join9(CONFIG_DIRECTORY, "credential_metadata.json");
874
+ var CREDENTIAL_FAMILY_PATH = join9(CONFIG_DIRECTORY, "credential_family.json");
875
+ var CREDENTIAL_MIGRATION_PATH = join9(CONFIG_DIRECTORY, "credential_migration.json");
876
+ var CREDENTIAL_LOCK_PATH = join9(CONFIG_DIRECTORY, "credentials.lock");
577
877
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
578
878
  var CREDENTIAL_MIGRATION_VERSION = 1;
579
879
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
580
880
  function readTrimmed(path) {
581
881
  try {
582
- const value = readFileSync6(path, "utf8").trim();
882
+ const value = readFileSync7(path, "utf8").trim();
583
883
  return value || void 0;
584
884
  } catch {
585
885
  return void 0;
@@ -616,7 +916,7 @@ function resolveAuthCredential(options = {}) {
616
916
  return { token: stored, source: "token_file" };
617
917
  }
618
918
  function credentialFingerprint(value) {
619
- return createHash4("sha256").update(value).digest("hex");
919
+ return createHash6("sha256").update(value).digest("hex");
620
920
  }
621
921
  function parseLegacyBrokerCredentialMetadata(value) {
622
922
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -636,7 +936,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
636
936
  function readBoundedCredentialJson(path) {
637
937
  let raw;
638
938
  try {
639
- raw = readFileSync6(path, "utf8");
939
+ raw = readFileSync7(path, "utf8");
640
940
  } catch (error) {
641
941
  return error.code === "ENOENT" ? void 0 : null;
642
942
  }
@@ -705,8 +1005,8 @@ function decodeJwtPayload(token) {
705
1005
 
706
1006
  // src/daemon/client-instance-id.ts
707
1007
  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";
1008
+ import { chmodSync as chmodSync2, lstatSync as lstatSync5, readFileSync as readFileSync8 } from "fs";
1009
+ import { join as join10 } from "path";
710
1010
  var INSTANCE_BODY_CHARS = 43;
711
1011
  var INSTANCE_PREFIX = "pci_";
712
1012
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
@@ -714,63 +1014,24 @@ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
714
1014
  // src/lib/ingest-uploader.ts
715
1015
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
716
1016
 
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
1017
  // src/client.ts
757
- var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
1018
+ var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
758
1019
  function getSiteUrl() {
759
1020
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
760
1021
  }
761
1022
  function getSiteUrlForEnvironment(primApiUrl) {
762
- return primApiUrl?.trim() || DEFAULT_API_URL2;
1023
+ return primApiUrl?.trim() || DEFAULT_API_URL3;
763
1024
  }
764
1025
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
765
1026
 
766
1027
  // src/daemon/principal.ts
767
- import { createHash as createHash6 } from "crypto";
1028
+ import { createHash as createHash8 } from "crypto";
768
1029
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
769
1030
  function boundedClaim(value) {
770
1031
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
771
1032
  }
772
1033
  function sha256(value) {
773
- return createHash6("sha256").update(value).digest("hex");
1034
+ return createHash8("sha256").update(value).digest("hex");
774
1035
  }
775
1036
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
776
1037
  if (hasMachineConfiguration()) {
@@ -821,8 +1082,8 @@ function parseDaemonResponseEnvelope(value) {
821
1082
 
822
1083
  // src/daemon/client.ts
823
1084
  import { createConnection } from "net";
824
- import { join as join10 } from "path";
825
- var SOCK_PATH = join10(primConfigDirectory(), "sock");
1085
+ import { join as join12 } from "path";
1086
+ var SOCK_PATH = join12(primConfigDirectory(), "sock");
826
1087
  var DEFAULT_TIMEOUT_MS = 250;
827
1088
  var nextRequestId = 1;
828
1089
  function daemonRequest(method, params = {}, opts = {}) {
@@ -915,14 +1176,14 @@ function daemonRequest(method, params = {}, opts = {}) {
915
1176
  import { execFileSync as execFileSync4 } from "child_process";
916
1177
  import { existsSync as existsSync6, readFileSync as readFileSync11 } from "fs";
917
1178
  import { homedir as homedir2 } from "os";
918
- import { join as join13 } from "path";
1179
+ import { join as join14 } from "path";
919
1180
 
920
1181
  // 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";
1182
+ import { existsSync as existsSync5, mkdirSync as mkdirSync5, readFileSync as readFileSync10, rmSync as rmSync8, writeFileSync as writeFileSync4 } from "fs";
1183
+ import { join as join13 } from "path";
923
1184
  var CLOUD_PREPARED_MARKER = "cloud-prepared";
924
1185
  function cloudPreparedPath(env = process.env) {
925
- return join11(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
1186
+ return join13(primConfigDirectory({ env }), CLOUD_PREPARED_MARKER);
926
1187
  }
927
1188
  function isPreparedCloudSession(env = process.env) {
928
1189
  if (!isClaudeCloudSession(env)) return false;
@@ -934,17 +1195,17 @@ function isPreparedCloudSession(env = process.env) {
934
1195
  }
935
1196
 
936
1197
  // src/lib/demo-pause.ts
937
- import { execFileSync as execFileSync2 } from "child_process";
1198
+ import { execFileSync as execFileSync3 } from "child_process";
938
1199
  var DEMO_PAUSE_MS = 30 * 6e4;
939
1200
  var PAUSE_KEY = "prim.demoPause";
940
- var GIT_TIMEOUT_MS = 1e3;
1201
+ var GIT_TIMEOUT_MS2 = 1e3;
941
1202
  function git(cwd, args) {
942
1203
  try {
943
- return execFileSync2("git", args, {
1204
+ return execFileSync3("git", args, {
944
1205
  cwd,
945
1206
  encoding: "utf-8",
946
1207
  stdio: ["ignore", "pipe", "ignore"],
947
- timeout: GIT_TIMEOUT_MS
1208
+ timeout: GIT_TIMEOUT_MS2
948
1209
  });
949
1210
  } catch {
950
1211
  return void 0;
@@ -952,10 +1213,10 @@ function git(cwd, args) {
952
1213
  }
953
1214
  function setLocal(cwd, key, value) {
954
1215
  try {
955
- execFileSync2(
1216
+ execFileSync3(
956
1217
  "git",
957
1218
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
958
- { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
1219
+ { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS2 }
959
1220
  );
960
1221
  } catch (error) {
961
1222
  if (value !== null || error.status !== 5) throw error;
@@ -994,114 +1255,6 @@ function healDemoPause(cwd, pause, options = {}) {
994
1255
  }
995
1256
  }
996
1257
 
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
1258
  // src/lib/activation.ts
1106
1259
  var PRIM_ACTIVE_KEY = "prim.active";
1107
1260
  var PRIM_ACTIVE_DECLARATION = "PRIM_ACTIVE";
@@ -1164,7 +1317,7 @@ function repositoryBindingState(cwd) {
1164
1317
  function projectPrimInstallAt(root) {
1165
1318
  if (root === null || root === homedir2()) return false;
1166
1319
  for (const rel of PROJECT_INSTALL_FILES) {
1167
- const path = join13(root, rel);
1320
+ const path = join14(root, rel);
1168
1321
  if (existsSync6(path)) {
1169
1322
  try {
1170
1323
  const content = readFileSync11(path, "utf-8");