@primitive.ai/prim 0.1.0-alpha.123 → 0.1.0-alpha.125

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 +90 -0
  2. package/dist/{chunk-RUEIVZ6T.js → chunk-2BEUR3DU.js} +2 -2
  3. package/dist/{chunk-5ME3WD3P.js → chunk-6KXQQ7CQ.js} +6 -3
  4. package/dist/{chunk-CWV5ZQR6.js → chunk-6OPSSJHO.js} +5 -5
  5. package/dist/{chunk-4NUGCUQC.js → chunk-74DQDWLW.js} +2 -2
  6. package/dist/{chunk-WN7OURQ3.js → chunk-BFYJLI7V.js} +1 -1
  7. package/dist/{chunk-T2T45KF6.js → chunk-DT7E3SD5.js} +4 -4
  8. package/dist/{chunk-DQ4I3FLF.js → chunk-EZXIKEMA.js} +3 -3
  9. package/dist/{chunk-4M23K2KZ.js → chunk-FYYHBOOM.js} +2 -2
  10. package/dist/{chunk-3WQ7SBOZ.js → chunk-HPA7RGSZ.js} +3 -3
  11. package/dist/{chunk-NL5VU7EU.js → chunk-JFWJN2ME.js} +3 -3
  12. package/dist/{chunk-GOMEWFMG.js → chunk-L32WYFJT.js} +143 -61
  13. package/dist/{chunk-OXW6PSPT.js → chunk-NBNQI3YJ.js} +15 -3
  14. package/dist/{chunk-LOFMI3D4.js → chunk-ND6TYHNI.js} +2 -2
  15. package/dist/{chunk-4GYJHN26.js → chunk-NJBN3WXF.js} +1607 -549
  16. package/dist/{chunk-HLMC7VS4.js → chunk-O73J3KQQ.js} +5702 -2860
  17. package/dist/{chunk-JZC2LHS6.js → chunk-PPZ56EVJ.js} +1 -1
  18. package/dist/{chunk-FXXMDO7D.js → chunk-R35M4RCY.js} +4 -4
  19. package/dist/chunk-TI37ME2D.js +210 -0
  20. package/dist/{chunk-NMZSCSMY.js → chunk-YP4OXKNX.js} +13 -1
  21. package/dist/{chunk-S3ZIMGXV.js → chunk-ZKXNJB6U.js} +76 -2
  22. package/dist/daemon/server.js +12321 -8354
  23. package/dist/hook-runtime/daemon/server.js +12321 -8354
  24. package/dist/hook-runtime/hooks/post-commit.js +6743 -3634
  25. package/dist/hook-runtime/hooks/post-rewrite.js +6776 -3668
  26. package/dist/hook-runtime/hooks/post-tool-use.js +7108 -3140
  27. package/dist/hook-runtime/hooks/pre-commit.js +1263 -280
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +15115 -11297
  29. package/dist/hook-runtime/hooks/prim-hook.js +10879 -7024
  30. package/dist/hook-runtime/hooks/session-end.js +399 -139
  31. package/dist/hook-runtime/hooks/session-start.js +13277 -9454
  32. package/dist/hook-runtime/index.js +17575 -13050
  33. package/dist/hook-runtime/statusline-main.js +375 -122
  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 +31 -21
  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 +16 -12
  42. package/dist/index.js +9124 -8763
  43. package/dist/statusline-main.js +375 -122
  44. package/package.json +3 -1
  45. package/dist/chunk-RRAC76LJ.js +0 -36
@@ -2,39 +2,86 @@
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 createHash2 } from "crypto";
5
+ import { createHash as createHash5 } from "crypto";
6
6
 
7
7
  // src/lib/credentials.ts
8
- import { createHash } from "crypto";
9
- import { readFileSync } from "fs";
10
- import { join as join2 } from "path";
8
+ import { createHash as createHash4 } from "crypto";
9
+ import { readFileSync as readFileSync6 } from "fs";
10
+ import { join as join7 } from "path";
11
11
 
