@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.120

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 (56) hide show
  1. package/README.md +540 -38
  2. package/SKILL.md +315 -75
  3. package/assets/primitive-gameplan/SKILL.md +134 -0
  4. package/assets/primitive-gameplan/claude-hooks.json +28 -0
  5. package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
  6. package/dist/chunk-2AKDX4RU.js +209 -0
  7. package/dist/chunk-4GLVJLEQ.js +55 -0
  8. package/dist/chunk-5BQ2NEMP.js +22695 -0
  9. package/dist/chunk-A6M2M5A2.js +36 -0
  10. package/dist/chunk-CCGFRNAA.js +1871 -0
  11. package/dist/chunk-D235RJNO.js +164 -0
  12. package/dist/chunk-EYBE724K.js +135 -0
  13. package/dist/chunk-EZXEWFDG.js +210 -0
  14. package/dist/chunk-GYQOZGGF.js +168 -0
  15. package/dist/chunk-HXICZG5J.js +503 -0
  16. package/dist/chunk-JSBRDJBE.js +30 -0
  17. package/dist/chunk-KZB4ABIB.js +13 -0
  18. package/dist/chunk-L52OD62C.js +1444 -0
  19. package/dist/chunk-LBCPRHNG.js +175 -0
  20. package/dist/chunk-LTTF4MBE.js +439 -0
  21. package/dist/chunk-MWNRXAEB.js +1572 -0
  22. package/dist/chunk-NQFRQ56V.js +262 -0
  23. package/dist/chunk-OYHYCK4K.js +13 -0
  24. package/dist/chunk-P2O7NLVN.js +1341 -0
  25. package/dist/chunk-R2NUH4B7.js +96 -0
  26. package/dist/chunk-SLDZJD6Q.js +157 -0
  27. package/dist/chunk-TC4FTRYO.js +253 -0
  28. package/dist/chunk-U67RBNIZ.js +844 -0
  29. package/dist/chunk-VOC4KOOP.js +258 -0
  30. package/dist/chunk-YTF6OCF3.js +459 -0
  31. package/dist/daemon/server.js +26444 -0
  32. package/dist/hook-runtime/daemon/server.js +26445 -0
  33. package/dist/hook-runtime/hooks/post-commit.js +23836 -0
  34. package/dist/hook-runtime/hooks/post-rewrite.js +23735 -0
  35. package/dist/hook-runtime/hooks/post-tool-use.js +36151 -0
  36. package/dist/hook-runtime/hooks/pre-commit.js +1737 -0
  37. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35067 -0
  38. package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
  39. package/dist/hook-runtime/hooks/prim-hook.js +36211 -0
  40. package/dist/hook-runtime/hooks/session-end.js +1188 -0
  41. package/dist/hook-runtime/hooks/session-start.js +33950 -0
  42. package/dist/hook-runtime/index.js +71245 -0
  43. package/dist/hook-runtime/statusline-main.js +892 -0
  44. package/dist/hooks/post-commit.js +197 -0
  45. package/dist/hooks/post-rewrite.js +206 -0
  46. package/dist/hooks/post-tool-use.js +295 -0
  47. package/dist/hooks/pre-commit.js +16 -108
  48. package/dist/hooks/pre-tool-use-worker.js +238 -0
  49. package/dist/hooks/pre-tool-use.js +87 -0
  50. package/dist/hooks/prim-hook.js +245 -0
  51. package/dist/hooks/session-end.js +67 -0
  52. package/dist/hooks/session-start.js +312 -0
  53. package/dist/index.js +10998 -572
  54. package/dist/statusline-main.js +891 -0
  55. package/package.json +49 -16
  56. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,844 @@
