@cortexkit/anthropic-auth-core 2.10.1 → 2.11.0

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.
package/dist/index.js CHANGED
@@ -1343,16 +1343,16 @@ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexki
1343
1343
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
1344
1344
  import { createHash, randomBytes, randomUUID as randomUUID4 } from "node:crypto";
1345
1345
  import { constants as fsConstants } from "node:fs";
1346
- import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat3, unlink as unlink2 } from "node:fs/promises";
1347
- import { basename, dirname as dirname5, extname, isAbsolute, join as join4, resolve as resolve7 } from "node:path";
1346
+ import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat3, unlink as unlink3 } from "node:fs/promises";
1347
+ import { basename as basename2, dirname as dirname5, extname, isAbsolute, join as join4, resolve as resolve7 } from "node:path";
1348
1348
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
1349
1349
 
1350
1350
  // ../../node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
1351
1351
  import { lstat as lstat2, stat } from "node:fs/promises";
1352
1352
  import { resolve as resolve4 } from "node:path";
1353
- async function identity(path, followSymlinks) {
1353
+ async function identity(path, probe) {
1354
1354
  try {
1355
- const metadata = await (followSymlinks ? stat(path) : lstat2(path));
1355
+ const metadata = await probe(path);
1356
1356
  return metadata.isFile() ? metadata : undefined;
1357
1357
  } catch (error) {
1358
1358
  return error.code === "ENOENT" ? "absent" : undefined;
@@ -1365,15 +1365,15 @@ function sameIdentity(left, right) {
1365
1365
  }
1366
1366
 
1367
1367
  class FileReadCache {
1368
- #followSymlinks;
1368
+ #probe;
1369
1369
  #entries = new Map;
1370
1370
  constructor(options = {}) {
1371
- this.#followSymlinks = options.followSymlinks ?? false;
1371
+ this.#probe = options.followSymlinks ? (path) => (options.stat ?? stat)(path) : (path) => (options.lstat ?? lstat2)(path);
1372
1372
  }
1373
1373
  async read(paths, read, validateHit) {
1374
1374
  const resolvedPaths = paths.map((path) => resolve4(path));
1375
1375
  const key = JSON.stringify(resolvedPaths);
1376
- const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#followSymlinks)));
1376
+ const probed = await Promise.all(resolvedPaths.map((path) => identity(path, this.#probe)));
1377
1377
  const identities = probed.every((entry) => entry !== undefined) ? probed : undefined;
1378
1378
  const cached = this.#entries.get(key);
1379
1379
  if (identities && cached && identities.every((entry, index) => {
@@ -1500,8 +1500,8 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
1500
1500
  });
1501
1501
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
1502
1502
  import { randomUUID as randomUUID3 } from "node:crypto";
1503
- import { link, lstat as lstat3, mkdir as mkdir2, open as open3, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
1504
- import { dirname as dirname4, join as join3 } from "node:path";
1503
+ import { link, lstat as lstat3, mkdir as mkdir2, open as open3, readdir, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2, unlink as unlink2 } from "node:fs/promises";
1504
+ import { basename, dirname as dirname4, join as join3 } from "node:path";
1505
1505
 
1506
1506
  // ../../node_modules/@cortexkit/common-auth/dist/fs/lock-record.js
1507
1507
  import { resolve as resolve5 } from "node:path";
@@ -1662,6 +1662,88 @@ async function writeExclusiveText(path, text) {
1662
1662
  await handle.close();
1663
1663
  }
1664
1664
  }
1665
+ var STAGING_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
1666
+ var STAGING_SWEEP_MIN_AGE_MS = 10 * 60000;
1667
+ var STAGING_SWEEP_MAX_CANDIDATES = 256;
1668
+ var STAGING_SWEEP_MAX_BYTES = 4096;
1669
+ var sweptLockPaths = new Set;
1670
+ var pendingStagingSweeps = new Set;
1671
+ var stagingSweepTestHooks;
1672
+ function isStagingName(name, lockName) {
1673
+ const prefix = `${lockName}.`;
1674
+ const suffix = ".tmp";
1675
+ if (!name.startsWith(prefix) || !name.endsWith(suffix))
1676
+ return false;
1677
+ return STAGING_UUID.test(name.slice(prefix.length, -suffix.length));
1678
+ }
1679
+ function sameStagingFile(a, b) {
1680
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.birthtimeMs === b.birthtimeMs;
1681
+ }
1682
+ async function readStagedOwner(path) {
1683
+ const before = await lstat3(path);
1684
+ if (!before.isFile() || before.isSymbolicLink())
1685
+ return;
1686
+ if (before.size > STAGING_SWEEP_MAX_BYTES)
1687
+ return;
1688
+ const handle = await open3(path, "r");
1689
+ let text;
1690
+ try {
1691
+ if (!sameStagingFile(before, await handle.stat()))
1692
+ return;
1693
+ text = await handle.readFile("utf8");
1694
+ } finally {
1695
+ await handle.close();
1696
+ }
1697
+ let record2;
1698
+ try {
1699
+ record2 = JSON.parse(text);
1700
+ } catch {
1701
+ return;
1702
+ }
1703
+ if (!record2 || typeof record2 !== "object" || Array.isArray(record2))
1704
+ return;
1705
+ const keys = Object.keys(record2).sort();
1706
+ if (keys.length !== 2 || keys[0] !== "expiresAt" || keys[1] !== "ownerId")
1707
+ return;
1708
+ const { ownerId, expiresAt } = record2;
1709
+ if (typeof ownerId !== "string" || !STAGING_UUID.test(ownerId))
1710
+ return;
1711
+ if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt))
1712
+ return;
1713
+ return { identity: before, expiresAt };
1714
+ }
1715
+ async function sweepAbandonedStaging(lockPath, ttlMs, now) {
1716
+ const directory = dirname4(lockPath);
1717
+ const lockName = basename(lockPath);
1718
+ const hooks = stagingSweepTestHooks;
1719
+ const names = await (hooks?.readdir ?? readdir)(directory);
1720
+ const candidates = names.filter((name) => isStagingName(name, lockName)).slice(0, STAGING_SWEEP_MAX_CANDIDATES);
1721
+ const marginMs = Math.max(Number.isFinite(ttlMs) ? ttlMs : 0, STAGING_SWEEP_MIN_AGE_MS);
1722
+ for (const name of candidates) {
1723
+ const path = join3(directory, name);
1724
+ try {
1725
+ if (now() - (await lstat3(path)).mtimeMs < marginMs)
1726
+ continue;
1727
+ const staged = await readStagedOwner(path);
1728
+ if (!staged || !(staged.expiresAt < now() - marginMs))
1729
+ continue;
1730
+ if (hooks?.beforeUnlink)
1731
+ await hooks.beforeUnlink(path);
1732
+ const current = await readStagedOwner(path);
1733
+ if (!current || !sameStagingFile(staged.identity, current.identity) || !(current.expiresAt < now() - marginMs))
1734
+ continue;
1735
+ await (hooks?.unlink ?? unlink2)(path);
1736
+ } catch {}
1737
+ }
1738
+ }
1739
+ function startStagingSweep(lockPath, ttlMs, now) {
1740
+ if (sweptLockPaths.has(lockPath))
1741
+ return;
1742
+ sweptLockPaths.add(lockPath);
1743
+ const sweep = Promise.resolve().then(() => sweepAbandonedStaging(lockPath, ttlMs, now)).catch(() => {});
1744
+ pendingStagingSweeps.add(sweep);
1745
+ sweep.finally(() => pendingStagingSweeps.delete(sweep));
1746
+ }
1665
1747
  var setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
1666
1748
  var clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
1667
1749
  function isLostMarkerRaceError(error) {
@@ -2350,6 +2432,7 @@ async function acquireRefreshFileLockWithClock(options) {
2350
2432
  return null;
2351
2433
  }
2352
2434
  scheduleRenewal();
2435
+ startStagingSweep(lockPath, options.ttlMs, now);
2353
2436
  return {
2354
2437
  ownerId,
2355
2438
  whenLost: () => lostPromise,
@@ -2413,17 +2496,15 @@ async function acquireRefreshFileLockWithClock(options) {
2413
2496
  removalConfirmed = true;
2414
2497
  }, deadline);
2415
2498
  changingRecordError = undefined;
2416
- if (markerAcquired) {
2417
- if (windowsPrivateFiles && !removalConfirmed)
2418
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
2419
- code: "EIO"
2420
- });
2421
- releaseConfirmed = removalConfirmed;
2499
+ if (markerAcquired && removalConfirmed) {
2500
+ releaseConfirmed = true;
2422
2501
  return;
2423
2502
  }
2424
- if (signal?.aborted)
2425
- return;
2426
- await recoverStaleEvictionMarker(deadline);
2503
+ if (!markerAcquired) {
2504
+ if (signal?.aborted)
2505
+ return;
2506
+ await recoverStaleEvictionMarker(deadline);
2507
+ }
2427
2508
  } catch (error) {
2428
2509
  const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
2429
2510
  lockPath,
@@ -2453,6 +2534,9 @@ async function acquireRefreshFileLockWithClock(options) {
2453
2534
  throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
2454
2535
  code: "ETIMEDOUT"
2455
2536
  });
2537
+ createLogger("fs").warn("File lock release deadline expired", {
2538
+ lockPath
2539
+ });
2456
2540
  }
2457
2541
  };
2458
2542
  }
@@ -2609,7 +2693,7 @@ function connectClaustrumEnrollmentClient(options) {
2609
2693
  }
2610
2694
  function getClaustrumEnrollmentPaths(tokenPath) {
2611
2695
  const extension = extname(tokenPath) || ".json";
2612
- const stem = basename(tokenPath, extname(tokenPath));
2696
+ const stem = basename2(tokenPath, extname(tokenPath));
2613
2697
  return {
2614
2698
  statePath: join4(dirname5(tokenPath), `${stem}-state${extension}`),
2615
2699
  tokenPath
@@ -2864,7 +2948,7 @@ async function writeStateAtomic(path, state, ancestorOptions = {}) {
2864
2948
  }
2865
2949
  if (windowsPrivateFiles)
2866
2950
  return writePrivateAtomic(path, bytes);
2867
- const temporary = join4(parent, `.${basename(path)}.${process.pid}.${randomUUID4()}.tmp`);
2951
+ const temporary = join4(parent, `.${basename2(path)}.${process.pid}.${randomUUID4()}.tmp`);
2868
2952
  let descriptor;
2869
2953
  let created = false;
2870
2954
  try {
@@ -2880,7 +2964,7 @@ async function writeStateAtomic(path, state, ancestorOptions = {}) {
2880
2964
  } finally {
2881
2965
  await descriptor?.close().catch(() => {});
2882
2966
  if (created)
2883
- await unlink2(temporary).catch(() => {});
2967
+ await unlink3(temporary).catch(() => {});
2884
2968
  }
2885
2969
  }
2886
2970
  var enrollmentStatusCache = new FileReadCache;
@@ -3162,7 +3246,7 @@ class ClaustrumEnrollmentManager {
3162
3246
  }
3163
3247
  if (refusal.code === UNSUPPORTED_ENROLLMENT_CODE) {
3164
3248
  await lock.assertOwned();
3165
- await unlink2(this.#paths.statePath).catch((cause) => {
3249
+ await unlink3(this.#paths.statePath).catch((cause) => {
3166
3250
  if (cause.code !== "ENOENT")
3167
3251
  throw cause;
3168
3252
  });
@@ -3254,7 +3338,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
3254
3338
  if (state.phase === "pending")
3255
3339
  return "refused-pending";
3256
3340
  await lock.assertOwned();
3257
- await unlink2(paths.statePath);
3341
+ await unlink3(paths.statePath);
3258
3342
  return "reset";
3259
3343
  } finally {
3260
3344
  await lock.release();
@@ -3262,7 +3346,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
3262
3346
  }
3263
3347
  async function removeIfPresent(path) {
3264
3348
  try {
3265
- await unlink2(path);
3349
+ await unlink3(path);
3266
3350
  return true;
3267
3351
  } catch (error) {
3268
3352
  if (error.code === "ENOENT")
@@ -6206,7 +6290,7 @@ class ClaustrumConsumer {
6206
6290
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/hub.js
6207
6291
  import { createHash as createHash3 } from "node:crypto";
6208
6292
  import { channel as channel2 } from "node:diagnostics_channel";
6209
- import { readdir, stat as stat5 } from "node:fs/promises";
6293
+ import { readdir as readdir2, stat as stat5 } from "node:fs/promises";
6210
6294
  import { dirname as dirname6, join as join5, resolve as resolve10 } from "node:path";
6211
6295
  var sharedRosters = new Map;
6212
6296
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
@@ -6854,7 +6938,7 @@ class ClaustrumDiscoveryHub {
6854
6938
  const name = `${entry.provider}.json`;
6855
6939
  const candidates = [join5(this.#generationDirectory, name)];
6856
6940
  try {
6857
- for (const key of await readdir(this.#generationDirectory))
6941
+ for (const key of await readdir2(this.#generationDirectory))
6858
6942
  if (key !== this.#key && FINGERPRINT.test(key))
6859
6943
  candidates.push(join5(this.#generationDirectory, key, name));
6860
6944
  } catch {}
@@ -7308,6 +7392,28 @@ function selectionFor(answer, candidates) {
7308
7392
  }
7309
7393
  return { candidate };
7310
7394
  }
7395
+ function refusalFor(value) {
7396
+ if (!isObject(value))
7397
+ return;
7398
+ const code = value.code;
7399
+ if (code !== "account_limit_exhausted" && code !== "account_selection_refused" && code !== "account_selection_final") {
7400
+ return;
7401
+ }
7402
+ const refused = { code };
7403
+ const routingCode = value.routing_code;
7404
+ if (typeof routingCode === "string" && /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
7405
+ refused.routingCode = routingCode;
7406
+ }
7407
+ const retryAfterSecs = value.retry_after_secs;
7408
+ if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs >= 0) {
7409
+ refused.retryAfterSecs = retryAfterSecs;
7410
+ }
7411
+ const resetsAtMs = value.resets_at_ms;
7412
+ if (typeof resetsAtMs === "number" && Number.isSafeInteger(resetsAtMs) && resetsAtMs > 0) {
7413
+ refused.resetsAtMs = resetsAtMs;
7414
+ }
7415
+ return { refused };
7416
+ }
7311
7417
  async function askRouting(input) {
7312
7418
  let timer;
7313
7419
  try {
@@ -7317,8 +7423,8 @@ async function askRouting(input) {
7317
7423
  const accountFor = handle.accountFor;
7318
7424
  if (typeof accountFor !== "function")
7319
7425
  return;
7320
- const requested = input.deadlineMs ?? 500;
7321
- const deadlineMs = Number.isNaN(requested) ? 500 : Math.min(2000, Math.max(1, requested));
7426
+ const requested = input.deadlineMs ?? 1500;
7427
+ const deadlineMs = Number.isNaN(requested) ? 1500 : Math.min(2000, Math.max(1, requested));
7322
7428
  const expired = new Promise((resolve11) => {
7323
7429
  timer = setTimeout(() => resolve11(undefined), deadlineMs);
7324
7430
  timer.unref();
@@ -7331,10 +7437,15 @@ async function askRouting(input) {
7331
7437
  if (typeof cap === "number" && Number.isFinite(cap)) {
7332
7438
  request2.hold_wait_max_s = Math.max(0, Math.floor(cap));
7333
7439
  }
7440
+ if (input.refusals === true)
7441
+ request2.refusals = true;
7334
7442
  const pending = accountFor.call(handle, request2, { deadlineMs });
7335
7443
  if (!isObject(pending) || typeof pending.then !== "function")
7336
7444
  return;
7337
7445
  const answer = await Promise.race([pending, expired]);
7446
+ if (input.refusals === true && isObject(answer) && "refused" in answer) {
7447
+ return refusalFor(answer.refused);
7448
+ }
7338
7449
  return selectionFor(answer, input.candidates);
7339
7450
  } catch {
7340
7451
  return;
@@ -7443,6 +7554,17 @@ function reportRouting(input) {
7443
7554
  };
7444
7555
  break;
7445
7556
  }
7557
+ case "credential_refused": {
7558
+ const { credentialId, providerCode } = input;
7559
+ if (!isNonEmptyString(credentialId) || typeof providerCode !== "string" || !/^[a-z0-9._-]{1,64}$/.test(providerCode))
7560
+ return;
7561
+ payload = {
7562
+ ...identity2,
7563
+ outcome: "credential_refused",
7564
+ provider_code: providerCode
7565
+ };
7566
+ break;
7567
+ }
7446
7568
  default:
7447
7569
  return;
7448
7570
  }
@@ -7843,11 +7965,17 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
7843
7965
  grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === undefined ? "category" : "exact"} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`
7844
7966
  }
7845
7967
  }));
7968
+ const access = {
7969
+ grants,
7970
+ ...status.requestedGrantsStatus !== undefined && {
7971
+ requestedGrantsStatus: status.requestedGrantsStatus
7972
+ }
7973
+ };
7846
7974
  if (status.requestedGrantsStatus === "dropped")
7847
- return { state: "older-vault", grants };
7975
+ return { ...access, state: "older-vault" };
7848
7976
  try {
7849
7977
  if (!client.listScoped)
7850
- return { state: "unconfirmed", grants };
7978
+ return { ...access, state: "unconfirmed" };
7851
7979
  const { token } = await readClaustrumEnrollmentToken(tokenPath);
7852
7980
  const inventory = await client.listScoped(token);
7853
7981
  const confirmed = grants.map((entry) => ({
@@ -7855,6 +7983,7 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
7855
7983
  reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) && (entry.grant.selector.exact !== undefined ? row.id === entry.grant.selector.exact : row.categories.includes(entry.grant.selector.category))).length
7856
7984
  }));
7857
7985
  return {
7986
+ ...access,
7858
7987
  state: confirmed.every((entry) => entry.reachableLogins > 0) ? "reachable" : confirmed.some((entry) => entry.reachableLogins > 0) ? "partial" : "no-logins",
7859
7988
  grants: confirmed.map((entry) => {
7860
7989
  if (entry.reachableLogins === 0)
@@ -7864,10 +7993,12 @@ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGran
7864
7993
  })
7865
7994
  };
7866
7995
  } catch {
7867
- return { state: "unconfirmed", grants };
7996
+ return { ...access, state: "unconfirmed" };
7868
7997
  }
7869
7998
  }
7870
- function enrollmentAccessLines(access) {
7999
+ function enrollmentAccessLines(access, grantFallback = "setup") {
8000
+ if (grantFallback === "plugin" && access.requestedGrantsStatus !== "sent")
8001
+ return [];
7871
8002
  const lines = [];
7872
8003
  const remedy = access.grants.some((entry) => entry.grantCommand) ? "run:" : "check ck auth status for the approved name before granting access.";
7873
8004
  if (access.state === "older-vault")
@@ -7931,8 +8062,9 @@ var OUTCOME_TEXT = {
7931
8062
  "not-enrolled": "not connected",
7932
8063
  unknown: "unknown, check with ck auth status"
7933
8064
  };
7934
- function setupEnrollmentLine({ host, outcome, access }) {
7935
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` — ${enrollmentAccessLines(access).join(`
8065
+ function setupEnrollmentLine({ host, outcome, access }, grantFallback = "setup") {
8066
+ const lines = access ? enrollmentAccessLines(access, grantFallback) : [];
8067
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${lines.length ? ` — ${lines.join(`
7936
8068
  `)}` : ""}`;
7937
8069
  }
7938
8070
  var recordedEnrollment = new WeakMap;
@@ -8477,7 +8609,7 @@ function approveCommand(requestId, name) {
8477
8609
  async function connectSetupHost(plugin, host, io, terminal, fence) {
8478
8610
  if (hasVaultHost())
8479
8611
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
8480
- const { name, displayName, requestedGrants, paths: input } = plugin.vault.hosts[host];
8612
+ const { name, displayName, requestedGrants, grantFallback, paths: input } = plugin.vault.hosts[host];
8481
8613
  const paths = hostEnrollmentPaths(input);
8482
8614
  await fence();
8483
8615
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
@@ -8506,7 +8638,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8506
8638
  printLine(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
8507
8639
  const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
8508
8640
  if (access)
8509
- for (const line of enrollmentAccessLines(access))
8641
+ for (const line of enrollmentAccessLines(access, grantFallback))
8510
8642
  printLine(terminal, line);
8511
8643
  return access;
8512
8644
  }
@@ -8522,7 +8654,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8522
8654
  printLine(terminal, `Connected ${host} to Claustrum.`);
8523
8655
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
8524
8656
  if (access)
8525
- for (const line of enrollmentAccessLines(access))
8657
+ for (const line of enrollmentAccessLines(access, grantFallback))
8526
8658
  printLine(terminal, line);
8527
8659
  return access;
8528
8660
  }
@@ -8731,8 +8863,8 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
8731
8863
 
8732
8864
  // ../../node_modules/@cortexkit/common-auth/dist/setup/config-write.js
8733
8865
  import { randomUUID as randomUUID5 } from "node:crypto";
8734
- import { mkdir as mkdir4, open as open5, rename as rename5, stat as stat7, unlink as unlink3 } from "node:fs/promises";
8735
- import { basename as basename2, dirname as dirname7, join as join7 } from "node:path";
8866
+ import { mkdir as mkdir4, open as open5, rename as rename5, stat as stat7, unlink as unlink4 } from "node:fs/promises";
8867
+ import { basename as basename3, dirname as dirname7, join as join7 } from "node:path";
8736
8868
  import { setTimeout as delay2 } from "node:timers/promises";
8737
8869
  async function writeHostConfigAtomic(file, content, options = {}) {
8738
8870
  const windows = (options.platform ?? process.platform) === "win32";
@@ -8747,7 +8879,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
8747
8879
  throw error;
8748
8880
  }
8749
8881
  }
8750
- const stage = join7(parent, `.${basename2(file)}.${(options.stageName ?? randomUUID5)()}.tmp`);
8882
+ const stage = join7(parent, `.${basename3(file)}.${(options.stageName ?? randomUUID5)()}.tmp`);
8751
8883
  let created = false;
8752
8884
  try {
8753
8885
  const handle = await open5(stage, "wx", mode ?? 438);
@@ -8777,7 +8909,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
8777
8909
  }
8778
8910
  } finally {
8779
8911
  if (created)
8780
- await unlink3(stage).catch(() => {});
8912
+ await unlink4(stage).catch(() => {});
8781
8913
  }
8782
8914
  }
8783
8915
 
@@ -8972,6 +9104,8 @@ function validatePlugin(plugin) {
8972
9104
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
8973
9105
  if (host.requestedGrants !== undefined && !validEnrollmentRequestedGrants(host.requestedGrants))
8974
9106
  throw new Error("invalid Claustrum enrollment requested grants");
9107
+ if (host.grantFallback !== undefined && host.grantFallback !== "setup" && host.grantFallback !== "plugin")
9108
+ throw new Error("invalid Claustrum enrollment grant fallback");
8975
9109
  }
8976
9110
  }
8977
9111
  async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
@@ -9162,7 +9296,7 @@ ${write.content}`);
9162
9296
  const report2 = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
9163
9297
  recordSetupEnrollment(error, report2);
9164
9298
  for (const entry of report2)
9165
- printLine(terminal, setupEnrollmentLine(entry));
9299
+ printLine(terminal, setupEnrollmentLine(entry, plugin.vault.hosts[entry.host].grantFallback));
9166
9300
  } catch {}
9167
9301
  throw error;
9168
9302
  }
@@ -12901,11 +13035,11 @@ import {
12901
13035
  realpath as realpath2,
12902
13036
  rename as rename7,
12903
13037
  stat as stat9,
12904
- unlink as unlink4
13038
+ unlink as unlink5
12905
13039
  } from "node:fs/promises";
12906
13040
  import { homedir as homedir4 } from "node:os";
12907
13041
  import {
12908
- basename as basename4,
13042
+ basename as basename5,
12909
13043
  dirname as dirname11,
12910
13044
  extname as extname2,
12911
13045
  isAbsolute as isAbsolute3,
@@ -13316,7 +13450,7 @@ function connectClaustrumEnrollmentClient2(options = {}) {
13316
13450
  }
13317
13451
  function getClaustrumEnrollmentPaths2(tokenPath) {
13318
13452
  const extension = extname2(tokenPath) || ".json";
13319
- const stem = basename4(tokenPath, extname2(tokenPath));
13453
+ const stem = basename5(tokenPath, extname2(tokenPath));
13320
13454
  return {
13321
13455
  statePath: join12(dirname11(tokenPath), `${stem}-state${extension}`),
13322
13456
  tokenPath
@@ -13473,7 +13607,7 @@ async function writeStateAtomic2(path2, state, beforeRename) {
13473
13607
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES2) {
13474
13608
  throw new Error("Claustrum enrollment state is too large");
13475
13609
  }
13476
- const temporary = join12(parent, `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
13610
+ const temporary = join12(parent, `.${basename5(path2)}.${process.pid}.${randomUUID8()}.tmp`);
13477
13611
  let descriptor;
13478
13612
  try {
13479
13613
  const nativeCreated = await createWindowsOwnerOnly(temporary, bytes);
@@ -13488,17 +13622,17 @@ async function writeStateAtomic2(path2, state, beforeRename) {
13488
13622
  await rename7(temporary, path2);
13489
13623
  } finally {
13490
13624
  await descriptor?.close().catch(() => {});
13491
- await unlink4(temporary).catch(() => {});
13625
+ await unlink5(temporary).catch(() => {});
13492
13626
  }
13493
13627
  }
13494
13628
  async function writeTokenAtomic(path2, value, writeTokenFile, beforeRename) {
13495
- const staged = join12(dirname11(path2), `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
13629
+ const staged = join12(dirname11(path2), `.${basename5(path2)}.${process.pid}.${randomUUID8()}.tmp`);
13496
13630
  try {
13497
13631
  await writeTokenFile(staged, value);
13498
13632
  await beforeRename();
13499
13633
  await rename7(staged, path2);
13500
13634
  } finally {
13501
- await unlink4(staged).catch(() => {});
13635
+ await unlink5(staged).catch(() => {});
13502
13636
  }
13503
13637
  }
13504
13638
  async function readClaustrumEnrollmentStatus2(paths, proposedName = CLAUSTRUM_OPENCODE_ENROLLMENT_NAME, ownership = {}) {
@@ -13781,7 +13915,7 @@ async function resetClaustrumEnrollmentState2(paths, proposedName) {
13781
13915
  if (state.phase === "pending")
13782
13916
  return "refused-pending";
13783
13917
  await lock.assertOwned();
13784
- await unlink4(paths.statePath);
13918
+ await unlink5(paths.statePath);
13785
13919
  return "reset";
13786
13920
  } finally {
13787
13921
  await lock.release();
@@ -15060,10 +15194,10 @@ import { createHash as createHash8, randomBytes as randomBytes4 } from "node:cry
15060
15194
  import {
15061
15195
  lstat as lstat5,
15062
15196
  mkdir as mkdir7,
15063
- readdir as readdir2,
15197
+ readdir as readdir3,
15064
15198
  readFile as readFile6,
15065
15199
  rename as rename8,
15066
- unlink as unlink5,
15200
+ unlink as unlink6,
15067
15201
  writeFile as writeFile2
15068
15202
  } from "node:fs/promises";
15069
15203
  import { tmpdir as tmpdir5 } from "node:os";
@@ -15151,7 +15285,7 @@ async function writeDumpFile(path2, contents) {
15151
15285
  if (error.code === "EEXIST")
15152
15286
  continue;
15153
15287
  if (created)
15154
- await unlink5(partialPath).catch(() => {});
15288
+ await unlink6(partialPath).catch(() => {});
15155
15289
  throw error;
15156
15290
  }
15157
15291
  }
@@ -15171,7 +15305,7 @@ async function sweepDumpDirectory(options) {
15171
15305
  if (dumpDirStats.isSymbolicLink())
15172
15306
  return emptyResult;
15173
15307
  const protectedPaths = new Set((options.protectedPaths ?? []).map((path2) => resolve12(path2)));
15174
- const entries = await readdir2(dumpDir, { withFileTypes: true });
15308
+ const entries = await readdir3(dumpDir, { withFileTypes: true });
15175
15309
  const files = [];
15176
15310
  await Promise.all(entries.map(async (entry) => {
15177
15311
  if (!entry.isFile())
@@ -15200,7 +15334,7 @@ async function sweepDumpDirectory(options) {
15200
15334
  let freedBytes = 0;
15201
15335
  const removeFile = async (file) => {
15202
15336
  try {
15203
- await unlink5(file.path);
15337
+ await unlink6(file.path);
15204
15338
  totalBytes -= file.size;
15205
15339
  freedBytes += file.size;
15206
15340
  removed += 1;
@@ -15377,7 +15511,7 @@ async function loadLatestDumpBody(input) {
15377
15511
  const dumpDir = getDumpDirectory();
15378
15512
  let names;
15379
15513
  try {
15380
- names = await readdir2(dumpDir);
15514
+ names = await readdir3(dumpDir);
15381
15515
  } catch {
15382
15516
  return;
15383
15517
  }
@@ -18719,7 +18853,7 @@ import {
18719
18853
  link as link2,
18720
18854
  lstat as lstat13,
18721
18855
  mkdir as mkdir11,
18722
- readdir as readdir3,
18856
+ readdir as readdir4,
18723
18857
  readFile as readFile12,
18724
18858
  rename as rename12,
18725
18859
  rm as rm7,
@@ -18735,7 +18869,7 @@ import { randomUUID as randomUUID15 } from "node:crypto";
18735
18869
  import { readFileSync as readFileSync2 } from "node:fs";
18736
18870
  import { lstat as lstat12, mkdir as mkdir10, readFile as readFile11 } from "node:fs/promises";
18737
18871
  import { uptime } from "node:os";
18738
- import { basename as basename9, dirname as dirname17, join as join20 } from "node:path";
18872
+ import { basename as basename10, dirname as dirname17, join as join20 } from "node:path";
18739
18873
 
18740
18874
  // src/native-lock-observer.ts
18741
18875
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
@@ -18778,17 +18912,17 @@ function observeNativeLocks(acquire, observer) {
18778
18912
 
18779
18913
  // src/native-vault-paths.ts
18780
18914
  import { createHash as createHash18 } from "node:crypto";
18781
- import { basename as basename8, dirname as dirname15, join as join17 } from "node:path";
18915
+ import { basename as basename9, dirname as dirname15, join as join17 } from "node:path";
18782
18916
 
18783
18917
  // src/pool-paths.ts
18784
18918
  import { createHash as createHash17 } from "node:crypto";
18785
18919
  import { realpath as realpath3 } from "node:fs/promises";
18786
- import { basename as basename7, dirname as dirname14, join as join16, resolve as resolve13 } from "node:path";
18920
+ import { basename as basename8, dirname as dirname14, join as join16, resolve as resolve13 } from "node:path";
18787
18921
 
18788
18922
  // src/sticky-routing.ts
18789
18923
  import { createHash as createHash16, randomUUID as randomUUID13 } from "node:crypto";
18790
18924
  import { mkdir as mkdir9, readFile as readFile8, rename as rename11, rm as rm6, stat as stat10, writeFile as writeFile3 } from "node:fs/promises";
18791
- import { basename as basename6, dirname as dirname13, join as join15 } from "node:path";
18925
+ import { basename as basename7, dirname as dirname13, join as join15 } from "node:path";
18792
18926
 
18793
18927
  // src/native-vault-seed.ts
18794
18928
  import { lstat as lstat7, readFile as readFile7 } from "node:fs/promises";
@@ -22781,7 +22915,7 @@ var nativeQuotaCodec = {
22781
22915
  import { randomUUID as randomUUID12 } from "node:crypto";
22782
22916
  import { constants as constants2 } from "node:fs";
22783
22917
  import { lstat as lstat6, mkdir as mkdir8, open as open8, rename as rename10, rm as rm5 } from "node:fs/promises";
22784
- import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute4, join as join14 } from "node:path";
22918
+ import { basename as basename6, dirname as dirname12, isAbsolute as isAbsolute4, join as join14 } from "node:path";
22785
22919
  import { types as utilTypes5 } from "node:util";
22786
22920
 
22787
22921
  // src/pool-binding.ts
@@ -23391,7 +23525,7 @@ async function writeNativeRuntimeOutcome(path2, storageId, change, hooks, firstI
23391
23525
  assertTransitions(current, next, firstIdentity);
23392
23526
  const bytes = `${JSON.stringify(next, null, 2)}
23393
23527
  `;
23394
- const stage = join14(dirname12(path2), `${basename5(path2)}.native-runtime.${randomUUID12()}.partial`);
23528
+ const stage = join14(dirname12(path2), `${basename6(path2)}.native-runtime.${randomUUID12()}.partial`);
23395
23529
  let ownsStage = false;
23396
23530
  try {
23397
23531
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
@@ -24930,7 +25064,7 @@ function stickyRetainRetryHeaders(upstream, now = Date.now()) {
24930
25064
  return headers;
24931
25065
  }
24932
25066
  function getStickyRoutingStatePath(accountStoragePath) {
24933
- const name = basename6(accountStoragePath);
25067
+ const name = basename7(accountStoragePath);
24934
25068
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
24935
25069
  return join15(dirname13(accountStoragePath), `${stem}-routing-state.json`);
24936
25070
  }
@@ -25368,7 +25502,7 @@ class StickySessionRouter {
25368
25502
  storage: input.storage,
25369
25503
  now: this.now()
25370
25504
  }) > 0) : undefined;
25371
- const selected = preferred ?? this.selectCandidate({ ...input, candidates, state });
25505
+ const selected = input.routingAccountId ? candidates.find((row) => row.accountId === input.routingAccountId) : preferred ?? this.selectCandidate({ ...input, candidates, state });
25372
25506
  if (!selected) {
25373
25507
  if (current && !input.preserveOnNoCandidate) {
25374
25508
  delete state.assignments[key];
@@ -25425,10 +25559,10 @@ async function canonicalPath(path2) {
25425
25559
  const parent = dirname14(absolute);
25426
25560
  if (parent === absolute)
25427
25561
  return absolute;
25428
- return join16(await canonicalPath(parent), basename7(absolute));
25562
+ return join16(await canonicalPath(parent), basename8(absolute));
25429
25563
  }
25430
25564
  function sibling(path2, legacyName, name, suffix) {
25431
- return basename7(path2) === legacyName ? join16(dirname14(path2), name) : `${path2}.${suffix}.json`;
25565
+ return basename8(path2) === legacyName ? join16(dirname14(path2), name) : `${path2}.${suffix}.json`;
25432
25566
  }
25433
25567
  async function resolveNativePoolPaths(legacyConfig = getAccountStoragePath(), legacyState = getAccountStatePath(legacyConfig), layout) {
25434
25568
  const [sourceConfig, sourceState] = await Promise.all([
@@ -25478,7 +25612,7 @@ async function resolveNativePoolPaths(legacyConfig = getAccountStoragePath(), le
25478
25612
 
25479
25613
  // src/native-vault-paths.ts
25480
25614
  function sibling2(path2, expected, name, suffix) {
25481
- return basename8(path2) === expected ? join17(dirname15(path2), name) : path2.replace(/(?:\.json)?$/, `.${suffix}.json`);
25615
+ return basename9(path2) === expected ? join17(dirname15(path2), name) : path2.replace(/(?:\.json)?$/, `.${suffix}.json`);
25482
25616
  }
25483
25617
  function nativeVaultPaths(local, layout = stateLayoutOfPaths(local)) {
25484
25618
  const config = sibling2(local.legacyConfig, "anthropic-auth.json", "anthropic-auth-vault-settings.json", "vault-settings");
@@ -25749,7 +25883,7 @@ class StateLayoutLockStack {
25749
25883
 
25750
25884
  // src/state-layout-record.ts
25751
25885
  import { randomUUID as randomUUID14 } from "node:crypto";
25752
- import { lstat as lstat9, readFile as readFile10, unlink as unlink6 } from "node:fs/promises";
25886
+ import { lstat as lstat9, readFile as readFile10, unlink as unlink7 } from "node:fs/promises";
25753
25887
  import { join as join18 } from "node:path";
25754
25888
  var RELOCATION_ROLES = [
25755
25889
  "localPoolState",
@@ -25970,7 +26104,7 @@ async function publishStateLayoutRecord(record11, guard, fs3) {
25970
26104
  if (outcome === "skipped")
25971
26105
  throw new Error(`anthropic-auth could not publish ${path2}`);
25972
26106
  } catch (error) {
25973
- await unlink6(stage).catch(() => {});
26107
+ await unlink7(stage).catch(() => {});
25974
26108
  throw error;
25975
26109
  }
25976
26110
  await fs3.syncDirectory(record11.sub);
@@ -26319,9 +26453,9 @@ function nativeHolderDatasetFiles(paths) {
26319
26453
  ].sort();
26320
26454
  }
26321
26455
  function isDestinationShapedDirectory(dir) {
26322
- const name = basename9(dir);
26456
+ const name = basename10(dir);
26323
26457
  const parent = dirname17(dir);
26324
- return (name === "opencode" || /^opencode-[0-9a-f]{16}$/.test(name)) && basename9(parent) === "anthropic-auth" && basename9(dirname17(parent)) === "cortexkit";
26458
+ return (name === "opencode" || /^opencode-[0-9a-f]{16}$/.test(name)) && basename10(parent) === "anthropic-auth" && basename10(dirname17(parent)) === "cortexkit";
26325
26459
  }
26326
26460
  function openCodeHolderKind(env = process.env) {
26327
26461
  return env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() ? "explicit" : "legacy";
@@ -26888,7 +27022,7 @@ class CacheKeepSessionRegistry {
26888
27022
  async recordPaths() {
26889
27023
  return (await Promise.all(this.directories.map(async (directory) => {
26890
27024
  try {
26891
- return (await readdir3(directory)).filter((name) => name.endsWith(".json")).map((name) => join21(directory, name));
27025
+ return (await readdir4(directory)).filter((name) => name.endsWith(".json")).map((name) => join21(directory, name));
26892
27026
  } catch {
26893
27027
  return [];
26894
27028
  }
@@ -26974,7 +27108,7 @@ class CacheKeepSessionRegistry {
26974
27108
  // src/cachekeep-store.ts
26975
27109
  import { createHash as createHash20, randomUUID as randomUUID17 } from "node:crypto";
26976
27110
  import { constants as constants3 } from "node:fs";
26977
- import { lstat as lstat14, mkdir as mkdir12, open as open10, readdir as readdir4, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
27111
+ import { lstat as lstat14, mkdir as mkdir12, open as open10, readdir as readdir5, rm as rm8, writeFile as writeFile5 } from "node:fs/promises";
26978
27112
  import { tmpdir as tmpdir7 } from "node:os";
26979
27113
  import { join as join22 } from "node:path";
26980
27114
  import { promisify } from "node:util";
@@ -27127,7 +27261,7 @@ class CacheKeepStore {
27127
27261
  let directory = this.directory;
27128
27262
  const firstLoad = !this.legacyLoadAttempted;
27129
27263
  this.legacyLoadAttempted = true;
27130
- if (!this.options.host && firstLoad && (await readdir4(directory)).length === 0) {
27264
+ if (!this.options.host && firstLoad && (await readdir5(directory)).length === 0) {
27131
27265
  const legacy = legacyCacheKeepStoreDirectory(this.options.storageId, this.options.legacyRoot ?? this.options.root);
27132
27266
  try {
27133
27267
  await lstat14(legacy);
@@ -27141,7 +27275,7 @@ class CacheKeepStore {
27141
27275
  let restored = 0;
27142
27276
  let dropped = 0;
27143
27277
  try {
27144
- for (const name of (await readdir4(directory)).sort()) {
27278
+ for (const name of (await readdir5(directory)).sort()) {
27145
27279
  if (!FILE.test(name) && !TEMP.test(name))
27146
27280
  continue;
27147
27281
  const release2 = claim ? await claim(name.slice(0, 64)) : undefined;
@@ -27295,7 +27429,7 @@ class CacheKeepStore {
27295
27429
  this.latest.clear();
27296
27430
  this.lastWrite.clear();
27297
27431
  this.enqueue(async () => {
27298
- for (const name of await readdir4(this.directory))
27432
+ for (const name of await readdir5(this.directory))
27299
27433
  if (FILE.test(name) || TEMP.test(name))
27300
27434
  await rm8(join22(this.directory, name), { force: true });
27301
27435
  });
@@ -37141,7 +37275,7 @@ function relayGeneration(input) {
37141
37275
  }
37142
37276
  // src/native-host-auth-write.ts
37143
37277
  import { randomUUID as randomUUID21 } from "node:crypto";
37144
- import { lstat as lstat16, open as open12, rename as rename13, unlink as unlink7 } from "node:fs/promises";
37278
+ import { lstat as lstat16, open as open12, rename as rename13, unlink as unlink8 } from "node:fs/promises";
37145
37279
  import { dirname as dirname19, isAbsolute as isAbsolute6, join as join23 } from "node:path";
37146
37280
  class NativeHostAuthWriteError extends Error {
37147
37281
  code;
@@ -37225,7 +37359,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
37225
37359
  await barrier(beforeRename, "hook-failed");
37226
37360
  await barrier(processFence, "process-fence-refused");
37227
37361
  if (removingFile) {
37228
- await unlink7(authPath);
37362
+ await unlink8(authPath);
37229
37363
  effect = outcome;
37230
37364
  await barrier(afterUnlink, "hook-failed", effect);
37231
37365
  } else {
@@ -37255,7 +37389,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
37255
37389
  try {
37256
37390
  const current = await lstat16(stage);
37257
37391
  if (current.dev === ownedStage.dev && current.ino === ownedStage.ino)
37258
- await unlink7(stage);
37392
+ await unlink8(stage);
37259
37393
  } catch {}
37260
37394
  }
37261
37395
  }
@@ -37263,7 +37397,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
37263
37397
 
37264
37398
  // src/native-migration.ts
37265
37399
  import { createHash as createHash25 } from "node:crypto";
37266
- import { lstat as lstat17, mkdir as mkdir13, unlink as unlink8 } from "node:fs/promises";
37400
+ import { lstat as lstat17, mkdir as mkdir13, unlink as unlink9 } from "node:fs/promises";
37267
37401
  import { dirname as dirname20, isAbsolute as isAbsolute7 } from "node:path";
37268
37402
  class NativeMigrationError extends Error {
37269
37403
  code;
@@ -37692,7 +37826,7 @@ async function retire(input, journal, assertOwned, hooks) {
37692
37826
  await requireUnchangedNativeMigrationSource(snapshot);
37693
37827
  await input.processFence();
37694
37828
  await assertOwned();
37695
- await unlink8(snapshot.path);
37829
+ await unlink9(snapshot.path);
37696
37830
  await hooks.onStep?.(`after:retire:${snapshot.role}`);
37697
37831
  }
37698
37832
  return advanceNativeMigration(input.paths, "committed", "retired", {
@@ -40520,7 +40654,7 @@ function placeholderSecret(integrationID) {
40520
40654
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
40521
40655
  import { createHash as createHash26 } from "node:crypto";
40522
40656
  import { constants as constants5 } from "node:fs";
40523
- import { lstat as lstat18, mkdir as mkdir15, open as open13, unlink as unlink9 } from "node:fs/promises";
40657
+ import { lstat as lstat18, mkdir as mkdir15, open as open13, unlink as unlink10 } from "node:fs/promises";
40524
40658
  import { dirname as dirname21, resolve as resolve16 } from "node:path";
40525
40659
  import { setTimeout as sleep } from "node:timers/promises";
40526
40660
 
@@ -40999,7 +41133,7 @@ function createPiSlot(options, onStep, hooks) {
40999
41133
  }
41000
41134
  async function deleteStash(assertLock) {
41001
41135
  assertLock();
41002
- await unlink9(stashPath);
41136
+ await unlink10(stashPath);
41003
41137
  await syncDir(dirname21(stashPath));
41004
41138
  onStep?.("stash-deleted");
41005
41139
  }
@@ -41200,7 +41334,7 @@ function createAnthropicOAuthFetch(options = {}) {
41200
41334
  // src/prime.ts
41201
41335
  import { createHash as createHash27 } from "node:crypto";
41202
41336
  import { realpathSync as realpathSync3 } from "node:fs";
41203
- import { mkdir as mkdir16, readdir as readdir5, rm as rm9, stat as stat12, writeFile as writeFile6 } from "node:fs/promises";
41337
+ import { mkdir as mkdir16, readdir as readdir6, rm as rm9, stat as stat12, writeFile as writeFile6 } from "node:fs/promises";
41204
41338
  import { tmpdir as tmpdir8 } from "node:os";
41205
41339
  import { join as join25, resolve as resolve18 } from "node:path";
41206
41340
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
@@ -41742,7 +41876,7 @@ class PrimeManager {
41742
41876
  }
41743
41877
  async readMarkerNames(dir) {
41744
41878
  try {
41745
- return await readdir5(dir);
41879
+ return await readdir6(dir);
41746
41880
  } catch (error) {
41747
41881
  if (error.code === "ENOENT")
41748
41882
  return [];
@@ -41767,7 +41901,7 @@ class PrimeManager {
41767
41901
  const dir = this.markerDir(accountFingerprint);
41768
41902
  const prefix = `${encodeURIComponent(accountId2)}-`;
41769
41903
  try {
41770
- return (await readdir5(dir)).some((entry2) => entry2.startsWith(prefix));
41904
+ return (await readdir6(dir)).some((entry2) => entry2.startsWith(prefix));
41771
41905
  } catch (error) {
41772
41906
  if (error.code === "ENOENT")
41773
41907
  return false;
@@ -41879,7 +42013,7 @@ class PrimeManager {
41879
42013
  async sweepMarkerDirectory(dir, now) {
41880
42014
  let entries;
41881
42015
  try {
41882
- entries = await readdir5(dir);
42016
+ entries = await readdir6(dir);
41883
42017
  } catch {
41884
42018
  return 0;
41885
42019
  }
@@ -41913,7 +42047,7 @@ import {
41913
42047
  chmod as chmod3,
41914
42048
  lstat as lstat19,
41915
42049
  mkdir as mkdir17,
41916
- readdir as readdir6,
42050
+ readdir as readdir7,
41917
42051
  readFile as readFile13,
41918
42052
  rename as rename14,
41919
42053
  rm as rm10,
@@ -42140,7 +42274,7 @@ class QuotaHeaderFeedRegistry {
42140
42274
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
42141
42275
  let names2;
42142
42276
  try {
42143
- names2 = await readdir6(directory);
42277
+ names2 = await readdir7(directory);
42144
42278
  } catch {
42145
42279
  return;
42146
42280
  }
@@ -42167,7 +42301,7 @@ class QuotaHeaderFeedRegistry {
42167
42301
  const leaseMs = this.options.leaseMs ?? QUOTA_HEADER_FEED_LEASE_MS;
42168
42302
  let names2;
42169
42303
  try {
42170
- names2 = (await readdir6(directory)).filter((name) => name.endsWith(".json"));
42304
+ names2 = (await readdir7(directory)).filter((name) => name.endsWith(".json"));
42171
42305
  } catch {
42172
42306
  return [];
42173
42307
  }
@@ -42355,7 +42489,7 @@ function buildClaudeQuotaSummary(input) {
42355
42489
  }
42356
42490
  // src/request-gzip.ts
42357
42491
  import { mkdir as mkdir18, readFile as readFile14, rename as rename15, rm as rm11, writeFile as writeFile8 } from "node:fs/promises";
42358
- import { basename as basename10, dirname as dirname23, join as join27 } from "node:path";
42492
+ import { basename as basename11, dirname as dirname23, join as join27 } from "node:path";
42359
42493
  import { promisify as promisify2 } from "node:util";
42360
42494
  import { gzip as gzip2 } from "node:zlib";
42361
42495
  var gzipAsync = promisify2(gzip2);
@@ -42501,7 +42635,7 @@ function getRequestGzipLatch(path2) {
42501
42635
  function getRequestGzipLatchPath(accountStoragePath, layout = LEGACY_STATE_LAYOUT) {
42502
42636
  if (layout.kind === "state-home")
42503
42637
  return stateHomeFilePaths(layout.dir).requestGzip;
42504
- const name = basename10(accountStoragePath);
42638
+ const name = basename11(accountStoragePath);
42505
42639
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
42506
42640
  return join27(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
42507
42641
  }
@@ -42782,6 +42916,129 @@ function reportRoutingResponse(sessionId, subject, headers, status, modelId, ser
42782
42916
  }
42783
42917
  }).catch(() => {});
42784
42918
  }
42919
+
42920
+ // src/routing-relay.ts
42921
+ var ROUTING_HOLD_LIMIT_MS = 15 * 60000 + 20000;
42922
+ function routingCandidates(accounts) {
42923
+ return accounts.filter((account) => account.type === "oauth" && nativeAccountCanServe(account));
42924
+ }
42925
+ function routingChoiceMatches(choice, account) {
42926
+ return account.accountIdentity === choice.account_id && (account.credentialId ?? "local") === choice.credential_id;
42927
+ }
42928
+
42929
+ class RoutingRefusalError extends Error {
42930
+ code;
42931
+ retryAfterSecs;
42932
+ status;
42933
+ constructor(refusal2, now = Date.now()) {
42934
+ super(refusal2.code === "account_selection_final" ? "Shared routing refused an account for this request." : "Shared routing has no account for this request right now.");
42935
+ this.name = "RoutingRefusalError";
42936
+ this.code = refusal2.code;
42937
+ this.status = refusal2.code === "account_selection_final" ? 403 : 429;
42938
+ this.retryAfterSecs = this.status === 429 ? refusal2.retryAfterSecs ?? (refusal2.resetsAtMs === undefined ? undefined : Math.max(0, Math.ceil((refusal2.resetsAtMs - now) / 1000))) : undefined;
42939
+ }
42940
+ response() {
42941
+ return new Response(JSON.stringify({
42942
+ type: "error",
42943
+ error: {
42944
+ type: this.status === 429 ? "rate_limit_error" : "permission_error",
42945
+ code: this.code,
42946
+ message: this.message
42947
+ }
42948
+ }), {
42949
+ status: this.status,
42950
+ headers: {
42951
+ "content-type": "application/json",
42952
+ ...this.retryAfterSecs === undefined ? {} : { "retry-after": String(this.retryAfterSecs) }
42953
+ }
42954
+ });
42955
+ }
42956
+ }
42957
+ function createRoutingRelay(quotaFor) {
42958
+ const overridden = new Set;
42959
+ const admissions = new Map;
42960
+ const silenced = new Set;
42961
+ const override = (sessionId, reason) => {
42962
+ if (admissions.delete(sessionId)) {
42963
+ if (silenced.size >= 512) {
42964
+ const first = silenced.values().next();
42965
+ if (!first.done)
42966
+ silenced.delete(first.value);
42967
+ }
42968
+ silenced.add(sessionId);
42969
+ }
42970
+ if (overridden.has(sessionId))
42971
+ return;
42972
+ if (overridden.size >= 512) {
42973
+ const first = overridden.values().next();
42974
+ if (!first.done)
42975
+ overridden.delete(first.value);
42976
+ }
42977
+ overridden.add(sessionId);
42978
+ logger2.debug("routing-relay", "Using local account choice", {
42979
+ sessionId,
42980
+ reason
42981
+ });
42982
+ };
42983
+ return {
42984
+ override,
42985
+ shouldReport(sessionId) {
42986
+ return !silenced.has(sessionId);
42987
+ },
42988
+ admitted(sessionId, subject) {
42989
+ const choice = admissions.get(sessionId);
42990
+ return !!choice && routingChoiceMatches(choice, subject);
42991
+ },
42992
+ policy(sessionId, account, snapshot, modelId) {
42993
+ const choice = admissions.get(sessionId);
42994
+ return choice && routingChoiceMatches(choice, account) && nativeAccountCanServe(account) ? { status: "allowed" } : nativeAccountPolicy(account, snapshot, modelId);
42995
+ },
42996
+ async accountFor(sessionId, modelId, candidates) {
42997
+ admissions.delete(sessionId);
42998
+ silenced.delete(sessionId);
42999
+ const result = await askRouting({
43000
+ sessionId,
43001
+ provider: "anthropic",
43002
+ modelId,
43003
+ deadlineMs: 2000,
43004
+ refusals: true,
43005
+ candidates: candidates.flatMap((row) => row.accountIdentity ? [
43006
+ {
43007
+ accountId: row.accountIdentity,
43008
+ credentialId: row.credentialId ?? "local"
43009
+ }
43010
+ ] : [])
43011
+ });
43012
+ if (!result) {
43013
+ override(sessionId, "no valid answer within routing deadline");
43014
+ return null;
43015
+ }
43016
+ if ("refused" in result)
43017
+ throw new RoutingRefusalError(result.refused);
43018
+ const choice = {
43019
+ account_id: result.candidate.accountId,
43020
+ credential_id: result.candidate.credentialId,
43021
+ ...result.hold && result.hold.retry_after_ms > 0 ? {
43022
+ hold: {
43023
+ retry_after_ms: Math.min(result.hold.retry_after_ms, ROUTING_HOLD_LIMIT_MS)
43024
+ }
43025
+ } : {}
43026
+ };
43027
+ if (admissions.size >= 512) {
43028
+ const first = admissions.keys().next();
43029
+ if (!first.done)
43030
+ admissions.delete(first.value);
43031
+ }
43032
+ admissions.set(sessionId, choice);
43033
+ return choice;
43034
+ },
43035
+ report(sessionId, subject, headers, status, modelId, served = status < 400) {
43036
+ if (silenced.has(sessionId))
43037
+ return;
43038
+ reportRoutingResponse(sessionId, subject, headers, status, modelId, served, quotaFor ? () => quotaFor(subject) : undefined);
43039
+ }
43040
+ };
43041
+ }
42785
43042
  // src/start.ts
42786
43043
  var CLAUDE_START_COMMAND_NAME = "claude-start";
42787
43044
  var START_STATUS_TITLE = "## Claude Lane Start Status";
@@ -42815,14 +43072,14 @@ function executeLaneStartCommand(input) {
42815
43072
  };
42816
43073
  }
42817
43074
  // src/state-layout-decision.ts
42818
- import { mkdir as mkdir19, readdir as readdir9 } from "node:fs/promises";
43075
+ import { mkdir as mkdir19, readdir as readdir10 } from "node:fs/promises";
42819
43076
  import { homedir as homedir8 } from "node:os";
42820
- import { basename as basename13, dirname as dirname25, join as join31 } from "node:path";
43077
+ import { basename as basename14, dirname as dirname25, join as join31 } from "node:path";
42821
43078
 
42822
43079
  // src/layout-fence.ts
42823
- import { open as open14, readdir as readdir7 } from "node:fs/promises";
43080
+ import { open as open14, readdir as readdir8 } from "node:fs/promises";
42824
43081
  import { homedir as homedir6 } from "node:os";
42825
- import { basename as basename11, join as join28, resolve as resolve19 } from "node:path";
43082
+ import { basename as basename12, join as join28, resolve as resolve19 } from "node:path";
42826
43083
  var STATE_PATH_OVERRIDE_VARIABLES = [
42827
43084
  "OPENCODE_ANTHROPIC_AUTH_FILE",
42828
43085
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -42924,7 +43181,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
42924
43181
  }
42925
43182
  async function listDir(dir, blockers) {
42926
43183
  try {
42927
- return await readdir7(dir);
43184
+ return await readdir8(dir);
42928
43185
  } catch (error) {
42929
43186
  if (errorCode5(error) === "ENOENT")
42930
43187
  return [];
@@ -43007,7 +43264,7 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
43007
43264
  function describeFenceBlocker(blocker) {
43008
43265
  switch (blocker.kind) {
43009
43266
  case "holder":
43010
- return `pid ${blocker.pid ?? "unknown"} (${blocker.role ?? "unknown role"}) in ${basename11(blocker.holderFile)} uses ${blocker.file ?? "an unreadable file list"}`;
43267
+ return `pid ${blocker.pid ?? "unknown"} (${blocker.role ?? "unknown role"}) in ${basename12(blocker.holderFile)} uses ${blocker.file ?? "an unreadable file list"}`;
43011
43268
  case "holder-file":
43012
43269
  return `${blocker.holderFile} can't be read (${blocker.reason})`;
43013
43270
  case "pre-n-artifact":
@@ -43021,8 +43278,8 @@ function describeFenceBlocker(blocker) {
43021
43278
 
43022
43279
  // src/state-layout-move.ts
43023
43280
  import { randomUUID as randomUUID23 } from "node:crypto";
43024
- import { lstat as lstat20, readdir as readdir8, readFile as readFile15, stat as stat14, unlink as unlink10 } from "node:fs/promises";
43025
- import { basename as basename12, dirname as dirname24, join as join29, sep as sep2 } from "node:path";
43281
+ import { lstat as lstat20, readdir as readdir9, readFile as readFile15, stat as stat14, unlink as unlink11 } from "node:fs/promises";
43282
+ import { basename as basename13, dirname as dirname24, join as join29, sep as sep2 } from "node:path";
43026
43283
  var ACCOUNT_FILE = "anthropic-auth.json";
43027
43284
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
43028
43285
  var LAYOUT_LOCK_NAME = "runtime-layout";
@@ -43324,7 +43581,7 @@ async function removeOwnStaging(path2) {
43324
43581
  try {
43325
43582
  const info = await lstat20(path2);
43326
43583
  if (info.isFile())
43327
- await unlink10(path2);
43584
+ await unlink11(path2);
43328
43585
  } catch (error) {
43329
43586
  if (errorCode6(error) !== "ENOENT")
43330
43587
  throw error;
@@ -43376,7 +43633,7 @@ async function movePreconditionFailure(dataset, platform) {
43376
43633
  if (platform !== "win32" && typeof process.getuid === "function" && info.uid !== process.getuid())
43377
43634
  return `${path2} belongs to another user`;
43378
43635
  }
43379
- if (dirname24(slot.from) !== dataset.oldDir || basename12(slot.from) !== basename12(slot.configured))
43636
+ if (dirname24(slot.from) !== dataset.oldDir || basename13(slot.from) !== basename13(slot.configured))
43380
43637
  return `${slot.configured} resolves to ${slot.from}, not to a file of its own in the config folder`;
43381
43638
  const fromExists = await exists3(slot.from);
43382
43639
  anyOld ||= fromExists;
@@ -43520,7 +43777,7 @@ async function rollbackPreparing(record13, dataset, ctx) {
43520
43777
  continue;
43521
43778
  await owned2(ctx, { kind: "unlink", path: file.to }, expectDigest(file.to, file.sha256));
43522
43779
  }
43523
- for (const name of await readdir8(dataset.sub))
43780
+ for (const name of await readdir9(dataset.sub))
43524
43781
  if (isLayoutRecordStage(name, attempt))
43525
43782
  await removeOwnStaging(join29(dataset.sub, name));
43526
43783
  await stateLayoutStep(ctx, "rollback:destination-removed");
@@ -44529,7 +44786,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
44529
44786
  }
44530
44787
  let names2;
44531
44788
  try {
44532
- names2 = await readdir9(dirname25(journal));
44789
+ names2 = await readdir10(dirname25(journal));
44533
44790
  } catch (error) {
44534
44791
  if (error?.code === "ENOENT")
44535
44792
  return false;
@@ -44542,7 +44799,7 @@ async function oldFolderTransition(old, recordedMovingJournal) {
44542
44799
  return false;
44543
44800
  }
44544
44801
  }
44545
- return names2.some((name) => isMovingJournalName(basename13(journal), name));
44802
+ return names2.some((name) => isMovingJournalName(basename14(journal), name));
44546
44803
  }
44547
44804
  async function recordedMovingJournal(journal, identity4, options) {
44548
44805
  try {
@@ -45175,6 +45432,8 @@ export {
45175
45432
  runPiCommandMenu,
45176
45433
  runNativeMigration,
45177
45434
  runNativeCustodyActivation,
45435
+ routingChoiceMatches,
45436
+ routingCandidates,
45178
45437
  restoreLegacyLayout,
45179
45438
  resolveStateHomeTarget,
45180
45439
  resolveNativePoolPaths,
@@ -45486,6 +45745,7 @@ export {
45486
45745
  createStringPatch,
45487
45746
  createStickyNoRouteResponse,
45488
45747
  createSseFramer,
45748
+ createRoutingRelay,
45489
45749
  createRelocationGuard,
45490
45750
  createRelayPatch,
45491
45751
  createQuotaRefusalResponse,
@@ -45595,9 +45855,11 @@ export {
45595
45855
  SERVER_FALLBACK_USAGE_SIGNATURE_PREFIX,
45596
45856
  SERVER_FALLBACK_USAGE_MARKER_TEXT,
45597
45857
  SECRET_KEY_EXACT2 as SECRET_KEY_EXACT,
45858
+ RoutingRefusalError,
45598
45859
  RequestGzipLatch,
45599
45860
  RelocatedError,
45600
45861
  ROUTING_MODES,
45862
+ ROUTING_HOLD_LIMIT_MS,
45601
45863
  RESTORE_LEGACY_COMMAND,
45602
45864
  REQUIRED_BETAS,
45603
45865
  RELOCATION_MOVE_ENABLED,