12
- // src/lib/paths.ts
13
- import { homedir } from "os";
14
- import { isAbsolute, join, normalize } from "path";
15
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
16
- function absolutePath(value, variable) {
17
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
18
- throw new Error(`${variable} contains unsafe characters`);
19
- }
20
- if (!value || value.trim() !== value || !isAbsolute(value)) return;
21
- const normalized = normalize(value);
22
- return normalized === value ? value : void 0;
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";
16
+ import { createRequire } from "module";
17
+ import { dirname as dirname4, join as join6 } from "path";
18
+ import { fileURLToPath as fileURLToPath3 } from "url";
19
+
20
+ // src/lib/atomic-file.ts
21
+ import { randomUUID } from "crypto";
22
+ import {
23
+ constants,
24
+ closeSync,
25
+ fchmodSync,
26
+ fsyncSync,
27
+ mkdirSync,
28
+ openSync,
29
+ renameSync,
30
+ rmSync,
31
+ writeFileSync
32
+ } from "fs";
33
+ import { dirname } from "path";
34
+
35
+ // src/lib/file-lock.ts
36
+ import { randomBytes } from "crypto";
37
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
38
+ import { dirname as dirname2, join } from "path";
39
+ var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
40
+
41
+ // src/lib/machine-broker.ts
42
+ import { spawn } from "child_process";
43
+ import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
44
+ import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
45
+ import { createServer } from "http";
46
+ import { basename, join as join4 } from "path";
47
+ import { fileURLToPath as fileURLToPath2 } from "url";
48
+
49
+ // src/lib/bin-path.ts
50
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
51
+ import { dirname as dirname3, isAbsolute, join as join2 } from "path";
52
+ import { fileURLToPath } from "url";
53
+ var PKG_NAME = "@primitive.ai/prim";
54
+ var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
55
+ function shellQuote(value) {
56
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
23
57
  }
