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

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 +63 -0
  2. package/dist/{chunk-5ME3WD3P.js → chunk-3OKVMKK2.js} +6 -3
  3. package/dist/chunk-5BZWFN62.js +206 -0
  4. package/dist/{chunk-FXXMDO7D.js → chunk-5KPDY5GF.js} +4 -4
  5. package/dist/{chunk-HLMC7VS4.js → chunk-5MH2C5QG.js} +3878 -2644
  6. package/dist/{chunk-NMZSCSMY.js → chunk-6PSCGY2A.js} +11 -1
  7. package/dist/{chunk-OXW6PSPT.js → chunk-6VJ7C2B5.js} +15 -3
  8. package/dist/{chunk-DQ4I3FLF.js → chunk-6W72SEXC.js} +3 -3
  9. package/dist/{chunk-4M23K2KZ.js → chunk-6WKJWW6D.js} +2 -2
  10. package/dist/{chunk-3WQ7SBOZ.js → chunk-A6YTFBQ4.js} +3 -3
  11. package/dist/{chunk-NL5VU7EU.js → chunk-DGZX3MID.js} +3 -3
  12. package/dist/{chunk-4NUGCUQC.js → chunk-EER7VG3P.js} +2 -2
  13. package/dist/{chunk-JZC2LHS6.js → chunk-EWV7VIZ3.js} +1 -1
  14. package/dist/{chunk-WN7OURQ3.js → chunk-KMWXI7KO.js} +1 -1
  15. package/dist/{chunk-LOFMI3D4.js → chunk-KTXJJE5K.js} +2 -2
  16. package/dist/{chunk-4GYJHN26.js → chunk-Q2PVD5W2.js} +1575 -549
  17. package/dist/{chunk-S3ZIMGXV.js → chunk-QZWLZH6D.js} +76 -2
  18. package/dist/{chunk-CWV5ZQR6.js → chunk-TS2NX6YT.js} +5 -5
  19. package/dist/{chunk-GOMEWFMG.js → chunk-WLVEXOHC.js} +143 -61
  20. package/dist/{chunk-RUEIVZ6T.js → chunk-WQFJ5TEG.js} +2 -2
  21. package/dist/{chunk-T2T45KF6.js → chunk-ZMH6GJUG.js} +4 -4
  22. package/dist/daemon/server.js +7795 -5449
  23. package/dist/hook-runtime/daemon/server.js +7795 -5449
  24. package/dist/hook-runtime/hooks/post-commit.js +5828 -4329
  25. package/dist/hook-runtime/hooks/post-rewrite.js +4331 -2833
  26. package/dist/hook-runtime/hooks/post-tool-use.js +5241 -2891
  27. package/dist/hook-runtime/hooks/pre-commit.js +1253 -280
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +4177 -1971
  29. package/dist/hook-runtime/hooks/prim-hook.js +4718 -2478
  30. package/dist/hook-runtime/hooks/session-end.js +392 -139
  31. package/dist/hook-runtime/hooks/session-start.js +4206 -1997
  32. package/dist/hook-runtime/index.js +6155 -3542
  33. package/dist/hook-runtime/statusline-main.js +368 -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 +229 -149
  43. package/dist/statusline-main.js +368 -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,278 @@ 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 { issuer: record.issuer, audience: record.audience };
