@cortexkit/anthropic-auth-core 2.4.8 → 2.4.9

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
@@ -1,6 +1,104 @@
1
1
  import { createRequire } from "node:module";
2
2
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
3
 
4
+ // ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
5
+ function isObject(value) {
6
+ return typeof value === "object" && value !== null;
7
+ }
8
+ function routingHandle(sessionId) {
9
+ const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
10
+ if (typeof routing !== "function")
11
+ return;
12
+ const handle = routing(sessionId);
13
+ return isObject(handle) ? handle : undefined;
14
+ }
15
+ function selectionFor(answer, candidates) {
16
+ if (!isObject(answer))
17
+ return;
18
+ const accountId = answer.account_id;
19
+ const credentialId = answer.credential_id;
20
+ if (typeof accountId !== "string")
21
+ return;
22
+ if (credentialId !== undefined && typeof credentialId !== "string") {
23
+ return;
24
+ }
25
+ const candidate = candidates.find((route) => route.accountId === accountId && (credentialId === undefined || route.credentialId === credentialId));
26
+ if (!candidate)
27
+ return;
28
+ const hold = answer.hold;
29
+ const retryAfterMs = isObject(hold) ? hold.retry_after_ms : undefined;
30
+ if (typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
31
+ return { candidate, hold: { retry_after_ms: retryAfterMs } };
32
+ }
33
+ return { candidate };
34
+ }
35
+ async function askRouting(input) {
36
+ let timer;
37
+ try {
38
+ const handle = routingHandle(input.sessionId);
39
+ if (!handle)
40
+ return;
41
+ const accountFor = handle.accountFor;
42
+ if (typeof accountFor !== "function")
43
+ return;
44
+ const requested = input.deadlineMs ?? 500;
45
+ const deadlineMs = Number.isNaN(requested) ? 500 : Math.min(2000, Math.max(1, requested));
46
+ const expired = new Promise((resolve) => {
47
+ timer = setTimeout(() => resolve(undefined), deadlineMs);
48
+ timer.unref();
49
+ });
50
+ const pending = accountFor.call(handle, { provider: input.provider, modelId: input.modelId }, { deadlineMs });
51
+ if (!isObject(pending) || typeof pending.then !== "function")
52
+ return;
53
+ const answer = await Promise.race([pending, expired]);
54
+ return selectionFor(answer, input.candidates);
55
+ } catch {
56
+ return;
57
+ } finally {
58
+ clearTimeout(timer);
59
+ }
60
+ }
61
+ function reportRouting(input) {
62
+ try {
63
+ const handle = routingHandle(input.sessionId);
64
+ if (!handle)
65
+ return;
66
+ const report = handle.report;
67
+ if (typeof report !== "function")
68
+ return;
69
+ const identity = {
70
+ account_id: input.accountId,
71
+ ...input.credentialId !== undefined ? { credential_id: input.credentialId } : {}
72
+ };
73
+ let payload;
74
+ switch (input.outcome) {
75
+ case "served":
76
+ payload = { ...identity, outcome: "served", headers: input.headers };
77
+ break;
78
+ case "exhausted": {
79
+ const { window, pool } = input;
80
+ if (window !== "5h" && window !== "7d")
81
+ return;
82
+ if (pool !== undefined && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
83
+ return;
84
+ payload = {
85
+ ...identity,
86
+ outcome: "exhausted",
87
+ window,
88
+ ...pool ? { pool } : {},
89
+ ...input.resetsAt !== undefined ? { resets_at: input.resetsAt } : {}
90
+ };
91
+ break;
92
+ }
93
+ default:
94
+ return;
95
+ }
96
+ const pending = report.call(handle, payload);
97
+ if (isObject(pending) && typeof pending.then === "function") {
98
+ Promise.resolve(pending).catch(() => {});
99
+ }
100
+ } catch {}
101
+ }
4
102
  // ../../node_modules/@cortexkit/common-auth/dist/auth-menu/ansi.js
5
103
  var ANSI = {
6
104
  hide: "\x1B[?25l",
@@ -241,7 +339,7 @@ async function select(terminal, items, options) {
241
339
  import { createHash, randomBytes, randomUUID as randomUUID4 } from "node:crypto";
242
340
  import { constants as fsConstants } from "node:fs";
243
341
  import { chmod, mkdir as mkdir3, open as open3, readFile as readFile3, realpath, rename as rename4, stat as stat2, unlink as unlink2 } from "node:fs/promises";
244
- import { basename, dirname as dirname4, extname, isAbsolute, join as join3, resolve as resolve3 } from "node:path";
342
+ import { basename, dirname as dirname4, extname, isAbsolute, join as join4, resolve as resolve4 } from "node:path";
245
343
  import { ClaustrumCredentialError, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
246
344
 
247
345
  // ../../node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
@@ -688,9 +786,10 @@ var WRITER_LOCK_CONSTANTS = Object.freeze({
688
786
  // ../../node_modules/@cortexkit/common-auth/dist/fs/refresh-file-lock.js
689
787
  import { randomUUID as randomUUID3 } from "node:crypto";
690
788
  import { lstat as lstat3, mkdir as mkdir2, open as open2, readFile as readFile2, rename as rename3, rm as rm2, stat } from "node:fs/promises";
691
- import { dirname as dirname3, join as join2 } from "node:path";
789
+ import { dirname as dirname3, join as join3 } from "node:path";
692
790
 
693
791
  // ../../node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
792
+ import { join as join2, resolve as resolve3 } from "node:path";
694
793
  function lockPathFor(target, name) {
695
794
  return `${target}.${name}.lock`;
696
795
  }
@@ -712,18 +811,33 @@ class LockOwnershipError extends Error {
712
811
  this.details = details;
713
812
  }
714
813
  }
814
+ function isChangingLockRead(error, target, name) {
815
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.reason !== "io-error" || error.win32Code !== 32 && error.win32Code !== 303 || error.stage !== "read" && error.stage !== "verify")
816
+ return false;
817
+ const path = resolve3(lockPathFor(target, name));
818
+ return error.path === path || error.path === join2(path, "owner.json");
819
+ }
715
820
  async function withLock(target, options, fn) {
716
821
  const started = performance.now();
717
822
  for (;; ) {
718
823
  options.signal?.throwIfAborted();
719
- const lock = await acquireRefreshFileLock({
720
- path: target,
721
- name: options.name,
722
- ttlMs: options.ttlMs,
723
- renew: options.renew ?? false,
724
- ...options.onStep ? { onStep: options.onStep } : {},
725
- ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
726
- });
824
+ let lock;
825
+ let changingReadError;
826
+ try {
827
+ lock = await acquireRefreshFileLock({
828
+ path: target,
829
+ name: options.name,
830
+ ttlMs: options.ttlMs,
831
+ renew: options.renew ?? false,
832
+ ...options.onStep ? { onStep: options.onStep } : {},
833
+ ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
834
+ });
835
+ } catch (error) {
836
+ if (!isChangingLockRead(error, target, options.name))
837
+ throw error;
838
+ lock = null;
839
+ changingReadError = error;
840
+ }
727
841
  if (lock) {
728
842
  try {
729
843
  options.signal?.throwIfAborted();
@@ -734,13 +848,15 @@ async function withLock(target, options, fn) {
734
848
  }
735
849
  const remaining = options.timeoutMs - (performance.now() - started);
736
850
  if (remaining <= 0) {
851
+ if (changingReadError)
852
+ throw changingReadError;
737
853
  throw new LockContentionError({
738
854
  target,
739
855
  name: options.name,
740
856
  timeoutMs: options.timeoutMs
741
857
  });
742
858
  }
743
- await new Promise((resolve3) => setTimeout(resolve3, Math.min(25, Math.ceil(remaining))));
859
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(25, Math.ceil(remaining))));
744
860
  }
745
861
  }
746
862
 
@@ -789,7 +905,7 @@ function acquireRefreshFileLock(options) {
789
905
  }
790
906
  async function acquireRefreshFileLockWithClock(options) {
791
907
  const lockPath = lockPathFor(options.path, options.name);
792
- const legacyOwnerPath = join2(lockPath, "owner.json");
908
+ const legacyOwnerPath = join3(lockPath, "owner.json");
793
909
  const ownerId = randomUUID3();
794
910
  const now = options.now ?? Date.now;
795
911
  let renewTimer = null;
@@ -797,8 +913,8 @@ async function acquireRefreshFileLockWithClock(options) {
797
913
  let releaseConfirmed = false;
798
914
  let loss;
799
915
  let resolveLoss;
800
- const lostPromise = new Promise((resolve3) => {
801
- resolveLoss = resolve3;
916
+ const lostPromise = new Promise((resolve4) => {
917
+ resolveLoss = resolve4;
802
918
  });
803
919
  function notifyTimerStep(event) {
804
920
  try {
@@ -830,7 +946,7 @@ async function acquireRefreshFileLockWithClock(options) {
830
946
  let terminalIOError;
831
947
  let renewalInFlight = null;
832
948
  const evictPath = `${lockPath}.evicting`;
833
- const evictOwnerPath = join2(evictPath, "owner.json");
949
+ const evictOwnerPath = join3(evictPath, "owner.json");
834
950
  const evictOwnerId = randomUUID3();
835
951
  const EVICT_TTL = 5000;
836
952
  const MAX_STEAL_ATTEMPTS = 8;
@@ -955,7 +1071,7 @@ async function acquireRefreshFileLockWithClock(options) {
955
1071
  }
956
1072
  }
957
1073
  async function backoff() {
958
- await new Promise((resolve3) => setTimeout(resolve3, Math.floor(Math.random() * 4)));
1074
+ await new Promise((resolve4) => setTimeout(resolve4, Math.floor(Math.random() * 4)));
959
1075
  }
960
1076
  async function readLockState(notifyReady = true) {
961
1077
  if (notifyReady && options.onStep)
@@ -1439,7 +1555,7 @@ async function acquireRefreshFileLockWithClock(options) {
1439
1555
  const remainingMs = deadline - performance.now();
1440
1556
  if (remainingMs <= 0)
1441
1557
  break;
1442
- await new Promise((resolve3) => setTimeout(resolve3, Math.min(delayMs, remainingMs)));
1558
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(delayMs, remainingMs)));
1443
1559
  delayMs = Math.min(delayMs * 2, 50);
1444
1560
  }
1445
1561
  if (windowsPrivateFiles)
@@ -1496,7 +1612,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
1496
1612
  const extension = extname(tokenPath) || ".json";
1497
1613
  const stem = basename(tokenPath, extname(tokenPath));
1498
1614
  return {
1499
- statePath: join3(dirname4(tokenPath), `${stem}-state${extension}`),
1615
+ statePath: join4(dirname4(tokenPath), `${stem}-state${extension}`),
1500
1616
  tokenPath
1501
1617
  };
1502
1618
  }
@@ -1504,7 +1620,7 @@ function hostEnrollmentPaths(input) {
1504
1620
  const override = input.override?.trim();
1505
1621
  if (override && !isAbsolute(override) && !input.cwd)
1506
1622
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
1507
- const tokenPath = override ? isAbsolute(override) ? override : resolve3(input.cwd, override) : join3(input.stateDir, `${input.host}-enrollment.json`);
1623
+ const tokenPath = override ? isAbsolute(override) ? override : resolve4(input.cwd, override) : join4(input.stateDir, `${input.host}-enrollment.json`);
1508
1624
  return getClaustrumEnrollmentPaths(tokenPath);
1509
1625
  }
1510
1626
  function isRecord(value) {
@@ -1740,7 +1856,7 @@ async function writeStateAtomic(path, state, ancestorOptions = {}) {
1740
1856
  }
1741
1857
  if (windowsPrivateFiles)
1742
1858
  return writePrivateAtomic(path, bytes);
1743
- const temporary = join3(parent, `.${basename(path)}.${process.pid}.${randomUUID4()}.tmp`);
1859
+ const temporary = join4(parent, `.${basename(path)}.${process.pid}.${randomUUID4()}.tmp`);
1744
1860
  let descriptor;
1745
1861
  let created = false;
1746
1862
  try {
@@ -2241,7 +2357,7 @@ class ByteTail {
2241
2357
  }
2242
2358
  var defaultCommandRunner = {
2243
2359
  run(file, args, options = {}) {
2244
- return new Promise((resolve4) => {
2360
+ return new Promise((resolve5) => {
2245
2361
  const started = performance.now();
2246
2362
  const timeoutMs = options.timeoutMs ?? 15000;
2247
2363
  const stderr = new ByteTail;
@@ -2259,7 +2375,7 @@ var defaultCommandRunner = {
2259
2375
  stdio: ["ignore", "pipe", "pipe"]
2260
2376
  });
2261
2377
  } catch {
2262
- resolve4({
2378
+ resolve5({
2263
2379
  exitCode: 1,
2264
2380
  stdout: "",
2265
2381
  stderr: "",
@@ -2294,7 +2410,7 @@ var defaultCommandRunner = {
2294
2410
  settled = true;
2295
2411
  if (timer)
2296
2412
  clearTimeout(timer);
2297
- resolve4({
2413
+ resolve5({
2298
2414
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code ?? 1,
2299
2415
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
2300
2416
  stderr: stderr.toString(),
@@ -2388,7 +2504,7 @@ function setupEnrollment(error) {
2388
2504
  import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from "node:fs";
2389
2505
  import { mkdtemp, rm as rm3 } from "node:fs/promises";
2390
2506
  import { tmpdir as tmpdir2 } from "node:os";
2391
- import { join as join4 } from "node:path";
2507
+ import { join as join5 } from "node:path";
2392
2508
  import { parse } from "jsonc-parser";
2393
2509
 
2394
2510
  // ../../node_modules/@cortexkit/common-auth/dist/setup/paths.js
@@ -2557,7 +2673,7 @@ async function detectHosts(plugin, io = {}) {
2557
2673
  return null;
2558
2674
  let root;
2559
2675
  try {
2560
- root = await mkdtemp(join4(tmpdir2(), "common-auth-setup-version-"));
2676
+ root = await mkdtemp(join5(tmpdir2(), "common-auth-setup-version-"));
2561
2677
  const probeEnv = {
2562
2678
  ...env,
2563
2679
  HOME: root,
@@ -3151,7 +3267,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
3151
3267
  // ../../node_modules/@cortexkit/common-auth/dist/setup/config-write.js
3152
3268
  import { randomUUID as randomUUID5 } from "node:crypto";
3153
3269
  import { mkdir as mkdir4, open as open4, rename as rename5, stat as stat4, unlink as unlink3 } from "node:fs/promises";
3154
- import { basename as basename2, dirname as dirname5, join as join5 } from "node:path";
3270
+ import { basename as basename2, dirname as dirname5, join as join6 } from "node:path";
3155
3271
  import { setTimeout as delay2 } from "node:timers/promises";
3156
3272
  async function writeHostConfigAtomic(file, content, options = {}) {
3157
3273
  const windows = (options.platform ?? process.platform) === "win32";
@@ -3166,7 +3282,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
3166
3282
  throw error;
3167
3283
  }
3168
3284
  }
3169
- const stage = join5(parent, `.${basename2(file)}.${(options.stageName ?? randomUUID5)()}.tmp`);
3285
+ const stage = join6(parent, `.${basename2(file)}.${(options.stageName ?? randomUUID5)()}.tmp`);
3170
3286
  let created = false;
3171
3287
  try {
3172
3288
  const handle = await open4(stage, "wx", mode ?? 438);
@@ -3583,13 +3699,13 @@ ${write.content}`);
3583
3699
  import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
3584
3700
  import { mkdir as mkdir5, readFile as readFile5, rename as rename6, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
3585
3701
  import { homedir as homedir2 } from "node:os";
3586
- import { dirname as dirname6, join as join7 } from "node:path";
3702
+ import { dirname as dirname6, join as join8 } from "node:path";
3587
3703
 
3588
3704
  // src/claustrum.ts
3589
3705
  import { readdirSync, statSync as statSync2 } from "node:fs";
3590
3706
  import * as fs from "node:fs/promises";
3591
3707
  import { tmpdir as tmpdir3, userInfo } from "node:os";
3592
- import { join as join6 } from "node:path";
3708
+ import { join as join7 } from "node:path";
3593
3709
  function errorCode(error) {
3594
3710
  return error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : "unknown";
3595
3711
  }
@@ -3617,7 +3733,7 @@ function listSubcTempConnectionFiles(dir) {
3617
3733
  if (!name.startsWith(CLAUSTRUM_TEMP_PREFIX) || !name.endsWith(CLAUSTRUM_TEMP_SUFFIX)) {
3618
3734
  continue;
3619
3735
  }
3620
- const candidate = join6(dir, name);
3736
+ const candidate = join7(dir, name);
3621
3737
  if (safeIsFile(candidate))
3622
3738
  matches.push(candidate);
3623
3739
  }
@@ -3627,13 +3743,13 @@ function listSubcTempConnectionFiles(dir) {
3627
3743
  function findExistingClaustrumConnectionPath(env = process.env) {
3628
3744
  const runtime = env.XDG_RUNTIME_DIR?.trim();
3629
3745
  if (runtime) {
3630
- const candidate = join6(runtime, PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3746
+ const candidate = join7(runtime, PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3631
3747
  if (safeIsFile(candidate))
3632
3748
  return candidate;
3633
3749
  }
3634
3750
  const home = env.HOME?.trim();
3635
3751
  if (home) {
3636
- const candidate = join6(home, ".local", "share", "cortexkit", "run", PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3752
+ const candidate = join7(home, ".local", "share", "cortexkit", "run", PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3637
3753
  if (safeIsFile(candidate))
3638
3754
  return candidate;
3639
3755
  }
@@ -3652,11 +3768,11 @@ function getDefaultClaustrumConnectionPath(env = process.env) {
3652
3768
  return existing;
3653
3769
  const runtime = env.XDG_RUNTIME_DIR?.trim();
3654
3770
  if (runtime && (process.platform !== "darwin" || safeIsFile(runtime))) {
3655
- return join6(runtime, PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3771
+ return join7(runtime, PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3656
3772
  }
3657
3773
  if (process.platform === "darwin") {
3658
3774
  const home = env.HOME?.trim() || userInfo().homedir;
3659
- return join6(home, ".local", "share", "cortexkit", "run", PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3775
+ return join7(home, ".local", "share", "cortexkit", "run", PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME);
3660
3776
  }
3661
3777
  const uid = process.getuid?.() ?? userInfo().uid;
3662
3778
  return `/run/user/${uid}/${PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME}`;
@@ -4252,7 +4368,7 @@ async function refreshClaudeOAuthToken(input) {
4252
4368
  try {
4253
4369
  if (attempt > 0) {
4254
4370
  const delay3 = baseDelayMs * 2 ** (attempt - 1);
4255
- await new Promise((resolve4) => setTimeoutImpl(resolve4, delay3));
4371
+ await new Promise((resolve5) => setTimeoutImpl(resolve5, delay3));
4256
4372
  }
4257
4373
  const response = await fetchImpl(TOKEN_URL, {
4258
4374
  method: "POST",
@@ -4444,16 +4560,16 @@ function getOpenCodeConfigDir(env = process.env, home = homedir2()) {
4444
4560
  if (env.OPENCODE_CONFIG_DIR?.trim()) {
4445
4561
  return env.OPENCODE_CONFIG_DIR.trim();
4446
4562
  }
4447
- return join7(env.XDG_CONFIG_HOME || join7(home, ".config"), "opencode");
4563
+ return join8(env.XDG_CONFIG_HOME || join8(home, ".config"), "opencode");
4448
4564
  }
4449
4565
  function getAccountStoragePath() {
4450
- return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join7(getOpenCodeConfigDir(), ACCOUNT_FILE_NAME);
4566
+ return process.env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join8(getOpenCodeConfigDir(), ACCOUNT_FILE_NAME);
4451
4567
  }
4452
4568
  function getAccountStatePath(configPath = getAccountStoragePath()) {
4453
4569
  const explicit = process.env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim();
4454
4570
  if (explicit)
4455
4571
  return explicit;
4456
- return configPath.endsWith(ACCOUNT_FILE_NAME) ? join7(dirname6(configPath), ACCOUNT_STATE_FILE_NAME) : `${configPath}.state.json`;
4572
+ return configPath.endsWith(ACCOUNT_FILE_NAME) ? join8(dirname6(configPath), ACCOUNT_STATE_FILE_NAME) : `${configPath}.state.json`;
4457
4573
  }
4458
4574
  function createEmptyStorage() {
4459
4575
  return {
@@ -4581,7 +4697,7 @@ function getClaustrumMode(storage) {
4581
4697
  async function acquireRefreshFileLock2(options) {
4582
4698
  const accountPath = options.path ?? getAccountStoragePath();
4583
4699
  const lockPath = `${accountPath}.${options.name}.lock`;
4584
- const legacyOwnerPath = join7(lockPath, "owner.json");
4700
+ const legacyOwnerPath = join8(lockPath, "owner.json");
4585
4701
  const ownerId = randomUUID6();
4586
4702
  const now = Date.now;
4587
4703
  let renewTimer = null;
@@ -4635,12 +4751,12 @@ async function acquireRefreshFileLock2(options) {
4635
4751
  let acquired = await tryAcquire();
4636
4752
  if (!acquired) {
4637
4753
  const evictPath = `${lockPath}.evicting`;
4638
- const evictOwnerPath = join7(evictPath, "owner.json");
4754
+ const evictOwnerPath = join8(evictPath, "owner.json");
4639
4755
  const evictOwnerId = randomUUID6();
4640
4756
  const EVICT_TTL = 5000;
4641
4757
  const MAX_STEAL_ATTEMPTS = 8;
4642
4758
  async function backoff() {
4643
- await new Promise((resolve4) => setTimeout(resolve4, Math.floor(Math.random() * 4)));
4759
+ await new Promise((resolve5) => setTimeout(resolve5, Math.floor(Math.random() * 4)));
4644
4760
  }
4645
4761
  async function lockIsLive() {
4646
4762
  try {
@@ -5985,7 +6101,7 @@ import {
5985
6101
  writeFile as writeFile2
5986
6102
  } from "node:fs/promises";
5987
6103
  import { tmpdir as tmpdir5 } from "node:os";
5988
- import { join as join9, resolve as resolve4 } from "node:path";
6104
+ import { join as join10, resolve as resolve5 } from "node:path";
5989
6105
 
5990
6106
  // src/json.ts
5991
6107
  function parseJsonRedacted(text) {
@@ -6256,7 +6372,7 @@ var DUMP_USAGE_TITLE = "## Claude Dump Usage";
6256
6372
  var DUMP_USAGE = "Usage: `/claude-dump`, `/claude-dump on`, or `/claude-dump off`.";
6257
6373
  var DUMP_DIR_ENV = "OPENCODE_ANTHROPIC_AUTH_DUMP_DIR";
6258
6374
  var DUMP_MAX_BYTES_ENV = "OPENCODE_ANTHROPIC_AUTH_DUMP_MAX_BYTES";
6259
- var DEFAULT_DUMP_DIR = join9(tmpdir5(), "opencode-anthropic-auth-dumps");
6375
+ var DEFAULT_DUMP_DIR = join10(tmpdir5(), "opencode-anthropic-auth-dumps");
6260
6376
  var DEFAULT_DUMP_MAX_BYTES = 512 * 1024 * 1024;
6261
6377
  var DUMP_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
6262
6378
  var DUMP_SWEEP_NEWNESS_FLOOR_MS = 60 * 1000;
@@ -6293,7 +6409,7 @@ function getDumpMaxBytes() {
6293
6409
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_DUMP_MAX_BYTES;
6294
6410
  }
6295
6411
  function isConfiguredDumpDirectory(path2) {
6296
- return resolve4(path2) === resolve4(getDumpDirectory());
6412
+ return resolve5(path2) === resolve5(getDumpDirectory());
6297
6413
  }
6298
6414
  function isDumpArtifactFileName(name) {
6299
6415
  const stem = name.replace(DUMP_ARTIFACT_SUFFIX_PATTERN, "");
@@ -6350,7 +6466,7 @@ async function sweepDumpDirectory(options) {
6350
6466
  const dumpDirStats = await lstat4(dumpDir);
6351
6467
  if (dumpDirStats.isSymbolicLink())
6352
6468
  return emptyResult;
6353
- const protectedPaths = new Set((options.protectedPaths ?? []).map((path2) => resolve4(path2)));
6469
+ const protectedPaths = new Set((options.protectedPaths ?? []).map((path2) => resolve5(path2)));
6354
6470
  const entries = await readdir(dumpDir, { withFileTypes: true });
6355
6471
  const files = [];
6356
6472
  await Promise.all(entries.map(async (entry) => {
@@ -6359,7 +6475,7 @@ async function sweepDumpDirectory(options) {
6359
6475
  const partial = isDumpPartialFileName(entry.name);
6360
6476
  if (!partial && !isDumpArtifactFileName(entry.name))
6361
6477
  return;
6362
- const path2 = join9(dumpDir, entry.name);
6478
+ const path2 = join10(dumpDir, entry.name);
6363
6479
  try {
6364
6480
  const stats = await lstat4(path2);
6365
6481
  if (!stats.isFile() || stats.isSymbolicLink())
@@ -6388,7 +6504,7 @@ async function sweepDumpDirectory(options) {
6388
6504
  };
6389
6505
  const partials = files.filter((file) => file.partial).sort((left, right) => left.mtimeMs - right.mtimeMs || left.path.localeCompare(right.path));
6390
6506
  for (const file of partials) {
6391
- if (protectedPaths.has(resolve4(file.path)))
6507
+ if (protectedPaths.has(resolve5(file.path)))
6392
6508
  continue;
6393
6509
  if (now - file.mtimeMs < partialStaleMs)
6394
6510
  continue;
@@ -6412,7 +6528,7 @@ async function sweepDumpDirectory(options) {
6412
6528
  break;
6413
6529
  if (now - group.newestMtimeMs < minAgeMs)
6414
6530
  continue;
6415
- if (group.files.some((file) => protectedPaths.has(resolve4(file.path)))) {
6531
+ if (group.files.some((file) => protectedPaths.has(resolve5(file.path)))) {
6416
6532
  continue;
6417
6533
  }
6418
6534
  for (const file of group.files)
@@ -6564,7 +6680,7 @@ async function loadLatestDumpBody(input) {
6564
6680
  const candidates = names.map((name) => ({ name, tag: dumpBodyTagForAffinity(name, affinity) })).filter((candidate) => candidate.tag !== undefined).sort((a, b) => b.name.localeCompare(a.name));
6565
6681
  for (const candidate of candidates) {
6566
6682
  try {
6567
- const path2 = join9(dumpDir, candidate.name);
6683
+ const path2 = join10(dumpDir, candidate.name);
6568
6684
  const metadataPath = path2.replace(/\.body\.json$/, ".meta.json");
6569
6685
  if (!(await lstat4(path2)).isFile())
6570
6686
  continue;
@@ -6691,7 +6807,7 @@ async function dumpRequest(input) {
6691
6807
  const tagSegment = dumpTagSegment(input.tag);
6692
6808
  const id = `${new Date().toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(6, "0")}-${dumpFileSessionSegment(affinity, 80 - tagSegment.length)}${tagSegment}-${dumpRequestSegment(input)}`;
6693
6809
  const dumpDir = getDumpDirectory();
6694
- const prefix = join9(dumpDir, id);
6810
+ const prefix = join10(dumpDir, id);
6695
6811
  const files = {
6696
6812
  body: `${prefix}.body.json`,
6697
6813
  metadata: `${prefix}.meta.json`,
@@ -7034,7 +7150,7 @@ function classifyVaultFailure(error) {
7034
7150
  }
7035
7151
 
7036
7152
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/insula.js
7037
- import { resolve as resolve5 } from "node:path";
7153
+ import { resolve as resolve6 } from "node:path";
7038
7154
  import { storeIdentity } from "@cortexkit/claustrum-client";
7039
7155
  import { SubcClient } from "@cortexkit/subc-client";
7040
7156
 
@@ -7568,8 +7684,8 @@ class InsulaQuotaSource {
7568
7684
  }
7569
7685
  function acquireInsulaQuotaSource(transport, tokenPath) {
7570
7686
  const key = JSON.stringify([
7571
- resolve5(transport.connectionFile),
7572
- resolve5(tokenPath)
7687
+ resolve6(transport.connectionFile),
7688
+ resolve6(tokenPath)
7573
7689
  ]);
7574
7690
  let shared = sources.get(key);
7575
7691
  if (!shared) {
@@ -7595,7 +7711,7 @@ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexki
7595
7711
  // ../../node_modules/@cortexkit/common-auth/dist/logger/engine.js
7596
7712
  import { appendFileSync as appendFileSync2, chmodSync, existsSync as existsSync3, renameSync as renameSync2, statSync as statSync4 } from "node:fs";
7597
7713
  import { open as open5 } from "node:fs/promises";
7598
- import { dirname as dirname7, resolve as resolve6 } from "node:path";
7714
+ import { dirname as dirname7, resolve as resolve7 } from "node:path";
7599
7715
  var ORDER = {
7600
7716
  error: 0,
7601
7717
  warn: 1,
@@ -7653,7 +7769,7 @@ async function openWindowsFile(sink, file) {
7653
7769
  return sink.handle;
7654
7770
  }
7655
7771
  async function flushWindowsFile(sink, file, text) {
7656
- file = resolve6(file);
7772
+ file = resolve7(file);
7657
7773
  try {
7658
7774
  if (sink.file !== file)
7659
7775
  await closeWindowsFile(sink);
@@ -7929,10 +8045,10 @@ async function drainShutdown(pending, onTimeout) {
7929
8045
  try {
7930
8046
  await Promise.race([
7931
8047
  drained,
7932
- new Promise((resolve7) => {
8048
+ new Promise((resolve8) => {
7933
8049
  timer = setTimeout(() => {
7934
8050
  expired = true;
7935
- resolve7();
8051
+ resolve8();
7936
8052
  }, 2000);
7937
8053
  })
7938
8054
  ]);
@@ -8548,7 +8664,7 @@ class ClaustrumScopedCustody {
8548
8664
  }
8549
8665
 
8550
8666
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
8551
- import { resolve as resolve8 } from "node:path";
8667
+ import { resolve as resolve9 } from "node:path";
8552
8668
 
8553
8669
  // ../../node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
8554
8670
  var QUOTA_COMMIT_INTERVAL_MS = 30000;
@@ -8877,7 +8993,7 @@ function displayOrder(left, right) {
8877
8993
  return left.label < right.label ? -1 : left.label > right.label ? 1 : 0;
8878
8994
  }
8879
8995
  function quotaWindowParts(quota, options) {
8880
- const { windows, age } = scopedWindowParts(quota, options);
8996
+ const { windows, age } = scopedWindowParts(quota, options, true);
8881
8997
  const parts = windows.map(({ part }) => part);
8882
8998
  return age === undefined ? { windows: parts } : { windows: parts, age };
8883
8999
  }
@@ -8888,25 +9004,36 @@ function withShortNames(windows) {
8888
9004
  }
8889
9005
  return windows;
8890
9006
  }
8891
- function scopedWindowParts(quota, options) {
9007
+ function hasWindowReading(limit) {
9008
+ return Number.isFinite(limit.remainingPercent) && Number.isFinite(limit.checkedAt);
9009
+ }
9010
+ function scopedWindowParts(quota, options, includeUnknown = false) {
8892
9011
  if (!quota)
8893
9012
  return { windows: [] };
8894
9013
  const { now } = options;
8895
- const readings = quota.limits.filter((limit) => limit.kind === "reading" && limit.remainingPercent !== undefined).sort(displayOrder);
9014
+ const readings = quota.limits.filter((limit) => limit.kind === "reading" && (includeUnknown || hasWindowReading(limit))).sort(displayOrder);
8896
9015
  const windows = readings.map((limit) => {
8897
- const remainingPercent = clampPercent2(limit.remainingPercent ?? 0);
9016
+ const part = hasWindowReading(limit) ? {
9017
+ kind: "window",
9018
+ reading: "known",
9019
+ name: quotaWindowName(limit),
9020
+ short: "",
9021
+ figure: percentLeft(limit.remainingPercent),
9022
+ remainingPercent: clampPercent2(limit.remainingPercent),
9023
+ checkedAt: limit.checkedAt,
9024
+ ...resetDetails(limit.resetsAt, limit.checkedAt, now)
9025
+ } : {
9026
+ kind: "window",
9027
+ reading: "unknown",
9028
+ name: quotaWindowName(limit),
9029
+ short: "",
9030
+ figure: "no reading",
9031
+ resetSinceReading: false
9032
+ };
8898
9033
  return {
8899
9034
  scope: limit.scope,
8900
9035
  ...limit.windowMinutes === undefined ? {} : { windowMinutes: limit.windowMinutes },
8901
- part: {
8902
- kind: "window",
8903
- name: quotaWindowName(limit),
8904
- short: "",
8905
- figure: percentLeft(limit.remainingPercent ?? 0),
8906
- remainingPercent,
8907
- checkedAt: limit.checkedAt,
8908
- ...resetDetails(limit.resetsAt, limit.checkedAt, now)
8909
- }
9036
+ part
8910
9037
  };
8911
9038
  });
8912
9039
  const budget = quota.budget;
@@ -8918,6 +9045,7 @@ function scopedWindowParts(quota, options) {
8918
9045
  spent: budget.reached,
8919
9046
  part: {
8920
9047
  kind: "budget",
9048
+ reading: "known",
8921
9049
  name: "credits",
8922
9050
  short: "",
8923
9051
  figure,
@@ -8928,8 +9056,9 @@ function scopedWindowParts(quota, options) {
8928
9056
  });
8929
9057
  }
8930
9058
  withShortNames(windows);
8931
- if (windows.length > 0) {
8932
- const age = now - Math.min(...windows.map(({ part }) => part.checkedAt));
9059
+ const readingTimes = windows.flatMap(({ part }) => part.reading === "known" && part.checkedAt !== undefined ? [part.checkedAt] : []);
9060
+ if (readingTimes.length > 0) {
9061
+ const age = now - Math.min(...readingTimes);
8933
9062
  if (age > (options.staleAfterMs ?? QUOTA_STALE_AFTER_MS)) {
8934
9063
  return { windows, age: `checked ${shortSpan(age)} ago` };
8935
9064
  }
@@ -9029,13 +9158,13 @@ function narrowTextParts(quota, options) {
9029
9158
  function quotaTextParts(quota, options) {
9030
9159
  if (options.form === "narrow")
9031
9160
  return narrowTextParts(quota, options);
9032
- const parts = quotaWindowParts(quota, options);
9161
+ const { windows, age } = scopedWindowParts(quota, options);
9033
9162
  const full = (options.form ?? "full") === "full";
9034
- const text = parts.windows.map((part) => {
9163
+ const text = windows.map(({ part }) => {
9035
9164
  const reset = full && part.resetIn ? `, resets ${part.resetIn}` : "";
9036
9165
  return `${part.kind === "budget" ? "" : `${part.name} `}${part.figure}${reset}`;
9037
9166
  });
9038
- return parts.age === undefined ? text : [...text, parts.age];
9167
+ return age === undefined ? text : [...text, age];
9039
9168
  }
9040
9169
  function formatQuota(quota, options) {
9041
9170
  const parts = quotaTextParts(quota, options);
@@ -9094,7 +9223,7 @@ function quotaFields(publication, witness = "") {
9094
9223
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
9095
9224
  import { createHash as createHash5 } from "node:crypto";
9096
9225
  import { stat as stat6 } from "node:fs/promises";
9097
- import { resolve as resolve7 } from "node:path";
9226
+ import { resolve as resolve8 } from "node:path";
9098
9227
 
9099
9228
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
9100
9229
  function matches(entry, credentialId, accountIdentity) {
@@ -9519,16 +9648,16 @@ function applyVaultQuota(current, input) {
9519
9648
  }
9520
9649
  var pendingDiscoveries = new Map;
9521
9650
  function forgetPendingVaultDiscovery(path2) {
9522
- pendingDiscoveries.delete(resolve7(path2));
9651
+ pendingDiscoveries.delete(resolve8(path2));
9523
9652
  }
9524
9653
  function isVaultRosterLockRefusal(path2, error) {
9525
- const target = resolve7(path2);
9654
+ const target = resolve8(path2);
9526
9655
  if (error instanceof ClaustrumConsumerError)
9527
9656
  return error.kind === "roster-busy";
9528
9657
  if (error instanceof LockContentionError || error instanceof LockOwnershipError)
9529
- return resolve7(error.details.target) === target;
9658
+ return resolve8(error.details.target) === target;
9530
9659
  if (error instanceof PrivateFileError) {
9531
- const failed = resolve7(error.path);
9660
+ const failed = resolve8(error.path);
9532
9661
  return [WRITE_LOCK.name, DISCOVERY_LEASE.name].some((name) => {
9533
9662
  const lock = lockPathFor(target, name);
9534
9663
  return failed === lock || failed.startsWith(`${lock}.`);
@@ -9589,7 +9718,7 @@ async function refreshVaultRoster(options) {
9589
9718
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
9590
9719
  return persisted;
9591
9720
  }
9592
- const key = resolve7(options.path);
9721
+ const key = resolve8(options.path);
9593
9722
  const listedOver = options.listedOver;
9594
9723
  let discovered;
9595
9724
  try {
@@ -9652,7 +9781,7 @@ var writers = new Map;
9652
9781
  var logger2 = createLogger("claustrum");
9653
9782
  var COALESCE_MS = 100;
9654
9783
  function writerFor(path2, clock = quotaCommitTimer) {
9655
- const key = resolve8(path2);
9784
+ const key = resolve9(path2);
9656
9785
  let writer = writers.get(key);
9657
9786
  if (!writer) {
9658
9787
  writer = {
@@ -9716,7 +9845,7 @@ function orderedFields(pending) {
9716
9845
  return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
9717
9846
  }
9718
9847
  function pendingVaultQuota(path2, roster) {
9719
- const writer = writers.get(resolve8(path2));
9848
+ const writer = writers.get(resolve9(path2));
9720
9849
  if (writer) {
9721
9850
  for (const field of orderedFields(writer.pending)) {
9722
9851
  if (field.priorReading)
@@ -9727,7 +9856,7 @@ function pendingVaultQuota(path2, roster) {
9727
9856
  return roster;
9728
9857
  }
9729
9858
  function hasPendingVaultQuota(path2) {
9730
- return !!writers.get(resolve8(path2))?.pending.size;
9859
+ return !!writers.get(resolve9(path2))?.pending.size;
9731
9860
  }
9732
9861
  function schedule(writer, delay3) {
9733
9862
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
@@ -9792,7 +9921,7 @@ function flush2(writer) {
9792
9921
  return writer.running;
9793
9922
  }
9794
9923
  async function drainVaultQuota(path2, timeoutMs = 1000) {
9795
- const key = resolve8(path2);
9924
+ const key = resolve9(path2);
9796
9925
  const writer = writers.get(key);
9797
9926
  if (!writer)
9798
9927
  return;
@@ -9902,7 +10031,7 @@ class ClaustrumConsumer {
9902
10031
  this.#shutdown.signal,
9903
10032
  ...signal ? [signal] : []
9904
10033
  ]);
9905
- return new Promise((resolve9, reject) => {
10034
+ return new Promise((resolve10, reject) => {
9906
10035
  const cleanup = () => {
9907
10036
  combined.signal.removeEventListener("abort", abort);
9908
10037
  combined.dispose();
@@ -9917,7 +10046,7 @@ class ClaustrumConsumer {
9917
10046
  if (combined.signal.aborted)
9918
10047
  reject(combined.signal.reason);
9919
10048
  else
9920
- resolve9(value);
10049
+ resolve10(value);
9921
10050
  }, (error) => {
9922
10051
  cleanup();
9923
10052
  reject(error);
@@ -10520,7 +10649,7 @@ class ClaustrumConsumer {
10520
10649
  import { createHash as createHash6 } from "node:crypto";
10521
10650
  import { channel as channel2 } from "node:diagnostics_channel";
10522
10651
  import { readdir as readdir2, stat as stat7 } from "node:fs/promises";
10523
- import { dirname as dirname8, join as join10, resolve as resolve9 } from "node:path";
10652
+ import { dirname as dirname8, join as join11, resolve as resolve10 } from "node:path";
10524
10653
  var sharedRosters = new Map;
10525
10654
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
10526
10655
  var WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/;
@@ -10584,12 +10713,12 @@ function unreachableConnect2() {
10584
10713
  return new ClaustrumUnreachableError;
10585
10714
  }
10586
10715
  function untilAborted(pending, signal) {
10587
- return new Promise((resolve10, reject) => {
10716
+ return new Promise((resolve11, reject) => {
10588
10717
  const abort = () => reject(signal.reason);
10589
10718
  signal.addEventListener("abort", abort, { once: true });
10590
10719
  pending.then((value) => {
10591
10720
  signal.removeEventListener("abort", abort);
10592
- resolve10(value);
10721
+ resolve11(value);
10593
10722
  }, (error) => {
10594
10723
  signal.removeEventListener("abort", abort);
10595
10724
  reject(error);
@@ -10635,13 +10764,13 @@ class ClaustrumDiscoveryHub {
10635
10764
  this.#options = options;
10636
10765
  this.#logger = options.logger ?? createLogger("claustrum");
10637
10766
  this.#warnShutdown = shutdownWarning(this.#logger, this.#shutdown.signal);
10638
- this.#generationDirectory = join10(options.stateDir, "rosters", hostGeneration);
10767
+ this.#generationDirectory = join11(options.stateDir, "rosters", hostGeneration);
10639
10768
  this.#key = rosterFingerprint(options, providers);
10640
- const directory = join10(this.#generationDirectory, this.#key);
10769
+ const directory = join11(this.#generationDirectory, this.#key);
10641
10770
  for (const provider of providers)
10642
10771
  this.#members.set(provider, {
10643
10772
  provider,
10644
- path: join10(directory, `${provider}.json`),
10773
+ path: join11(directory, `${provider}.json`),
10645
10774
  closed: false
10646
10775
  });
10647
10776
  }
@@ -10716,7 +10845,7 @@ class ClaustrumDiscoveryHub {
10716
10845
  };
10717
10846
  const { consumer, hooks } = createHubMember(port, consumerOptions);
10718
10847
  entry.hooks = hooks;
10719
- const path2 = resolve9(entry.path);
10848
+ const path2 = resolve10(entry.path);
10720
10849
  const subscribers = sharedRosters.get(path2) ?? new Set;
10721
10850
  const install = (roster) => {
10722
10851
  if (entry.closed || this.#active !== true || !this.#current || !this.#live(this.#current) || !hooks.roster() || this.#collides(hooks, roster))
@@ -10747,7 +10876,7 @@ class ClaustrumDiscoveryHub {
10747
10876
  return;
10748
10877
  entry.seen = JSON.stringify(decodedVaultRoster(roster));
10749
10878
  entry.hooks?.install(roster);
10750
- for (const install of sharedRosters.get(resolve9(entry.path)) ?? []) {
10879
+ for (const install of sharedRosters.get(resolve10(entry.path)) ?? []) {
10751
10880
  if (!this.#live(generation))
10752
10881
  return;
10753
10882
  if (install !== entry.receiveRoster)
@@ -11151,17 +11280,17 @@ class ClaustrumDiscoveryHub {
11151
11280
  for (const directory of [
11152
11281
  dirname8(this.#generationDirectory),
11153
11282
  this.#generationDirectory,
11154
- join10(this.#generationDirectory, this.#key)
11283
+ join11(this.#generationDirectory, this.#key)
11155
11284
  ])
11156
11285
  await ensureClaustrumPrivateDirectory(directory, {}, "roster directory");
11157
11286
  }
11158
11287
  async#seed(entry) {
11159
11288
  const name = `${entry.provider}.json`;
11160
- const candidates = [join10(this.#generationDirectory, name)];
11289
+ const candidates = [join11(this.#generationDirectory, name)];
11161
11290
  try {
11162
11291
  for (const key of await readdir2(this.#generationDirectory))
11163
11292
  if (key !== this.#key && FINGERPRINT.test(key))
11164
- candidates.push(join10(this.#generationDirectory, key, name));
11293
+ candidates.push(join11(this.#generationDirectory, key, name));
11165
11294
  } catch {}
11166
11295
  let newest;
11167
11296
  for (const path2 of candidates) {
@@ -11401,8 +11530,8 @@ import {
11401
11530
  dirname as dirname11,
11402
11531
  extname as extname2,
11403
11532
  isAbsolute as isAbsolute3,
11404
- join as join12,
11405
- resolve as resolve10
11533
+ join as join13,
11534
+ resolve as resolve11
11406
11535
  } from "node:path";
11407
11536
  import {
11408
11537
  ClaustrumCredentialError as ClaustrumCredentialError5,
@@ -11799,13 +11928,13 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
11799
11928
  const extension = extname2(tokenPath) || ".json";
11800
11929
  const stem = basename4(tokenPath, extname2(tokenPath));
11801
11930
  return {
11802
- statePath: join12(dirname11(tokenPath), `${stem}-state${extension}`),
11931
+ statePath: join13(dirname11(tokenPath), `${stem}-state${extension}`),
11803
11932
  tokenPath
11804
11933
  };
11805
11934
  }
11806
11935
  function getHostClaustrumEnrollmentPaths(host, env = process.env, cwd = process.cwd()) {
11807
11936
  const configured = env[`${host.toUpperCase()}_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE`]?.trim();
11808
- const tokenPath = configured ? isAbsolute3(configured) ? configured : resolve10(cwd, configured) : join12(anthropicAuthStateRoot({
11937
+ const tokenPath = configured ? isAbsolute3(configured) ? configured : resolve11(cwd, configured) : join13(anthropicAuthStateRoot({
11809
11938
  xdgStateHome: env.XDG_STATE_HOME,
11810
11939
  home: homedir4(),
11811
11940
  acceptRelative: true
@@ -11954,7 +12083,7 @@ async function writeStateAtomic2(path2, state, beforeRename) {
11954
12083
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES2) {
11955
12084
  throw new Error("Claustrum enrollment state is too large");
11956
12085
  }
11957
- const temporary = join12(parent, `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
12086
+ const temporary = join13(parent, `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
11958
12087
  let descriptor;
11959
12088
  try {
11960
12089
  const nativeCreated = await createWindowsOwnerOnly(temporary, bytes);
@@ -11973,7 +12102,7 @@ async function writeStateAtomic2(path2, state, beforeRename) {
11973
12102
  }
11974
12103
  }
11975
12104
  async function writeTokenAtomic(path2, value, writeTokenFile, beforeRename) {
11976
- const staged = join12(dirname11(path2), `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
12105
+ const staged = join13(dirname11(path2), `.${basename4(path2)}.${process.pid}.${randomUUID8()}.tmp`);
11977
12106
  try {
11978
12107
  await writeTokenFile(staged, value);
11979
12108
  await beforeRename();
@@ -12357,8 +12486,8 @@ function createNativeCustody(options) {
12357
12486
  let stopped = false;
12358
12487
  let inner;
12359
12488
  let finish = () => {};
12360
- const ended = new Promise((resolve11) => {
12361
- finish = resolve11;
12489
+ const ended = new Promise((resolve12) => {
12490
+ finish = resolve12;
12362
12491
  });
12363
12492
  const failed = (error) => stopped || closed2 || error instanceof NativeCustodyError ? { kind: "stopped" } : classifyVaultFailure(error) === "unreachable" ? { kind: "transport_lost", error: new ClaustrumUnreachableError } : { kind: "ended" };
12364
12493
  Promise.resolve().then(connection).then((owned) => {
@@ -14018,8 +14147,8 @@ function createProviderErrorResponseScope(secrets, mode) {
14018
14147
  wrappedBodies: 0
14019
14148
  };
14020
14149
  let resolveSettled = () => {};
14021
- const settled = new Promise((resolve11) => {
14022
- resolveSettled = resolve11;
14150
+ const settled = new Promise((resolve12) => {
14151
+ resolveSettled = resolve12;
14023
14152
  });
14024
14153
  let retired = false;
14025
14154
  let used = false;
@@ -14877,14 +15006,14 @@ import {
14877
15006
  writeFile as writeFile4
14878
15007
  } from "node:fs/promises";
14879
15008
  import { tmpdir as tmpdir6 } from "node:os";
14880
- import { join as join20 } from "node:path";
15009
+ import { join as join21 } from "node:path";
14881
15010
 
14882
15011
  // src/holder-registry.ts
14883
15012
  import { execFile } from "node:child_process";
14884
15013
  import { randomUUID as randomUUID14 } from "node:crypto";
14885
15014
  import { readFileSync as readFileSync2 } from "node:fs";
14886
15015
  import { lstat as lstat12, mkdir as mkdir10, readFile as readFile11 } from "node:fs/promises";
14887
- import { basename as basename9, dirname as dirname17, join as join19 } from "node:path";
15016
+ import { basename as basename9, dirname as dirname17, join as join20 } from "node:path";
14888
15017
 
14889
15018
  // src/native-lock-observer.ts
14890
15019
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -14927,17 +15056,17 @@ function observeNativeLocks(acquire, observer) {
14927
15056
 
14928
15057
  // src/native-vault-paths.ts
14929
15058
  import { createHash as createHash18 } from "node:crypto";
14930
- import { basename as basename8, dirname as dirname15, join as join16 } from "node:path";
15059
+ import { basename as basename8, dirname as dirname15, join as join17 } from "node:path";
14931
15060
 
14932
15061
  // src/pool-paths.ts
14933
15062
  import { createHash as createHash17 } from "node:crypto";
14934
15063
  import { realpath as realpath3 } from "node:fs/promises";
14935
- import { basename as basename7, dirname as dirname14, join as join15, resolve as resolve11 } from "node:path";
15064
+ import { basename as basename7, dirname as dirname14, join as join16, resolve as resolve12 } from "node:path";
14936
15065
 
14937
15066
  // src/sticky-routing.ts
14938
15067
  import { createHash as createHash16, randomUUID as randomUUID12 } from "node:crypto";
14939
15068
  import { mkdir as mkdir9, readFile as readFile8, rename as rename11, rm as rm6, stat as stat9, writeFile as writeFile3 } from "node:fs/promises";
14940
- import { basename as basename6, dirname as dirname13, join as join14 } from "node:path";
15069
+ import { basename as basename6, dirname as dirname13, join as join15 } from "node:path";
14941
15070
 
14942
15071
  // src/native-vault-seed.ts
14943
15072
  import { lstat as lstat7, readFile as readFile7 } from "node:fs/promises";
@@ -15108,7 +15237,7 @@ async function acquirePoolLock(spec, defaults, env) {
15108
15237
  });
15109
15238
  }
15110
15239
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
15111
- await new Promise((resolve11) => setTimeout(resolve11, Math.min(options.retryMs + jitter, remaining)));
15240
+ await new Promise((resolve12) => setTimeout(resolve12, Math.min(options.retryMs + jitter, remaining)));
15112
15241
  }
15113
15242
  }
15114
15243
  function definedOnly(spec) {
@@ -17750,11 +17879,11 @@ class PoolQuotaWriter {
17750
17879
  const left = deadline - performance.now();
17751
17880
  if (left <= 0)
17752
17881
  throw refusal("pull", id, "lock-contention", `pool quota queue for ${id} is full (${POOL_QUOTA_QUEUE_LIMIT} readings) and the store locks stayed held`, true);
17753
- await new Promise((resolve11) => {
17882
+ await new Promise((resolve12) => {
17754
17883
  const done = () => {
17755
17884
  clearTimeout(timer);
17756
17885
  this.wake.delete(done);
17757
- resolve11();
17886
+ resolve12();
17758
17887
  };
17759
17888
  const timer = setTimeout(done, left);
17760
17889
  this.wake.add(done);
@@ -18866,7 +18995,7 @@ var nativeQuotaCodec = {
18866
18995
  import { randomUUID as randomUUID11 } from "node:crypto";
18867
18996
  import { constants as constants2 } from "node:fs";
18868
18997
  import { lstat as lstat6, mkdir as mkdir8, open as open8, rename as rename10, rm as rm5 } from "node:fs/promises";
18869
- import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute4, join as join13 } from "node:path";
18998
+ import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute4, join as join14 } from "node:path";
18870
18999
  import { types as utilTypes5 } from "node:util";
18871
19000
 
18872
19001
  // src/pool-binding.ts
@@ -19070,7 +19199,7 @@ async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry
19070
19199
  return "published";
19071
19200
  }
19072
19201
  const now = options.now ?? (() => performance.now());
19073
- const sleep = options.sleep ?? ((ms) => new Promise((resolve11) => setTimeout(resolve11, ms)));
19202
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve12) => setTimeout(resolve12, ms)));
19074
19203
  const start = now();
19075
19204
  let original;
19076
19205
  try {
@@ -19437,7 +19566,7 @@ async function writeNativeRuntimeOutcome(path2, storageId, change, hooks, firstI
19437
19566
  assertTransitions(current, next, firstIdentity);
19438
19567
  const bytes = `${JSON.stringify(next, null, 2)}
19439
19568
  `;
19440
- const stage = join13(dirname12(path2), `${basename5(path2)}.native-runtime.${randomUUID11()}.partial`);
19569
+ const stage = join14(dirname12(path2), `${basename5(path2)}.native-runtime.${randomUUID11()}.partial`);
19441
19570
  let ownsStage = false;
19442
19571
  try {
19443
19572
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
@@ -20914,7 +21043,7 @@ function stickyRetainRetryHeaders(upstream, now = Date.now()) {
20914
21043
  function getStickyRoutingStatePath(accountStoragePath) {
20915
21044
  const name = basename6(accountStoragePath);
20916
21045
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
20917
- return join14(dirname13(accountStoragePath), `${stem}-routing-state.json`);
21046
+ return join15(dirname13(accountStoragePath), `${stem}-routing-state.json`);
20918
21047
  }
20919
21048
  function stickyRetryAfterWithJitter(sessionId, retryAfterSeconds) {
20920
21049
  const hash2 = createHash16("sha256").update(sessionId).digest().readUInt32BE(0);
@@ -21015,7 +21144,7 @@ class StickySessionRouter {
21015
21144
  if (!wait || performance.now() >= deadline) {
21016
21145
  throw new Error("Timed out acquiring sticky routing state lock");
21017
21146
  }
21018
- await new Promise((resolve11) => setTimeout(resolve11, STICKY_ROUTING_LOCK_POLL_MS));
21147
+ await new Promise((resolve12) => setTimeout(resolve12, STICKY_ROUTING_LOCK_POLL_MS));
21019
21148
  }
21020
21149
  }
21021
21150
  recoverLocalPins() {
@@ -21386,7 +21515,7 @@ function resolveLocalRoutingDestination(host, paths, env) {
21386
21515
  return (host === "opencode" ? env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE : env.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE) || getStickyRoutingStatePath(paths.config);
21387
21516
  }
21388
21517
  async function canonicalPath(path2) {
21389
- const absolute = resolve11(path2);
21518
+ const absolute = resolve12(path2);
21390
21519
  try {
21391
21520
  return await realpath3(absolute);
21392
21521
  } catch (error) {
@@ -21397,10 +21526,10 @@ async function canonicalPath(path2) {
21397
21526
  const parent = dirname14(absolute);
21398
21527
  if (parent === absolute)
21399
21528
  return absolute;
21400
- return join15(await canonicalPath(parent), basename7(absolute));
21529
+ return join16(await canonicalPath(parent), basename7(absolute));
21401
21530
  }
21402
21531
  function sibling(path2, legacyName, name, suffix) {
21403
- return basename7(path2) === legacyName ? join15(dirname14(path2), name) : `${path2}.${suffix}.json`;
21532
+ return basename7(path2) === legacyName ? join16(dirname14(path2), name) : `${path2}.${suffix}.json`;
21404
21533
  }
21405
21534
  async function resolveNativePoolPaths(legacyConfig = getAccountStoragePath(), legacyState = getAccountStatePath(legacyConfig), layout) {
21406
21535
  const [sourceConfig, sourceState] = await Promise.all([
@@ -21450,7 +21579,7 @@ async function resolveNativePoolPaths(legacyConfig = getAccountStoragePath(), le
21450
21579
 
21451
21580
  // src/native-vault-paths.ts
21452
21581
  function sibling2(path2, expected, name, suffix) {
21453
- return basename8(path2) === expected ? join16(dirname15(path2), name) : path2.replace(/(?:\.json)?$/, `.${suffix}.json`);
21582
+ return basename8(path2) === expected ? join17(dirname15(path2), name) : path2.replace(/(?:\.json)?$/, `.${suffix}.json`);
21454
21583
  }
21455
21584
  function nativeVaultPaths(local, layout = stateLayoutOfPaths(local)) {
21456
21585
  const config = sibling2(local.legacyConfig, "anthropic-auth.json", "anthropic-auth-vault-settings.json", "vault-settings");
@@ -21494,7 +21623,7 @@ import { lstat as lstat11 } from "node:fs/promises";
21494
21623
 
21495
21624
  // src/state-home-serving-guard.ts
21496
21625
  import { lstat as lstat10 } from "node:fs/promises";
21497
- import { dirname as dirname16, join as join18 } from "node:path";
21626
+ import { dirname as dirname16, join as join19 } from "node:path";
21498
21627
 
21499
21628
  // src/state-layout-errors.ts
21500
21629
  var RESTORE_LEGACY_COMMAND = "npx @cortexkit/opencode-anthropic-auth setup --restore-legacy";
@@ -21687,7 +21816,7 @@ class StateLayoutLockStack {
21687
21816
  name: spec.name,
21688
21817
  timeoutMs
21689
21818
  });
21690
- await new Promise((resolve12) => setTimeout(resolve12, Math.min(remaining, POOL_LOCK_DEFAULTS.retryMs + Math.floor(Math.random() * 25))));
21819
+ await new Promise((resolve13) => setTimeout(resolve13, Math.min(remaining, POOL_LOCK_DEFAULTS.retryMs + Math.floor(Math.random() * 25))));
21691
21820
  }
21692
21821
  }
21693
21822
  async assertAll() {
@@ -21722,7 +21851,7 @@ class StateLayoutLockStack {
21722
21851
  // src/state-layout-record.ts
21723
21852
  import { randomUUID as randomUUID13 } from "node:crypto";
21724
21853
  import { lstat as lstat9, readFile as readFile10, unlink as unlink6 } from "node:fs/promises";
21725
- import { join as join17 } from "node:path";
21854
+ import { join as join18 } from "node:path";
21726
21855
  var RELOCATION_ROLES = [
21727
21856
  "localPoolState",
21728
21857
  "journal",
@@ -21901,7 +22030,7 @@ function parseRestore(value, phase) {
21901
22030
  };
21902
22031
  }
21903
22032
  function layoutRecordPath(sub) {
21904
- return join17(sub, STATE_HOME_FILE_NAMES.layoutMarker);
22033
+ return join18(sub, STATE_HOME_FILE_NAMES.layoutMarker);
21905
22034
  }
21906
22035
  function movingJournalPath(journal, attempt) {
21907
22036
  return `${journal}.moving-${attempt}`;
@@ -21959,11 +22088,11 @@ function stateHomeServingFiles(paths) {
21959
22088
  const oldDir = dirname16(paths.legacyState);
21960
22089
  return {
21961
22090
  sub: dirname16(paths.runtime),
21962
- oldPoolState: join18(oldDir, STATE_HOME_FILE_NAMES.localPoolState),
22091
+ oldPoolState: join19(oldDir, STATE_HOME_FILE_NAMES.localPoolState),
21963
22092
  newPoolState: paths.state,
21964
- oldJournal: join18(oldDir, STATE_HOME_FILE_NAMES.journal),
22093
+ oldJournal: join19(oldDir, STATE_HOME_FILE_NAMES.journal),
21965
22094
  newJournal: paths.journal,
21966
- oldMetadata: METADATA_ROLES.map((role) => join18(oldDir, STATE_HOME_FILE_NAMES[role]))
22095
+ oldMetadata: METADATA_ROLES.map((role) => join19(oldDir, STATE_HOME_FILE_NAMES[role]))
21967
22096
  };
21968
22097
  }
21969
22098
  var METADATA_ROLES = [
@@ -22088,14 +22217,14 @@ function guardIoFailure(sub, error) {
22088
22217
  return error instanceof StateLayoutRefusalError ? error : stateLayoutIoFailure(`check the state of ${sub}`, [sub], error);
22089
22218
  }
22090
22219
  function markerRefusal(sub, cause) {
22091
- const path2 = join18(sub, STATE_HOME_FILE_NAMES.layoutMarker);
22220
+ const path2 = join19(sub, STATE_HOME_FILE_NAMES.layoutMarker);
22092
22221
  return new StateLayoutRefusalError("marker-unreadable", `anthropic-auth can't read ${path2}, which records where its state is, so it stopped using that state. Restore the file from a backup or ask for help; do not delete the state folder.`, [path2], cause);
22093
22222
  }
22094
22223
  var reported = new Set;
22095
22224
  var observations = new Map;
22096
22225
  var probe;
22097
22226
  function createStateHomeServingGuard(files) {
22098
- const marker = join18(files.sub, STATE_HOME_FILE_NAMES.layoutMarker);
22227
+ const marker = join19(files.sub, STATE_HOME_FILE_NAMES.layoutMarker);
22099
22228
  const dataset = JSON.stringify(files);
22100
22229
  function report(refusal2) {
22101
22230
  if (refusal2 && !reported.has(refusal2.message)) {
@@ -22355,10 +22484,10 @@ async function linuxIncarnation(pid) {
22355
22484
  }
22356
22485
  }
22357
22486
  function macosIncarnation(pid) {
22358
- return new Promise((resolve12) => {
22487
+ return new Promise((resolve13) => {
22359
22488
  execFile("ps", ["-o", "lstart=", "-p", String(pid)], { env: { ...process.env, TZ: "UTC0" }, timeout: 5000 }, (error, stdout) => {
22360
22489
  const text5 = String(stdout ?? "").trim();
22361
- resolve12(error || !text5 ? null : text5);
22490
+ resolve13(error || !text5 ? null : text5);
22362
22491
  });
22363
22492
  });
22364
22493
  }
@@ -22442,7 +22571,7 @@ async function anyExists(paths) {
22442
22571
  return false;
22443
22572
  }
22444
22573
  async function isManagedDirectory(dir) {
22445
- return await exists2(join19(dir, STATE_HOME_FILE_NAMES.configDirMarker)) || await exists2(join19(dir, STATE_HOME_FILE_NAMES.layoutMarker));
22574
+ return await exists2(join20(dir, STATE_HOME_FILE_NAMES.configDirMarker)) || await exists2(join20(dir, STATE_HOME_FILE_NAMES.layoutMarker));
22446
22575
  }
22447
22576
  async function assertUnmanagedInjectedPaths(paths) {
22448
22577
  if (stateLayoutOfPaths(paths).kind === "state-home")
@@ -22561,7 +22690,7 @@ async function buildEntry(options) {
22561
22690
  async function registerNativePoolHolder(options) {
22562
22691
  const entry2 = await buildEntry(options);
22563
22692
  const dirs = [...new Set(entry2.files.map((file) => dirname17(file)))].sort();
22564
- const holderFiles = dirs.map((dir) => join19(dir, HOLDER_FILE_NAME));
22693
+ const holderFiles = dirs.map((dir) => join20(dir, HOLDER_FILE_NAME));
22565
22694
  const done = {
22566
22695
  status: "registered",
22567
22696
  settled: Promise.resolve(),
@@ -22599,7 +22728,7 @@ function warnRegistrationFailure(dir, error) {
22599
22728
  }
22600
22729
  function registrationAttempt(options, entry2, mandatory) {
22601
22730
  const dirs = [...new Set(entry2.files.map((file) => dirname17(file)))].sort();
22602
- const holderFiles = dirs.map((dir) => join19(dir, HOLDER_FILE_NAME));
22731
+ const holderFiles = dirs.map((dir) => join20(dir, HOLDER_FILE_NAME));
22603
22732
  return async () => {
22604
22733
  let complete = true;
22605
22734
  for (const holderFile of holderFiles) {
@@ -22628,8 +22757,8 @@ function retryInBackground(attempt, options) {
22628
22757
  let timer;
22629
22758
  let closed2 = false;
22630
22759
  let settle = () => {};
22631
- const settled = new Promise((resolve12) => {
22632
- settle = resolve12;
22760
+ const settled = new Promise((resolve13) => {
22761
+ settle = resolve13;
22633
22762
  });
22634
22763
  const schedule2 = () => {
22635
22764
  if (closed2)
@@ -22698,7 +22827,7 @@ function isExpiredRecord(record8, now, leaseMs) {
22698
22827
  return record8.updatedAt <= now && now - record8.updatedAt > leaseMs;
22699
22828
  }
22700
22829
  function getDefaultCacheKeepRegistryDirectory(scope) {
22701
- return join20(tmpdir6(), "opencode-anthropic-auth", "cachekeep-sessions", scope);
22830
+ return join21(tmpdir6(), "opencode-anthropic-auth", "cachekeep-sessions", scope);
22702
22831
  }
22703
22832
 
22704
22833
  class CacheKeepSessionRegistry {
@@ -22709,7 +22838,7 @@ class CacheKeepSessionRegistry {
22709
22838
  constructor(options) {
22710
22839
  this.options = options;
22711
22840
  const instanceId = options.instanceId ?? `${process.pid}-${randomUUID15()}`;
22712
- this.filePath = join20(options.directory, `${instanceId}.json`);
22841
+ this.filePath = join21(options.directory, `${instanceId}.json`);
22713
22842
  }
22714
22843
  publish(sessions) {
22715
22844
  const snapshot = sessions.map((session) => ({ ...session }));
@@ -22750,7 +22879,7 @@ class CacheKeepSessionRegistry {
22750
22879
  }
22751
22880
  const records = await Promise.all(names.map(async (name) => {
22752
22881
  try {
22753
- const raw = await readFile12(join20(this.options.directory, name), "utf8");
22882
+ const raw = await readFile12(join21(this.options.directory, name), "utf8");
22754
22883
  return normalizeRecord(JSON.parse(raw));
22755
22884
  } catch {
22756
22885
  return;
@@ -22792,7 +22921,7 @@ class CacheKeepSessionRegistry {
22792
22921
  return;
22793
22922
  }
22794
22923
  await Promise.all(names.map(async (name) => {
22795
- const recordPath = join20(this.options.directory, name);
22924
+ const recordPath = join21(this.options.directory, name);
22796
22925
  if (recordPath === this.filePath)
22797
22926
  return;
22798
22927
  let initialRecord;
@@ -24272,13 +24401,13 @@ function logCommittedNativeAccountAdded(account) {
24272
24401
  }
24273
24402
 
24274
24403
  // src/native-vault-invalidation.ts
24275
- import { resolve as resolve12 } from "node:path";
24404
+ import { resolve as resolve13 } from "node:path";
24276
24405
  var holders = new Set;
24277
24406
  function watchNativeVaultAuthority(holder) {
24278
24407
  const held = {
24279
24408
  ...holder,
24280
- roster: resolve12(holder.roster),
24281
- tokenPath: resolve12(holder.tokenPath)
24409
+ roster: resolve13(holder.roster),
24410
+ tokenPath: resolve13(holder.tokenPath)
24282
24411
  };
24283
24412
  holders.add(held);
24284
24413
  return () => {
@@ -24287,12 +24416,12 @@ function watchNativeVaultAuthority(holder) {
24287
24416
  }
24288
24417
  function retainNativeVaultRoster(path2, roster) {
24289
24418
  for (const holder of holders)
24290
- if (holder.roster === resolve12(path2))
24419
+ if (holder.roster === resolve13(path2))
24291
24420
  holder.retain(roster);
24292
24421
  }
24293
24422
  function closeNativeVaultAuthority(tokenPath) {
24294
24423
  for (const holder of holders)
24295
- if (holder.tokenPath === resolve12(tokenPath))
24424
+ if (holder.tokenPath === resolve13(tokenPath))
24296
24425
  holder.close();
24297
24426
  }
24298
24427
 
@@ -24601,12 +24730,12 @@ async function joinNativePoolWrite(paths, signals, check, onLockEvent) {
24601
24730
  function pause(ms, signals) {
24602
24731
  if (signals.some((signal) => signal.aborted))
24603
24732
  return Promise.resolve();
24604
- return new Promise((resolve13) => {
24733
+ return new Promise((resolve14) => {
24605
24734
  const wake = () => {
24606
24735
  clearTimeout(timer);
24607
24736
  for (const signal of signals)
24608
24737
  signal.removeEventListener("abort", wake);
24609
- resolve13();
24738
+ resolve14();
24610
24739
  };
24611
24740
  const timer = setTimeout(wake, ms);
24612
24741
  for (const signal of signals)
@@ -24862,7 +24991,7 @@ function createNativeRefreshCoordinator(options) {
24862
24991
  name: spec.name,
24863
24992
  timeoutMs: POOL_LOCK_DEFAULTS.timeoutMs
24864
24993
  });
24865
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(POOL_LOCK_DEFAULTS.retryMs, remaining)));
24994
+ await new Promise((resolve14) => setTimeout(resolve14, Math.min(POOL_LOCK_DEFAULTS.retryMs, remaining)));
24866
24995
  }
24867
24996
  }
24868
24997
  async function run(job, request) {
@@ -26257,7 +26386,7 @@ function createPublisher() {
26257
26386
  const batch = { patch, result: Promise.resolve(false) };
26258
26387
  pending.set(key, batch);
26259
26388
  batch.result = run(async () => {
26260
- await new Promise((resolve13) => setTimeout(resolve13, 0));
26389
+ await new Promise((resolve14) => setTimeout(resolve14, 0));
26261
26390
  pending.delete(key);
26262
26391
  return write(batch.patch);
26263
26392
  });
@@ -26379,7 +26508,7 @@ function createNativeUsagePublisher(channel3) {
26379
26508
  return {
26380
26509
  observe: observe2,
26381
26510
  publish(write) {
26382
- observe2(new Promise((resolve13) => setTimeout(resolve13, 0)).then(write));
26511
+ observe2(new Promise((resolve14) => setTimeout(resolve14, 0)).then(write));
26383
26512
  },
26384
26513
  async drain() {
26385
26514
  while (pending.size)
@@ -26466,7 +26595,7 @@ class NativeQuotaObservations extends Map {
26466
26595
  }
26467
26596
 
26468
26597
  // src/native-runtime-registry.ts
26469
- import { resolve as resolve13 } from "node:path";
26598
+ import { resolve as resolve14 } from "node:path";
26470
26599
  var identities = new WeakMap;
26471
26600
  var nextIdentity = 0;
26472
26601
  function nativeRuntimeOptionIdentity(value) {
@@ -26495,14 +26624,14 @@ function nativeRuntimeStorageKey(options) {
26495
26624
  "runtime",
26496
26625
  "journal",
26497
26626
  "roster"
26498
- ].map((field) => resolve13(paths[field])),
26499
- resolve13(enrollment.tokenPath),
26500
- resolve13(enrollment.statePath),
26501
- resolve13(connection)
26627
+ ].map((field) => resolve14(paths[field])),
26628
+ resolve14(enrollment.tokenPath),
26629
+ resolve14(enrollment.statePath),
26630
+ resolve14(connection)
26502
26631
  ]);
26503
26632
  }
26504
26633
  function nativeRuntimeConnectionFile(host, env) {
26505
- return resolve13(resolveClaustrumConnectionPath(host === "pi" ? env.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE : undefined, host === "pi" ? {
26634
+ return resolve14(resolveClaustrumConnectionPath(host === "pi" ? env.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE : undefined, host === "pi" ? {
26506
26635
  ...env,
26507
26636
  OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE: undefined
26508
26637
  } : env));
@@ -26977,8 +27106,8 @@ function validateNativeVaultRosterSeed(existing, input) {
26977
27106
  // src/quota-manager.ts
26978
27107
  var nativeSetTimeout = globalThis.setTimeout;
26979
27108
  function pauseOnRealTimer(ms) {
26980
- return new Promise((resolve14) => {
26981
- const id2 = nativeSetTimeout(resolve14, ms);
27109
+ return new Promise((resolve15) => {
27110
+ const id2 = nativeSetTimeout(resolve15, ms);
26982
27111
  if (typeof id2 === "object" && "unref" in id2)
26983
27112
  id2.unref();
26984
27113
  });
@@ -28582,7 +28711,7 @@ function recencyOnly(patch) {
28582
28711
  return keys4.length === 1 && keys4[0] === "lastUsed" && typeof patch.lastUsed === "number";
28583
28712
  }
28584
28713
  function waitFor(pending, signal) {
28585
- return new Promise((resolve14, reject) => {
28714
+ return new Promise((resolve15, reject) => {
28586
28715
  const abort = () => {
28587
28716
  cleanup2();
28588
28717
  reject(signal.reason);
@@ -28591,7 +28720,7 @@ function waitFor(pending, signal) {
28591
28720
  signal.addEventListener("abort", abort, { once: true });
28592
28721
  pending.then((value) => {
28593
28722
  cleanup2();
28594
- signal.aborted ? reject(signal.reason) : resolve14(value);
28723
+ signal.aborted ? reject(signal.reason) : resolve15(value);
28595
28724
  }, (error) => {
28596
28725
  cleanup2();
28597
28726
  reject(error);
@@ -29202,7 +29331,7 @@ class PersistentRelaySession {
29202
29331
  return;
29203
29332
  if (this.connecting)
29204
29333
  return await this.connecting;
29205
- this.connecting = new Promise((resolve14, reject) => {
29334
+ this.connecting = new Promise((resolve15, reject) => {
29206
29335
  const url = toWebSocketUrl(this.config.url, this.config.token);
29207
29336
  const parsed = new URL(url);
29208
29337
  parsed.searchParams.set("affinity", this.affinity);
@@ -29224,7 +29353,7 @@ class PersistentRelaySession {
29224
29353
  if (message.type === "ready") {
29225
29354
  this.timers.clearTimeout(timeout);
29226
29355
  this.serverState = message.state;
29227
- resolve14();
29356
+ resolve15();
29228
29357
  return;
29229
29358
  }
29230
29359
  this.handleMessage(message);
@@ -29276,15 +29405,15 @@ class PersistentRelaySession {
29276
29405
  const sentAt = perfNowMs();
29277
29406
  let resolveDone;
29278
29407
  let rejectDone;
29279
- const done = new Promise((resolve14, reject) => {
29280
- resolveDone = resolve14;
29408
+ const done = new Promise((resolve15, reject) => {
29409
+ resolveDone = resolve15;
29281
29410
  rejectDone = reject;
29282
29411
  });
29283
- const response = new Promise((resolve14, reject) => {
29412
+ const response = new Promise((resolve15, reject) => {
29284
29413
  const pending = {
29285
29414
  payload,
29286
29415
  bodyText,
29287
- resolve: resolve14,
29416
+ resolve: resolve15,
29288
29417
  reject,
29289
29418
  streamDone: false,
29290
29419
  accepted: false,
@@ -30697,7 +30826,7 @@ function createNativeAccountRuntime(options) {
30697
30826
  const { mode, paths: paths2, store: store2 } = await selectedStorage();
30698
30827
  for (let attempt = 0;attempt < 4; attempt++) {
30699
30828
  if (attempt)
30700
- await new Promise((resolve14) => setTimeout(resolve14, 10));
30829
+ await new Promise((resolve15) => setTimeout(resolve15, 10));
30701
30830
  const settings = await store2.readSettings();
30702
30831
  if (settings.status !== "ready")
30703
30832
  throw new NativeRuntimeError("publication-refused");
@@ -31429,7 +31558,7 @@ function relayGeneration(input) {
31429
31558
  // src/native-host-auth-write.ts
31430
31559
  import { randomUUID as randomUUID18 } from "node:crypto";
31431
31560
  import { lstat as lstat14, open as open11, rename as rename13, unlink as unlink7 } from "node:fs/promises";
31432
- import { dirname as dirname18, isAbsolute as isAbsolute6, join as join21 } from "node:path";
31561
+ import { dirname as dirname18, isAbsolute as isAbsolute6, join as join22 } from "node:path";
31433
31562
  class NativeHostAuthWriteError extends Error {
31434
31563
  code;
31435
31564
  effect;
@@ -31490,7 +31619,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
31490
31619
  const removingFile = host === "pi" && Object.keys(next).length === 0;
31491
31620
  const outcome = Object.freeze(host === "pi" ? { status: "removed", file: removingFile ? "unlinked" : "replaced" } : { status: snapshot.data === undefined ? "created" : "replaced" });
31492
31621
  if (!removingFile) {
31493
- stage = join21(dirname18(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
31622
+ stage = join22(dirname18(authPath), `.native-host-auth-write.${randomUUID18()}.tmp`);
31494
31623
  const bytes = `${JSON.stringify(next, null, 2)}
31495
31624
  `;
31496
31625
  const nativeCreated = await createWindowsOwnerOnly(stage, bytes);
@@ -33030,8 +33159,8 @@ async function runNativeCustodyActivation(options, hooks = {}) {
33030
33159
  }
33031
33160
  async function commitMode(paths, routingPath, plan, context) {
33032
33161
  let openGate = () => {};
33033
- const gate = new Promise((resolve14) => {
33034
- openGate = resolve14;
33162
+ const gate = new Promise((resolve15) => {
33163
+ openGate = resolve15;
33035
33164
  });
33036
33165
  let leases;
33037
33166
  let scope;
@@ -34733,11 +34862,11 @@ async function refreshForRequest(runtime2, ready) {
34733
34862
  break;
34734
34863
  if (combined.aborted)
34735
34864
  break;
34736
- await new Promise((resolve14) => {
34865
+ await new Promise((resolve15) => {
34737
34866
  const finish = () => {
34738
34867
  clearTimeout(pause2);
34739
34868
  combined.removeEventListener("abort", finish);
34740
- resolve14();
34869
+ resolve15();
34741
34870
  };
34742
34871
  const pause2 = setTimeout(finish, 25);
34743
34872
  combined.addEventListener("abort", finish, { once: true });
@@ -34753,16 +34882,16 @@ async function refreshForRequest(runtime2, ready) {
34753
34882
  function waitForRequest(pending, signal) {
34754
34883
  if (!signal)
34755
34884
  return pending;
34756
- return new Promise((resolve14, reject) => {
34885
+ return new Promise((resolve15, reject) => {
34757
34886
  const abort = () => reject(signal.reason);
34758
34887
  signal.addEventListener("abort", abort, { once: true });
34759
- pending.then(resolve14, reject).finally(() => signal.removeEventListener("abort", abort));
34888
+ pending.then(resolve15, reject).finally(() => signal.removeEventListener("abort", abort));
34760
34889
  if (signal.aborted)
34761
34890
  abort();
34762
34891
  });
34763
34892
  }
34764
34893
  // src/native-vault-connection.ts
34765
- import { dirname as dirname21, join as join22, resolve as resolve15 } from "node:path";
34894
+ import { dirname as dirname21, join as join23, resolve as resolve16 } from "node:path";
34766
34895
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
34767
34896
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
34768
34897
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -34776,7 +34905,7 @@ var MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
34776
34905
  import { createHash as createHash24 } from "node:crypto";
34777
34906
  import { constants as constants4 } from "node:fs";
34778
34907
  import { lstat as lstat16, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
34779
- import { dirname as dirname20, resolve as resolve14 } from "node:path";
34908
+ import { dirname as dirname20, resolve as resolve15 } from "node:path";
34780
34909
  import { setTimeout as sleep } from "node:timers/promises";
34781
34910
 
34782
34911
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
@@ -35179,8 +35308,8 @@ function createPiSlot(options, onStep, hooks) {
35179
35308
  if (!provider || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
35180
35309
  throw new PiSlotError("invalid-options");
35181
35310
  }
35182
- const authPath = resolve14(options.authPath);
35183
- const stashPath = resolve14(options.stashPath);
35311
+ const authPath = resolve15(options.authPath);
35312
+ const stashPath = resolve15(options.stashPath);
35184
35313
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
35185
35314
  throw new PiSlotError("invalid-options");
35186
35315
  }
@@ -35318,8 +35447,8 @@ function createPiSlot(options, onStep, hooks) {
35318
35447
  // src/native-vault-connection.ts
35319
35448
  function nativePiAuthSlotPaths(options) {
35320
35449
  return {
35321
- authPath: resolve15(options.authPath),
35322
- stashPath: join22(dirname21(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
35450
+ authPath: resolve16(options.authPath),
35451
+ stashPath: join23(dirname21(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
35323
35452
  provider: "anthropic",
35324
35453
  placeholderKey: placeholderSecret("anthropic")
35325
35454
  };
@@ -35446,7 +35575,7 @@ import { createHash as createHash25 } from "node:crypto";
35446
35575
  import { realpathSync as realpathSync3 } from "node:fs";
35447
35576
  import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat11, writeFile as writeFile5 } from "node:fs/promises";
35448
35577
  import { tmpdir as tmpdir7 } from "node:os";
35449
- import { join as join23, resolve as resolve16 } from "node:path";
35578
+ import { join as join24, resolve as resolve17 } from "node:path";
35450
35579
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
35451
35580
  var PRIME_TICK_MS = 60000;
35452
35581
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -35634,10 +35763,10 @@ function buildPrimeRequestBody() {
35634
35763
  return JSON.parse(JSON.stringify(PRIME_REQUEST_BODY));
35635
35764
  }
35636
35765
  function defaultMarkerDir() {
35637
- return join23(tmpdir7(), "opencode-anthropic-auth", "prime");
35766
+ return join24(tmpdir7(), "opencode-anthropic-auth", "prime");
35638
35767
  }
35639
35768
  function primeStorageFingerprint(storagePath) {
35640
- const absolutePath = resolve16(storagePath);
35769
+ const absolutePath = resolve17(storagePath);
35641
35770
  let canonicalPath2;
35642
35771
  try {
35643
35772
  canonicalPath2 = realpathSync3(absolutePath);
@@ -35649,19 +35778,19 @@ function primeStorageFingerprint(storagePath) {
35649
35778
  return createHash25("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
35650
35779
  }
35651
35780
  function primeMarkerNamespaceDir(markerDir, storagePath) {
35652
- return join23(markerDir, primeStorageFingerprint(storagePath));
35781
+ return join24(markerDir, primeStorageFingerprint(storagePath));
35653
35782
  }
35654
35783
  function primeAccountMarkerDir(markerDir, storagePath, accountFingerprint) {
35655
35784
  if (!/^[a-f0-9]{12,}$/i.test(accountFingerprint)) {
35656
35785
  throw new Error("Prime account fingerprint must be a hexadecimal digest");
35657
35786
  }
35658
- return join23(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
35787
+ return join24(primeMarkerNamespaceDir(markerDir, storagePath), accountFingerprint.toLowerCase().slice(0, 12));
35659
35788
  }
35660
35789
  function primeMarkerPath(markerDir, accountId2, resetsAtEpochMs) {
35661
- return join23(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
35790
+ return join24(markerDir, `${encodeURIComponent(accountId2)}-${resetsAtEpochMs}`);
35662
35791
  }
35663
35792
  function primeBootstrapMarkerPath(markerDir, accountId2) {
35664
- return join23(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
35793
+ return join24(markerDir, `${encodeURIComponent(accountId2)}-bootstrap`);
35665
35794
  }
35666
35795
  function primeAccountLabel(id2, fallback) {
35667
35796
  if (id2 === "main")
@@ -36103,7 +36232,7 @@ class PrimeManager {
36103
36232
  let swept = 0;
36104
36233
  for (const entry2 of entries) {
36105
36234
  try {
36106
- const path2 = join23(dir, entry2);
36235
+ const path2 = join24(dir, entry2);
36107
36236
  const s = await stat11(path2);
36108
36237
  if (s.isDirectory()) {
36109
36238
  swept += await this.sweepMarkerDirectory(path2, now);
@@ -36138,11 +36267,11 @@ import {
36138
36267
  writeFile as writeFile6
36139
36268
  } from "node:fs/promises";
36140
36269
  import { tmpdir as tmpdir8 } from "node:os";
36141
- import { join as join24 } from "node:path";
36270
+ import { join as join25 } from "node:path";
36142
36271
  var QUOTA_HEADER_FEED_SCHEMA_VERSION = 3;
36143
36272
  var QUOTA_HEADER_FEED_LEASE_MS = 180000;
36144
36273
  function getDefaultQuotaHeaderFeedDirectory() {
36145
- return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join24(tmpdir8(), "opencode-anthropic-auth", "quota-header-feed");
36274
+ return process.env.OPENCODE_ANTHROPIC_AUTH_QUOTA_FEED_DIR ?? join25(tmpdir8(), "opencode-anthropic-auth", "quota-header-feed");
36146
36275
  }
36147
36276
  function configuredAnthropicOAuthAccountCount(input) {
36148
36277
  const fallbackCount = input.storage?.accounts.filter(isOAuthAccount).length ?? 0;
@@ -36301,7 +36430,7 @@ class QuotaHeaderFeedRegistry {
36301
36430
  constructor(options = {}) {
36302
36431
  this.options = options;
36303
36432
  const instanceId = options.instanceId ?? `${process.pid}-${randomUUID19()}`;
36304
- this.filePath = join24(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
36433
+ this.filePath = join25(options.directory ?? getDefaultQuotaHeaderFeedDirectory(), `${instanceId}.json`);
36305
36434
  }
36306
36435
  publish(entry2) {
36307
36436
  const { accountKey, quota: quota2 } = entry2;
@@ -36362,7 +36491,7 @@ class QuotaHeaderFeedRegistry {
36362
36491
  return;
36363
36492
  }
36364
36493
  await Promise.all(names2.filter((name) => /^\d+-[0-9a-f-]+\.json$/i.test(name)).map(async (name) => {
36365
- const path2 = join24(directory, name);
36494
+ const path2 = join25(directory, name);
36366
36495
  if (path2 === this.filePath)
36367
36496
  return;
36368
36497
  try {
@@ -36391,7 +36520,7 @@ class QuotaHeaderFeedRegistry {
36391
36520
  const newest = new Map;
36392
36521
  await Promise.all(names2.map(async (name) => {
36393
36522
  try {
36394
- const record9 = JSON.parse(await readFile13(join24(directory, name), "utf8"));
36523
+ const record9 = JSON.parse(await readFile13(join25(directory, name), "utf8"));
36395
36524
  if (record9.version !== QUOTA_HEADER_FEED_SCHEMA_VERSION || !record9.entries || typeof record9.entries !== "object")
36396
36525
  return;
36397
36526
  for (const [accountKey, candidate] of Object.entries(record9.entries)) {
@@ -36572,7 +36701,7 @@ function buildClaudeQuotaSummary(input) {
36572
36701
  }
36573
36702
  // src/request-gzip.ts
36574
36703
  import { mkdir as mkdir17, readFile as readFile14, rename as rename15, rm as rm10, writeFile as writeFile7 } from "node:fs/promises";
36575
- import { basename as basename10, dirname as dirname22, join as join25 } from "node:path";
36704
+ import { basename as basename10, dirname as dirname22, join as join26 } from "node:path";
36576
36705
  import { promisify } from "node:util";
36577
36706
  import { gzip } from "node:zlib";
36578
36707
  var gzipAsync = promisify(gzip);
@@ -36718,7 +36847,7 @@ function getRequestGzipLatch(path2) {
36718
36847
  function getRequestGzipLatchPath(accountStoragePath) {
36719
36848
  const name = basename10(accountStoragePath);
36720
36849
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
36721
- return join25(dirname22(accountStoragePath), `${stem}-request-gzip.json`);
36850
+ return join26(dirname22(accountStoragePath), `${stem}-request-gzip.json`);
36722
36851
  }
36723
36852
  async function decideRequestGzip(options) {
36724
36853
  if (!CLAUDE_CODE_GZIPS_REQUEST_BODIES)
@@ -37035,12 +37164,12 @@ function executeLaneStartCommand(input) {
37035
37164
  // src/state-layout-decision.ts
37036
37165
  import { mkdir as mkdir18, readdir as readdir8 } from "node:fs/promises";
37037
37166
  import { homedir as homedir7 } from "node:os";
37038
- import { basename as basename13, dirname as dirname24, join as join29 } from "node:path";
37167
+ import { basename as basename13, dirname as dirname24, join as join30 } from "node:path";
37039
37168
 
37040
37169
  // src/layout-fence.ts
37041
37170
  import { readdir as readdir6, readFile as readFile15 } from "node:fs/promises";
37042
37171
  import { homedir as homedir5 } from "node:os";
37043
- import { basename as basename11, join as join26, resolve as resolve17 } from "node:path";
37172
+ import { basename as basename11, join as join27, resolve as resolve18 } from "node:path";
37044
37173
  var STATE_PATH_OVERRIDE_VARIABLES = [
37045
37174
  "OPENCODE_ANTHROPIC_AUTH_FILE",
37046
37175
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -37076,7 +37205,7 @@ async function holderFenceBlockers(input) {
37076
37205
  const files = new Set(input.files);
37077
37206
  const blockers = [];
37078
37207
  for (const dir of [...new Set(input.directories)].sort()) {
37079
- const holderFile = join26(dir, HOLDER_FILE_NAME);
37208
+ const holderFile = join27(dir, HOLDER_FILE_NAME);
37080
37209
  let contents;
37081
37210
  try {
37082
37211
  contents = await readHolderFile(holderFile);
@@ -37126,8 +37255,8 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir5()) {
37126
37255
  });
37127
37256
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
37128
37257
  return {
37129
- rpcRoots: [join26(root, "rpc")],
37130
- rpcDirs: rpcOverride ? [resolve17(rpcOverride)] : [],
37258
+ rpcRoots: [join27(root, "rpc")],
37259
+ rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
37131
37260
  cacheKeepDirs: [
37132
37261
  ...new Set([
37133
37262
  getDefaultCacheKeepRegistryDirectory("opencode"),
@@ -37176,12 +37305,12 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
37176
37305
  const portDirs = [...locations.rpcDirs];
37177
37306
  for (const root of locations.rpcRoots)
37178
37307
  for (const name of await listDir(root, blockers))
37179
- portDirs.push(join26(root, name));
37308
+ portDirs.push(join27(root, name));
37180
37309
  for (const dir of [...new Set(portDirs)]) {
37181
37310
  for (const name of await listDir(dir, blockers)) {
37182
37311
  if (!/^port-\d+\.json$/.test(name))
37183
37312
  continue;
37184
- const path2 = join26(dir, name);
37313
+ const path2 = join27(dir, name);
37185
37314
  const value = await readArtifact(path2, blockers);
37186
37315
  if (value === undefined || stamped(value))
37187
37316
  continue;
@@ -37199,7 +37328,7 @@ async function preNArtifactBlockers(locations, pidAlive2 = defaultLiveness2.pidA
37199
37328
  const match = /^(\d+)-.+\.json$/.exec(name);
37200
37329
  if (!match)
37201
37330
  continue;
37202
- const path2 = join26(dir, name);
37331
+ const path2 = join27(dir, name);
37203
37332
  const value = await readArtifact(path2, blockers);
37204
37333
  if (value === undefined || stamped(value))
37205
37334
  continue;
@@ -37228,13 +37357,13 @@ function describeFenceBlocker(blocker) {
37228
37357
  // src/state-layout-move.ts
37229
37358
  import { randomUUID as randomUUID20 } from "node:crypto";
37230
37359
  import { lstat as lstat18, readdir as readdir7, readFile as readFile16, stat as stat13, unlink as unlink10 } from "node:fs/promises";
37231
- import { basename as basename12, dirname as dirname23, join as join27, sep as sep2 } from "node:path";
37360
+ import { basename as basename12, dirname as dirname23, join as join28, sep as sep2 } from "node:path";
37232
37361
  var ACCOUNT_FILE = "anthropic-auth.json";
37233
37362
  var ACCOUNT_STATE_FILE = "anthropic-auth-state.json";
37234
37363
  var LAYOUT_LOCK_NAME = "runtime-layout";
37235
37364
  var LAYOUT_LOCK_TIMEOUT_MS = 120000;
37236
37365
  async function resolveLegacyDatasetFiles(configDir) {
37237
- const oldPaths = await resolveNativePoolPaths(join27(configDir, ACCOUNT_FILE), join27(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
37366
+ const oldPaths = await resolveNativePoolPaths(join28(configDir, ACCOUNT_FILE), join28(configDir, ACCOUNT_STATE_FILE), { kind: "legacy" });
37238
37367
  return {
37239
37368
  oldDir: await canonicalPath(configDir),
37240
37369
  oldPaths,
@@ -37242,8 +37371,8 @@ async function resolveLegacyDatasetFiles(configDir) {
37242
37371
  };
37243
37372
  }
37244
37373
  async function resolveRelocationDataset(input) {
37245
- const legacyConfig = join27(input.configDir, ACCOUNT_FILE);
37246
- const legacyState = join27(input.configDir, ACCOUNT_STATE_FILE);
37374
+ const legacyConfig = join28(input.configDir, ACCOUNT_FILE);
37375
+ const legacyState = join28(input.configDir, ACCOUNT_STATE_FILE);
37247
37376
  const { oldDir, oldPaths, oldVault } = await resolveLegacyDatasetFiles(input.configDir);
37248
37377
  const stateHome = { kind: "state-home", dir: input.sub };
37249
37378
  const newPaths = await resolveNativePoolPaths(legacyConfig, legacyState, stateHome);
@@ -37272,7 +37401,7 @@ async function resolveRelocationDataset(input) {
37272
37401
  role,
37273
37402
  from: pairs[role][0],
37274
37403
  to: pairs[role][1],
37275
- configured: join27(input.configDir, STATE_HOME_FILE_NAMES[role])
37404
+ configured: join28(input.configDir, STATE_HOME_FILE_NAMES[role])
37276
37405
  })),
37277
37406
  storageIds: { local: oldPaths.storageId, vault: oldVault.storageId }
37278
37407
  };
@@ -37294,8 +37423,8 @@ function errorCode6(error) {
37294
37423
  }
37295
37424
  function transitionHolderFiles(dataset) {
37296
37425
  return [
37297
- join27(dataset.oldDir, HOLDER_FILE_NAME),
37298
- join27(dataset.sub, HOLDER_FILE_NAME)
37426
+ join28(dataset.oldDir, HOLDER_FILE_NAME),
37427
+ join28(dataset.sub, HOLDER_FILE_NAME)
37299
37428
  ].sort();
37300
37429
  }
37301
37430
  async function acquireHolderLock(ctx, holderFile, timeoutMs) {
@@ -37312,7 +37441,7 @@ async function acquireHolderLock(ctx, holderFile, timeoutMs) {
37312
37441
  }
37313
37442
  }
37314
37443
  async function acquireHolderLocks(dataset, ctx) {
37315
- const oldHolders = join27(dataset.oldDir, HOLDER_FILE_NAME);
37444
+ const oldHolders = join28(dataset.oldDir, HOLDER_FILE_NAME);
37316
37445
  for (const file of transitionHolderFiles(dataset)) {
37317
37446
  if (file === oldHolders)
37318
37447
  await stateLayoutStep(ctx, "old-holders-locking");
@@ -37728,7 +37857,7 @@ async function rollbackPreparing(record9, dataset, ctx) {
37728
37857
  }
37729
37858
  for (const name of await readdir7(dataset.sub))
37730
37859
  if (isLayoutRecordStage(name, attempt))
37731
- await removeOwnStaging(join27(dataset.sub, name));
37860
+ await removeOwnStaging(join28(dataset.sub, name));
37732
37861
  await stateLayoutStep(ctx, "rollback:destination-removed");
37733
37862
  await ctx.fs.syncDirectory(dataset.sub);
37734
37863
  await stateLayoutStep(ctx, "rollback:sub-flushed");
@@ -37842,7 +37971,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
37842
37971
  });
37843
37972
  const sha = (role) => files.find((file) => file.role === role)?.sha256 ?? null;
37844
37973
  await ctx.stack.assertAll();
37845
- const configDirPath = join27(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
37974
+ const configDirPath = join28(dataset.sub, STATE_HOME_FILE_NAMES.configDirMarker);
37846
37975
  if (!await exists3(configDirPath)) {
37847
37976
  const stage = `${configDirPath}.${attempt}.tmp`;
37848
37977
  await createOwnerOnlyFile(ctx.fs, stage, Buffer.from(`${JSON.stringify({ version: 1, identity: dataset.identity })}
@@ -37853,7 +37982,7 @@ async function moveDataset(dataset, ctx, checkArtifacts) {
37853
37982
  await removeOwnStaging(stage);
37854
37983
  }
37855
37984
  }
37856
- const holderFile = join27(dataset.sub, HOLDER_FILE_NAME);
37985
+ const holderFile = join28(dataset.sub, HOLDER_FILE_NAME);
37857
37986
  if (!await exists3(holderFile))
37858
37987
  await writeJsonAtomic(holderFile, { version: 1, entries: [] }, {
37859
37988
  beforeRename: () => ctx.stack.assertAll(),
@@ -38007,7 +38136,7 @@ async function rollbackAfterFailure(preparing, dataset, ctx) {
38007
38136
  import { randomUUID as randomUUID21 } from "node:crypto";
38008
38137
  import { readFile as readFile17 } from "node:fs/promises";
38009
38138
  import { homedir as homedir6 } from "node:os";
38010
- import { join as join28 } from "node:path";
38139
+ import { join as join29 } from "node:path";
38011
38140
  var DATA_ROLES = [
38012
38141
  "localPoolState",
38013
38142
  "localRoster",
@@ -38283,7 +38412,7 @@ async function newRestoreProblems(record9, dataset, options) {
38283
38412
  if (await exists3(path2))
38284
38413
  problems.push(`${path2} changed after the move and was kept; move it aside or delete it`);
38285
38414
  }
38286
- problems.push(...await holderProblems(join28(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join28(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
38415
+ problems.push(...await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true), ...await holderProblems(join29(dataset.oldDir, HOLDER_FILE_NAME), options.liveness, false));
38287
38416
  const artifacts = options.artifacts ?? defaultPreNArtifactLocations(options.env ?? process.env, options.home ?? homedir6());
38288
38417
  for (const blocker of await preNArtifactBlockers(artifacts, options.liveness?.pidAlive))
38289
38418
  problems.push(`${describeFenceBlocker(blocker)} is still running`);
@@ -38472,7 +38601,7 @@ async function restoreLegacyLayout(options = {}) {
38472
38601
  break;
38473
38602
  case "restore-staged": {
38474
38603
  await syncObservedRestoreRecord(dataset, ctx);
38475
- const problems = await holderProblems(join28(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
38604
+ const problems = await holderProblems(join29(dataset.sub, HOLDER_FILE_NAME), options.liveness, true);
38476
38605
  if (problems.length)
38477
38606
  throw refused2(`anthropic-auth can't finish restoring its state to ${dataset.oldDir}: ${problems.join("; ")}. Close them, then run ${RESTORE_LEGACY_COMMAND} again.`, [dataset.sub]);
38478
38607
  result = await finishStagedRestore(record9, dataset, ctx);
@@ -38587,7 +38716,7 @@ function deferLegacyRegistration(paths, dir, options, error) {
38587
38716
  }
38588
38717
  async function registerLegacyHeld(oldDir, paths, identity3, options, ctx) {
38589
38718
  try {
38590
- await registerHeld(join29(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
38719
+ await registerHeld(join30(oldDir, HOLDER_FILE_NAME), paths, "legacy", identity3, options, ctx);
38591
38720
  return;
38592
38721
  } catch (error) {
38593
38722
  if (unmovedRegistrationPolicy(options) === "mandatory")
@@ -38620,14 +38749,14 @@ async function admitHeld(dataset, options, ctx, moved, allowPendingCleanup) {
38620
38749
  throw conflict;
38621
38750
  }
38622
38751
  await warnReappearedMetadata(record9);
38623
- await registerHeld(join29(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
38752
+ await registerHeld(join30(dataset.sub, HOLDER_FILE_NAME), dataset.newPaths, "state-home", dataset.identity, options, ctx);
38624
38753
  const layout = { kind: "state-home", dir: dataset.sub };
38625
38754
  recordProcessStateLayout(dataset.oldPaths.legacyConfig, layout);
38626
38755
  return { kind: "state-home", layout, dataset, record: record9, moved };
38627
38756
  }
38628
38757
  async function admitFast(dataset, options, ctx) {
38629
38758
  try {
38630
- await acquireHolderLock(ctx, join29(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38759
+ await acquireHolderLock(ctx, join30(dataset.sub, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38631
38760
  } catch (error) {
38632
38761
  if (error instanceof LockContentionError)
38633
38762
  busy(dataset.configDir, error);
@@ -38735,7 +38864,7 @@ async function legacyWhileMoveOff(configDir, identity3, options, ctx, stayReason
38735
38864
  await stateLayoutStep(ctx, "old-holders-locking");
38736
38865
  let lockFailure;
38737
38866
  try {
38738
- await acquireHolderLock(ctx, join29(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38867
+ await acquireHolderLock(ctx, join30(old.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38739
38868
  } catch (error) {
38740
38869
  lockFailure = { error };
38741
38870
  }
@@ -38765,8 +38894,8 @@ async function decideOpenCodeStateLayout(options) {
38765
38894
  holderLockTimeoutMs: options.timeouts?.holderMs
38766
38895
  });
38767
38896
  if (isExplicit(env)) {
38768
- const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join29(configDir, ACCOUNT_FILE2);
38769
- const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join29(dirname24(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
38897
+ const legacyConfig = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join30(configDir, ACCOUNT_FILE2);
38898
+ const legacyState = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (legacyConfig.endsWith(ACCOUNT_FILE2) ? join30(dirname24(legacyConfig), ACCOUNT_STATE_FILE2) : `${legacyConfig}.state.json`);
38770
38899
  const paths = await resolveNativePoolPaths(legacyConfig, legacyState, LEGACY_STATE_LAYOUT);
38771
38900
  const registration = await registerNativePoolHolder({
38772
38901
  paths,
@@ -38789,7 +38918,7 @@ async function decideOpenCodeStateLayout(options) {
38789
38918
  } catch (error) {
38790
38919
  if (unmovedRegistrationPolicy(options) === "mandatory")
38791
38920
  throw new HolderRegistrationError("unavailable", configDir, error);
38792
- const paths = await resolveNativePoolPaths(join29(configDir, ACCOUNT_FILE2), join29(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
38921
+ const paths = await resolveNativePoolPaths(join30(configDir, ACCOUNT_FILE2), join30(configDir, ACCOUNT_STATE_FILE2), LEGACY_STATE_LAYOUT);
38793
38922
  return chooseLegacy(paths, [reason], true, deferLegacyRegistration(paths, configDir, options, error));
38794
38923
  }
38795
38924
  identity3 = configIdentity(configDir);
@@ -38859,7 +38988,7 @@ async function decideOpenCodeStateLayout(options) {
38859
38988
  try {
38860
38989
  await stateLayoutStep(ctx, "old-holders-locking");
38861
38990
  try {
38862
- await acquireHolderLock(ctx, join29(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38991
+ await acquireHolderLock(ctx, join30(dataset.oldDir, HOLDER_FILE_NAME), ctx.holderLockTimeoutMs);
38863
38992
  } catch (error) {
38864
38993
  if (unmovedRegistrationPolicy(options) === "mandatory")
38865
38994
  throw error;
@@ -39291,6 +39420,7 @@ export {
39291
39420
  requireNoSupervisedAuthContentSnapshot,
39292
39421
  requireAnthropicOAuthOrigin,
39293
39422
  requestGzipPadding,
39423
+ reportRouting,
39294
39424
  renameWithWindowsSharingRetry,
39295
39425
  remapRequestBodyModel,
39296
39426
  remapModelId,
@@ -39601,6 +39731,7 @@ export {
39601
39731
  assertNotCustodyTombstone,
39602
39732
  assertNoMeaningfulTrailingAssistant,
39603
39733
  assertHostsStopped,
39734
+ askRouting,
39604
39735
  applyTurnEndNotes,
39605
39736
  applyThinkingBindingControls,
39606
39737
  applyMidConversationOutputConfig,