24
- function resolvePrimConfigDirectory(options = {}) {
25
- const env = options.env ?? process.env;
26
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
27
- if (explicit) return { path: explicit, source: "explicit" };
28
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
29
- if (xdgConfigHome) return { path: join(xdgConfigHome, "prim"), source: "xdg" };
30
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
31
- if (!home) {
32
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
58
+ var STABLE_HOOK_ARGUMENTS_RE = /^[-A-Za-z0-9_ ]*$/u;
59
+ var STABLE_HOOK_BIN_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/u;
60
+ var PRIM_CONFIG_SHELL_RESOLVER = [
61
+ 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
62
+ 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
63
+ 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
64
+ '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
+ "fi; fi; "
66
+ ].join("");
67
+ function stableHookCommand(bin, args = "") {
68
+ if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
69
+ throw new Error("invalid stable hook command");
33
70
  }
34
- return { path: join(home, ".config", "prim"), source: "default" };
71
+ const resolver = [
72
+ // #242 and earlier identify managed commands by this package marker. Keep
73
+ // it as inert data during the rolling window so an older uninstall or
74
+ // reinstall can remove the stable entry without invoking npm or PATH.
75
+ `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
76
+ PRIM_CONFIG_SHELL_RESOLVER,
77
+ `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
78
+ 'exec "$prim_launcher" "$@"'
79
+ ].join("");
80
+ const suffix = args ? ` ${args}` : "";
81
+ return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
35
82
  }
36
- function primConfigDirectory(options = {}) {
37
- return resolvePrimConfigDirectory(options).path;
83
+ function detachedHookShimCommand(bin, args = "") {
84
+ return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
38
85
  }
39
86
 
40
87
  // src/lib/workos-connect.ts
@@ -116,28 +163,283 @@ function parseWorkosConnectCredentialMetadata(value) {
116
163
  };
117
164
  }
118
165
 
166
+ // src/lib/machine-protocol.ts
167
+ var MachineAuthError = class extends Error {
168
+ constructor(code, message, terminal = false, retryAt) {
169
+ super(message);
170
+ this.code = code;
171
+ this.terminal = terminal;
172
+ this.retryAt = retryAt;
173
+ this.name = "MachineAuthError";
174
+ }
175
+ };
176
+ function machineString(value, maximum = 4096) {
177
+ return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
178
+ }
179
+ function machineRecord(value) {
180
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
181
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
182
+ }
183
+ return value;
184
+ }
185
+ function machineApiUrl(value) {
186
+ const url = new URL(value);
187
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
188
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
189
+ throw new MachineAuthError("invalid_configuration", "The API URL must be an HTTPS origin.");
190
+ }
191
+ return url.origin;
192
+ }
193
+ function parseMachineConfiguration(value) {
194
+ const record = machineRecord(value);
195
+ if (record.protocol_version !== 1 || !machineString(record.issuer, 2048) || !machineString(record.audience, 256) || !/^client_[\w-]+$/u.test(record.audience)) {
196
+ throw new MachineAuthError("invalid_configuration", "Invalid M2M discovery configuration.");
197
+ }
198
+ const issuer = new URL(record.issuer);
199
+ if (issuer.protocol !== "https:" || issuer.origin !== record.issuer) {
200
+ throw new MachineAuthError(
201
+ "invalid_configuration",
202
+ "The WorkOS issuer must be an HTTPS origin."
203
+ );
204
+ }
205
+ return {
206
+ issuer: record.issuer,
207
+ audience: record.audience,
208
+ ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
209
+ };
210
+ }
211
+ function parseMachineIdentity(value, clientId) {
212
+ const data = machineRecord(value);
213
+ const principal = machineRecord(data.principal);
214
+ if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || ![2, 3].includes(data.organizationBindingVersion) || (data.organizationBindingVersion === 3 ? !machineString(principal.authorizedUserId, 256) : principal.authorizedUserId !== void 0) || principal.kind !== "machine" || principal.clientId !== clientId || !machineString(principal.machineId, 256) || !machineString(principal.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.workosOrganizationId, 256) || !Array.isArray(principal.scopes) || !principal.scopes.every((scope) => machineString(scope, 128))) {
215
+ throw new MachineAuthError(
216
+ "machine_identity_rejected",
217
+ "The API did not verify a machine identity.",
218
+ true
219
+ );
220
+ }
221
+ return {
222
+ machineId: principal.machineId,
223
+ ...data.organizationBindingVersion === 3 ? { authorizedUserId: principal.authorizedUserId } : {},
224
+ clientId,
225
+ displayName: principal.displayName,
226
+ organizationId: data.organizationId,
227
+ workosOrganizationId: data.workosOrganizationId,
228
+ scopes: principal.scopes
229
+ };
230
+ }
231
+
232
+ // src/lib/paths.ts
233
+ import { homedir } from "os";
234
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
235
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
236
+ function absolutePath(value, variable) {
237
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
238
+ throw new Error(`${variable} contains unsafe characters`);
239
+ }
240
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
241
+ const normalized = normalize(value);
242
+ return normalized === value ? value : void 0;
243
+ }
244
+ function resolvePrimConfigDirectory(options = {}) {
245
+ const env = options.env ?? process.env;
246
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
247
+ if (explicit) return { path: explicit, source: "explicit" };
248
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
249
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
250
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
251
+ if (!home) {
252
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
253
+ }
254
+ return { path: join3(home, ".config", "prim"), source: "default" };
255
+ }
256
+ function primConfigDirectory(options = {}) {
257
+ return resolvePrimConfigDirectory(options).path;
258
+ }
259
+
260
+ // src/lib/machine-broker.ts
261
+ var MAX_RESPONSE_BYTES = 96 * 1024;
262
+ var IDLE_MS = 5 * 6e4;
263
+
264
+ // src/lib/machine-retry.ts
265
+ import { createHash as createHash2 } from "crypto";
266
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
267
+ import { join as join5 } from "path";
268
+
269
+ // src/lib/machine-credentials.ts
270
+ var require2 = createRequire(import.meta.url);
271
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
272
+ var PROFILE_FILE = "machine_profile.json";
273
+ var cached;
274
+ function configurationDirectory(deps) {
275
+ return deps.directory ?? primConfigDirectory({ env: deps.env });
276
+ }
277
+ function apiUrlFor(deps) {
278
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
279
+ }
280
+ function hash(value) {
281
+ return createHash3("sha256").update(value).digest("hex");
282
+ }
283
+ function environmentContextPath(deps, clientId) {
284
+ return join6(
285
+ configurationDirectory(deps),
286
+ `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
287
+ );
288
+ }
289
+ function readEnvironmentContext(environment, deps) {
290
+ try {
291
+ const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
292
+ if (data.generation !== environment.generation || data.clientId !== environment.clientId || data.apiUrl !== apiUrlFor(deps) || typeof data.expiresAt !== "number" || !Number.isFinite(data.expiresAt) || data.expiresAt <= Date.now())
293
+ return void 0;
294
+ const configuration = parseMachineConfiguration({
295
+ protocol_version: data.version,
296
+ issuer: data.issuer,
297
+ audience: data.audience
298
+ });
299
+ const identity = parseStoredIdentity(data);
300
+ return {
301
+ ...configuration,
302
+ ...identity,
303
+ apiUrl: data.apiUrl,
304
+ generation: environment.generation
305
+ };
306
+ } catch {
307
+ return void 0;
308
+ }
309
+ }
310
+ function readPrivate(path) {
311
+ let raw;
312
+ try {
313
+ const stat = lstatSync3(path);
314
+ if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
315
+ throw new MachineAuthError(
316
+ "unsafe_storage",
317
+ "Machine credential files must be owner-only regular files."
318
+ );
319
+ }
320
+ raw = readFileSync5(path, "utf8");
321
+ } catch (error) {
322
+ if (error.code === "ENOENT") return void 0;
323
+ throw error;
324
+ }
325
+ try {
326
+ return JSON.parse(raw);
327
+ } catch {
328
+ throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
329
+ }
330
+ }
331
+ function parseStoredIdentity(data) {
332
+ return parseMachineIdentity(
333
+ {
334
+ authenticated: true,
335
+ organizationBindingVersion: data.authorizedUserId ? 3 : 2,
336
+ captureAuthorityKind: "workos_m2m",
337
+ organizationId: data.organizationId,
338
+ workosOrganizationId: data.workosOrganizationId,
339
+ principal: { ...data, kind: "machine" }
340
+ },
341
+ String(data.clientId)
342
+ );
343
+ }
344
+ function parseProfile(value) {
345
+ const data = machineRecord(value);
346
+ const config = parseMachineConfiguration({
347
+ protocol_version: data.version,
348
+ issuer: data.issuer,
349
+ audience: data.audience
350
+ });
351
+ if (typeof data.apiUrl !== "string" || machineApiUrl(data.apiUrl) !== data.apiUrl || !machineString(data.generation, 64) || !/^[a-f0-9-]{36}$/u.test(data.generation) || data.storage !== "keychain" && data.storage !== "file" || !machineString(data.clientId, 256)) {
352
+ throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
353
+ }
354
+ const identity = parseStoredIdentity(data);
355
+ return {
356
+ ...config,
357
+ ...identity,
358
+ version: 1,
359
+ apiUrl: data.apiUrl,
360
+ generation: data.generation,
361
+ storage: data.storage
362
+ };
363
+ }
364
+ function readMachineProfile(deps = {}) {
365
+ const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
366
+ return value === void 0 ? void 0 : parseProfile(value);
367
+ }
368
+ function environmentCredentials(deps) {
369
+ 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;
372
+ if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
373
+ throw new MachineAuthError(
374
+ "incomplete_machine_credentials",
375
+ "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
376
+ );
377
+ }
378
+ return {
379
+ clientId,
380
+ clientSecret,
381
+ generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
382
+ };
383
+ }
384
+ function hasMachineConfiguration(deps = {}) {
385
+ 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));
387
+ if (configured && env.PRIM_TOKEN?.trim()) {
388
+ throw new MachineAuthError(
389
+ "conflicting_credentials",
390
+ "Unset PRIM_TOKEN when using machine credentials."
391
+ );
392
+ }
393
+ if (configured) environmentCredentials(deps);
394
+ return configured;
395
+ }
396
+ function machineContext(deps = {}) {
397
+ if (!hasMachineConfiguration(deps)) return void 0;
398
+ const environment = environmentCredentials(deps);
399
+ if (environment) {
400
+ if (environmentTerminal === environment.generation) return void 0;
401
+ return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
402
+ }
403
+ const profile = readMachineProfile(deps);
404
+ if (profile && profile.apiUrl !== apiUrlFor(deps))
405
+ throw new MachineAuthError(
406
+ "deployment_mismatch",
407
+ "Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
408
+ );
409
+ return profile;
410
+ }
411
+ function cachedMachineCredential(deps = {}) {
412
+ const context = machineContext(deps);
413
+ return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
414
+ }
415
+ var environmentTerminal;
416
+
119
417
  // src/lib/credentials.ts
120
418
  var CONFIG_DIRECTORY = primConfigDirectory();
121
- var TOKEN_FILE_PATH = join2(CONFIG_DIRECTORY, "token");
122
- var REFRESH_TOKEN_PATH = join2(CONFIG_DIRECTORY, "refresh_token");
123
- var TOKEN_EXPIRES_PATH = join2(CONFIG_DIRECTORY, "token_expires_at");
124
- var TERMINAL_REFRESH_PATH = join2(CONFIG_DIRECTORY, "refresh_terminal");
125
- var CREDENTIAL_METADATA_PATH = join2(CONFIG_DIRECTORY, "credential_metadata.json");
126
- var CREDENTIAL_FAMILY_PATH = join2(CONFIG_DIRECTORY, "credential_family.json");
127
- var CREDENTIAL_MIGRATION_PATH = join2(CONFIG_DIRECTORY, "credential_migration.json");
128
- var CREDENTIAL_LOCK_PATH = join2(CONFIG_DIRECTORY, "credentials.lock");
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");
129
427
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
130
428
  var CREDENTIAL_MIGRATION_VERSION = 1;
131
429
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
132
430
  function readTrimmed(path) {
133
431
  try {
134
- const value = readFileSync(path, "utf8").trim();
432
+ const value = readFileSync6(path, "utf8").trim();
135
433
  return value || void 0;
136
434
  } catch {
137
435
  return void 0;
138
436
  }
139
437
  }
140
438
  function resolveAuthCredential(options = {}) {
439
+ if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
440
+ const machine = cachedMachineCredential({ env: options.env });
441
+ return machine ? { token: machine.accessToken, source: "machine" } : void 0;
442
+ }
141
443
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
142
444
  if (envToken) return { token: envToken, source: "environment" };
143
445
  const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
@@ -164,7 +466,7 @@ function resolveAuthCredential(options = {}) {
164
466
  return { token: stored, source: "token_file" };
165
467
  }
166
468
  function credentialFingerprint(value) {
167
- return createHash("sha256").update(value).digest("hex");
469
+ return createHash4("sha256").update(value).digest("hex");
168
470
  }
169
471
  function parseLegacyBrokerCredentialMetadata(value) {
170
472
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -184,7 +486,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
184
486
  function readBoundedCredentialJson(path) {
185
487
  let raw;
186
488
  try {
187
- raw = readFileSync(path, "utf8");
489
+ raw = readFileSync6(path, "utf8");
188
490
  } catch (error) {
189
491
  return error.code === "ENOENT" ? void 0 : null;
190
492
  }
@@ -257,9 +559,19 @@ function boundedClaim(value) {
257
559
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
258
560
  }
259
561
  function sha256(value) {
260
- return createHash2("sha256").update(value).digest("hex");
562
+ return createHash5("sha256").update(value).digest("hex");
261
563
  }
262
564
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
565
+ if (hasMachineConfiguration()) {
566
+ const machine = machineContext();
567
+ return machine ? {
568
+ principalId: sha256(
569
+ `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
570
+ ),
571
+ organizationId: machine.workosOrganizationId,
572
+ credentialFingerprint: sha256(machine.generation)
573
+ } : void 0;
574
+ }
263
575
  if (!token) return void 0;