206
+ }
207
+ function parseMachineIdentity(value, clientId) {
208
+ const data = machineRecord(value);
209
+ const principal = machineRecord(data.principal);
210
+ if (data.authenticated !== true || data.captureAuthorityKind !== "workos_m2m" || data.organizationBindingVersion !== 2 || 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))) {
211
+ throw new MachineAuthError(
212
+ "machine_identity_rejected",
213
+ "The API did not verify a machine identity.",
214
+ true
215
+ );
216
+ }
217
+ return {
218
+ machineId: principal.machineId,
219
+ clientId,
220
+ displayName: principal.displayName,
221
+ organizationId: data.organizationId,
222
+ workosOrganizationId: data.workosOrganizationId,
223
+ scopes: principal.scopes
224
+ };
225
+ }
226
+
227
+ // src/lib/paths.ts
228
+ import { homedir } from "os";
229
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
230
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
231
+ function absolutePath(value, variable) {
232
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
233
+ throw new Error(`${variable} contains unsafe characters`);
234
+ }
235
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
236
+ const normalized = normalize(value);
237
+ return normalized === value ? value : void 0;
238
+ }
239
+ function resolvePrimConfigDirectory(options = {}) {
240
+ const env = options.env ?? process.env;
241
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
242
+ if (explicit) return { path: explicit, source: "explicit" };
243
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
244
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
245
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
246
+ if (!home) {
247
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
248
+ }
249
+ return { path: join3(home, ".config", "prim"), source: "default" };
250
+ }
251
+ function primConfigDirectory(options = {}) {
252
+ return resolvePrimConfigDirectory(options).path;
253
+ }
254
+
255
+ // src/lib/machine-broker.ts
256
+ var MAX_RESPONSE_BYTES = 96 * 1024;
257
+ var IDLE_MS = 5 * 6e4;
258
+
259
+ // src/lib/machine-retry.ts
260
+ import { createHash as createHash2 } from "crypto";
261
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
262
+ import { join as join5 } from "path";
263
+
264
+ // src/lib/machine-credentials.ts
265
+ var require2 = createRequire(import.meta.url);
266
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
267
+ var PROFILE_FILE = "machine_profile.json";
268
+ var cached;
269
+ function configurationDirectory(deps) {
270
+ return deps.directory ?? primConfigDirectory({ env: deps.env });
271
+ }
272
+ function apiUrlFor(deps) {
273
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
274
+ }
275
+ function hash(value) {
276
+ return createHash3("sha256").update(value).digest("hex");
277
+ }
278
+ function environmentContextPath(deps, clientId) {
279
+ return join6(
280
+ configurationDirectory(deps),
281
+ `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
282
+ );
283
+ }
284
+ function readEnvironmentContext(environment, deps) {
285
+ try {
286
+ const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
287
+ 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())
288
+ return void 0;
289
+ const configuration = parseMachineConfiguration({
290
+ protocol_version: data.version,
291
+ issuer: data.issuer,
292
+ audience: data.audience
293
+ });
294
+ const identity = parseStoredIdentity(data);
295
+ return {
296
+ ...configuration,
297
+ ...identity,
298
+ apiUrl: data.apiUrl,
299
+ generation: environment.generation
300
+ };
301
+ } catch {
302
+ return void 0;
303
+ }
304
+ }
305
+ function readPrivate(path) {
306
+ let raw;
307
+ try {
308
+ const stat = lstatSync3(path);
309
+ if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
310
+ throw new MachineAuthError(
311
+ "unsafe_storage",
312
+ "Machine credential files must be owner-only regular files."
313
+ );
314
+ }
315
+ raw = readFileSync5(path, "utf8");
316
+ } catch (error) {
317
+ if (error.code === "ENOENT") return void 0;
318
+ throw error;
319
+ }
320
+ try {
321
+ return JSON.parse(raw);
322
+ } catch {
323
+ throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
324
+ }
325
+ }
326
+ function parseStoredIdentity(data) {
327
+ return parseMachineIdentity(
328
+ {
329
+ authenticated: true,
330
+ organizationBindingVersion: 2,
331
+ captureAuthorityKind: "workos_m2m",
332
+ organizationId: data.organizationId,
333
+ workosOrganizationId: data.workosOrganizationId,
334
+ principal: { ...data, kind: "machine" }
335
+ },
336
+ String(data.clientId)
337
+ );
338
+ }
339
+ function parseProfile(value) {
340
+ const data = machineRecord(value);
341
+ const config = parseMachineConfiguration({
342
+ protocol_version: data.version,
343
+ issuer: data.issuer,
344
+ audience: data.audience
345
+ });
346
+ 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)) {
347
+ throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
348
+ }
349
+ const identity = parseStoredIdentity(data);
350
+ return {
351
+ ...config,
352
+ ...identity,
353
+ version: 1,
354
+ apiUrl: data.apiUrl,
355
+ generation: data.generation,
356
+ storage: data.storage
357
+ };
358
+ }
359
+ function readMachineProfile(deps = {}) {
360
+ const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
361
+ return value === void 0 ? void 0 : parseProfile(value);
362
+ }
363
+ function environmentCredentials(deps) {
364
+ const env = deps.env ?? process.env;
365
+ const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
366
+ if (clientId === void 0 && clientSecret === void 0) return void 0;
367
+ if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
368
+ throw new MachineAuthError(
369
+ "incomplete_machine_credentials",
370
+ "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
371
+ );
372
+ }
373
+ return {
374
+ clientId,
375
+ clientSecret,
376
+ generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
377
+ };
378
+ }
379
+ function hasMachineConfiguration(deps = {}) {
380
+ const env = deps.env ?? process.env;
381
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
382
+ if (configured && env.PRIM_TOKEN?.trim()) {
383
+ throw new MachineAuthError(
384
+ "conflicting_credentials",
385
+ "Unset PRIM_TOKEN when using machine credentials."
386
+ );
387
+ }
388
+ if (configured) environmentCredentials(deps);
389
+ return configured;
390
+ }
391
+ function machineContext(deps = {}) {
392
+ if (!hasMachineConfiguration(deps)) return void 0;
393
+ const environment = environmentCredentials(deps);
394
+ if (environment) {
395
+ if (environmentTerminal === environment.generation) return void 0;
396
+ return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
397
+ }
398
+ const profile = readMachineProfile(deps);
399
+ if (profile && profile.apiUrl !== apiUrlFor(deps))
400
+ throw new MachineAuthError(
401
+ "deployment_mismatch",
402
+ "Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
403
+ );
404
+ return profile;
405
+ }
406
+ function cachedMachineCredential(deps = {}) {
407
+ const context = machineContext(deps);
408
+ return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
409
+ }
410
+ var environmentTerminal;
411
+
119
412
  // src/lib/credentials.ts
120
413
  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");
414
+ var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
415
+ var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
416
+ var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
417
+ var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
418
+ var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
419
+ var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
420
+ var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
421
+ var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
129
422
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
130
423
  var CREDENTIAL_MIGRATION_VERSION = 1;
131
424
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
132
425
  function readTrimmed(path) {
133
426
  try {
134
- const value = readFileSync(path, "utf8").trim();
427
+ const value = readFileSync6(path, "utf8").trim();
135
428
  return value || void 0;
136
429
  } catch {
137
430
  return void 0;
138
431
  }
139
432
  }
140
433
  function resolveAuthCredential(options = {}) {
434
+ if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
435
+ const machine = cachedMachineCredential({ env: options.env });
436
+ return machine ? { token: machine.accessToken, source: "machine" } : void 0;
437
+ }
141
438
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
142
439
  if (envToken) return { token: envToken, source: "environment" };
143
440
  const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
@@ -164,7 +461,7 @@ function resolveAuthCredential(options = {}) {
164
461
  return { token: stored, source: "token_file" };
165
462
  }
166
463
  function credentialFingerprint(value) {
167
- return createHash("sha256").update(value).digest("hex");
464
+ return createHash4("sha256").update(value).digest("hex");
168
465
  }
169
466
  function parseLegacyBrokerCredentialMetadata(value) {
170
467
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -184,7 +481,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
184
481
  function readBoundedCredentialJson(path) {
185
482
  let raw;
186
483
  try {
187
- raw = readFileSync(path, "utf8");
484
+ raw = readFileSync6(path, "utf8");
188
485
  } catch (error) {
189
486
  return error.code === "ENOENT" ? void 0 : null;
190
487
  }
@@ -257,9 +554,17 @@ function boundedClaim(value) {
257
554
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
258
555
  }
259
556
  function sha256(value) {
260
- return createHash2("sha256").update(value).digest("hex");
557
+ return createHash5("sha256").update(value).digest("hex");
261
558
  }
262
559
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
560
+ if (hasMachineConfiguration()) {
561
+ const machine = machineContext();
562
+ return machine ? {
563
+ principalId: sha256(`${machine.issuer}\0${machine.clientId}`),
564
+ organizationId: machine.workosOrganizationId,
565
+ credentialFingerprint: sha256(machine.generation)
566
+ } : void 0;
567
+ }
263
568
  if (!token) return void 0;
264
569
  const payload = decodeJwtPayload(token);
265
570
  const subject = boundedClaim(payload?.sub);
@@ -298,8 +603,8 @@ function parseDaemonResponseEnvelope(value) {
298
603
 
299
604
  // src/daemon/client.ts
300
605
  import { createConnection } from "net";
301
- import { join as join3 } from "path";
302
- var SOCK_PATH = join3(primConfigDirectory(), "sock");
606
+ import { join as join8 } from "path";
607
+ var SOCK_PATH = join8(primConfigDirectory(), "sock");
303
608
  var DEFAULT_TIMEOUT_MS = 250;
304
609
  var nextRequestId = 1;
305
610
  function daemonRequest(method, params = {}, opts = {}) {
@@ -389,19 +694,19 @@ function daemonRequest(method, params = {}, opts = {}) {
389
694
  }
390
695
 
391
696
  // src/lib/activation.ts
392
- import { execFileSync as execFileSync3 } from "child_process";
393
- import { existsSync, readFileSync as readFileSync2 } from "fs";
697
+ import { execFileSync as execFileSync4 } from "child_process";
698
+ import { existsSync as existsSync4, readFileSync as readFileSync7 } from "fs";
394
699
  import { homedir as homedir2 } from "os";
395
- import { join as join4 } from "path";
700
+ import { join as join9 } from "path";
396
701
 
397
702
  // src/lib/demo-pause.ts
398
- import { execFileSync } from "child_process";
703
+ import { execFileSync as execFileSync2 } from "child_process";
399
704
  var DEMO_PAUSE_MS = 30 * 6e4;
400
705
  var PAUSE_KEY = "prim.demoPause";
401
706
  var GIT_TIMEOUT_MS = 1e3;
402
707
  function git(cwd, args) {
403
708
  try {
404
- return execFileSync("git", args, {
709
+ return execFileSync2("git", args, {
405
710
  cwd,
406
711
  encoding: "utf-8",
407
712
  stdio: ["ignore", "pipe", "ignore"],
@@ -413,7 +718,7 @@ function git(cwd, args) {
413
718
  }
414
719
  function setLocal(cwd, key, value) {
415
720
  try {
416
- execFileSync(
721
+ execFileSync2(
417
722
  "git",
418
723
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
419
724
  { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
@@ -456,16 +761,16 @@ function healDemoPause(cwd, pause, options = {}) {
456
761
  }
457
762
 
458
763
  // 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";
764
+ import { execFileSync as execFileSync3 } from "child_process";
765
+ import { createHash as createHash6 } from "crypto";
766
+ import { lstatSync as lstatSync4, realpathSync } from "fs";
767
+ import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve, sep } from "path";
463
768
  var GIT_TIMEOUT_MS2 = 1e3;
464
769
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
465
770
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
466
771
  function gitToplevel(cwd) {
467
772
  try {
468
- return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
773
+ return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
469
774
  cwd,
470
775
  encoding: "utf-8",
471
776
  stdio: ["ignore", "pipe", "ignore"],
@@ -477,7 +782,7 @@ function gitToplevel(cwd) {
477
782
  }
478
783
  function gitValue(cwd, args) {
479
784
  try {
480
- const value = execFileSync2("git", args, {
785
+ const value = execFileSync3("git", args, {
481
786
  cwd,
482
787
  encoding: "utf-8",
483
788
  stdio: ["ignore", "pipe", "ignore"],
@@ -524,7 +829,7 @@ function normalizeOriginRemote(remote) {
524
829
  }
525
830
  }
526
831
  function opaqueRepoKey(source, value) {
527
- return `repo_v1_${createHash3("sha256").update(`${source}\0${value}`).digest("hex")}`;
832
+ return `repo_v1_${createHash6("sha256").update(`${source}\0${value}`).digest("hex")}`;
528
833
  }
529
834
  function resolveRepositoryContext(cwd = process.cwd()) {
530
835
  const top = gitToplevel(cwd);
@@ -565,7 +870,7 @@ var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cur
565
870
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
566
871
  function repoActiveFlag(cwd, strict = false) {
567
872
  try {
568
- const value = execFileSync3("git", ["config", "--get", PRIM_ACTIVE_KEY], {
873
+ const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
569
874
  cwd,
570
875
  encoding: "utf-8",
571
876
  stdio: ["ignore", "pipe", "ignore"],
@@ -585,10 +890,10 @@ function hasProjectPrimInstall(cwd) {
585
890
  const root = gitToplevel(cwd);
586
891
  if (root === null || root === homedir2()) return false;
587
892
  for (const rel of PROJECT_INSTALL_FILES) {
588
- const path = join4(root, rel);
589
- if (existsSync(path)) {
893
+ const path = join9(root, rel);
894
+ if (existsSync4(path)) {
590
895
  try {
591
- const content = readFileSync2(path, "utf-8");
896
+ const content = readFileSync7(path, "utf-8");
592
897
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
593
898
  } catch {
594
899
  }
@@ -615,90 +920,31 @@ function parseAgent(argv) {
615
920
  }
616
921
 
617
922
  // src/commands/cursor-install.ts
618
- import { existsSync as existsSync6, readFileSync as readFileSync7 } from "fs";
923
+ import { existsSync as existsSync8, readFileSync as readFileSync10 } from "fs";
619
924
  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
- }
925
+ import { isAbsolute as isAbsolute5, join as join13 } from "path";
674
926
 
675
927
  // src/lib/hook-runtime.ts
676
- import { createHash as createHash4, randomBytes as randomBytes2 } from "crypto";
928
+ import { createHash as createHash7, randomBytes as randomBytes3 } from "crypto";
677
929
  import {
678
930
  constants as constants2,
679
931
  accessSync,
680
- chmodSync,
932
+ chmodSync as chmodSync2,
681
933
  copyFileSync,
682
- existsSync as existsSync4,
683
- lstatSync as lstatSync2,
684
- mkdirSync as mkdirSync3,
934
+ existsSync as existsSync6,
935
+ lstatSync as lstatSync5,
936
+ mkdirSync as mkdirSync4,
685
937
  mkdtempSync,
686
- readFileSync as readFileSync5,
938
+ readFileSync as readFileSync8,
687
939
  readdirSync,
688
940
  realpathSync as realpathSync2,
689
941
  renameSync as renameSync2,
690
- rmSync as rmSync3,
942
+ rmSync as rmSync6,
691
943
  statSync as statSync2,
692
944
  utimesSync,
693
945
  writeFileSync as writeFileSync3
694
946
  } 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));
947
+ import { delimiter, dirname as dirname7, isAbsolute as isAbsolute4, join as join11, resolve as resolve2 } from "path";
702
948
 
703
949
  // src/lib/git-hook-contract.ts
704
950
  var GIT_HOOK_ENTRYPOINT_CONTENT = `#!/bin/sh
@@ -745,6 +991,13 @@ esac
745
991
  exit 0
746
992
  `;
747
993
 
994
+ // src/lib/native-keyring.ts
995
+ import { existsSync as existsSync5 } from "fs";
996
+ import { createRequire as createRequire2 } from "module";
997
+ import { dirname as dirname6, join as join10 } from "path";
998
+ import { fileURLToPath as fileURLToPath4 } from "url";
999
+ var require3 = createRequire2(import.meta.url);
1000
+
748
1001
  // src/lib/hook-runtime.ts
749
1002
  var RELEASE_PREFIX = "release-";
750
1003
  var MAX_MANIFEST_BYTES = 64 * 1024;
@@ -792,12 +1045,12 @@ exec "$prim_node" "$prim_entry" "$@"
792
1045
  `;
793
1046
 
794
1047
  // src/lib/preflight-host.ts
795
- import { execFileSync as execFileSync4 } from "child_process";
1048
+ import { execFileSync as execFileSync5 } from "child_process";
796
1049
 
797
1050
  // src/commands/claude-install.ts
798
- import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
1051
+ import { existsSync as existsSync7, readFileSync as readFileSync9 } from "fs";
799
1052
  import { homedir as homedir3 } from "os";
800
- import { join as join8 } from "path";
1053
+ import { join as join12 } from "path";
801
1054
  var CAPTURE_BIN = "prim-hook";
802
1055
  var GATE_BIN = "prim-pre-tool-use";
803
1056
  var POST_TOOL_USE_BIN = "prim-post-tool-use";
@@ -806,7 +1059,7 @@ var SESSION_END_BIN = "prim-session-end";
806
1059
  var STATUSLINE_BIN = "prim-statusline";
807
1060
  var STATUSLINE_ARGS = "";
808
1061
  var STATUSLINE_COMMAND = stableHookCommand(STATUSLINE_BIN, STATUSLINE_ARGS);
809
- var USER_SCOPE_PATH = join8(homedir3(), ".claude", "settings.json");
1062
+ var USER_SCOPE_PATH = join12(homedir3(), ".claude", "settings.json");
810
1063
  function projectRoot() {
811
1064
  return gitToplevel() ?? process.cwd();
812
1065
  }
@@ -886,20 +1139,20 @@ function cursorConfigDirectory(env = process.env, home = homedir4(), platform =
886
1139
  const explicit = env.CURSOR_CONFIG_DIR?.trim();
887
1140
  if (explicit && isAbsolute5(explicit)) return explicit;
888
1141
  const xdg = env.XDG_CONFIG_HOME?.trim();
889
- if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join9(xdg, "cursor");
890
- return join9(home, ".cursor");
1142
+ if (platform !== "darwin" && xdg && isAbsolute5(xdg)) return join13(xdg, "cursor");
1143
+ return join13(home, ".cursor");
891
1144
  }
892
1145
  function cursorHooksPath(scope, root = projectRoot()) {
893
- return scope === "user" ? join9(cursorConfigDirectory(), "hooks.json") : join9(root, ".cursor", "hooks.json");
1146
+ return scope === "user" ? join13(cursorConfigDirectory(), "hooks.json") : join13(root, ".cursor", "hooks.json");
894
1147
  }
895
1148
  function plainObject(value) {
896
1149
  return typeof value === "object" && value !== null && !Array.isArray(value);
897
1150
  }
898
1151
  function readCursorHooks(path) {
899
- if (!existsSync6(path)) return {};
1152
+ if (!existsSync8(path)) return {};
900
1153
  let parsed;
901
1154
  try {
902
- parsed = JSON.parse(readFileSync7(path, "utf8"));
1155
+ parsed = JSON.parse(readFileSync10(path, "utf8"));
903
1156
  } catch {
904
1157
  throw new Error(`invalid Cursor hooks JSON at ${path}`);
905
1158
  }
@@ -1042,7 +1295,7 @@ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
1042
1295
  }
1043
1296
 
1044
1297
  // src/hooks/normalize.ts
1045
- import { createHash as createHash5 } from "crypto";
1298
+ import { createHash as createHash8 } from "crypto";
1046
1299
  import { realpathSync as realpathSync3 } from "fs";
1047
1300
  import { isAbsolute as isAbsolute6, resolve as resolve3 } from "path";
1048
1301
  var HERMES_EVENT_MAP = {
@@ -1087,7 +1340,7 @@ function requiredId(value, field) {
1087
1340
  }
1088
1341
  function cursorToolUseId(value) {
1089
1342
  if (SAFE_CORRELATION_ID_RE.test(value)) return value;
1090
- return `cursor:tool:v1:${createHash5("sha256").update(value).digest("hex")}`;
1343
+ return `cursor:tool:v1:${createHash8("sha256").update(value).digest("hex")}`;
1091
1344
  }
1092
1345
  function workspaceCandidates(value) {
1093
1346
  if (!Array.isArray(value)) return [];
@@ -1184,7 +1437,7 @@ function normalizeEnvelope(parsed, agent) {
1184
1437
  ]);
1185
1438
  return {
1186
1439
  ...parsed,
1187
- tool_use_id: `codex:fallback:v1:${createHash5("sha256").update(stableToolIdentity).digest("hex")}`
1440
+ tool_use_id: `codex:fallback:v1:${createHash8("sha256").update(stableToolIdentity).digest("hex")}`
1188
1441
  };
1189
1442
  }
1190
1443
  return parsed;