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