264
576
  const payload = decodeJwtPayload(token);
265
577
  const subject = boundedClaim(payload?.sub);
@@ -298,8 +610,8 @@ function parseDaemonResponseEnvelope(value) {
298
610
 
299
611
  // src/daemon/client.ts
300
612
  import { createConnection } from "net";
301
- import { join as join3 } from "path";
302
- var SOCK_PATH = join3(primConfigDirectory(), "sock");
613
+ import { join as join8 } from "path";
614
+ var SOCK_PATH = join8(primConfigDirectory(), "sock");
303
615
  var DEFAULT_TIMEOUT_MS = 250;
304
616
  var nextRequestId = 1;
305
617
  function daemonRequest(method, params = {}, opts = {}) {
@@ -389,19 +701,19 @@ function daemonRequest(method, params = {}, opts = {}) {
389
701
  }
390
702
 
391
703
  // src/lib/activation.ts
392
- import { execFileSync as execFileSync3 } from "child_process";
393
- import { existsSync, readFileSync as readFileSync2 } from "fs";
704
+ import { execFileSync as execFileSync4 } from "child_process";
705
+ import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
394
706
  import { homedir as homedir2 } from "os";
395
- import { join as join4 } from "path";
707
+ import { join as join9 } from "path";
396
708
 
397
709
  // src/lib/demo-pause.ts
398
- import { execFileSync } from "child_process";
710
+ import { execFileSync as execFileSync2 } from "child_process";
399
711
  var DEMO_PAUSE_MS = 30 * 6e4;
400
712
  var PAUSE_KEY = "prim.demoPause";
401
713
  var GIT_TIMEOUT_MS = 1e3;
402
714
  function git(cwd, args) {
403
715
  try {
404
- return execFileSync("git", args, {
716
+ return execFileSync2("git", args, {
405
717
  cwd,
406
718
  encoding: "utf-8",
407
719
  stdio: ["ignore", "pipe", "ignore"],
@@ -413,7 +725,7 @@ function git(cwd, args) {
413
725
  }
414
726
  function setLocal(cwd, key, value) {
415
727
  try {
416
- execFileSync(
728
+ execFileSync2(
417
729
  "git",
418
730
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
419
731
  { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
@@ -456,16 +768,16 @@ function healDemoPause(cwd, pause, options = {}) {
456
768
  }
457
769
 
458
770
  // src/lib/git.ts
459
- import { execFileSync as execFileSync2 } from "child_process";
460
- import { createHash as createHash3 } from "crypto";
461
- import { lstatSync, realpathSync } from "fs";
462
- import { basename, dirname, isAbsolute as isAbsolute2, relative, resolve, sep } from "path";
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";
463
775
  var GIT_TIMEOUT_MS2 = 1e3;
464
776
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
465
777
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
466
778
  function gitToplevel(cwd) {
467
779
  try {
468
- return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
780
+ return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
469
781
  cwd,
470
782
  encoding: "utf-8",
471
783
  stdio: ["ignore", "pipe", "ignore"],
@@ -477,7 +789,7 @@ function gitToplevel(cwd) {
477
789
  }
478
790
  function gitValue(cwd, args) {
479
791
  try {
480
- const value = execFileSync2("git", args, {
792
+ const value = execFileSync3("git", args, {
481
793
  cwd,
482
794
  encoding: "utf-8",
483
795
  stdio: ["ignore", "pipe", "ignore"],
@@ -524,7 +836,7 @@ function normalizeOriginRemote(remote) {
524
836
  }
525
837
  }
526
838
  function opaqueRepoKey(source, value) {
527
- return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
839
+ return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
528
840
  }
529
841
  function resolveRepositoryContext(cwd = process.cwd()) {
530
842
  const top = gitToplevel(cwd);
@@ -565,7 +877,7 @@ var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cur
565
877
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
566
878
  function repoActiveFlag(cwd, strict = false) {
567
879
  try {
568
- const value = execFileSync3("git", ["config", "--get", PRIM_ACTIVE_KEY], {
880
+ const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
569
881
  cwd,
570
882
  encoding: "utf-8",
571
883
  stdio: ["ignore", "pipe", "ignore"],
@@ -585,10 +897,10 @@ function hasProjectPrimInstall(cwd) {
585
897
  const root = gitToplevel(cwd);
586
898
  if (root === null || root === homedir2()) return false;
587
899
  for (const rel of PROJECT_INSTALL_FILES) {
588
- const path = join4(root, rel);
589
- if (existsSync(path)) {
900
+ const path = join9(root, rel);
901
+ if (existsSync4(path)) {
590
902
  try {
591
- const content = readFileSync2(path, "utf-8");
903
+ const content = readFileSync7(path, "utf-8");
592
904
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
593
905
  } catch {
594
906
  }
@@ -615,90 +927,31 @@ function parseAgent(argv) {
615
927
  }
616
928
 
617
929
  // src/commands/cursor-install.ts
618
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
930
+ import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
619
931
  import { homedir as homedir4 } from "os";
620
- import { isAbsolute as isAbsolute5, join as join9 } from "path";
621
-
622
- // src/lib/atomic-file.ts
623
- import { randomUUID } from "crypto";
624
- import {
625
- constants,
626
- closeSync,
627
- fchmodSync,
628
- fsyncSync,
629
- mkdirSync,
630
- openSync,
631
- renameSync,
632
- rmSync,
633
- writeFileSync
634
- } from "fs";
635
- import { dirname as dirname2 } from "path";
636
-
637
- // src/lib/bin-path.ts
638
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
639
- import { dirname as dirname3, isAbsolute as isAbsolute3, join as join5 } from "path";
640
- import { fileURLToPath } from "url";
641
- var PKG_NAME = "@primitive.ai/prim";
642
- var STABLE_HOOK_LAUNCHER_NAME = "prim-hook-launcher-v1";
643
- function shellQuote(value) {
644
- return `'${value.replaceAll("'", `'"'"'`)}'`;
645
- }
646
- var STABLE_HOOK_ARGUMENTS_RE = /^[-A-Za-z0-9_ ]*$/u;
647
- var STABLE_HOOK_BIN_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/u;
648
- var PRIM_CONFIG_SHELL_RESOLVER = [
649
- 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
650
- 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
651
- 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
652
- '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; ',
653
- "fi; fi; "
654
- ].join("");
655
- function stableHookCommand(bin, args = "") {
656
- if (!STABLE_HOOK_BIN_RE.test(bin) || !STABLE_HOOK_ARGUMENTS_RE.test(args)) {
657
- throw new Error("invalid stable hook command");
658
- }
659
- const resolver = [
660
- // #242 and earlier identify managed commands by this package marker. Keep
661
- // it as inert data during the rolling window so an older uninstall or
662
- // reinstall can remove the stable entry without invoking npm or PATH.
663
- `prim_legacy_reader='-p ${PKG_NAME}@stable prim-shim.sh ${bin} '; `,
664
- PRIM_CONFIG_SHELL_RESOLVER,
665
- `case "$prim_config" in /) prim_launcher=/${STABLE_HOOK_LAUNCHER_NAME} ;; *) prim_launcher="$prim_config/${STABLE_HOOK_LAUNCHER_NAME}" ;; esac; `,
666
- 'exec "$prim_launcher" "$@"'
667
- ].join("");
668
- const suffix = args ? ` ${args}` : "";
669
- return `/bin/sh -c ${shellQuote(resolver)} ${STABLE_HOOK_LAUNCHER_NAME} ${bin}${suffix}`;
670
- }
671
- function detachedHookShimCommand(bin, args = "") {
672
- return `payload=$(cat); { trap '' HUP; printf '%s' "$payload" | { ${stableHookCommand(bin, args)}; }; } </dev/null >/dev/null 2>&1 &`;
673
- }
932
+ import { isAbsolute as isAbsolute5, join as join13 } from "path";
674
933
 
675
934
  // src/lib/hook-runtime.ts
676
- import { createHash as createHash4, randomBytes as randomBytes2 } from "crypto";
935
+ import { createHash as createHash7, randomBytes as randomBytes3 } from "crypto";
677
936
  import {
678
937
  constants as constants2,
679
938
  accessSync,
680
- chmodSync,
939
+ chmodSync as chmodSync2,
681
940
  copyFileSync,
682
- existsSync as existsSync4,
683
- lstatSync as lstatSync2,
684
- mkdirSync as mkdirSync3,
941
+ existsSync as existsSync6,
942
+ lstatSync as lstatSync5,
943
+ mkdirSync as mkdirSync4,
685
944
  mkdtempSync,
686
- readFileSync as readFileSync5,
945
+ readFileSync as readFileSync8,
687
946
  readdirSync,
688
947
  realpathSync as realpathSync2,
689
948
  renameSync as renameSync2,
690
- rmSync as rmSync3,
949
+ rmSync as rmSync6,
691
950
  statSync as statSync2,
692
951
  utimesSync,
693
952
  writeFileSync as writeFileSync3
694
953
  } from "fs";
695
- import { delimiter, dirname as dirname5, isAbsolute as isAbsolute4, join as join7, resolve as resolve2 } from "path";
696
-
697
- // src/lib/file-lock.ts
698
- import { randomBytes } from "crypto";
699
- import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync4, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
700
- import { dirname as dirname4, join as join6 } from "path";
701
- var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
954
+ import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join11, resolve as resolve2 } from "path";
702
955
 
703
956
  // src/lib/git-hook-contract.ts
704
957
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -745,6 +998,13 @@ esac
745
998
  exit 0
746
999
  `;
747
1000
 
1001
+ // src/lib/native-keyring.ts
1002
+ import { existsSync as existsSync5 } from "fs";
1003
+ import { createRequire as createRequire2 } from "module";
1004
+ import { dirname as dirname6, join as join10 } from "path";
1005
+ import { fileURLToPath as fileURLToPath4 } from "url";
1006
+ var require3 = createRequire2(import.meta.url);
1007
+
748
1008
  // src/lib/hook-runtime.ts
749
1009
  var RELEASE_PREFIX = "release-";
750
1010
  var MAX_MANIFEST_BYTES = 64 * 1024;
@@ -792,12 +1052,12 @@ exec "$prim_node" "$prim_entry" "$@"
792
1052
  `;
793
1053
 
794
1054
  // src/lib/preflight-host.ts
795
- import { execFileSync as execFileSync4 } from "child_process";
1055
+ import { execFileSync as execFileSync5 } from "child_process";
796
1056
 
797
1057
  // src/commands/claude-install.ts
798
- import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1058
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
799
1059
  import { homedir as homedir3 } from "os";
800
- import { join as join8 } from "path";
1060
+ import { join as join12 } from "path";
801
1061
  var CAPTURE_BIN = "prim-hook";
802
1062
  var GATE_BIN = "prim-pre-tool-use";
803
1063
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -806,7 +1066,7 @@ var SESSION_END_BIN = "prim-session-end";
806
1066
  var STATUSLINE_BIN = "prim-statusline";
807
1067
  var STATUSLINE_ARGS = "";
808
1068
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
809
- var USER_SCOPE_PATH = join8(homedir3(), ".claude", "settings.json");
1069
+ var USER_SCOPE_PATH = join12(homedir3(), ".claude", "settings.json");
810
1070
  function projectRoot() {
811
1071
  return gitToplevel() ?? process.cwd();
812
1072
  }
@@ -886,20 +1146,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
886
1146
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
887
1147
  if (explicit && isAbsolute5(explicit)) return explicit;
888
1148
  const xdg = env.XDG_CONFIG_HOME?.trim();
889
- if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join9(xdg, "cursor");
890
- return join9(home, ".cursor");
1149
+ if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join13(xdg, "cursor");
1150
+ return join13(home, ".cursor");
891
1151
  }
892
1152
  function cursorHooksPath(scope, root = projectRoot()) {
893
- return scope === "user" ? join9(cursorConfigDirectory(), "hooks.json") : join9(root, ".cursor", "hooks.json");
1153
+ return scope === "user" ? join13(cursorConfigDirectory(), "hooks.json") : join13(root, ".cursor", "hooks.json");
894
1154
  }
895
1155
  function plainObject(value) {
896
1156
  return typeof value === "object" && value !== null && !Array.isArray(value);
897
1157
  }
898
1158
  function readCursorHooks(path) {
899
- if (!existsSync6(path)) return {};
1159
+ if (!existsSync8(path)) return {};
900
1160
  let parsed;
901
1161
  try {
902
- parsed = JSON.parse(readFileSync7(path, "utf8"));
1162
+ parsed = JSON.parse(readFileSync10(path, "utf8"));
903
1163
  } catch {
904
1164
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
905
1165
  }
@@ -1042,7 +1302,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1042
1302
  }
1043
1303
 
1044
1304
  // src/hooks/normalize.ts
1045
- import { createHash as createHash5 } from "crypto";
1305
+ import { createHash as createHash8 } from "crypto";
1046
1306
  import { realpathSync as realpathSync3 } from "fs";
1047
1307
  import { isAbsolute as isAbsolute6, resolve as resolve3 } from "path";
1048
1308
  var HERMES_EVENT_MAP = {
@@ -1087,7 +1347,7 @@ function requiredId(value, field) {
1087
1347
  }
1088
1348
  function cursorToolUseId(value) {
1089
1349
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
1090
- return `cursor:tool:v1:${createHash5("sha256").update(value).digest("hex")}`;
1350
+ return `cursor:tool:v1:${createHash8("sha256").update(value).digest("hex")}`;
1091
1351
  }
1092
1352
  function workspaceCandidates(value) {
1093
1353
  if (!Array.isArray(value)) return [];
@@ -1184,7 +1444,7 @@ function normalizeEnvelope(parsed, agent) {
1184
1444
  ]);
1185
1445
  return {
1186
1446
  ...parsed,
1187
- tool_use_id: `codex:fallback:v1:${createHash5("sha256").update(stableToolIdentity).digest("hex")}`
1447
+ tool_use_id: `codex:fallback:v1:${createHash8("sha256").update(stableToolIdentity).digest("hex")}`
1188
1448
  };
1189
1449
  }
1190
1450
  return parsed;