@primitive.ai/prim 0.1.0-alpha.122 → 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 (47) hide show
  1. package/README.md +81 -5
  2. package/dist/{chunk-5ME3WD3P.js → chunk-3OKVMKK2.js} +6 -3
  3. package/dist/chunk-5BZWFN62.js +206 -0
  4. package/dist/{chunk-QG3GASJO.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-JYPVPYW3.js → chunk-A6YTFBQ4.js} +3 -3
  11. package/dist/{chunk-7LXRFXZG.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-HG7FJK7R.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-ZQ7UK5US.js → chunk-TS2NX6YT.js} +31 -9
  19. package/dist/{chunk-AKGRY7OU.js → chunk-WLVEXOHC.js} +145 -63
  20. package/dist/{chunk-FT673ALA.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 +5242 -2892
  27. package/dist/hook-runtime/hooks/pre-commit.js +1253 -280
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +4272 -1982
  29. package/dist/hook-runtime/hooks/pre-tool-use.js +13 -3
  30. package/dist/hook-runtime/hooks/prim-hook.js +4719 -2479
  31. package/dist/hook-runtime/hooks/session-end.js +393 -140
  32. package/dist/hook-runtime/hooks/session-start.js +4207 -1998
  33. package/dist/hook-runtime/index.js +6157 -3544
  34. package/dist/hook-runtime/statusline-main.js +368 -122
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +31 -21
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +88 -18
  40. package/dist/hooks/pre-tool-use.js +13 -3
  41. package/dist/hooks/prim-hook.js +16 -16
  42. package/dist/hooks/session-end.js +4 -4
  43. package/dist/hooks/session-start.js +16 -12
  44. package/dist/index.js +230 -150
  45. package/dist/statusline-main.js +368 -122
  46. package/package.json +5 -2
  47. package/dist/chunk-RRAC76LJ.js +0 -36
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/commands/statusline.ts
4
- import { readFileSync as readFileSync7 } from "fs";
5
- import { dirname as dirname6, resolve as resolve3 } from "path";
6
- import { fileURLToPath as fileURLToPath2 } from "url";
4
+ import { readFileSync as readFileSync10 } from "fs";
5
+ import { dirname as dirname7, resolve as resolve3 } from "path";
6
+ import { fileURLToPath as fileURLToPath4 } from "url";
7
7
 
8
8
  // src/client.ts
9
- import { createHash as createHash2 } from "crypto";
10
- import { chmodSync as chmodSync2, existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync3 } from "fs";
11
- import { dirname as dirname4 } from "path";
9
+ import { createHash as createHash5 } from "crypto";
10
+ import { chmodSync as chmodSync3, existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync8, rmSync as rmSync6 } from "fs";
11
+ import { dirname as dirname5 } from "path";
12
12
 
13
13
  // src/lib/atomic-file.ts
14
14
  import { randomUUID } from "crypto";
@@ -26,37 +26,75 @@ import {
26
26
  import { dirname } from "path";
27
27
 
28
28
  // src/lib/credentials.ts
29
- import { createHash } from "crypto";
30
- import { readFileSync } from "fs";
31
- import { join as join2 } from "path";
29
+ import { createHash as createHash4 } from "crypto";
30
+ import { readFileSync as readFileSync6 } from "fs";
31
+ import { join as join7 } from "path";
32
32
 
33
- // src/lib/paths.ts
34
- import { homedir } from "os";
35
- import { isAbsolute, join, normalize } from "path";
36
- var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
37
- function absolutePath(value, variable) {
38
- if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
39
- throw new Error(`${variable} contains unsafe characters`);
33
+ // src/lib/machine-credentials.ts
34
+ import { execFileSync } from "child_process";
35
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "crypto";
36
+ import { chmodSync, existsSync as existsSync3, lstatSync as lstatSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5, rmSync as rmSync5 } from "fs";
37
+ import { createRequire } from "module";
38
+ import { dirname as dirname4, join as join6 } from "path";
39
+ import { fileURLToPath as fileURLToPath3 } from "url";
40
+
41
+ // src/lib/file-lock.ts
42
+ import { randomBytes } from "crypto";
43
+ import { existsSync, mkdirSync as mkdirSync2, readFileSync, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
44
+ import { dirname as dirname2, join } from "path";
45
+ var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
46
+
47
+ // src/lib/machine-broker.ts
48
+ import { spawn } from "child_process";
49
+ import { createHash, createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
50
+ import { lstatSync, readFileSync as readFileSync3, rmSync as rmSync3 } from "fs";
51
+ import { createServer } from "http";
52
+ import { basename, join as join4 } from "path";
53
+ import { fileURLToPath as fileURLToPath2 } from "url";
54
+
55
+ // src/lib/bin-path.ts
56
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
57
+ import { dirname as dirname3, isAbsolute, join as join2 } from "path";
58
+ import { fileURLToPath } from "url";
59
+ var PKG_NAME = "@primitive.ai/prim";
60
+ var ROOT_WALK_LIMIT = 6;
61
+ var resolvedRoot;
62
+ function locateRoot() {
63
+ if (resolvedRoot !== void 0) {
64
+ return resolvedRoot;
40
65
  }
41
- if (!value || value.trim() !== value || !isAbsolute(value)) return;
42
- const normalized = normalize(value);
43
- return normalized === value ? value : void 0;
44
- }
45
- function resolvePrimConfigDirectory(options = {}) {
46
- const env = options.env ?? process.env;
47
- const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
48
- if (explicit) return { path: explicit, source: "explicit" };
49
- const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
50
- if (xdgConfigHome) return { path: join(xdgConfigHome, "prim"), source: "xdg" };
51
- const home = absolutePath(options.homeDir ?? homedir(), "HOME");
52
- if (!home) {
53
- throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
66
+ let dir = dirname3(fileURLToPath(import.meta.url));
67
+ for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
68
+ const manifestPath = join2(dir, "package.json");
69
+ if (existsSync2(manifestPath)) {
70
+ try {
71
+ const manifest = JSON.parse(readFileSync2(manifestPath, "utf-8"));
72
+ if (manifest.name === PKG_NAME && manifest.bin) {
73
+ resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
74
+ return resolvedRoot;
75
+ }
76
+ } catch {
77
+ }
78
+ }
79
+ const parent = dirname3(dir);
80
+ if (parent === dir) {
81
+ break;
82
+ }
83
+ dir = parent;
54
84
  }
55
- return { path: join(home, ".config", "prim"), source: "default" };
85
+ resolvedRoot = null;
86
+ return resolvedRoot;
56
87
  }
57
- function primConfigDirectory(options = {}) {
58
- return resolvePrimConfigDirectory(options).path;
88
+ function packageVersion() {
89
+ return locateRoot()?.version ?? null;
59
90
  }
91
+ var PRIM_CONFIG_SHELL_RESOLVER = [
92
+ 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
93
+ 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
94
+ 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
95
+ '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; ',
96
+ "fi; fi; "
97
+ ].join("");
60
98
 
61
99
  // src/lib/workos-connect.ts
62
100
  var DISCOVERY_MAX_BYTES = 16 * 1024;
@@ -137,28 +175,278 @@ function parseWorkosConnectCredentialMetadata(value) {
137
175
  };
138
176
  }
139
177
 
178
+ // src/lib/machine-protocol.ts
179
+ var MachineAuthError = class extends Error {
180
+ constructor(code, message, terminal = false, retryAt) {
181
+ super(message);
182
+ this.code = code;
183
+ this.terminal = terminal;
184
+ this.retryAt = retryAt;
185
+ this.name = "MachineAuthError";
186
+ }
187
+ };
188
+ function machineString(value, maximum = 4096) {
189
+ return typeof value === "string" && value.length > 0 && value.length <= maximum && value.trim() === value && !/[\p{Cc}\p{Cf}]/u.test(value);
190
+ }
191
+ function machineRecord(value) {
192
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
193
+ throw new MachineAuthError("invalid_response", "Invalid machine authentication response.");
194
+ }
195
+ return value;
196
+ }
197
+ function machineApiUrl(value) {
198
+ const url = new URL(value);
199
+ const local = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
200
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:") || url.username || url.password || url.search || url.hash || url.pathname !== "/") {
201
+ throw new MachineAuthError("invalid_configuration", "The API URL must be an HTTPS origin.");
202
+ }
203
+ return url.origin;
204
+ }
205
+ function parseMachineConfiguration(value) {
206
+ const record = machineRecord(value);
207
+ if (record.protocol_version !== 1 || !machineString(record.issuer, 2048) || !machineString(record.audience, 256) || !/^client_[\w-]+$/u.test(record.audience)) {
208
+ throw new MachineAuthError("invalid_configuration", "Invalid M2M discovery configuration.");
209
+ }
210
+ const issuer = new URL(record.issuer);
211
+ if (issuer.protocol !== "https:" || issuer.origin !== record.issuer) {
212
+ throw new MachineAuthError(
213
+ "invalid_configuration",
214
+ "The WorkOS issuer must be an HTTPS origin."
215
+ );
216
+ }
217
+ return { issuer: record.issuer, audience: record.audience };
218
+ }
219
+ function parseMachineIdentity(value, clientId) {
220
+ const data = machineRecord(value);
221
+ const principal = machineRecord(data.principal);
222
+ 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))) {
223
+ throw new MachineAuthError(
224
+ "machine_identity_rejected",
225
+ "The API did not verify a machine identity.",
226
+ true
227
+ );
228
+ }
229
+ return {
230
+ machineId: principal.machineId,
231
+ clientId,
232
+ displayName: principal.displayName,
233
+ organizationId: data.organizationId,
234
+ workosOrganizationId: data.workosOrganizationId,
235
+ scopes: principal.scopes
236
+ };
237
+ }
238
+
239
+ // src/lib/paths.ts
240
+ import { homedir } from "os";
241
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
242
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
243
+ function absolutePath(value, variable) {
244
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
245
+ throw new Error(`${variable} contains unsafe characters`);
246
+ }
247
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
248
+ const normalized = normalize(value);
249
+ return normalized === value ? value : void 0;
250
+ }
251
+ function resolvePrimConfigDirectory(options = {}) {
252
+ const env = options.env ?? process.env;
253
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
254
+ if (explicit) return { path: explicit, source: "explicit" };
255
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
256
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
257
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
258
+ if (!home) {
259
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
260
+ }
261
+ return { path: join3(home, ".config", "prim"), source: "default" };
262
+ }
263
+ function primConfigDirectory(options = {}) {
264
+ return resolvePrimConfigDirectory(options).path;
265
+ }
266
+
267
+ // src/lib/machine-broker.ts
268
+ var MAX_RESPONSE_BYTES = 96 * 1024;
269
+ var IDLE_MS = 5 * 6e4;
270
+
271
+ // src/lib/machine-retry.ts
272
+ import { createHash as createHash2 } from "crypto";
273
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
274
+ import { join as join5 } from "path";
275
+
276
+ // src/lib/machine-credentials.ts
277
+ var require2 = createRequire(import.meta.url);
278
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
279
+ var PROFILE_FILE = "machine_profile.json";
280
+ var cached;
281
+ function configurationDirectory(deps) {
282
+ return deps.directory ?? primConfigDirectory({ env: deps.env });
283
+ }
284
+ function apiUrlFor(deps) {
285
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
286
+ }
287
+ function hash(value) {
288
+ return createHash3("sha256").update(value).digest("hex");
289
+ }
290
+ function environmentContextPath(deps, clientId) {
291
+ return join6(
292
+ configurationDirectory(deps),
293
+ `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
294
+ );
295
+ }
296
+ function readEnvironmentContext(environment, deps) {
297
+ try {
298
+ const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
299
+ 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())
300
+ return void 0;
301
+ const configuration = parseMachineConfiguration({
302
+ protocol_version: data.version,
303
+ issuer: data.issuer,
304
+ audience: data.audience
305
+ });
306
+ const identity = parseStoredIdentity(data);
307
+ return {
308
+ ...configuration,
309
+ ...identity,
310
+ apiUrl: data.apiUrl,
311
+ generation: environment.generation
312
+ };
313
+ } catch {
314
+ return void 0;
315
+ }
316
+ }
317
+ function readPrivate(path) {
318
+ let raw;
319
+ try {
320
+ const stat = lstatSync3(path);
321
+ if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
322
+ throw new MachineAuthError(
323
+ "unsafe_storage",
324
+ "Machine credential files must be owner-only regular files."
325
+ );
326
+ }
327
+ raw = readFileSync5(path, "utf8");
328
+ } catch (error) {
329
+ if (error.code === "ENOENT") return void 0;
330
+ throw error;
331
+ }
332
+ try {
333
+ return JSON.parse(raw);
334
+ } catch {
335
+ throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
336
+ }
337
+ }
338
+ function parseStoredIdentity(data) {
339
+ return parseMachineIdentity(
340
+ {
341
+ authenticated: true,
342
+ organizationBindingVersion: 2,
343
+ captureAuthorityKind: "workos_m2m",
344
+ organizationId: data.organizationId,
345
+ workosOrganizationId: data.workosOrganizationId,
346
+ principal: { ...data, kind: "machine" }
347
+ },
348
+ String(data.clientId)
349
+ );
350
+ }
351
+ function parseProfile(value) {
352
+ const data = machineRecord(value);
353
+ const config = parseMachineConfiguration({
354
+ protocol_version: data.version,
355
+ issuer: data.issuer,
356
+ audience: data.audience
357
+ });
358
+ 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)) {
359
+ throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
360
+ }
361
+ const identity = parseStoredIdentity(data);
362
+ return {
363
+ ...config,
364
+ ...identity,
365
+ version: 1,
366
+ apiUrl: data.apiUrl,
367
+ generation: data.generation,
368
+ storage: data.storage
369
+ };
370
+ }
371
+ function readMachineProfile(deps = {}) {
372
+ const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
373
+ return value === void 0 ? void 0 : parseProfile(value);
374
+ }
375
+ function environmentCredentials(deps) {
376
+ const env = deps.env ?? process.env;
377
+ const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
378
+ if (clientId === void 0 && clientSecret === void 0) return void 0;
379
+ if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
380
+ throw new MachineAuthError(
381
+ "incomplete_machine_credentials",
382
+ "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
383
+ );
384
+ }
385
+ return {
386
+ clientId,
387
+ clientSecret,
388
+ generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
389
+ };
390
+ }
391
+ function hasMachineConfiguration(deps = {}) {
392
+ const env = deps.env ?? process.env;
393
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
394
+ if (configured && env.PRIM_TOKEN?.trim()) {
395
+ throw new MachineAuthError(
396
+ "conflicting_credentials",
397
+ "Unset PRIM_TOKEN when using machine credentials."
398
+ );
399
+ }
400
+ if (configured) environmentCredentials(deps);
401
+ return configured;
402
+ }
403
+ function machineContext(deps = {}) {
404
+ if (!hasMachineConfiguration(deps)) return void 0;
405
+ const environment = environmentCredentials(deps);
406
+ if (environment) {
407
+ if (environmentTerminal === environment.generation) return void 0;
408
+ return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
409
+ }
410
+ const profile = readMachineProfile(deps);
411
+ if (profile && profile.apiUrl !== apiUrlFor(deps))
412
+ throw new MachineAuthError(
413
+ "deployment_mismatch",
414
+ "Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
415
+ );
416
+ return profile;
417
+ }
418
+ function cachedMachineCredential(deps = {}) {
419
+ const context = machineContext(deps);
420
+ return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
421
+ }
422
+ var environmentTerminal;
423
+
140
424
  // src/lib/credentials.ts
141
425
  var CONFIG_DIRECTORY = primConfigDirectory();
142
- var TOKEN_FILE_PATH = join2(CONFIG_DIRECTORY, "token");
143
- var REFRESH_TOKEN_PATH = join2(CONFIG_DIRECTORY, "refresh_token");
144
- var TOKEN_EXPIRES_PATH = join2(CONFIG_DIRECTORY, "token_expires_at");
145
- var TERMINAL_REFRESH_PATH = join2(CONFIG_DIRECTORY, "refresh_terminal");
146
- var CREDENTIAL_METADATA_PATH = join2(CONFIG_DIRECTORY, "credential_metadata.json");
147
- var CREDENTIAL_FAMILY_PATH = join2(CONFIG_DIRECTORY, "credential_family.json");
148
- var CREDENTIAL_MIGRATION_PATH = join2(CONFIG_DIRECTORY, "credential_migration.json");
149
- var CREDENTIAL_LOCK_PATH = join2(CONFIG_DIRECTORY, "credentials.lock");
426
+ var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
427
+ var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
428
+ var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
429
+ var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
430
+ var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
431
+ var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
432
+ var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
433
+ var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
150
434
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
151
435
  var CREDENTIAL_MIGRATION_VERSION = 1;
152
436
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
153
437
  function readTrimmed(path) {
154
438
  try {
155
- const value = readFileSync(path, "utf8").trim();
439
+ const value = readFileSync6(path, "utf8").trim();
156
440
  return value || void 0;
157
441
  } catch {
158
442
  return void 0;
159
443
  }
160
444
  }
161
445
  function resolveAuthCredential(options = {}) {
446
+ if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
447
+ const machine = cachedMachineCredential({ env: options.env });
448
+ return machine ? { token: machine.accessToken, source: "machine" } : void 0;
449
+ }
162
450
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
163
451
  if (envToken) return { token: envToken, source: "environment" };
164
452
  const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
@@ -185,7 +473,7 @@ function resolveAuthCredential(options = {}) {
185
473
  return { token: stored, source: "token_file" };
186
474
  }
187
475
  function credentialFingerprint(value) {
188
- return createHash("sha256").update(value).digest("hex");
476
+ return createHash4("sha256").update(value).digest("hex");
189
477
  }
190
478
  function parseLegacyBrokerCredentialMetadata(value) {
191
479
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -205,7 +493,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
205
493
  function readBoundedCredentialJson(path) {
206
494
  let raw;
207
495
  try {
208
- raw = readFileSync(path, "utf8");
496
+ raw = readFileSync6(path, "utf8");
209
497
  } catch (error) {
210
498
  return error.code === "ENOENT" ? void 0 : null;
211
499
  }
@@ -272,64 +560,14 @@ function decodeJwtPayload(token) {
272
560
  }
273
561
  }
274
562
 
275
- // src/lib/file-lock.ts
276
- import { randomBytes } from "crypto";
277
- import { existsSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, rmSync as rmSync2, statSync, writeFileSync as writeFileSync2 } from "fs";
278
- import { dirname as dirname2, join as join3 } from "path";
279
- var syncSleeper = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
280
-
281
563
  // src/daemon/client-instance-id.ts
282
- import { randomBytes as randomBytes2 } from "crypto";
283
- import { chmodSync, lstatSync, readFileSync as readFileSync3 } from "fs";
284
- import { join as join4 } from "path";
564
+ import { randomBytes as randomBytes3 } from "crypto";
565
+ import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
566
+ import { join as join8 } from "path";
285
567
  var INSTANCE_BODY_CHARS = 43;
286
568
  var INSTANCE_PREFIX = "pci_";
287
569
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
288
570
 
289
- // src/lib/bin-path.ts
290
- import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
291
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join5 } from "path";
292
- import { fileURLToPath } from "url";
293
- var PKG_NAME = "@primitive.ai/prim";
294
- var ROOT_WALK_LIMIT = 6;
295
- var resolvedRoot;
296
- function locateRoot() {
297
- if (resolvedRoot !== void 0) {
298
- return resolvedRoot;
299
- }
300
- let dir = dirname3(fileURLToPath(import.meta.url));
301
- for (let depth = 0; depth < ROOT_WALK_LIMIT; depth++) {
302
- const manifestPath = join5(dir, "package.json");
303
- if (existsSync2(manifestPath)) {
304
- try {
305
- const manifest = JSON.parse(readFileSync4(manifestPath, "utf-8"));
306
- if (manifest.name === PKG_NAME && manifest.bin) {
307
- resolvedRoot = { dir, version: manifest.version, bin: manifest.bin };
308
- return resolvedRoot;
309
- }
310
- } catch {
311
- }
312
- }
313
- const parent = dirname3(dir);
314
- if (parent === dir) {
315
- break;
316
- }
317
- dir = parent;
318
- }
319
- resolvedRoot = null;
320
- return resolvedRoot;
321
- }
322
- function packageVersion() {
323
- return locateRoot()?.version ?? null;
324
- }
325
- var PRIM_CONFIG_SHELL_RESOLVER = [
326
- 'prim_absolute() { case "$1" in [/]* ) ;; *) return 1 ;; esac; case "$1" in [[:space:]]*|*[[:space:]]|*[/][/]*|*[/].[/]*|*[/]..[/]*|*[/].|*[/]..|?*[/]) return 1 ;; esac; }; ',
327
- 'prim_config=${PRIM_CONFIG_DIR:-}; if ! prim_absolute "$prim_config"; then prim_config=${XDG_CONFIG_HOME:-}; if prim_absolute "$prim_config"; then ',
328
- 'case "$prim_config" in /) prim_config=/prim ;; *) prim_config="$prim_config/prim" ;; esac; ',
329
- '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; ',
330
- "fi; fi; "
331
- ].join("");
332
-
333
571
  // src/lib/ingest-uploader.ts
334
572
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
335
573
 
@@ -373,25 +611,33 @@ function terminalSafeText(value) {
373
611
  var stripControlChars = terminalSafeText;
374
612
 
375
613
  // src/client.ts
376
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
614
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
377
615
  function getSiteUrl() {
378
616
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
379
617
  }
380
618
  function getSiteUrlForEnvironment(primApiUrl) {
381
- return primApiUrl?.trim() || DEFAULT_API_URL;
619
+ return primApiUrl?.trim() || DEFAULT_API_URL2;
382
620
  }
383
621
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
384
622
 
385
623
  // src/daemon/principal.ts
386
- import { createHash as createHash3 } from "crypto";
624
+ import { createHash as createHash6 } from "crypto";
387
625
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
388
626
  function boundedClaim(value) {
389
627
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
390
628
  }
391
629
  function sha256(value) {
392
- return createHash3("sha256").update(value).digest("hex");
630
+ return createHash6("sha256").update(value).digest("hex");
393
631
  }
394
632
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
633
+ if (hasMachineConfiguration()) {
634
+ const machine = machineContext();
635
+ return machine ? {
636
+ principalId: sha256(`${machine.issuer}\0${machine.clientId}`),
637
+ organizationId: machine.workosOrganizationId,
638
+ credentialFingerprint: sha256(machine.generation)
639
+ } : void 0;
640
+ }
395
641
  if (!token) return void 0;
396
642
  const payload = decodeJwtPayload(token);
397
643
  const subject = boundedClaim(payload?.sub);
@@ -430,8 +676,8 @@ function parseDaemonResponseEnvelope(value) {
430
676
 
431
677
  // src/daemon/client.ts
432
678
  import { createConnection } from "net";
433
- import { join as join7 } from "path";
434
- var SOCK_PATH = join7(primConfigDirectory(), "sock");
679
+ import { join as join10 } from "path";
680
+ var SOCK_PATH = join10(primConfigDirectory(), "sock");
435
681
  var DEFAULT_TIMEOUT_MS = 250;
436
682
  var nextRequestId = 1;
437
683
  function daemonRequest(method, params = {}, opts = {}) {
@@ -521,19 +767,19 @@ function daemonRequest(method, params = {}, opts = {}) {
521
767
  }
522
768
 
523
769
  // src/lib/activation.ts
524
- import { execFileSync as execFileSync3 } from "child_process";
525
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
770
+ import { execFileSync as execFileSync4 } from "child_process";
771
+ import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
526
772
  import { homedir as homedir2 } from "os";
527
- import { join as join8 } from "path";
773
+ import { join as join11 } from "path";
528
774
 
529
775
  // src/lib/demo-pause.ts
530
- import { execFileSync } from "child_process";
776
+ import { execFileSync as execFileSync2 } from "child_process";
531
777
  var DEMO_PAUSE_MS = 30 * 6e4;
532
778
  var PAUSE_KEY = "prim.demoPause";
533
779
  var GIT_TIMEOUT_MS = 1e3;
534
780
  function git(cwd, args) {
535
781
  try {
536
- return execFileSync("git", args, {
782
+ return execFileSync2("git", args, {
537
783
  cwd,
538
784
  encoding: "utf-8",
539
785
  stdio: ["ignore", "pipe", "ignore"],
@@ -545,7 +791,7 @@ function git(cwd, args) {
545
791
  }
546
792
  function setLocal(cwd, key, value) {
547
793
  try {
548
- execFileSync(
794
+ execFileSync2(
549
795
  "git",
550
796
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
551
797
  { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
@@ -588,16 +834,16 @@ function healDemoPause(cwd, pause, options = {}) {
588
834
  }
589
835
 
590
836
  // src/lib/git.ts
591
- import { execFileSync as execFileSync2 } from "child_process";
592
- import { createHash as createHash4 } from "crypto";
593
- import { lstatSync as lstatSync2, realpathSync } from "fs";
594
- import { basename, dirname as dirname5, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
837
+ import { execFileSync as execFileSync3 } from "child_process";
838
+ import { createHash as createHash7 } from "crypto";
839
+ import { lstatSync as lstatSync5, realpathSync } from "fs";
840
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
595
841
  var GIT_TIMEOUT_MS2 = 1e3;
596
842
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
597
843
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
598
844
  function gitToplevel(cwd) {
599
845
  try {
600
- return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
846
+ return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
601
847
  cwd,
602
848
  encoding: "utf-8",
603
849
  stdio: ["ignore", "pipe", "ignore"],
@@ -609,7 +855,7 @@ function gitToplevel(cwd) {
609
855
  }
610
856
  function gitValue(cwd, args) {
611
857
  try {
612
- const value = execFileSync2("git", args, {
858
+ const value = execFileSync3("git", args, {
613
859
  cwd,
614
860
  encoding: "utf-8",
615
861
  stdio: ["ignore", "pipe", "ignore"],
@@ -646,7 +892,7 @@ var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cur
646
892
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
647
893
  function repoActiveFlag(cwd, strict = false) {
648
894
  try {
649
- const value = execFileSync3("git", ["config", "--get", PRIM_ACTIVE_KEY], {
895
+ const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
650
896
  cwd,
651
897
  encoding: "utf-8",
652
898
  stdio: ["ignore", "pipe", "ignore"],
@@ -667,7 +913,7 @@ function isValidRepoSyncId(value) {
667
913
  }
668
914
  function localGitConfigValue(cwd, key) {
669
915
  try {
670
- const value = execFileSync3("git", ["config", "--local", "--get", key], {
916
+ const value = execFileSync4("git", ["config", "--local", "--get", key], {
671
917
  cwd,
672
918
  encoding: "utf-8",
673
919
  stdio: ["ignore", "pipe", "ignore"],
@@ -697,10 +943,10 @@ function hasProjectPrimInstall(cwd) {
697
943
  const root = gitToplevel(cwd);
698
944
  if (root === null || root === homedir2()) return false;
699
945
  for (const rel of PROJECT_INSTALL_FILES) {
700
- const path = join8(root, rel);
701
- if (existsSync4(path)) {
946
+ const path = join11(root, rel);
947
+ if (existsSync5(path)) {
702
948
  try {
703
- const content = readFileSync6(path, "utf-8");
949
+ const content = readFileSync9(path, "utf-8");
704
950
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
705
951
  } catch {
706
952
  }
@@ -801,7 +1047,7 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
801
1047
  const ingestionSuffix = (status) => status === void 0 ? "" : ` \xB7 Decision ingestion ${status}`;
802
1048
  const ingestionStatus = snapshot === null || snapshot.healthy === false ? options.includeIngestionWhenUnavailable ? resolveIngestionStatus() : void 0 : resolveIngestionStatus();
803
1049
  if (snapshot?.healthy === false && snapshot.needsReauth) {
804
- return `primitive ${version} (daemon: paused \xB7 run \`prim auth login\`${ingestionSuffix(ingestionStatus)})`;
1050
+ return `primitive ${version} (daemon: paused \xB7 run \`${hasMachineConfiguration() ? "prim auth status" : "prim auth login"}\`${ingestionSuffix(ingestionStatus)})`;
805
1051
  }
806
1052
  const repositoryLabel = repositoryBindingDiagnosticLabel(
807
1053
  snapshot !== null && snapshot.healthy !== false || options.includeIngestionWhenUnavailable === true ? options.resolveRepositoryBindingState?.() : void 0
@@ -848,7 +1094,7 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
848
1094
  var STATUSLINE_TIMEOUT_MS = 200;
849
1095
  function readPackageVersion() {
850
1096
  try {
851
- const here = dirname6(fileURLToPath2(import.meta.url));
1097
+ const here = dirname7(fileURLToPath4(import.meta.url));
852
1098
  const candidates = [
853
1099
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
854
1100
  // Keep resolving it while those legacy launchers transition to schema v3.
@@ -858,7 +1104,7 @@ function readPackageVersion() {
858
1104
  ];
859
1105
  for (const path of candidates) {
860
1106
  try {
861
- const pkg = JSON.parse(readFileSync7(path, "utf-8"));
1107
+ const pkg = JSON.parse(readFileSync10(path, "utf-8"));
862
1108
  if (pkg.version) {
863
1109
  return pkg.version;
864
1110
  }