1
+ import {
2
+ CREDENTIAL_FAMILY_PATH,
3
+ CREDENTIAL_LOCK_PATH,
4
+ CREDENTIAL_METADATA_PATH,
5
+ CREDENTIAL_MIGRATION_PATH,
6
+ CREDENTIAL_MIGRATION_STATE,
7
+ CREDENTIAL_MIGRATION_VERSION,
8
+ REFRESH_TOKEN_PATH,
9
+ TERMINAL_REFRESH_PATH,
10
+ TOKEN_EXPIRES_PATH,
11
+ TOKEN_FILE_PATH,
12
+ WORKOS_CONNECT_RESPONSE_MAX_BYTES,
13
+ atomicWriteFile,
14
+ ensureDurableDirectory,
15
+ jwtExpiresAt,
16
+ packageVersion,
17
+ parseWorkosConnectTokens,
18
+ primConfigDirectory,
19
+ readBoundedJson,
20
+ readCredentialMigrationState,
21
+ readStoredCredentialMetadata,
22
+ resolveAuthCredential,
23
+ syncDirectory,
24
+ withFileLock,
25
+ workosConnectTokenEndpoint
26
+ } from "./chunk-P2O7NLVN.js";
27
+
28
+ // src/decisions/identity.ts
29
+ var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
30
+ var BARE_ID = /^[0-9a-f]{8}$/u;
31
+ var OPAQUE_FIELDS = /* @__PURE__ */ new Set([
32
+ "cursor",
33
+ "continueCursor",
34
+ "nextCursor",
35
+ "reviewToken",
36
+ "bypassToken"
37
+ ]);
38
+ function decisionIdentifier(id, shortId) {
39
+ if (typeof id === "string" && PUBLIC_ID.test(id)) return id;
40
+ if (typeof shortId === "string" && BARE_ID.test(shortId)) return `dec_${shortId}`;
41
+ if (typeof id === "string" && BARE_ID.test(id)) return `dec_${id}`;
42
+ return void 0;
43
+ }
44
+ function publicDecisionResponse(value) {
45
+ const replacements = /* @__PURE__ */ new Map();
46
+ const referenceKeys = /* @__PURE__ */ new Set([
47
+ "decisionId",
48
+ "childId",
49
+ "parentId",
50
+ "supersededBy",
51
+ "activationDecisionId"
52
+ ]);
53
+ function visit(input, field = "") {
54
+ if (OPAQUE_FIELDS.has(field) || input === null || input === void 0) return input;
55
+ if (Array.isArray(input)) return input.map((item) => visit(item, field));
56
+ if (typeof input === "string" && (referenceKeys.has(field) || /DecisionIds$/u.test(field))) {
57
+ const id = decisionIdentifier(input);
58
+ if (!id) throw new Error("Decision identity unavailable; update Primitive and retry");
59
+ return id;
60
+ }
61
+ if (typeof input !== "object") return input;
62
+ const row = { ...input };
63
+ for (const [idKey, shortKey] of [
64
+ ["id", "shortId"],
65
+ ["_id", "shortId"],
66
+ ["decisionId", "shortId"],
67
+ ["childId", "childShortId"],
68
+ ["parentId", "parentShortId"]
69
+ ]) {
70
+ if (!(idKey in row) || (idKey === "id" || idKey === "_id") && !("intent" in row || "shortId" in row))
71
+ continue;
72
+ const id = decisionIdentifier(
73
+ row[idKey],
74
+ row[shortKey] ?? (idKey === "decisionId" ? row.decisionShortId : void 0)
75
+ );
76
+ if (!id) throw new Error("Decision identity unavailable; update Primitive and retry");
77
+ const previous = row[idKey];
78
+ if (typeof previous === "string" && !PUBLIC_ID.test(previous) && !BARE_ID.test(previous)) {
79
+ replacements.set(previous, id);
80
+ }
81
+ if (shortKey in row) row[shortKey] = id.slice(4);
82
+ if (idKey === "decisionId" && "decisionShortId" in row) row.decisionShortId = id.slice(4);
83
+ row[idKey] = id;
84
+ }
85
+ return Object.fromEntries(Object.entries(row).map(([key, item]) => [key, visit(item, key)]));
86
+ }
87
+ const projected = visit(value);
88
+ function replace(input, field = "") {
89
+ if (OPAQUE_FIELDS.has(field)) return input;
90
+ if (typeof input === "string") {
91
+ let output = input;
92
+ for (const [raw, id] of replacements) if (raw !== id) output = output.replaceAll(raw, id);
93
+ return output;
94
+ }
95
+ if (Array.isArray(input)) return input.map((item) => replace(item, field));
96
+ if (input && typeof input === "object")
97
+ return Object.fromEntries(
98
+ Object.entries(input).map(([key, item]) => [key, replace(item, key)])
99
+ );
100
+ return input;
101
+ }
102
+ return replace(projected);
103
+ }
104
+
105
+ // src/lib/terminal-safe.ts
106
+ function replaceIsolatedSurrogates(value) {
107
+ let out = "";
108
+ for (let index = 0; index < value.length; index += 1) {
109
+ const unit = value.charCodeAt(index);
110
+ if (unit >= 55296 && unit <= 56319) {
111
+ const next = value.charCodeAt(index + 1);
112
+ if (next >= 56320 && next <= 57343) {
113
+ out += value[index] + value[index + 1];
114
+ index += 1;
115
+ } else {
116
+ out += "\uFFFD";
117
+ }
118
+ } else if (unit >= 56320 && unit <= 57343) {
119
+ out += "\uFFFD";
120
+ } else {
121
+ out += value[index];
122
+ }
123
+ }
124
+ return out;
125
+ }
126
+ function isUnsafeTerminalCodePoint(point) {
127
+ const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
128
+ const bidiOrZeroWidth = point === 173 || // soft hyphen
129
+ point === 1564 || // Arabic letter mark
130
+ point === 6158 || // Mongolian vowel separator
131
+ point >= 8203 && point <= 8207 || // zero-width + directional marks
132
+ point >= 8234 && point <= 8238 || // bidi embeddings/overrides
133
+ point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
134
+ point >= 65529 && point <= 65531 || // interlinear annotation controls
135
+ point === 65279 || // zero-width no-break space / BOM
136
+ point >= 917504 && point <= 917631;
137
+ return c0OrC1 || bidiOrZeroWidth;
138
+ }
139
+ function terminalSafeText(value) {
140
+ return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
141
+ }
142
+ function terminalSafeLine(value) {
143
+ return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
144
+ }
145
+ function isTerminalSafeText(value) {
146
+ return terminalSafeText(value) === value;
147
+ }
148
+ var stripControlChars = terminalSafeText;
149
+
150
+ // src/client.ts
151
+ import { createHash } from "crypto";
152
+ import { chmodSync as chmodSync2, existsSync, mkdirSync, readFileSync as readFileSync2, rmSync } from "fs";
153
+ import { dirname } from "path";
154
+
155
+ // src/daemon/client-instance-id.ts
156
+ import { randomBytes } from "crypto";
157
+ import { chmodSync, lstatSync, readFileSync } from "fs";
158
+ import { join } from "path";
159
+ var CONFIG_DIRECTORY_MODE = 448;
160
+ var INSTANCE_FILE_MODE = 384;
161
+ var INSTANCE_ENTROPY_BYTES = 32;
162
+ var INSTANCE_BODY_CHARS = 43;
163
+ var INSTANCE_PREFIX = "pci_";
164
+ var CLIENT_INSTANCE_ID_RE = /^pci_[A-Za-z0-9_-]{43}$/u;
165
+ var MAX_STORED_BYTES = INSTANCE_PREFIX.length + INSTANCE_BODY_CHARS + 1;
166
+ function isClientInstanceId(value) {
167
+ return typeof value === "string" && CLIENT_INSTANCE_ID_RE.test(value);
168
+ }
169
+ function ensurePrivateConfigDirectory(configDir) {
170
+ ensureDurableDirectory(configDir, CONFIG_DIRECTORY_MODE);
171
+ const metadata = lstatSync(configDir);
172
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
173
+ throw new Error("prim config path must be a private directory");
174
+ }
175
+ chmodSync(configDir, CONFIG_DIRECTORY_MODE);
176
+ syncDirectory(configDir);
177
+ }
178
+ function readExisting(path) {
179
+ let metadata;
180
+ try {
181
+ metadata = lstatSync(path);
182
+ } catch (error) {
183
+ if (error.code === "ENOENT") {
184
+ return;
185
+ }
186
+ throw error;
187
+ }
188
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
189
+ throw new Error("stored client instance identity is invalid");
190
+ }
191
+ chmodSync(path, INSTANCE_FILE_MODE);
192
+ if (metadata.size > MAX_STORED_BYTES) {
193
+ throw new Error("stored client instance identity is invalid");
194
+ }
195
+ const raw = readFileSync(path, "utf8");
196
+ const value = raw.endsWith("\n") ? raw.slice(0, -1) : raw;
197
+ if (raw !== value && raw !== `${value}
198
+ ` || !isClientInstanceId(value)) {
199
+ throw new Error("stored client instance identity is invalid");
200
+ }
201
+ return value;
202
+ }
203
+ function atomicWrite(path, value) {
204
+ atomicWriteFile(path, `${value}
205
+ `, { mode: INSTANCE_FILE_MODE });
206
+ }
207
+ async function getOrCreateClientInstanceId(options) {
208
+ const configDir = options.configDir;
209
+ const path = join(configDir, "client_instance_id");
210
+ const lockPath = join(configDir, "client-instance.lock");
211
+ ensurePrivateConfigDirectory(configDir);
212
+ return withFileLock(
213
+ lockPath,
214
+ () => {
215
+ const existing = readExisting(path);
216
+ if (existing !== void 0) {
217
+ return existing;
218
+ }
219
+ const generated = `${INSTANCE_PREFIX}${randomBytes(INSTANCE_ENTROPY_BYTES).toString(
220
+ "base64url"
221
+ )}`;
222
+ if (!isClientInstanceId(generated)) {
223
+ throw new Error("generated client instance identity is invalid");
224
+ }
225
+ atomicWrite(path, generated);
226
+ return generated;
227
+ },
228
+ options.lockOptions
229
+ );
230
+ }
231
+
232
+ // src/lib/ingest-uploader.ts
233
+ var runtimeVersion = process.env.PRIM_RUNTIME_VERSION ?? packageVersion();
234
+ var VERSION_RE = /^\d+\.\d+\.\d+(?:-[A-Za-z0-9.-]+)?(?:\+[A-Za-z0-9.-]+)?$/u;
235
+ var instanceId;
236
+ async function ingestUploaderHeaders() {
237
+ const headers = {};
238
+ if (runtimeVersion && runtimeVersion.length <= 64 && VERSION_RE.test(runtimeVersion)) {
239
+ headers["X-Prim-Uploader-Version"] = runtimeVersion;
240
+ }
241
+ instanceId ??= getOrCreateClientInstanceId({
242
+ configDir: primConfigDirectory(),
243
+ // Attribution must not consume the upload deadline waiting for another process.
244
+ lockOptions: { timeoutMs: 0 }
245
+ }).catch(() => {
246
+ instanceId = void 0;
247
+ return void 0;
248
+ });
249
+ const id = await instanceId;
250
+ if (id) headers["X-Prim-Client-Instance-Id"] = id;
251
+ return headers;
252
+ }
253
+
254
+ // src/client.ts
255
+ var CONFIG_DIR_MODE = 448;
256
+ var CREDENTIAL_FILE_MODE = 384;
257
+ var REFRESH_THRESHOLD_MS = 6e4;
258
+ var DEFAULT_API_URL = "https://api.getprimitive.ai";
259
+ var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
260
+ function readTrimmed(path) {
261
+ try {
262
+ const value = readFileSync2(path, "utf8").trim();
263
+ return value || void 0;
264
+ } catch {
265
+ return void 0;
266
+ }
267
+ }
268
+ function getSiteUrl() {
269
+ return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
270
+ }
271
+ function getSiteUrlForEnvironment(primApiUrl) {
272
+ return primApiUrl?.trim() || DEFAULT_API_URL;
273
+ }
274
+ function expiresAtFor(token, expiresIn) {
275
+ return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
276
+ }
277
+ function ensureConfigDirectory() {
278
+ const directory = dirname(TOKEN_FILE_PATH);
279
+ mkdirSync(directory, { recursive: true, mode: CONFIG_DIR_MODE });
280
+ chmodSync2(directory, CONFIG_DIR_MODE);
281
+ }
282
+ function atomicWrite2(path, content) {
283
+ ensureConfigDirectory();
284
+ atomicWriteFile(path, content, { mode: CREDENTIAL_FILE_MODE });
285
+ }
286
+ function removeCredentialFile(path) {
287
+ if (!existsSync(path)) return false;
288
+ rmSync(path, { force: true });
289
+ return true;
290
+ }
291
+ function getTokenExpiresAt() {
292
+ const stored = readTrimmed(TOKEN_EXPIRES_PATH);
293
+ if (stored === void 0) return void 0;
294
+ const value = Number(stored);
295
+ return Number.isNaN(value) ? void 0 : value;
296
+ }
297
+ function isTokenExpiringSoon(credential) {
298
+ if (credential.source !== "token_file") return false;
299
+ const expiresAt = getTokenExpiresAt();
300
+ return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
301
+ }
302
+ function refreshFingerprint(refreshToken2) {
303
+ return createHash("sha256").update(refreshToken2).digest("hex");
304
+ }
305
+ function legacyBrokerCredentialMetadata(accessToken, refreshToken2) {
306
+ return {
307
+ version: 1,
308
+ family: "legacy_broker",
309
+ accessTokenHash: refreshFingerprint(accessToken),
310
+ refreshTokenHash: refreshFingerprint(refreshToken2)
311
+ };
312
+ }
313
+ function credentialFamilyMetadata(accessToken, refreshToken2, metadata) {
314
+ const hashes = {
315
+ accessTokenHash: refreshFingerprint(accessToken),
316
+ refreshTokenHash: refreshFingerprint(refreshToken2)
317
+ };
318
+ return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken2) : { ...metadata, ...hashes };
319
+ }
320
+ function writeCredentialMigrationSentinel() {
321
+ atomicWrite2(
322
+ CREDENTIAL_MIGRATION_PATH,
323
+ `${JSON.stringify({
324
+ version: CREDENTIAL_MIGRATION_VERSION,
325
+ state: CREDENTIAL_MIGRATION_STATE
326
+ })}
327
+ `
328
+ );
329
+ }
330
+ function bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata) {
331
+ if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken2) {
332
+ return { state: "invalid" };
333
+ }
334
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
335
+ if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
336
+ return { state: "invalid" };
337
+ }
338
+ if (metadata.metadata === void 0) {
339
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
340
+ `);
341
+ }
342
+ const migrationState = readCredentialMigrationState();
343
+ if (migrationState === "invalid") return { state: "invalid" };
344
+ if (migrationState === "absent") writeCredentialMigrationSentinel();
345
+ return { state: "legacy_broker", metadata: familyMetadata };
346
+ }
347
+ function preserveMarkerlessLegacyGeneration() {
348
+ const metadata = readStoredCredentialMetadata();
349
+ if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
350
+ const accessToken = readTrimmed(TOKEN_FILE_PATH);
351
+ const refreshToken2 = readTrimmed(REFRESH_TOKEN_PATH);
352
+ if (!(accessToken && refreshToken2)) return;
353
+ const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken2);
354
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
355
+ `);
356
+ }
357
+ function terminalFingerprint() {
358
+ return readTrimmed(TERMINAL_REFRESH_PATH);
359
+ }
360
+ function writeTerminalFingerprint(refreshToken2) {
361
+ atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken2)}
362
+ `);
363
+ }
364
+ function clearTerminalFingerprint() {
365
+ removeCredentialFile(TERMINAL_REFRESH_PATH);
366
+ }
367
+ function isSessionEnded() {
368
+ if (resolveAuthCredential()?.source !== "token_file") return false;
369
+ const refreshToken2 = readTrimmed(REFRESH_TOKEN_PATH);
370
+ const ended = terminalFingerprint();
371
+ return Boolean(refreshToken2 && ended && refreshFingerprint(refreshToken2) === ended);
372
+ }
373
+ function withCredentialLock(operation, options = {}) {
374
+ return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
375
+ }
376
+ function commitCredentialsUnlocked(credentials) {
377
+ const accessToken = credentials.accessToken.trim();
378
+ const refreshToken2 = credentials.refreshToken.trim();
379
+ if (!accessToken || !refreshToken2) {
380
+ throw new Error("OAuth credentials require both access and refresh tokens");
381
+ }
382
+ const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken2, credentials.metadata);
383
+ if (credentials.metadata !== void 0) {
384
+ preserveMarkerlessLegacyGeneration();
385
+ writeCredentialMigrationSentinel();
386
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
387
+ `);
388
+ atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
389
+ `);
390
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
391
+ `);
392
+ } else {
393
+ atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken2}
394
+ `);
395
+ atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
396
+ `);
397
+ removeCredentialFile(CREDENTIAL_METADATA_PATH);
398
+ }
399
+ const expiresAt = expiresAtFor(accessToken, credentials.expiresIn);
400
+ if (expiresAt === void 0) removeCredentialFile(TOKEN_EXPIRES_PATH);
401
+ else atomicWrite2(TOKEN_EXPIRES_PATH, `${expiresAt}
402
+ `);
403
+ atomicWrite2(TOKEN_FILE_PATH, `${accessToken}
404
+ `);
405
+ clearTerminalFingerprint();
406
+ _cachedCredential = { token: accessToken, source: "token_file" };
407
+ }
408
+ async function commitCredentials(credentials, options = {}) {
409
+ await withCredentialLock(() => commitCredentialsUnlocked(credentials), options);
410
+ }
411
+ async function setStoredToken(token, options = {}) {
412
+ const value = token.trim();
413
+ if (!value) throw new Error("Token cannot be empty");
414
+ await withCredentialLock(() => {
415
+ removeCredentialFile(REFRESH_TOKEN_PATH);
416
+ removeCredentialFile(TOKEN_EXPIRES_PATH);
417
+ removeCredentialFile(CREDENTIAL_FAMILY_PATH);
418
+ removeCredentialFile(CREDENTIAL_METADATA_PATH);
419
+ clearTerminalFingerprint();
420
+ removeCredentialFile(CREDENTIAL_MIGRATION_PATH);
421
+ atomicWrite2(TOKEN_FILE_PATH, `${value}
422
+ `);
423
+ _cachedCredential = { token: value, source: "token_file" };
424
+ }, options);
425
+ }
426
+ async function clearStoredCredentials(options = {}) {
427
+ const { beforeClear, ...lockOptions } = options;
428
+ return withCredentialLock(async () => {
429
+ const accessToken = readTrimmed(TOKEN_FILE_PATH);
430
+ const refreshToken2 = readTrimmed(REFRESH_TOKEN_PATH);
431
+ const metadata = readStoredCredentialMetadata();
432
+ let protectedMetadata = metadata;
433
+ if (metadata.state === "legacy_broker") {
434
+ try {
435
+ protectedMetadata = bindLegacyBrokerGeneration(accessToken, refreshToken2, metadata);
436
+ } catch {
437
+ protectedMetadata = { state: "invalid" };
438
+ }
439
+ }
440
+ let callbackError;
441
+ try {
442
+ await beforeClear?.(refreshToken2, protectedMetadata);
443
+ } catch (error) {
444
+ callbackError = error;
445
+ }
446
+ let removed = false;
447
+ for (const path of [
448
+ REFRESH_TOKEN_PATH,
449
+ TOKEN_EXPIRES_PATH,
450
+ CREDENTIAL_FAMILY_PATH,
451
+ CREDENTIAL_METADATA_PATH,
452
+ TERMINAL_REFRESH_PATH,
453
+ TOKEN_FILE_PATH,
454
+ CREDENTIAL_MIGRATION_PATH
455
+ ]) {
456
+ removed = removeCredentialFile(path) || removed;
457
+ }
458
+ _cachedCredential = void 0;
459
+ if (callbackError) throw callbackError;
460
+ return removed;
461
+ }, lockOptions);
462
+ }
463
+ function isTerminalRefreshResponse(response, detail) {
464
+ if (detail.includes("invalid_grant") || detail.includes("Session has already ended")) return true;
465
+ try {
466
+ const error = JSON.parse(detail).error;
467
+ return error === "invalid_grant" || response.status === 401 && error === "Invalid or expired refresh token";
468
+ } catch {
469
+ return response.status === 401 && detail.includes("Invalid or expired refresh token");
470
+ }
471
+ }
472
+ function workosConnectRefreshErrorCode(value) {
473
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return "";
474
+ return value.error === "invalid_grant" ? "invalid_grant" : "";
475
+ }
476
+ function refreshDiagnostic(response, detail, quiet, provider) {
477
+ if (quiet) return;
478
+ const statusText = terminalSafeLine(response.statusText).slice(0, 120);
479
+ const safeDetail = terminalSafeLine(detail).slice(0, 200);
480
+ process.stderr.write(
481
+ `[prim] token refresh rejected by ${provider}: ${response.status}${statusText ? ` ${statusText}` : ""}${safeDetail ? ` \u2014 ${safeDetail}` : ""}
482
+ `
483
+ );
484
+ }
485
+ function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken2) {
486
+ const current = readStoredCredentialMetadata();
487
+ if (expected.state === "legacy_broker") {
488
+ if (current.state !== "legacy_broker") return false;
489
+ if (!expected.metadata) return current.metadata === void 0;
490
+ return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
491
+ }
492
+ if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
493
+ return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken2) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
494
+ }
495
+ function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
496
+ if (!expected || readCredentialMigrationState() !== "valid") return void 0;
497
+ const stored = readStoredCredentialMetadata();
498
+ if (stored.state !== "legacy_broker" || stored.metadata === void 0 || stored.metadata.accessTokenHash !== expected.accessTokenHash || stored.metadata.refreshTokenHash !== expected.refreshTokenHash) {
499
+ return void 0;
500
+ }
501
+ const replacementRefreshToken = readTrimmed(REFRESH_TOKEN_PATH);
502
+ if (!replacementRefreshToken || replacementRefreshToken === currentGeneration) return void 0;
503
+ return readTrimmed(TOKEN_FILE_PATH);
504
+ }
505
+ function winnerAfterRefreshRace(currentGeneration, expectedLegacyGeneration) {
506
+ if (readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration) return void 0;
507
+ const winner = resolveAuthCredential();
508
+ return (winner?.source === "token_file" ? winner.token : void 0) ?? uncoordinatedLegacyWinnerAccessToken(expectedLegacyGeneration, currentGeneration);
509
+ }
510
+ async function performTokenRefresh(options = {}) {
511
+ const selected = resolveAuthCredential();
512
+ if (selected?.source !== "token_file") return void 0;
513
+ const startingGeneration = readTrimmed(REFRESH_TOKEN_PATH);
514
+ if (!startingGeneration || isSessionEnded()) return void 0;
515
+ const startingAccessToken = selected.token;
516
+ return withCredentialLock(
517
+ async () => {
518
+ const currentCredential = resolveAuthCredential();
519
+ if (currentCredential?.source !== "token_file") return void 0;
520
+ const currentGeneration = readTrimmed(REFRESH_TOKEN_PATH);
521
+ if (!currentGeneration) return void 0;
522
+ if (currentGeneration !== startingGeneration) {
523
+ return currentCredential.token;
524
+ }
525
+ if (currentCredential.token !== startingAccessToken) {
526
+ return currentCredential.token;
527
+ }
528
+ if (isSessionEnded()) return void 0;
529
+ let metadata = readStoredCredentialMetadata();
530
+ const markerlessLegacyAtStart = metadata.state === "legacy_broker" && metadata.metadata === void 0;
531
+ if (metadata.state === "invalid" || metadata.state === "workos_connect" && (metadata.metadata.accessTokenHash !== refreshFingerprint(currentCredential.token) || metadata.metadata.refreshTokenHash !== refreshFingerprint(currentGeneration))) {
532
+ return void 0;
533
+ }
534
+ if (metadata.state === "legacy_broker") {
535
+ try {
536
+ metadata = bindLegacyBrokerGeneration(
537
+ currentCredential.token,
538
+ currentGeneration,
539
+ metadata
540
+ );
541
+ } catch {
542
+ return void 0;
543
+ }
544
+ if (metadata.state !== "legacy_broker") return void 0;
545
+ }
546
+ const expectedLegacyGeneration = markerlessLegacyAtStart && metadata.state === "legacy_broker" ? metadata.metadata : void 0;
547
+ const connectContext = metadata.state === "workos_connect" ? {
548
+ version: 1,
549
+ family: "workos_connect",
550
+ issuer: metadata.metadata.issuer,
551
+ clientId: metadata.metadata.clientId
552
+ } : void 0;
553
+ const response = await fetch(
554
+ connectContext ? workosConnectTokenEndpoint(connectContext.issuer) : `${getSiteUrl()}/mcp/broker/refresh`,
555
+ connectContext ? {
556
+ method: "POST",
557
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
558
+ body: new URLSearchParams({
559
+ grant_type: "refresh_token",
560
+ refresh_token: currentGeneration,
561
+ client_id: connectContext.clientId
562
+ }),
563
+ signal: options.signal
564
+ } : {
565
+ method: "POST",
566
+ headers: { "Content-Type": "application/json" },
567
+ body: JSON.stringify({ refresh_token: currentGeneration }),
568
+ signal: options.signal
569
+ }
570
+ );
571
+ let directResponse;
572
+ if (connectContext) {
573
+ try {
574
+ directResponse = await readBoundedJson(response, WORKOS_CONNECT_RESPONSE_MAX_BYTES);
575
+ } catch {
576
+ if (response.ok && readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration && metadataMatchesCredentialGeneration(
577
+ metadata,
578
+ currentCredential.token,
579
+ currentGeneration
580
+ )) {
581
+ writeTerminalFingerprint(currentGeneration);
582
+ }
583
+ return void 0;
584
+ }
585
+ }
586
+ if (!response.ok) {
587
+ let detail = "";
588
+ if (connectContext) {
589
+ detail = workosConnectRefreshErrorCode(directResponse);
590
+ } else {
591
+ detail = (await response.text().catch(() => "")).slice(0, 200);
592
+ }
593
+ if (isTerminalRefreshResponse(response, detail) && readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration && metadataMatchesCredentialGeneration(metadata, currentCredential.token, currentGeneration)) {
594
+ writeTerminalFingerprint(currentGeneration);
595
+ }
596
+ refreshDiagnostic(
597
+ response,
598
+ detail,
599
+ options.quiet,
600
+ connectContext ? "WorkOS Connect" : "broker"
601
+ );
602
+ return winnerAfterRefreshRace(currentGeneration, expectedLegacyGeneration);
603
+ }
604
+ let accessToken;
605
+ let replacementRefreshToken;
606
+ let expiresIn;
607
+ if (connectContext) {
608
+ try {
609
+ const tokens = parseWorkosConnectTokens(directResponse, {
610
+ fallbackRefreshToken: currentGeneration
611
+ });
612
+ accessToken = tokens.accessToken;
613
+ replacementRefreshToken = tokens.refreshToken;
614
+ expiresIn = tokens.expiresIn;
615
+ } catch {
616
+ if (readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration && metadataMatchesCredentialGeneration(
617
+ metadata,
618
+ currentCredential.token,
619
+ currentGeneration
620
+ )) {
621
+ writeTerminalFingerprint(currentGeneration);
622
+ }
623
+ return void 0;
624
+ }
625
+ } else {
626
+ let data;
627
+ try {
628
+ data = await response.json();
629
+ } catch {
630
+ if (readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration) {
631
+ writeTerminalFingerprint(currentGeneration);
632
+ }
633
+ return void 0;
634
+ }
635
+ const record = typeof data === "object" && data !== null && !Array.isArray(data) ? data : void 0;
636
+ accessToken = typeof record?.access_token === "string" ? record.access_token.trim() : "";
637
+ replacementRefreshToken = typeof record?.refresh_token === "string" ? record.refresh_token.trim() : "";
638
+ expiresIn = typeof record?.expires_in === "number" && Number.isFinite(record.expires_in) ? record.expires_in : void 0;
639
+ if (!(accessToken && replacementRefreshToken)) {
640
+ if (readTrimmed(REFRESH_TOKEN_PATH) === currentGeneration) {
641
+ writeTerminalFingerprint(currentGeneration);
642
+ }
643
+ return void 0;
644
+ }
645
+ }
646
+ const latestCredential = resolveAuthCredential();
647
+ if (readTrimmed(REFRESH_TOKEN_PATH) !== currentGeneration || latestCredential?.source !== "token_file" || latestCredential.token !== currentCredential.token || !metadataMatchesCredentialGeneration(metadata, currentCredential.token, currentGeneration)) {
648
+ return latestCredential?.source === "token_file" ? latestCredential.token : winnerAfterRefreshRace(currentGeneration, expectedLegacyGeneration);
649
+ }
650
+ commitCredentialsUnlocked({
651
+ accessToken,
652
+ refreshToken: replacementRefreshToken,
653
+ expiresIn,
654
+ metadata: connectContext
655
+ });
656
+ return accessToken;
657
+ },
658
+ { signal: options.signal }
659
+ );
660
+ }
661
+ var _refreshInFlight;
662
+ function refreshToken(options = {}) {
663
+ if (_refreshInFlight) return _refreshInFlight;
664
+ const attempt = performTokenRefresh(options).then((token) => {
665
+ if (token) _cachedCredential = { token, source: "token_file" };
666
+ return token;
667
+ }).finally(() => {
668
+ if (_refreshInFlight === attempt) _refreshInFlight = void 0;
669
+ });
670
+ _refreshInFlight = attempt;
671
+ return attempt;
672
+ }
673
+ var HttpError = class extends Error {
674
+ status;
675
+ body;
676
+ constructor(status, message, body) {
677
+ super(message);
678
+ this.name = "HttpError";
679
+ this.status = status;
680
+ this.body = body;
681
+ }
682
+ };
683
+ var CliManagementResponseError = class extends Error {
684
+ constructor() {
685
+ super("Invalid API-key management response");
686
+ this.name = "CliManagementResponseError";
687
+ }
688
+ };
689
+ var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
690
+ async function managementResponseValue(response) {
691
+ if (response.status === 401) {
692
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
693
+ }
694
+ let value;
695
+ try {
696
+ value = await readBoundedJson(response, CLI_MANAGEMENT_RESPONSE_MAX_BYTES);
697
+ } catch {
698
+ if (response.ok) throw new CliManagementResponseError();
699
+ throw new HttpError(response.status, `HTTP ${response.status}`, null);
700
+ }
701
+ if (!response.ok) {
702
+ throw new HttpError(response.status, `HTTP ${response.status}`, value);
703
+ }
704
+ return value;
705
+ }
706
+ var _cachedCredential;
707
+ function selectedCredential() {
708
+ const resolved = resolveAuthCredential();
709
+ if (!_cachedCredential || resolved?.token !== _cachedCredential.token || resolved?.source !== _cachedCredential.source) {
710
+ _cachedCredential = resolved;
711
+ }
712
+ return _cachedCredential;
713
+ }
714
+ async function fetchWithToken(method, path, body, options, token, siteUrl) {
715
+ return fetch(`${siteUrl}${path}`, {
716
+ method,
717
+ headers: {
718
+ Authorization: `Bearer ${token}`,
719
+ "Content-Type": "application/json",
720
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
721
+ },
722
+ body: body === void 0 ? void 0 : JSON.stringify(body),
723
+ signal: options?.signal
724
+ });
725
+ }
726
+ async function responseValue(response) {
727
+ if (!response.ok) {
728
+ if (response.status === 401) {
729
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
730
+ }
731
+ const errorBody = await response.json().catch(() => null);
732
+ const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
733
+ const message = typeof errorRecord?.error === "string" ? errorRecord.error : `HTTP ${response.status}`;
734
+ throw new HttpError(response.status, message, errorBody);
735
+ }
736
+ return publicDecisionResponse(await response.json());
737
+ }
738
+ async function request(method, path, body, options) {
739
+ const siteUrl = getSiteUrl();
740
+ let credential = selectedCredential();
741
+ let refreshAttempted = false;
742
+ if (credential && isTokenExpiringSoon(credential)) {
743
+ refreshAttempted = true;
744
+ const token = await refreshToken({
745
+ signal: options?.signal,
746
+ quiet: options?.quietRefresh
747
+ });
748
+ if (token) credential = { token, source: "token_file" };
749
+ }
750
+ if (!credential) {
751
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
752
+ }
753
+ if (isTokenExpiringSoon(credential) && isSessionEnded()) {
754
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
755
+ }
756
+ const tokenUsed = credential.token;
757
+ let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
758
+ if (response.status === 401) {
759
+ const latest = resolveAuthCredential();
760
+ let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
761
+ if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
762
+ refreshAttempted = true;
763
+ retryToken = await refreshToken({ signal: options?.signal, quiet: options?.quietRefresh });
764
+ }
765
+ if (retryToken) {
766
+ _cachedCredential = {
767
+ token: retryToken,
768
+ source: latest?.source === "token_file" ? "token_file" : latest?.source ?? "token_file"
769
+ };
770
+ response = await fetchWithToken(method, path, body, options, retryToken, siteUrl);
771
+ }
772
+ }
773
+ return responseValue(response);
774
+ }
775
+ function getClient() {
776
+ return {
777
+ get: (path, options) => request("GET", path, void 0, options),
778
+ post: (path, body, options) => request("POST", path, body, options)
779
+ };
780
+ }
781
+ async function getPinnedClient(options = {}) {
782
+ const siteUrl = getSiteUrl();
783
+ let credential = selectedCredential();
784
+ if (credential && isTokenExpiringSoon(credential)) {
785
+ const token2 = await refreshToken({
786
+ signal: options.signal,
787
+ quiet: options.quietRefresh
788
+ });
789
+ if (token2) credential = { token: token2, source: "token_file" };
790
+ }
791
+ if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
792
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
793
+ }
794
+ const token = credential.token;
795
+ const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
796
+ return {
797
+ get: (path, requestOptions) => pinnedRequest("GET", path, void 0, requestOptions),
798
+ post: (path, body, requestOptions) => pinnedRequest("POST", path, body, requestOptions)
799
+ };
800
+ }
801
+ async function getPinnedManagementClient(options = {}) {
802
+ const siteUrl = getSiteUrl();
803
+ let credential = selectedCredential();
804
+ if (credential && isTokenExpiringSoon(credential)) {
805
+ const token2 = await refreshToken({
806
+ signal: options.signal,
807
+ quiet: options.quietRefresh
808
+ });
809
+ if (token2) credential = { token: token2, source: "token_file" };
810
+ }
811
+ if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
812
+ throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
813
+ }
814
+ const token = credential.token;
815
+ const pinnedRequest = async (method, path, body, requestOptions) => managementResponseValue(
816
+ await fetchWithToken(method, path, body, requestOptions, token, siteUrl)
817
+ );
818
+ return {
819
+ delete: (path, body, requestOptions) => pinnedRequest("DELETE", path, body, requestOptions),
820
+ get: (path, requestOptions) => pinnedRequest("GET", path, void 0, requestOptions),
821
+ post: (path, body, requestOptions) => pinnedRequest("POST", path, body, requestOptions)
822
+ };
823
+ }
824
+
825
+ export {
826
+ decisionIdentifier,
827
+ terminalSafeText,
828
+ terminalSafeLine,
829
+ isTerminalSafeText,
830
+ stripControlChars,
831
+ getSiteUrl,
832
+ getSiteUrlForEnvironment,
833
+ getTokenExpiresAt,
834
+ isSessionEnded,
835
+ commitCredentials,
836
+ setStoredToken,
837
+ clearStoredCredentials,
838
+ refreshToken,
839
+ HttpError,
840
+ CliManagementResponseError,
841
+ getClient,
842
+ getPinnedClient,
843
+ getPinnedManagementClient
844
+ };