@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
@@ -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,283 @@ 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 {
218
+ issuer: record.issuer,
219
+ audience: record.audience,
220
+ ...record.developer_enrollment === true ? { developerEnrollment: true } : {}
221
+ };
222
+ }
223
+ function parseMachineIdentity(value, clientId) {
224
+ const data = machineRecord(value);
225
+ const principal = machineRecord(data.principal);
226
+ 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))) {
227
+ throw new MachineAuthError(
228
+ "machine_identity_rejected",
229
+ "The API did not verify a machine identity.",
230
+ true
231
+ );
232
+ }
233
+ return {
234
+ machineId: principal.machineId,
235
+ ...data.organizationBindingVersion === 3 ? { authorizedUserId: principal.authorizedUserId } : {},
236
+ clientId,
237
+ displayName: principal.displayName,
238
+ organizationId: data.organizationId,
239
+ workosOrganizationId: data.workosOrganizationId,
240
+ scopes: principal.scopes
241
+ };
242
+ }
243
+
244
+ // src/lib/paths.ts
245
+ import { homedir } from "os";
246
+ import { isAbsolute as isAbsolute2, join as join3, normalize } from "path";
247
+ var UNSAFE_CONFIG_PATH_CHARACTERS = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u;
248
+ function absolutePath(value, variable) {
249
+ if (value !== void 0 && UNSAFE_CONFIG_PATH_CHARACTERS.test(value)) {
250
+ throw new Error(`${variable} contains unsafe characters`);
251
+ }
252
+ if (!value || value.trim() !== value || !isAbsolute2(value)) return;
253
+ const normalized = normalize(value);
254
+ return normalized === value ? value : void 0;
255
+ }
256
+ function resolvePrimConfigDirectory(options = {}) {
257
+ const env = options.env ?? process.env;
258
+ const explicit = absolutePath(env.PRIM_CONFIG_DIR, "PRIM_CONFIG_DIR");
259
+ if (explicit) return { path: explicit, source: "explicit" };
260
+ const xdgConfigHome = absolutePath(env.XDG_CONFIG_HOME, "XDG_CONFIG_HOME");
261
+ if (xdgConfigHome) return { path: join3(xdgConfigHome, "prim"), source: "xdg" };
262
+ const home = absolutePath(options.homeDir ?? homedir(), "HOME");
263
+ if (!home) {
264
+ throw new Error("cannot resolve Primitive config directory: HOME is not an absolute path");
265
+ }
266
+ return { path: join3(home, ".config", "prim"), source: "default" };
267
+ }
268
+ function primConfigDirectory(options = {}) {
269
+ return resolvePrimConfigDirectory(options).path;
270
+ }
271
+
272
+ // src/lib/machine-broker.ts
273
+ var MAX_RESPONSE_BYTES = 96 * 1024;
274
+ var IDLE_MS = 5 * 6e4;
275
+
276
+ // src/lib/machine-retry.ts
277
+ import { createHash as createHash2 } from "crypto";
278
+ import { lstatSync as lstatSync2, readFileSync as readFileSync4, rmSync as rmSync4 } from "fs";
279
+ import { join as join5 } from "path";
280
+
281
+ // src/lib/machine-credentials.ts
282
+ var require2 = createRequire(import.meta.url);
283
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
284
+ var PROFILE_FILE = "machine_profile.json";
285
+ var cached;
286
+ function configurationDirectory(deps) {
287
+ return deps.directory ?? primConfigDirectory({ env: deps.env });
288
+ }
289
+ function apiUrlFor(deps) {
290
+ return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL);
291
+ }
292
+ function hash(value) {
293
+ return createHash3("sha256").update(value).digest("hex");
294
+ }
295
+ function environmentContextPath(deps, clientId) {
296
+ return join6(
297
+ configurationDirectory(deps),
298
+ `machine_context_${hash(`${apiUrlFor(deps)}\0${clientId}`)}.json`
299
+ );
300
+ }
301
+ function readEnvironmentContext(environment, deps) {
302
+ try {
303
+ const data = machineRecord(readPrivate(environmentContextPath(deps, environment.clientId)));
304
+ 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())
305
+ return void 0;
306
+ const configuration = parseMachineConfiguration({
307
+ protocol_version: data.version,
308
+ issuer: data.issuer,
309
+ audience: data.audience
310
+ });
311
+ const identity = parseStoredIdentity(data);
312
+ return {
313
+ ...configuration,
314
+ ...identity,
315
+ apiUrl: data.apiUrl,
316
+ generation: environment.generation
317
+ };
318
+ } catch {
319
+ return void 0;
320
+ }
321
+ }
322
+ function readPrivate(path) {
323
+ let raw;
324
+ try {
325
+ const stat = lstatSync3(path);
326
+ if (!stat.isFile() || stat.size > 96 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.())) {
327
+ throw new MachineAuthError(
328
+ "unsafe_storage",
329
+ "Machine credential files must be owner-only regular files."
330
+ );
331
+ }
332
+ raw = readFileSync5(path, "utf8");
333
+ } catch (error) {
334
+ if (error.code === "ENOENT") return void 0;
335
+ throw error;
336
+ }
337
+ try {
338
+ return JSON.parse(raw);
339
+ } catch {
340
+ throw new MachineAuthError("invalid_storage", "Stored machine credentials are malformed.");
341
+ }
342
+ }
343
+ function parseStoredIdentity(data) {
344
+ return parseMachineIdentity(
345
+ {
346
+ authenticated: true,
347
+ organizationBindingVersion: data.authorizedUserId ? 3 : 2,
348
+ captureAuthorityKind: "workos_m2m",
349
+ organizationId: data.organizationId,
350
+ workosOrganizationId: data.workosOrganizationId,
351
+ principal: { ...data, kind: "machine" }
352
+ },
353
+ String(data.clientId)
354
+ );
355
+ }
356
+ function parseProfile(value) {
357
+ const data = machineRecord(value);
358
+ const config = parseMachineConfiguration({
359
+ protocol_version: data.version,
360
+ issuer: data.issuer,
361
+ audience: data.audience
362
+ });
363
+ 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)) {
364
+ throw new MachineAuthError("invalid_storage", "Stored machine profile is malformed.");
365
+ }
366
+ const identity = parseStoredIdentity(data);
367
+ return {
368
+ ...config,
369
+ ...identity,
370
+ version: 1,
371
+ apiUrl: data.apiUrl,
372
+ generation: data.generation,
373
+ storage: data.storage
374
+ };
375
+ }
376
+ function readMachineProfile(deps = {}) {
377
+ const value = readPrivate(join6(configurationDirectory(deps), PROFILE_FILE));
378
+ return value === void 0 ? void 0 : parseProfile(value);
379
+ }
380
+ function environmentCredentials(deps) {
381
+ const env = deps.env ?? process.env;
382
+ const { PRIM_M2M_CLIENT_ID: clientId, PRIM_M2M_CLIENT_SECRET: clientSecret } = env;
383
+ if (clientId === void 0 && clientSecret === void 0) return void 0;
384
+ if (!clientId || !clientSecret || !/^client_[\w-]+$/u.test(clientId) || !machineString(clientSecret)) {
385
+ throw new MachineAuthError(
386
+ "incomplete_machine_credentials",
387
+ "Set both PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
388
+ );
389
+ }
390
+ return {
391
+ clientId,
392
+ clientSecret,
393
+ generation: hash(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
394
+ };
395
+ }
396
+ function hasMachineConfiguration(deps = {}) {
397
+ const env = deps.env ?? process.env;
398
+ const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || existsSync3(join6(configurationDirectory(deps), PROFILE_FILE));
399
+ if (configured && env.PRIM_TOKEN?.trim()) {
400
+ throw new MachineAuthError(
401
+ "conflicting_credentials",
402
+ "Unset PRIM_TOKEN when using machine credentials."
403
+ );
404
+ }
405
+ if (configured) environmentCredentials(deps);
406
+ return configured;
407
+ }
408
+ function machineContext(deps = {}) {
409
+ if (!hasMachineConfiguration(deps)) return void 0;
410
+ const environment = environmentCredentials(deps);
411
+ if (environment) {
412
+ if (environmentTerminal === environment.generation) return void 0;
413
+ return cached?.generation === environment.generation && cached.expiresAt > Date.now() ? cached : readEnvironmentContext(environment, deps);
414
+ }
415
+ const profile = readMachineProfile(deps);
416
+ if (profile && profile.apiUrl !== apiUrlFor(deps))
417
+ throw new MachineAuthError(
418
+ "deployment_mismatch",
419
+ "Machine credentials belong to another API deployment. Configure this deployment or inject its credentials."
420
+ );
421
+ return profile;
422
+ }
423
+ function cachedMachineCredential(deps = {}) {
424
+ const context = machineContext(deps);
425
+ return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
426
+ }
427
+ var environmentTerminal;
428
+
140
429
  // src/lib/credentials.ts
141
430
  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");
431
+ var TOKEN_FILE_PATH = join7(CONFIG_DIRECTORY, "token");
432
+ var REFRESH_TOKEN_PATH = join7(CONFIG_DIRECTORY, "refresh_token");
433
+ var TOKEN_EXPIRES_PATH = join7(CONFIG_DIRECTORY, "token_expires_at");
434
+ var TERMINAL_REFRESH_PATH = join7(CONFIG_DIRECTORY, "refresh_terminal");
435
+ var CREDENTIAL_METADATA_PATH = join7(CONFIG_DIRECTORY, "credential_metadata.json");
436
+ var CREDENTIAL_FAMILY_PATH = join7(CONFIG_DIRECTORY, "credential_family.json");
437
+ var CREDENTIAL_MIGRATION_PATH = join7(CONFIG_DIRECTORY, "credential_migration.json");
438
+ var CREDENTIAL_LOCK_PATH = join7(CONFIG_DIRECTORY, "credentials.lock");
150
439
  var MAX_CREDENTIAL_METADATA_BYTES = 4096;
151
440
  var CREDENTIAL_MIGRATION_VERSION = 1;
152
441
  var CREDENTIAL_MIGRATION_STATE = "family_bound";
153
442
  function readTrimmed(path) {
154
443
  try {
155
- const value = readFileSync(path, "utf8").trim();
444
+ const value = readFileSync6(path, "utf8").trim();
156
445
  return value || void 0;
157
446
  } catch {
158
447
  return void 0;
159
448
  }
160
449
  }
161
450
  function resolveAuthCredential(options = {}) {
451
+ if (!options.tokenFilePath && hasMachineConfiguration({ env: options.env })) {
452
+ const machine = cachedMachineCredential({ env: options.env });
453
+ return machine ? { token: machine.accessToken, source: "machine" } : void 0;
454
+ }
162
455
  const envToken = (options.env ?? process.env).PRIM_TOKEN?.trim();
163
456
  if (envToken) return { token: envToken, source: "environment" };
164
457
  const stored = readTrimmed(options.tokenFilePath ?? TOKEN_FILE_PATH);
@@ -185,7 +478,7 @@ function resolveAuthCredential(options = {}) {
185
478
  return { token: stored, source: "token_file" };
186
479
  }
187
480
  function credentialFingerprint(value) {
188
- return createHash("sha256").update(value).digest("hex");
481
+ return createHash4("sha256").update(value).digest("hex");
189
482
  }
190
483
  function parseLegacyBrokerCredentialMetadata(value) {
191
484
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
@@ -205,7 +498,7 @@ function parseLegacyBrokerCredentialMetadata(value) {
205
498
  function readBoundedCredentialJson(path) {
206
499
  let raw;
207
500
  try {
208
- raw = readFileSync(path, "utf8");
501
+ raw = readFileSync6(path, "utf8");
209
502
  } catch (error) {
210
503
  return error.code === "ENOENT" ? void 0 : null;
211
504
  }
@@ -272,64 +565,14 @@ function decodeJwtPayload(token) {
272
565
  }
273
566
  }
274
567
 
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
568
  // 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";
569
+ import { randomBytes as randomBytes3 } from "crypto";
570
+ import { chmodSync as chmodSync2, lstatSync as lstatSync4, readFileSync as readFileSync7 } from "fs";
571
+ import { join as join8 } from "path";
285
572
  var INSTANCE_BODY_CHARS = 43;
286
573
  var INSTANCE_PREFIX = "pci_";
287
574
  var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
288
575
 
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
576
  // src/lib/ingest-uploader.ts
334
577
  var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
335
578
 
@@ -373,25 +616,35 @@ function terminalSafeText(value) {
373
616
  var stripControlChars = terminalSafeText;
374
617
 
375
618
  // src/client.ts
376
- var DEFAULT_API_URL = "https://api.getprimitive.ai";
619
+ var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
377
620
  function getSiteUrl() {
378
621
  return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
379
622
  }
380
623
  function getSiteUrlForEnvironment(primApiUrl) {
381
- return primApiUrl?.trim() || DEFAULT_API_URL;
624
+ return primApiUrl?.trim() || DEFAULT_API_URL2;
382
625
  }
383
626
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
384
627
 
385
628
  // src/daemon/principal.ts
386
- import { createHash as createHash3 } from "crypto";
629
+ import { createHash as createHash6 } from "crypto";
387
630
  var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
388
631
  function boundedClaim(value) {
389
632
  return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
390
633
  }
391
634
  function sha256(value) {
392
- return createHash3("sha256").update(value).digest("hex");
635
+ return createHash6("sha256").update(value).digest("hex");
393
636
  }
394
637
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
638
+ if (hasMachineConfiguration()) {
639
+ const machine = machineContext();
640
+ return machine ? {
641
+ principalId: sha256(
642
+ `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
643
+ ),
644
+ organizationId: machine.workosOrganizationId,
645
+ credentialFingerprint: sha256(machine.generation)
646
+ } : void 0;
647
+ }
395
648
  if (!token) return void 0;
396
649
  const payload = decodeJwtPayload(token);
397
650
  const subject = boundedClaim(payload?.sub);
@@ -430,8 +683,8 @@ function parseDaemonResponseEnvelope(value) {
430
683
 
431
684
  // src/daemon/client.ts
432
685
  import { createConnection } from "net";
433
- import { join as join7 } from "path";
434
- var SOCK_PATH = join7(primConfigDirectory(), "sock");
686
+ import { join as join10 } from "path";
687
+ var SOCK_PATH = join10(primConfigDirectory(), "sock");
435
688
  var DEFAULT_TIMEOUT_MS = 250;
436
689
  var nextRequestId = 1;
437
690
  function daemonRequest(method, params = {}, opts = {}) {
@@ -521,19 +774,19 @@ function daemonRequest(method, params = {}, opts = {}) {
521
774
  }
522
775
 
523
776
  // src/lib/activation.ts
524
- import { execFileSync as execFileSync3 } from "child_process";
525
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
777
+ import { execFileSync as execFileSync4 } from "child_process";
778
+ import { existsSync as existsSync5, readFileSync as readFileSync9 } from "fs";
526
779
  import { homedir as homedir2 } from "os";
527
- import { join as join8 } from "path";
780
+ import { join as join11 } from "path";
528
781
 
529
782
  // src/lib/demo-pause.ts
530
- import { execFileSync } from "child_process";
783
+ import { execFileSync as execFileSync2 } from "child_process";
531
784
  var DEMO_PAUSE_MS = 30 * 6e4;
532
785
  var PAUSE_KEY = "prim.demoPause";
533
786
  var GIT_TIMEOUT_MS = 1e3;
534
787
  function git(cwd, args) {
535
788
  try {
536
- return execFileSync("git", args, {
789
+ return execFileSync2("git", args, {
537
790
  cwd,
538
791
  encoding: "utf-8",
539
792
  stdio: ["ignore", "pipe", "ignore"],
@@ -545,7 +798,7 @@ function git(cwd, args) {
545
798
  }
546
799
  function setLocal(cwd, key, value) {
547
800
  try {
548
- execFileSync(
801
+ execFileSync2(
549
802
  "git",
550
803
  value === null ? ["config", "--local", "--unset", key] : ["config", "--local", key, value],
551
804
  { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: GIT_TIMEOUT_MS }
@@ -588,16 +841,16 @@ function healDemoPause(cwd, pause, options = {}) {
588
841
  }
589
842
 
590
843
  // 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";
844
+ import { execFileSync as execFileSync3 } from "child_process";
845
+ import { createHash as createHash7 } from "crypto";
846
+ import { lstatSync as lstatSync5, realpathSync } from "fs";
847
+ import { basename as basename2, dirname as dirname6, isAbsolute as isAbsolute3, relative, resolve as resolve2, sep } from "path";
595
848
  var GIT_TIMEOUT_MS2 = 1e3;
596
849
  var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
597
850
  var GITHUB_REPOSITORY_PATTERN = /^[A-Za-z0-9._-]{1,100}$/u;
598
851
  function gitToplevel(cwd) {
599
852
  try {
600
- return execFileSync2("git", ["rev-parse", "--show-toplevel"], {
853
+ return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
601
854
  cwd,
602
855
  encoding: "utf-8",
603
856
  stdio: ["ignore", "pipe", "ignore"],
@@ -609,7 +862,7 @@ function gitToplevel(cwd) {
609
862
  }
610
863
  function gitValue(cwd, args) {
611
864
  try {
612
- const value = execFileSync2("git", args, {
865
+ const value = execFileSync3("git", args, {
613
866
  cwd,
614
867
  encoding: "utf-8",
615
868
  stdio: ["ignore", "pipe", "ignore"],
@@ -646,7 +899,7 @@ var PROJECT_INSTALL_FILES = [".claude/settings.json", ".codex/hooks.json", ".cur
646
899
  var PRIM_HOOK_BINS = ["prim-hook", "prim-pre-tool-use", "prim-post-tool-use"];
647
900
  function repoActiveFlag(cwd, strict = false) {
648
901
  try {
649
- const value = execFileSync3("git", ["config", "--get", PRIM_ACTIVE_KEY], {
902
+ const value = execFileSync4("git", ["config", "--get", PRIM_ACTIVE_KEY], {
650
903
  cwd,
651
904
  encoding: "utf-8",
652
905
  stdio: ["ignore", "pipe", "ignore"],
@@ -667,7 +920,7 @@ function isValidRepoSyncId(value) {
667
920
  }
668
921
  function localGitConfigValue(cwd, key) {
669
922
  try {
670
- const value = execFileSync3("git", ["config", "--local", "--get", key], {
923
+ const value = execFileSync4("git", ["config", "--local", "--get", key], {
671
924
  cwd,
672
925
  encoding: "utf-8",
673
926
  stdio: ["ignore", "pipe", "ignore"],
@@ -697,10 +950,10 @@ function hasProjectPrimInstall(cwd) {
697
950
  const root = gitToplevel(cwd);
698
951
  if (root === null || root === homedir2()) return false;
699
952
  for (const rel of PROJECT_INSTALL_FILES) {
700
- const path = join8(root, rel);
701
- if (existsSync4(path)) {
953
+ const path = join11(root, rel);
954
+ if (existsSync5(path)) {
702
955
  try {
703
- const content = readFileSync6(path, "utf-8");
956
+ const content = readFileSync9(path, "utf-8");
704
957
  if (PRIM_HOOK_BINS.some((bin) => content.includes(bin))) return true;
705
958
  } catch {
706
959
  }
@@ -801,7 +1054,7 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
801
1054
  const ingestionSuffix = (status) => status === void 0 ? "" : ` \xB7 Decision ingestion ${status}`;
802
1055
  const ingestionStatus = snapshot === null || snapshot.healthy === false ? options.includeIngestionWhenUnavailable ? resolveIngestionStatus() : void 0 : resolveIngestionStatus();
803
1056
  if (snapshot?.healthy === false && snapshot.needsReauth) {
804
- return `primitive ${version} (daemon: paused \xB7 run \`prim auth login\`${ingestionSuffix(ingestionStatus)})`;
1057
+ return `primitive ${version} (daemon: paused \xB7 run \`${hasMachineConfiguration() ? "prim auth status" : "prim auth login"}\`${ingestionSuffix(ingestionStatus)})`;
805
1058
  }
806
1059
  const repositoryLabel = repositoryBindingDiagnosticLabel(
807
1060
  snapshot !== null && snapshot.healthy !== false || options.includeIngestionWhenUnavailable === true ? options.resolveRepositoryBindingState?.() : void 0
@@ -848,7 +1101,7 @@ function formatStatusline(version, snapshot, resolveIngestionStatus, options = {
848
1101
  var STATUSLINE_TIMEOUT_MS = 200;
849
1102
  function readPackageVersion() {
850
1103
  try {
851
- const here = dirname6(fileURLToPath2(import.meta.url));
1104
+ const here = dirname7(fileURLToPath4(import.meta.url));
852
1105
  const candidates = [
853
1106
  // Schema-v2 runtimes staged a manifest beside this standalone bundle.
854
1107
  // Keep resolving it while those legacy launchers transition to schema v3.
@@ -858,7 +1111,7 @@ function readPackageVersion() {
858
1111
  ];
859
1112
  for (const path of candidates) {
860
1113
  try {
861
- const pkg = JSON.parse(readFileSync7(path, "utf-8"));
1114
+ const pkg = JSON.parse(readFileSync10(path, "utf-8"));
862
1115
  if (pkg.version) {
863
1116
  return pkg.version;
864
1117
  }