@cortexkit/anthropic-auth-core 2.8.0 → 2.9.1

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
@@ -93,9 +93,12 @@ var VAULT_FAILURE_CLASSES = Object.freeze({
93
93
  });
94
94
 
95
95
  class ClaustrumUnreachableError extends ClaustrumConsumerError {
96
- constructor() {
96
+ reason;
97
+ constructor(reason) {
97
98
  super("unavailable", "Claustrum scoped operation unavailable");
98
99
  this.name = "ClaustrumUnreachableError";
100
+ if (reason === "host-accessor-missing" || reason === "host-accessor-failed")
101
+ this.reason = reason;
99
102
  }
100
103
  }
101
104
  function classifyVaultFailure(error) {
@@ -1341,7 +1344,7 @@ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexki
1341
1344
  import { createHash, randomBytes, randomUUID as randomUUID4 } from "node:crypto";
1342
1345
  import { constants as fsConstants } from "node:fs";
1343
1346
  import { chmod, mkdir as mkdir3, open as open4, readFile as readFile3, realpath, rename as rename4, stat as stat3, unlink as unlink2 } from "node:fs/promises";
1344
- import { basename, dirname as dirname5, extname, isAbsolute, join as join4, resolve as resolve6 } from "node:path";
1347
+ import { basename, dirname as dirname5, extname, isAbsolute, join as join4, resolve as resolve7 } from "node:path";
1345
1348
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
1346
1349
 
1347
1350
  // ../../node_modules/@cortexkit/common-auth/dist/fs/file-read-cache.js
@@ -1500,8 +1503,40 @@ import { randomUUID as randomUUID3 } from "node:crypto";
1500
1503
  import { link, lstat as lstat3, mkdir as mkdir2, open as open3, readFile as readFile2, rename as rename3, rm as rm2, stat as stat2 } from "node:fs/promises";
1501
1504
  import { dirname as dirname4, join as join3 } from "node:path";
1502
1505
 
1506
+ // ../../node_modules/@cortexkit/common-auth/dist/fs/lock-record.js
1507
+ import { resolve as resolve5 } from "node:path";
1508
+ class DisappearedLockRecordError extends Error {
1509
+ path;
1510
+ code = "ENOENT";
1511
+ constructor(path, cause) {
1512
+ super(`Lock record disappeared: ${path}`, { cause });
1513
+ this.path = path;
1514
+ }
1515
+ }
1516
+ function isWindowsAccessDeniedRead(error, paths) {
1517
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path) => resolve5(path) === error.path);
1518
+ }
1519
+ function isWindowsAccessDeniedCreate(error, paths, stage) {
1520
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path) => resolve5(path) === error.path);
1521
+ }
1522
+ async function readLockRecord(path, read) {
1523
+ try {
1524
+ return await read();
1525
+ } catch (error) {
1526
+ if (!isWindowsAccessDeniedRead(error, [path]))
1527
+ throw error;
1528
+ try {
1529
+ return await read();
1530
+ } catch (recheckError) {
1531
+ if (recheckError.code === "ENOENT")
1532
+ throw new DisappearedLockRecordError(path, error);
1533
+ throw error;
1534
+ }
1535
+ }
1536
+ }
1537
+
1503
1538
  // ../../node_modules/@cortexkit/common-auth/dist/fs/with-lock.js
1504
- import { join as join2, resolve as resolve5 } from "node:path";
1539
+ import { join as join2, resolve as resolve6 } from "node:path";
1505
1540
  function lockPathFor(target, name) {
1506
1541
  return `${target}.${name}.lock`;
1507
1542
  }
@@ -1523,18 +1558,17 @@ class LockOwnershipError extends Error {
1523
1558
  this.details = details;
1524
1559
  }
1525
1560
  }
1526
- function isChangingLockRead(error, target, name) {
1527
- if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
1528
- return false;
1529
- const path = resolve5(lockPathFor(target, name));
1530
- return error.path === path || error.path === join2(path, "owner.json");
1561
+ function isChangingLockRecord(error, target, name) {
1562
+ const path = resolve6(lockPathFor(target, name));
1563
+ const paths = [path, join2(path, "owner.json")];
1564
+ return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path], "create") || isWindowsAccessDeniedCreate(error, [`${path}.evicting`], "directory-create"));
1531
1565
  }
1532
1566
  async function withLock(target, options, fn) {
1533
1567
  const started = performance.now();
1568
+ let changingRecordError;
1534
1569
  for (;; ) {
1535
1570
  options.signal?.throwIfAborted();
1536
1571
  let lock;
1537
- let changingReadError;
1538
1572
  try {
1539
1573
  lock = await acquireRefreshFileLock({
1540
1574
  path: target,
@@ -1544,11 +1578,12 @@ async function withLock(target, options, fn) {
1544
1578
  ...options.onStep ? { onStep: options.onStep } : {},
1545
1579
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
1546
1580
  });
1581
+ changingRecordError = undefined;
1547
1582
  } catch (error) {
1548
- if (!isChangingLockRead(error, target, options.name))
1583
+ if (!isChangingLockRecord(error, target, options.name))
1549
1584
  throw error;
1550
1585
  lock = null;
1551
- changingReadError = error;
1586
+ changingRecordError ??= error;
1552
1587
  }
1553
1588
  if (lock) {
1554
1589
  try {
@@ -1560,15 +1595,15 @@ async function withLock(target, options, fn) {
1560
1595
  }
1561
1596
  const remaining = options.timeoutMs - (performance.now() - started);
1562
1597
  if (remaining <= 0) {
1563
- if (changingReadError)
1564
- throw changingReadError;
1598
+ if (changingRecordError)
1599
+ throw changingRecordError;
1565
1600
  throw new LockContentionError({
1566
1601
  target,
1567
1602
  name: options.name,
1568
1603
  timeoutMs: options.timeoutMs
1569
1604
  });
1570
1605
  }
1571
- await new Promise((resolve6) => setTimeout(resolve6, Math.min(25, Math.ceil(remaining))));
1606
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(25, Math.ceil(remaining))));
1572
1607
  }
1573
1608
  }
1574
1609
 
@@ -1655,8 +1690,8 @@ async function acquireRefreshFileLockWithClock(options) {
1655
1690
  let releaseConfirmed = false;
1656
1691
  let loss;
1657
1692
  let resolveLoss;
1658
- const lostPromise = new Promise((resolve6) => {
1659
- resolveLoss = resolve6;
1693
+ const lostPromise = new Promise((resolve7) => {
1694
+ resolveLoss = resolve7;
1660
1695
  });
1661
1696
  function notifyTimerStep(event) {
1662
1697
  try {
@@ -1692,15 +1727,18 @@ async function acquireRefreshFileLockWithClock(options) {
1692
1727
  const evictOwnerId = randomUUID3();
1693
1728
  const EVICT_TTL = 5000;
1694
1729
  const MAX_STEAL_ATTEMPTS = 8;
1730
+ function isChangingLockCreate(error) {
1731
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
1732
+ }
1695
1733
  async function readOwner() {
1696
1734
  if (windowsPrivateFiles) {
1697
1735
  try {
1698
- return JSON.parse(await readPrivateText(lockPath, true));
1736
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
1699
1737
  } catch (error) {
1700
1738
  if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
1701
1739
  throw error;
1702
- await verifyPrivate(lockPath, "directory", true);
1703
- return JSON.parse(await readPrivateText(legacyOwnerPath, true));
1740
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
1741
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
1704
1742
  }
1705
1743
  }
1706
1744
  try {
@@ -1774,8 +1812,8 @@ async function acquireRefreshFileLockWithClock(options) {
1774
1812
  await options.onStep("lease-contention-read-ready");
1775
1813
  try {
1776
1814
  if (code === "EISDIR") {
1777
- await verifyPrivate(lockPath, "directory", true);
1778
- await readPrivateText(legacyOwnerPath, true);
1815
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
1816
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
1779
1817
  } else
1780
1818
  await readOwner();
1781
1819
  } catch (readError) {
@@ -1813,7 +1851,7 @@ async function acquireRefreshFileLockWithClock(options) {
1813
1851
  }
1814
1852
  }
1815
1853
  async function backoff() {
1816
- await new Promise((resolve6) => setTimeout(resolve6, Math.floor(Math.random() * 4)));
1854
+ await new Promise((resolve7) => setTimeout(resolve7, Math.floor(Math.random() * 4)));
1817
1855
  }
1818
1856
  async function readLockState(notifyReady = true) {
1819
1857
  if (notifyReady && options.onStep)
@@ -1822,6 +1860,8 @@ async function acquireRefreshFileLockWithClock(options) {
1822
1860
  try {
1823
1861
  owner = await readOwner();
1824
1862
  } catch (error) {
1863
+ if (error instanceof DisappearedLockRecordError)
1864
+ return { status: "missing" };
1825
1865
  if (windowsPrivateFiles && error.code !== "ENOENT")
1826
1866
  throw error;
1827
1867
  }
@@ -1869,7 +1909,7 @@ async function acquireRefreshFileLockWithClock(options) {
1869
1909
  }
1870
1910
  async function ownsEvictionMarker() {
1871
1911
  try {
1872
- const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
1912
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
1873
1913
  return owner?.ownerId === evictOwnerId;
1874
1914
  } catch (error) {
1875
1915
  if (windowsPrivateFiles && error.code !== "ENOENT")
@@ -1903,7 +1943,7 @@ async function acquireRefreshFileLockWithClock(options) {
1903
1943
  const remainingMs = deadline - performance.now();
1904
1944
  if (remainingMs <= 0)
1905
1945
  throw original;
1906
- await new Promise((resolve6) => setTimeout(resolve6, Math.min(delayMs, remainingMs)));
1946
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(delayMs, remainingMs)));
1907
1947
  if (performance.now() >= deadline)
1908
1948
  throw original;
1909
1949
  delayMs = Math.min(delayMs * 2, 50);
@@ -2007,7 +2047,7 @@ async function acquireRefreshFileLockWithClock(options) {
2007
2047
  }
2008
2048
  if (windowsPrivateFiles) {
2009
2049
  try {
2010
- await verifyPrivate(evictPath, "directory", true);
2050
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
2011
2051
  } catch (error) {
2012
2052
  if (error.code === "ENOENT")
2013
2053
  return "missing";
@@ -2062,8 +2102,8 @@ async function acquireRefreshFileLockWithClock(options) {
2062
2102
  if (error.code === "EEXIST") {
2063
2103
  if (windowsPrivateFiles) {
2064
2104
  try {
2065
- await verifyPrivate(evictPath, "directory", true);
2066
- await readPrivateText(evictOwnerPath, true);
2105
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
2106
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
2067
2107
  } catch (ownerError) {
2068
2108
  if (ownerError.code !== "ENOENT")
2069
2109
  throw ownerError;
@@ -2084,7 +2124,11 @@ async function acquireRefreshFileLockWithClock(options) {
2084
2124
  try {
2085
2125
  await releaseEvictionMarker(deadline);
2086
2126
  } catch (error) {
2087
- if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
2127
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
2128
+ lockPath,
2129
+ legacyOwnerPath,
2130
+ evictOwnerPath
2131
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
2088
2132
  throw actionError;
2089
2133
  throw error;
2090
2134
  }
@@ -2100,7 +2144,7 @@ async function acquireRefreshFileLockWithClock(options) {
2100
2144
  try {
2101
2145
  owner = await readOwner();
2102
2146
  } catch (error) {
2103
- if (windowsPrivateFiles)
2147
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
2104
2148
  throw error;
2105
2149
  return;
2106
2150
  }
@@ -2178,7 +2222,7 @@ async function acquireRefreshFileLockWithClock(options) {
2178
2222
  await options.onStep("renewal-marker-unavailable");
2179
2223
  }
2180
2224
  } catch (error) {
2181
- if (windowsPrivateFiles && error instanceof PrivateFileError) {
2225
+ if (windowsPrivateFiles && error instanceof PrivateFileError && !isChangingLockCreate(error)) {
2182
2226
  terminalIOError = error;
2183
2227
  recordLoss("renewal-failed");
2184
2228
  shouldReschedule = false;
@@ -2221,72 +2265,90 @@ async function acquireRefreshFileLockWithClock(options) {
2221
2265
  } catch {}
2222
2266
  return null;
2223
2267
  }
2224
- let acquired = await tryAcquire();
2268
+ let acquired = false;
2269
+ let changingCreateError;
2270
+ try {
2271
+ acquired = await tryAcquire();
2272
+ } catch (error) {
2273
+ if (!isChangingLockCreate(error))
2274
+ throw error;
2275
+ changingCreateError = error;
2276
+ }
2225
2277
  if (!acquired) {
2226
2278
  for (let attempt = 0;attempt < MAX_STEAL_ATTEMPTS; attempt++) {
2227
- acquired = await tryAcquire();
2228
- if (acquired)
2229
- break;
2230
- const observed = await readLockState();
2231
- if (observed.status === "live")
2232
- return contended();
2233
- if (observed.status === "missing")
2234
- continue;
2235
- if (options.onStep)
2236
- await options.onStep("stale-lock-observed");
2237
- try {
2238
- if (!await tryAcquireEvictionMarker()) {
2239
- await backoff();
2240
- continue;
2241
- }
2242
- } catch (evictError) {
2243
- const code = evictError.code;
2244
- if (code !== "EEXIST")
2245
- throw evictError;
2246
- const recovered = await recoverStaleEvictionMarker();
2247
- if (recovered === "fresh")
2248
- return null;
2249
- await backoff();
2250
- continue;
2251
- }
2252
2279
  try {
2253
- const confirmed = await readLockState();
2254
- if (confirmed.status === "live")
2280
+ acquired = await tryAcquire();
2281
+ if (acquired)
2282
+ break;
2283
+ const observed = await readLockState();
2284
+ if (observed.status === "live")
2255
2285
  return contended();
2256
- if (!sameStaleLock(observed.identity, confirmed))
2286
+ if (observed.status === "missing")
2257
2287
  continue;
2258
- if (!await ownsEvictionMarker())
2259
- return null;
2260
2288
  if (options.onStep)
2261
- await options.onStep("stale-lock-confirmed");
2262
- if (!await ownsEvictionMarker())
2263
- return null;
2264
- const current = await readLockState(false);
2265
- if (!sameStaleLock(observed.identity, current))
2289
+ await options.onStep("stale-lock-observed");
2290
+ try {
2291
+ if (!await tryAcquireEvictionMarker()) {
2292
+ await backoff();
2293
+ continue;
2294
+ }
2295
+ } catch (evictError) {
2296
+ const code = evictError.code;
2297
+ if (code !== "EEXIST")
2298
+ throw evictError;
2299
+ const recovered = await recoverStaleEvictionMarker();
2300
+ if (recovered === "fresh")
2301
+ return null;
2302
+ await backoff();
2266
2303
  continue;
2267
- await removeLeaseObject(lockPath);
2268
- if (!await ownsEvictionMarker())
2269
- return null;
2270
- if (options.onStep)
2271
- await options.onStep("stale-lock-removed");
2272
- acquired = await tryAcquire();
2273
- if (!acquired)
2274
- return null;
2275
- if (options.onStep)
2276
- await options.onStep("stale-lock-recreated");
2277
- if (!await ownsEvictionMarker()) {
2278
- await relinquishLockAfterMarkerLoss();
2279
- acquired = false;
2280
- return null;
2281
2304
  }
2282
- break;
2283
- } finally {
2284
- await releaseEvictionMarker();
2305
+ try {
2306
+ const confirmed = await readLockState();
2307
+ if (confirmed.status === "live")
2308
+ return contended();
2309
+ if (!sameStaleLock(observed.identity, confirmed))
2310
+ continue;
2311
+ if (!await ownsEvictionMarker())
2312
+ return null;
2313
+ if (options.onStep)
2314
+ await options.onStep("stale-lock-confirmed");
2315
+ if (!await ownsEvictionMarker())
2316
+ return null;
2317
+ const current = await readLockState(false);
2318
+ if (!sameStaleLock(observed.identity, current))
2319
+ continue;
2320
+ await removeLeaseObject(lockPath);
2321
+ if (!await ownsEvictionMarker())
2322
+ return null;
2323
+ if (options.onStep)
2324
+ await options.onStep("stale-lock-removed");
2325
+ acquired = await tryAcquire();
2326
+ if (!acquired)
2327
+ return null;
2328
+ if (options.onStep)
2329
+ await options.onStep("stale-lock-recreated");
2330
+ if (!await ownsEvictionMarker()) {
2331
+ await relinquishLockAfterMarkerLoss();
2332
+ acquired = false;
2333
+ return null;
2334
+ }
2335
+ break;
2336
+ } finally {
2337
+ await releaseEvictionMarker();
2338
+ }
2339
+ } catch (error) {
2340
+ if (!isChangingLockCreate(error))
2341
+ throw error;
2342
+ changingCreateError ??= error;
2343
+ await backoff();
2285
2344
  }
2286
2345
  }
2287
2346
  }
2288
- if (!acquired)
2347
+ if (!acquired) {
2348
+ if (changingCreateError)
2349
+ throw changingCreateError;
2289
2350
  return null;
2351
+ }
2290
2352
  scheduleRenewal();
2291
2353
  return {
2292
2354
  ownerId,
@@ -2324,6 +2386,7 @@ async function acquireRefreshFileLockWithClock(options) {
2324
2386
  const deadline = performance.now() + EVICT_TTL + 1000;
2325
2387
  let delayMs = 5;
2326
2388
  let removalError;
2389
+ let changingRecordError;
2327
2390
  for (;; ) {
2328
2391
  try {
2329
2392
  let removalConfirmed = false;
@@ -2349,6 +2412,7 @@ async function acquireRefreshFileLockWithClock(options) {
2349
2412
  await removeLeaseObject(lockPath);
2350
2413
  removalConfirmed = true;
2351
2414
  }, deadline);
2415
+ changingRecordError = undefined;
2352
2416
  if (markerAcquired) {
2353
2417
  if (windowsPrivateFiles && !removalConfirmed)
2354
2418
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -2361,23 +2425,32 @@ async function acquireRefreshFileLockWithClock(options) {
2361
2425
  return;
2362
2426
  await recoverStaleEvictionMarker(deadline);
2363
2427
  } catch (error) {
2364
- if (!isRetryableRemoval(error, lockPath)) {
2428
+ const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
2429
+ lockPath,
2430
+ legacyOwnerPath,
2431
+ evictPath,
2432
+ evictOwnerPath
2433
+ ]));
2434
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
2365
2435
  if (windowsPrivateFiles)
2366
2436
  throw error;
2367
2437
  return;
2368
2438
  }
2369
- removalError ??= error;
2439
+ if (changingRecord)
2440
+ changingRecordError ??= error;
2441
+ else
2442
+ removalError ??= error;
2370
2443
  }
2371
2444
  const remainingMs = deadline - performance.now();
2372
2445
  if (remainingMs <= 0)
2373
2446
  break;
2374
- await new Promise((resolve6) => setTimeout(resolve6, Math.min(delayMs, remainingMs)));
2447
+ await new Promise((resolve7) => setTimeout(resolve7, Math.min(delayMs, remainingMs)));
2375
2448
  if (windowsPrivateFiles && performance.now() >= deadline)
2376
2449
  break;
2377
2450
  delayMs = Math.min(delayMs * 2, 50);
2378
2451
  }
2379
2452
  if (windowsPrivateFiles)
2380
- throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
2453
+ throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
2381
2454
  code: "ETIMEDOUT"
2382
2455
  });
2383
2456
  }
@@ -2401,7 +2474,7 @@ function hostError(error) {
2401
2474
  if (typeof value.code === "string" && (value.class === "transient" || value.class === "permanent" || value.class === "auth_required" || value.class === "context_overflow") && (value.action === "gone" || value.action === "reauth" || value.action === "retry" || value.action === "reduce_and_retry"))
2402
2475
  return new ClaustrumCredentialError2(value.code, value.class, value.action);
2403
2476
  if (value.name === "ClaustrumUnreachableError" || typeof value.code === "string" && classifyVaultFailure(Object.assign(new Error, { code: value.code })) === "unreachable")
2404
- return new ClaustrumUnreachableError;
2477
+ return new ClaustrumUnreachableError(value.reason === "host-accessor-missing" || value.reason === "host-accessor-failed" ? value.reason : undefined);
2405
2478
  return error;
2406
2479
  }
2407
2480
  function call(operation) {
@@ -2467,14 +2540,15 @@ function connectVaultHost(pluginId) {
2467
2540
  throw new ClaustrumUnreachableError;
2468
2541
  try {
2469
2542
  const accessor = globalThis[Symbol.for("cortexkit.vault")];
2470
- if (typeof accessor !== "function")
2471
- throw new ClaustrumUnreachableError;
2472
- const client = wrapHostClient(accessor(pluginId));
2473
- hostClients.add(client);
2474
- return client;
2543
+ if (typeof accessor === "function") {
2544
+ const client = wrapHostClient(accessor(pluginId));
2545
+ hostClients.add(client);
2546
+ return client;
2547
+ }
2475
2548
  } catch {
2476
- throw new ClaustrumUnreachableError;
2549
+ throw new ClaustrumUnreachableError("host-accessor-failed");
2477
2550
  }
2551
+ throw new ClaustrumUnreachableError("host-accessor-missing");
2478
2552
  }
2479
2553
 
2480
2554
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/enrollment.js
@@ -2507,6 +2581,10 @@ function classifyEnrollmentError(error) {
2507
2581
  disposition: error.action === "retry" ? "retry" : "terminal"
2508
2582
  };
2509
2583
  }
2584
+ function validEnrollmentDisplayName(displayName) {
2585
+ const length = Array.from(displayName).length;
2586
+ return length >= 1 && length <= 40 && !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName);
2587
+ }
2510
2588
  function connectClaustrumEnrollmentClient(options) {
2511
2589
  return ClaustrumWireClient.connect(options);
2512
2590
  }
@@ -2522,7 +2600,7 @@ function hostEnrollmentPaths(input) {
2522
2600
  const override = input.override?.trim();
2523
2601
  if (override && !isAbsolute(override) && !input.cwd)
2524
2602
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
2525
- const tokenPath = override ? isAbsolute(override) ? override : resolve6(input.cwd, override) : join4(input.stateDir, `${input.host}-enrollment.json`);
2603
+ const tokenPath = override ? isAbsolute(override) ? override : resolve7(input.cwd, override) : join4(input.stateDir, `${input.host}-enrollment.json`);
2526
2604
  return getClaustrumEnrollmentPaths(tokenPath);
2527
2605
  }
2528
2606
  function isRecord(value) {
@@ -2891,15 +2969,19 @@ class ClaustrumEnrollmentManager {
2891
2969
  #client;
2892
2970
  #paths;
2893
2971
  #proposedName;
2972
+ #displayName;
2894
2973
  #now;
2895
2974
  #mintSecret;
2896
2975
  #writeTokenFile;
2897
2976
  #ancestorOptions;
2898
2977
  constructor(options) {
2978
+ if (options.displayName !== undefined && !validEnrollmentDisplayName(options.displayName))
2979
+ throw new ClaustrumConsumerError("invalid-state", "invalid Claustrum enrollment display name");
2899
2980
  this.#ancestorOptions = options.ancestorOptions ?? {};
2900
2981
  this.#client = options.client;
2901
2982
  this.#paths = options.paths;
2902
2983
  this.#proposedName = options.proposedName;
2984
+ this.#displayName = options.displayName;
2903
2985
  this.#now = options.now ?? Date.now;
2904
2986
  this.#mintSecret = options.mintSecret ?? (() => randomBytes(32).toString("hex"));
2905
2987
  this.#writeTokenFile = options.writeTokenFile ?? writeEnrollmentTokenFile;
@@ -2989,10 +3071,23 @@ class ClaustrumEnrollmentManager {
2989
3071
  if (!state.requestId) {
2990
3072
  try {
2991
3073
  const requestSecretHash = createHash("sha256").update(Buffer.from(state.requestSecret, "hex")).digest("hex");
2992
- const proposed = await this.#client.enrollPropose({
3074
+ const proposal = {
2993
3075
  name: state.proposedName,
2994
3076
  requestSecretHash
2995
- });
3077
+ };
3078
+ let proposed;
3079
+ try {
3080
+ proposed = await this.#client.enrollPropose({
3081
+ ...proposal,
3082
+ ...this.#displayName !== undefined && {
3083
+ displayName: this.#displayName
3084
+ }
3085
+ });
3086
+ } catch (error) {
3087
+ if (this.#displayName === undefined || !(error instanceof ClaustrumCredentialError3) || error.code !== "invalid_params")
3088
+ throw error;
3089
+ proposed = await this.#client.enrollPropose(proposal);
3090
+ }
2996
3091
  state = {
2997
3092
  ...state,
2998
3093
  requestId: proposed.requestId,
@@ -3175,10 +3270,10 @@ async function drainShutdown(pending, onTimeout) {
3175
3270
  try {
3176
3271
  await Promise.race([
3177
3272
  drained,
3178
- new Promise((resolve7) => {
3273
+ new Promise((resolve8) => {
3179
3274
  timer = setTimeout(() => {
3180
3275
  expired = true;
3181
- resolve7();
3276
+ resolve8();
3182
3277
  }, 2000);
3183
3278
  })
3184
3279
  ]);
@@ -3495,8 +3590,14 @@ class ClaustrumScopedCustody {
3495
3590
  this.#warnShutdown = shutdownWarning(this.#logger);
3496
3591
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
3497
3592
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
3593
+ const currentClient = () => this.#client;
3498
3594
  this.#usage = new ScopedUsageReporter({
3499
- client: this.#client,
3595
+ client: {
3596
+ get reportUsageScoped() {
3597
+ const client = currentClient();
3598
+ return client.reportUsageScoped?.bind(client);
3599
+ }
3600
+ },
3500
3601
  owns: (id) => this.#usageServed.has(id),
3501
3602
  token: async () => hasVaultHost() ? "" : checkedEnrollmentToken(await this.#readToken()),
3502
3603
  logger: this.#logger,
@@ -3504,11 +3605,21 @@ class ClaustrumScopedCustody {
3504
3605
  clearTimeout: this.#clearTimeout
3505
3606
  });
3506
3607
  }
3608
+ replaceClient(next) {
3609
+ this.#check();
3610
+ if (next === this.#client)
3611
+ return;
3612
+ if (hasVaultHost() && !isVaultHostClient(next))
3613
+ throw new ClaustrumUnreachableError;
3614
+ this.#client = next;
3615
+ for (const watch of this.#watches)
3616
+ watch.restart();
3617
+ }
3507
3618
  transportLost(error) {
3508
3619
  if (this.#closed || this.#outage)
3509
3620
  return;
3510
3621
  this.#outage = true;
3511
- this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError;
3622
+ this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
3512
3623
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
3513
3624
  this.#scheduleProbe();
3514
3625
  }
@@ -3605,7 +3716,7 @@ class ClaustrumScopedCustody {
3605
3716
  if (error instanceof ClaustrumCredentialError5)
3606
3717
  throw error;
3607
3718
  if (classifyVaultFailure(error) === "unreachable")
3608
- throw new ClaustrumUnreachableError;
3719
+ throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : undefined);
3609
3720
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
3610
3721
  } finally {
3611
3722
  removeAbortListener?.();
@@ -3805,7 +3916,7 @@ class ClaustrumScopedCustody {
3805
3916
  if (kept.since === null)
3806
3917
  kept.since = this.#now();
3807
3918
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
3808
- this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
3919
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token });
3809
3920
  this.#keptAttempts.set(attempt, routeId);
3810
3921
  return attempt;
3811
3922
  }
@@ -3860,7 +3971,7 @@ class ClaustrumScopedCustody {
3860
3971
  recordVersion: served.recordVersion,
3861
3972
  expiresAtMs
3862
3973
  }, "accessToken", { value: accessToken, enumerable: false }));
3863
- this.#provenance.set(attempt, { token, client: this.#client });
3974
+ this.#provenance.set(attempt, { token });
3864
3975
  return attempt;
3865
3976
  }
3866
3977
  async reportFailure(attempt, status, reporterSource) {
@@ -3885,7 +3996,7 @@ class ClaustrumScopedCustody {
3885
3996
  const pending = this.#reports.get(attempt);
3886
3997
  if (pending)
3887
3998
  return pending;
3888
- const report = this.#call(() => provenance.client.reportAuthFailureScoped({
3999
+ const report = this.#call(() => this.#client.reportAuthFailureScoped({
3889
4000
  credentialId: attempt.credentialId,
3890
4001
  enrollmentToken: provenance.token,
3891
4002
  providerStatus: 401,
@@ -3907,34 +4018,62 @@ class ClaustrumScopedCustody {
3907
4018
  }
3908
4019
  watchRoster(options) {
3909
4020
  this.#check();
3910
- const watch = new ScopedRosterWatch({
3911
- client: this.#client,
3912
- enrollmentToken: () => this.#token(),
3913
- view: options.view ?? (() => this.#discoveredView),
3914
- discover: async (view) => {
3915
- await options.onView(view);
3916
- },
3917
- onRefused: (error) => {
3918
- this.listFailed(error);
3919
- options.onRefused?.(error);
4021
+ const currentView = options.view ?? (() => this.#discoveredView);
4022
+ let discovering;
4023
+ let watch;
4024
+ const create = (resubscribed = false) => {
4025
+ const opened = new ScopedRosterWatch({
4026
+ client: this.#client,
4027
+ enrollmentToken: () => this.#token(),
4028
+ view: () => resubscribed ? undefined : currentView(),
4029
+ discover: async (view) => {
4030
+ while (discovering)
4031
+ await discovering.catch(() => {});
4032
+ if (watch !== opened)
4033
+ return;
4034
+ resubscribed = false;
4035
+ discovering = Promise.resolve().then(() => options.onView(view));
4036
+ try {
4037
+ await discovering;
4038
+ } finally {
4039
+ discovering = undefined;
4040
+ }
4041
+ },
4042
+ onRefused: (error) => {
4043
+ this.listFailed(error);
4044
+ options.onRefused?.(error);
4045
+ },
4046
+ onTransportLost: () => this.transportLost(),
4047
+ onReachable: () => this.reachable(),
4048
+ onError: options.onError,
4049
+ onMode: options.onMode,
4050
+ logger: this.#logger,
4051
+ now: this.#now,
4052
+ setTimeoutImpl: this.#setTimeout,
4053
+ clearTimeoutImpl: this.#clearTimeout
4054
+ });
4055
+ return opened;
4056
+ };
4057
+ watch = create();
4058
+ const tracked = {
4059
+ restart: () => {
4060
+ const previousMode = watch.mode;
4061
+ watch.stop();
4062
+ watch = create(true);
4063
+ if (previousMode !== watch.mode)
4064
+ options.onMode?.(watch.mode);
4065
+ watch.start();
3920
4066
  },
3921
- onTransportLost: () => this.transportLost(),
3922
- onReachable: () => this.reachable(),
3923
- onError: options.onError,
3924
- onMode: options.onMode,
3925
- logger: this.#logger,
3926
- now: this.#now,
3927
- setTimeoutImpl: this.#setTimeout,
3928
- clearTimeoutImpl: this.#clearTimeout
3929
- });
3930
- this.#watches.add(watch);
4067
+ stop: () => watch.stop()
4068
+ };
4069
+ this.#watches.add(tracked);
3931
4070
  watch.start();
3932
4071
  return {
3933
4072
  get mode() {
3934
4073
  return watch.mode;
3935
4074
  },
3936
4075
  close: () => {
3937
- this.#watches.delete(watch);
4076
+ this.#watches.delete(tracked);
3938
4077
  watch.stop();
3939
4078
  }
3940
4079
  };
@@ -3981,7 +4120,7 @@ class ClaustrumScopedCustody {
3981
4120
  }
3982
4121
 
3983
4122
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/quota-writer.js
3984
- import { resolve as resolve8 } from "node:path";
4123
+ import { resolve as resolve9 } from "node:path";
3985
4124
 
3986
4125
  // ../../node_modules/@cortexkit/common-auth/dist/quota/commit-interval.js
3987
4126
  var QUOTA_COMMIT_INTERVAL_MS = 30000;
@@ -4540,7 +4679,7 @@ function quotaFields(publication, witness = "") {
4540
4679
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/roster.js
4541
4680
  import { createHash as createHash2 } from "node:crypto";
4542
4681
  import { stat as stat4 } from "node:fs/promises";
4543
- import { resolve as resolve7 } from "node:path";
4682
+ import { resolve as resolve8 } from "node:path";
4544
4683
 
4545
4684
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/interlock.js
4546
4685
  function matches(entry, credentialId, accountIdentity) {
@@ -4983,16 +5122,16 @@ function applyVaultQuota(current, input) {
4983
5122
  }
4984
5123
  var pendingDiscoveries = new Map;
4985
5124
  function forgetPendingVaultDiscovery(path) {
4986
- pendingDiscoveries.delete(resolve7(path));
5125
+ pendingDiscoveries.delete(resolve8(path));
4987
5126
  }
4988
5127
  function isVaultRosterLockRefusal(path, error) {
4989
- const target = resolve7(path);
5128
+ const target = resolve8(path);
4990
5129
  if (error instanceof ClaustrumConsumerError)
4991
5130
  return error.kind === "roster-busy";
4992
5131
  if (error instanceof LockContentionError || error instanceof LockOwnershipError)
4993
- return resolve7(error.details.target) === target;
5132
+ return resolve8(error.details.target) === target;
4994
5133
  if (error instanceof PrivateFileError) {
4995
- const failed = resolve7(error.path);
5134
+ const failed = resolve8(error.path);
4996
5135
  return [WRITE_LOCK.name, DISCOVERY_LEASE.name].some((name) => {
4997
5136
  const lock = lockPathFor(target, name);
4998
5137
  return failed === lock || failed.startsWith(`${lock}.`);
@@ -5053,7 +5192,7 @@ async function refreshVaultRoster(options) {
5053
5192
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
5054
5193
  return persisted;
5055
5194
  }
5056
- const key = resolve7(options.path);
5195
+ const key = resolve8(options.path);
5057
5196
  const listedOver = options.listedOver;
5058
5197
  let discovered;
5059
5198
  try {
@@ -5116,7 +5255,7 @@ var writers = new Map;
5116
5255
  var logger = createLogger("claustrum");
5117
5256
  var COALESCE_MS = 100;
5118
5257
  function writerFor(path, clock = quotaCommitTimer) {
5119
- const key = resolve8(path);
5258
+ const key = resolve9(path);
5120
5259
  let writer = writers.get(key);
5121
5260
  if (!writer) {
5122
5261
  writer = {
@@ -5180,7 +5319,7 @@ function orderedFields(pending) {
5180
5319
  return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
5181
5320
  }
5182
5321
  function pendingVaultQuota(path, roster) {
5183
- const writer = writers.get(resolve8(path));
5322
+ const writer = writers.get(resolve9(path));
5184
5323
  if (writer) {
5185
5324
  for (const field of orderedFields(writer.pending)) {
5186
5325
  if (field.priorReading)
@@ -5191,7 +5330,7 @@ function pendingVaultQuota(path, roster) {
5191
5330
  return roster;
5192
5331
  }
5193
5332
  function hasPendingVaultQuota(path) {
5194
- return !!writers.get(resolve8(path))?.pending.size;
5333
+ return !!writers.get(resolve9(path))?.pending.size;
5195
5334
  }
5196
5335
  function schedule(writer, delay) {
5197
5336
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
@@ -5256,7 +5395,7 @@ function flush(writer) {
5256
5395
  return writer.running;
5257
5396
  }
5258
5397
  async function drainVaultQuota(path, timeoutMs = 1000) {
5259
- const key = resolve8(path);
5398
+ const key = resolve9(path);
5260
5399
  const writer = writers.get(key);
5261
5400
  if (!writer)
5262
5401
  return;
@@ -5368,7 +5507,7 @@ class ClaustrumConsumer {
5368
5507
  this.#shutdown.signal,
5369
5508
  ...signal ? [signal] : []
5370
5509
  ]);
5371
- return new Promise((resolve9, reject) => {
5510
+ return new Promise((resolve10, reject) => {
5372
5511
  const cleanup = () => {
5373
5512
  combined.signal.removeEventListener("abort", abort);
5374
5513
  combined.dispose();
@@ -5383,7 +5522,7 @@ class ClaustrumConsumer {
5383
5522
  if (combined.signal.aborted)
5384
5523
  reject(combined.signal.reason);
5385
5524
  else
5386
- resolve9(value);
5525
+ resolve10(value);
5387
5526
  }, (error) => {
5388
5527
  cleanup();
5389
5528
  reject(error);
@@ -6011,7 +6150,7 @@ class ClaustrumConsumer {
6011
6150
  import { createHash as createHash3 } from "node:crypto";
6012
6151
  import { channel as channel2 } from "node:diagnostics_channel";
6013
6152
  import { readdir, stat as stat5 } from "node:fs/promises";
6014
- import { dirname as dirname6, join as join5, resolve as resolve9 } from "node:path";
6153
+ import { dirname as dirname6, join as join5, resolve as resolve10 } from "node:path";
6015
6154
  var sharedRosters = new Map;
6016
6155
  var FILE_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/;
6017
6156
  var WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/;
@@ -6075,12 +6214,12 @@ function unreachableConnect2() {
6075
6214
  return new ClaustrumUnreachableError;
6076
6215
  }
6077
6216
  function untilAborted(pending, signal) {
6078
- return new Promise((resolve10, reject) => {
6217
+ return new Promise((resolve11, reject) => {
6079
6218
  const abort = () => reject(signal.reason);
6080
6219
  signal.addEventListener("abort", abort, { once: true });
6081
6220
  pending.then((value) => {
6082
6221
  signal.removeEventListener("abort", abort);
6083
- resolve10(value);
6222
+ resolve11(value);
6084
6223
  }, (error) => {
6085
6224
  signal.removeEventListener("abort", abort);
6086
6225
  reject(error);
@@ -6207,7 +6346,7 @@ class ClaustrumDiscoveryHub {
6207
6346
  };
6208
6347
  const { consumer, hooks } = createHubMember(port, consumerOptions);
6209
6348
  entry.hooks = hooks;
6210
- const path = resolve9(entry.path);
6349
+ const path = resolve10(entry.path);
6211
6350
  const subscribers = sharedRosters.get(path) ?? new Set;
6212
6351
  const install = (roster) => {
6213
6352
  if (entry.closed || this.#active !== true || !this.#current || !this.#live(this.#current) || !hooks.roster() || this.#collides(hooks, roster))
@@ -6238,7 +6377,7 @@ class ClaustrumDiscoveryHub {
6238
6377
  return;
6239
6378
  entry.seen = JSON.stringify(decodedVaultRoster(roster));
6240
6379
  entry.hooks?.install(roster);
6241
- for (const install of sharedRosters.get(resolve9(entry.path)) ?? []) {
6380
+ for (const install of sharedRosters.get(resolve10(entry.path)) ?? []) {
6242
6381
  if (!this.#live(generation))
6243
6382
  return;
6244
6383
  if (install !== entry.receiveRoster)
@@ -6891,6 +7030,16 @@ function routingHandle(sessionId) {
6891
7030
  }
6892
7031
 
6893
7032
  // ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/cache-policy.js
7033
+ var CACHE_WARM_STOP_REASONS = [
7034
+ "cost-cap",
7035
+ "count-cap",
7036
+ "outside-hours",
7037
+ "session-ended",
7038
+ "unsupported"
7039
+ ];
7040
+ function isCacheWarmStopReason(value) {
7041
+ return CACHE_WARM_STOP_REASONS.some((reason) => reason === value);
7042
+ }
6894
7043
  var warned = new Set;
6895
7044
  function shape(value, seen = new Set) {
6896
7045
  if (typeof value !== "object" || value === null) {
@@ -6999,6 +7148,56 @@ function reportCacheWarmStopped(sessionId, input) {
6999
7148
  function isObject(value) {
7000
7149
  return typeof value === "object" && value !== null;
7001
7150
  }
7151
+ function isNonEmptyString(value) {
7152
+ return typeof value === "string" && value.length > 0;
7153
+ }
7154
+ function billingCache(value) {
7155
+ if (!isObject(value) || Array.isArray(value))
7156
+ return;
7157
+ const { ttlMs, implicit, warming } = value;
7158
+ const cache = {};
7159
+ if (!(ttlMs !== undefined && implicit !== undefined)) {
7160
+ if (typeof ttlMs === "number" && Number.isSafeInteger(ttlMs) && ttlMs > 0) {
7161
+ cache.ttl_ms = ttlMs;
7162
+ } else if (implicit === true) {
7163
+ cache.implicit = true;
7164
+ }
7165
+ }
7166
+ if (isObject(warming) && !Array.isArray(warming)) {
7167
+ const { on, stopReason } = warming;
7168
+ if (typeof on === "boolean") {
7169
+ cache.warming = {
7170
+ on,
7171
+ ...!on && isCacheWarmStopReason(stopReason) ? { stop_reason: stopReason } : {}
7172
+ };
7173
+ }
7174
+ }
7175
+ return Object.keys(cache).length > 0 ? cache : undefined;
7176
+ }
7177
+ function billingUsage(value) {
7178
+ if (!isObject(value) || Array.isArray(value))
7179
+ return;
7180
+ const usage = {};
7181
+ for (const [inputKey, payloadKey] of [
7182
+ ["input", "input"],
7183
+ ["output", "output"],
7184
+ ["cacheRead", "cache_read"],
7185
+ ["cacheWrite", "cache_write"],
7186
+ ["cacheWrite5m", "cache_write_5m"],
7187
+ ["cacheWrite1h", "cache_write_1h"],
7188
+ ["reasoning", "reasoning"]
7189
+ ]) {
7190
+ const count = value[inputKey];
7191
+ if (typeof count === "number" && Number.isSafeInteger(count) && count >= 0) {
7192
+ usage[payloadKey] = count;
7193
+ }
7194
+ }
7195
+ const reasoningIncludedInOutput = value.reasoningIncludedInOutput;
7196
+ if (typeof reasoningIncludedInOutput === "boolean") {
7197
+ usage.reasoning_included_in_output = reasoningIncludedInOutput;
7198
+ }
7199
+ return Object.keys(usage).length > 0 ? usage : undefined;
7200
+ }
7002
7201
  function turnNotes(sessionId) {
7003
7202
  try {
7004
7203
  const handle = routingHandle(sessionId);
@@ -7063,8 +7262,8 @@ async function askRouting(input) {
7063
7262
  return;
7064
7263
  const requested = input.deadlineMs ?? 500;
7065
7264
  const deadlineMs = Number.isNaN(requested) ? 500 : Math.min(2000, Math.max(1, requested));
7066
- const expired = new Promise((resolve10) => {
7067
- timer = setTimeout(() => resolve10(undefined), deadlineMs);
7265
+ const expired = new Promise((resolve11) => {
7266
+ timer = setTimeout(() => resolve11(undefined), deadlineMs);
7068
7267
  timer.unref();
7069
7268
  });
7070
7269
  const request2 = {
@@ -7097,6 +7296,47 @@ function reportRouting(input) {
7097
7296
  let payload;
7098
7297
  if ("kind" in input) {
7099
7298
  switch (input.kind) {
7299
+ case "billing": {
7300
+ const { attemptId, requestKind, credentialId, provider, model, outcome, accountId, providerRequestId, providerResponseId, userMessageId, status, attempt, chargeBasis, usage: inputUsage, usageByModel: inputUsageByModel, cache: inputCache } = input;
7301
+ if (!isNonEmptyString(attemptId) || !isNonEmptyString(credentialId) || !isNonEmptyString(provider) || !isNonEmptyString(model) || requestKind !== "primary" && requestKind !== "title" && requestKind !== "compaction" && requestKind !== "generate" && requestKind !== "keep_warm" && requestKind !== "prime" || outcome !== "completed" && outcome !== "cut" && outcome !== "failed")
7302
+ return;
7303
+ const usage = billingUsage(inputUsage);
7304
+ const cache = billingCache(inputCache);
7305
+ const usageByModel = [];
7306
+ if (Array.isArray(inputUsageByModel)) {
7307
+ for (const entry of inputUsageByModel) {
7308
+ if (!isObject(entry) || Array.isArray(entry))
7309
+ continue;
7310
+ const modelUsed = entry.modelUsed;
7311
+ if (!isNonEmptyString(modelUsed))
7312
+ continue;
7313
+ const modelUsage = billingUsage(entry.usage);
7314
+ if (!modelUsage)
7315
+ continue;
7316
+ usageByModel.push({ model_used: modelUsed, usage: modelUsage });
7317
+ }
7318
+ }
7319
+ payload = {
7320
+ kind: "billing",
7321
+ attempt_id: attemptId,
7322
+ request_kind: requestKind,
7323
+ credential_id: credentialId,
7324
+ provider,
7325
+ model,
7326
+ outcome,
7327
+ ...isNonEmptyString(accountId) ? { account_id: accountId } : {},
7328
+ ...isNonEmptyString(providerRequestId) ? { provider_request_id: providerRequestId } : {},
7329
+ ...isNonEmptyString(providerResponseId) ? { provider_response_id: providerResponseId } : {},
7330
+ ...isNonEmptyString(userMessageId) ? { user_message_id: userMessageId } : {},
7331
+ ...typeof status === "number" && Number.isInteger(status) && status >= 0 ? { status } : {},
7332
+ ...typeof attempt === "number" && Number.isInteger(attempt) && attempt >= 1 ? { attempt } : {},
7333
+ ...chargeBasis === "subscription_included" || chargeBasis === "metered_api" ? { charge_basis: chargeBasis } : {},
7334
+ ...usage ? { usage } : {},
7335
+ ...usageByModel.length > 0 ? { usage_by_model: usageByModel } : {},
7336
+ ...cache ? { cache } : {}
7337
+ };
7338
+ break;
7339
+ }
7100
7340
  case "turn_notes_supported": {
7101
7341
  const { model, supported } = input;
7102
7342
  if (typeof model !== "string" || model.length === 0 || typeof supported !== "boolean")
@@ -7323,7 +7563,7 @@ async function select(terminal, items, options) {
7323
7563
  writeLine("");
7324
7564
  renderedLines = lines;
7325
7565
  };
7326
- return new Promise((resolve10) => {
7566
+ return new Promise((resolve11) => {
7327
7567
  const wasRaw = stdin.isRaw ?? false;
7328
7568
  const cleanup = () => {
7329
7569
  if (cleaned)
@@ -7342,7 +7582,7 @@ async function select(terminal, items, options) {
7342
7582
  };
7343
7583
  const finish = (value) => {
7344
7584
  cleanup();
7345
- resolve10(value);
7585
+ resolve11(value);
7346
7586
  };
7347
7587
  const onSignal = () => finish(null);
7348
7588
  const onKey = (data) => {
@@ -7382,7 +7622,7 @@ async function select(terminal, items, options) {
7382
7622
  stdin.setRawMode(true);
7383
7623
  } catch {
7384
7624
  cleanup();
7385
- resolve10(null);
7625
+ resolve11(null);
7386
7626
  return;
7387
7627
  }
7388
7628
  stdin.resume();
@@ -7444,7 +7684,7 @@ class ByteTail {
7444
7684
  }
7445
7685
  var defaultCommandRunner = {
7446
7686
  run(file, args, options = {}) {
7447
- return new Promise((resolve10) => {
7687
+ return new Promise((resolve11) => {
7448
7688
  const started = performance.now();
7449
7689
  const timeoutMs = options.timeoutMs ?? 15000;
7450
7690
  const stderr = new ByteTail;
@@ -7462,7 +7702,7 @@ var defaultCommandRunner = {
7462
7702
  stdio: ["ignore", "pipe", "pipe"]
7463
7703
  });
7464
7704
  } catch {
7465
- resolve10({
7705
+ resolve11({
7466
7706
  exitCode: 1,
7467
7707
  stdout: "",
7468
7708
  stderr: "",
@@ -7497,7 +7737,7 @@ var defaultCommandRunner = {
7497
7737
  settled = true;
7498
7738
  if (timer)
7499
7739
  clearTimeout(timer);
7500
- resolve10({
7740
+ resolve11({
7501
7741
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code ?? 1,
7502
7742
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
7503
7743
  stderr: stderr.toString(),
@@ -8117,7 +8357,7 @@ function approveCommand(requestId, name) {
8117
8357
  async function connectSetupHost(plugin, host, io, terminal, fence) {
8118
8358
  if (hasVaultHost())
8119
8359
  throw new Error(VAULT_HOST_CONNECT_REFUSAL);
8120
- const { name, paths: input } = plugin.vault.hosts[host];
8360
+ const { name, displayName, paths: input } = plugin.vault.hosts[host];
8121
8361
  const paths = hostEnrollmentPaths(input);
8122
8362
  await fence();
8123
8363
  const client = await (io.connect ?? connectClaustrumEnrollmentClient)({
@@ -8131,6 +8371,7 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
8131
8371
  try {
8132
8372
  const manager = new ClaustrumEnrollmentManager({
8133
8373
  proposedName: name,
8374
+ displayName,
8134
8375
  paths,
8135
8376
  client,
8136
8377
  writeTokenFile: async (path, file) => {
@@ -9461,7 +9702,7 @@ function raceWithSignal(signal, operation) {
9461
9702
  return operation();
9462
9703
  if (signal.aborted)
9463
9704
  return Promise.reject(signal.reason);
9464
- return new Promise((resolve10, reject) => {
9705
+ return new Promise((resolve11, reject) => {
9465
9706
  const aborted = () => reject(signal.reason);
9466
9707
  signal.addEventListener("abort", aborted, { once: true });
9467
9708
  const finish = () => signal.removeEventListener("abort", aborted);
@@ -9473,7 +9714,7 @@ function raceWithSignal(signal, operation) {
9473
9714
  if (signal.aborted)
9474
9715
  reject(signal.reason);
9475
9716
  else
9476
- resolve10(value);
9717
+ resolve11(value);
9477
9718
  }, (error) => {
9478
9719
  finish();
9479
9720
  reject(signal.aborted ? signal.reason : error);
@@ -9562,7 +9803,7 @@ async function refreshClaudeOAuthToken(input) {
9562
9803
  try {
9563
9804
  if (attempt > 0) {
9564
9805
  const delay3 = baseDelayMs * 2 ** (attempt - 1);
9565
- await new Promise((resolve10) => setTimeoutImpl(resolve10, delay3));
9806
+ await new Promise((resolve11) => setTimeoutImpl(resolve11, delay3));
9566
9807
  }
9567
9808
  const signal = auxiliaryRequestSignal();
9568
9809
  const response = await raceWithSignal(signal, () => fetchImpl(TOKEN_URL, {
@@ -10048,7 +10289,7 @@ async function acquireRefreshFileLock2(options) {
10048
10289
  const EVICT_TTL = 5000;
10049
10290
  const MAX_STEAL_ATTEMPTS = 8;
10050
10291
  async function backoff() {
10051
- await new Promise((resolve10) => setTimeout(resolve10, Math.floor(Math.random() * 4)));
10292
+ await new Promise((resolve11) => setTimeout(resolve11, Math.floor(Math.random() * 4)));
10052
10293
  }
10053
10294
  async function lockIsLive() {
10054
10295
  try {
@@ -11008,6 +11249,7 @@ function positive(value, fallback) {
11008
11249
 
11009
11250
  class CacheKeepManager {
11010
11251
  targets = new Map;
11252
+ lastDropReasons = new Map;
11011
11253
  adapter;
11012
11254
  now;
11013
11255
  log;
@@ -11119,6 +11361,7 @@ class CacheKeepManager {
11119
11361
  warmCount: 0
11120
11362
  };
11121
11363
  this.targets.set(sessionKey, target);
11364
+ this.lastDropReasons.delete(sessionKey);
11122
11365
  this.totalBytes += bodyBytes;
11123
11366
  this.log?.debug("cachekeep captured target", { sessionKey, accountId });
11124
11367
  this.start();
@@ -11164,6 +11407,16 @@ class CacheKeepManager {
11164
11407
  this.totalBytes = 0;
11165
11408
  this.log?.debug("cachekeep stopped");
11166
11409
  }
11410
+ warming(sessionKey) {
11411
+ try {
11412
+ if (this.targets.has(sessionKey))
11413
+ return { on: true };
11414
+ const stopReason = this.lastDropReasons.get(sessionKey);
11415
+ return { on: false, ...stopReason !== undefined ? { stopReason } : {} };
11416
+ } catch {
11417
+ return { on: false };
11418
+ }
11419
+ }
11167
11420
  status() {
11168
11421
  const window = this.getWindow?.();
11169
11422
  return {
@@ -11573,6 +11826,16 @@ class CacheKeepManager {
11573
11826
  this.clearPlanTimer(target);
11574
11827
  this.totalBytes -= target.bodyBytes;
11575
11828
  this.targets.delete(sessionKey);
11829
+ if (reason !== null) {
11830
+ this.lastDropReasons.delete(sessionKey);
11831
+ this.lastDropReasons.set(sessionKey, reason);
11832
+ while (this.lastDropReasons.size > this.maxTargets * 4) {
11833
+ const oldest = this.lastDropReasons.keys().next();
11834
+ if (oldest.done)
11835
+ break;
11836
+ this.lastDropReasons.delete(oldest.value);
11837
+ }
11838
+ }
11576
11839
  if (reason !== null && target.hasWarmed && this.adapter.onWarmStopped) {
11577
11840
  this.report(() => this.adapter.onWarmStopped?.(sessionKey, { at: this.now(), reason }));
11578
11841
  }
@@ -11598,7 +11861,7 @@ import {
11598
11861
  extname as extname2,
11599
11862
  isAbsolute as isAbsolute3,
11600
11863
  join as join11,
11601
- resolve as resolve10
11864
+ resolve as resolve11
11602
11865
  } from "node:path";
11603
11866
  import {
11604
11867
  ClaustrumCredentialError as ClaustrumCredentialError7,
@@ -12012,7 +12275,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
12012
12275
  }
12013
12276
  function getHostClaustrumEnrollmentPaths(host, env = process.env, cwd = process.cwd()) {
12014
12277
  const configured = env[`${host.toUpperCase()}_ANTHROPIC_AUTH_CLAUSTRUM_ENROLLMENT_FILE`]?.trim();
12015
- const tokenPath = configured ? isAbsolute3(configured) ? configured : resolve10(cwd, configured) : join11(anthropicAuthStateRoot({
12278
+ const tokenPath = configured ? isAbsolute3(configured) ? configured : resolve11(cwd, configured) : join11(anthropicAuthStateRoot({
12016
12279
  xdgStateHome: env.XDG_STATE_HOME,
12017
12280
  home: homedir4(),
12018
12281
  acceptRelative: true
@@ -12808,7 +13071,6 @@ function createNativeCustody(options) {
12808
13071
  const onClose = new Set;
12809
13072
  const receipts = new WeakMap;
12810
13073
  const retryUsed = new WeakSet;
12811
- const reconnectReports = new WeakSet;
12812
13074
  let generation = 0;
12813
13075
  function check(signal) {
12814
13076
  if (authorityChanged)
@@ -12859,8 +13121,8 @@ function createNativeCustody(options) {
12859
13121
  let stopped = false;
12860
13122
  let inner;
12861
13123
  let finish = () => {};
12862
- const ended = new Promise((resolve11) => {
12863
- finish = resolve11;
13124
+ const ended = new Promise((resolve12) => {
13125
+ finish = resolve12;
12864
13126
  });
12865
13127
  const failed = (error) => stopped || closed2 || error instanceof NativeCustodyError ? { kind: "stopped" } : classifyVaultFailure(error) === "unreachable" ? { kind: "transport_lost", error: new ClaustrumUnreachableError } : { kind: "ended" };
12866
13128
  Promise.resolve().then(connection).then((owned) => {
@@ -12907,12 +13169,8 @@ function createNativeCustody(options) {
12907
13169
  if (held.closed || held.promoted)
12908
13170
  return;
12909
13171
  held.closed = true;
12910
- held.abort.abort(new NativeCustodyError("closed"));
12911
13172
  try {
12912
- if (held.primitive)
12913
- held.primitive.close();
12914
- else
12915
- held.client?.close();
13173
+ held.client?.close();
12916
13174
  } catch {}
12917
13175
  }
12918
13176
  function scheduleReconnect() {
@@ -12935,7 +13193,6 @@ function createNativeCustody(options) {
12935
13193
  return;
12936
13194
  const previous = primitive;
12937
13195
  const held = {
12938
- abort: new AbortController,
12939
13196
  closed: false,
12940
13197
  promoted: false
12941
13198
  };
@@ -12950,24 +13207,21 @@ function createNativeCustody(options) {
12950
13207
  return;
12951
13208
  }
12952
13209
  check();
12953
- held.primitive = makePrimitive(held.client);
12954
- if (retained)
12955
- held.primitive.retain(retained);
12956
- await held.primitive.discover(held.abort.signal);
13210
+ await held.client.listScoped();
12957
13211
  check();
12958
13212
  if (held.closed || primitive !== previous)
12959
13213
  return;
12960
13214
  if (previous instanceof HostedCustody && !previous.relayUnavailable)
12961
13215
  return;
12962
- if (retained)
12963
- held.primitive.retain(retained);
12964
- primitive = held.primitive;
13216
+ const oldClient = client;
13217
+ previous.replaceClient(held.client);
13218
+ previous.reachable();
12965
13219
  client = held.client;
12966
13220
  connecting = Promise.resolve(held.client);
12967
13221
  held.promoted = true;
12968
13222
  reconnectFailures = 0;
12969
13223
  try {
12970
- previous.close();
13224
+ oldClient?.close();
12971
13225
  } finally {
12972
13226
  options.onConnectionChanged?.();
12973
13227
  }
@@ -13073,7 +13327,7 @@ function createNativeCustody(options) {
13073
13327
  function requireReceipt(receipt) {
13074
13328
  if (!receipts.has(receipt))
13075
13329
  throw new NativeCustodyError("no-receipt");
13076
- if (receipts.get(receipt)?.generation !== generation)
13330
+ if (receipts.get(receipt) !== generation)
13077
13331
  throw new NativeCustodyError("route-unavailable");
13078
13332
  }
13079
13333
  function currentPrimitive() {
@@ -13081,13 +13335,7 @@ function createNativeCustody(options) {
13081
13335
  throw new NativeCustodyError("unavailable");
13082
13336
  return primitive;
13083
13337
  }
13084
- function previousConnectionReceipt(receipt) {
13085
- check();
13086
- requireReceipt(receipt);
13087
- return hosted2 && receipts.get(receipt)?.owner !== primitive;
13088
- }
13089
13338
  const custody = {
13090
- isPreviousConnectionReceipt: previousConnectionReceipt,
13091
13339
  get generation() {
13092
13340
  return generation;
13093
13341
  },
@@ -13116,7 +13364,7 @@ function createNativeCustody(options) {
13116
13364
  credentialType: "oauth"
13117
13365
  }, signal);
13118
13366
  check(signal);
13119
- receipts.set(receipt, { generation, owner });
13367
+ receipts.set(receipt, generation);
13120
13368
  return receipt;
13121
13369
  }, signal),
13122
13370
  reportFailure: (receipt, status, reporterSource) => run(async () => {
@@ -13124,13 +13372,6 @@ function createNativeCustody(options) {
13124
13372
  await ready();
13125
13373
  check();
13126
13374
  requireReceipt(receipt);
13127
- if (previousConnectionReceipt(receipt)) {
13128
- if (status === 401 && !reconnectReports.has(receipt)) {
13129
- reconnectReports.add(receipt);
13130
- logger3?.debug("Native custody 401 crossed a relay replacement; fresh authorization required");
13131
- }
13132
- return;
13133
- }
13134
13375
  await currentPrimitive().reportFailure(receipt, status, reporterSource);
13135
13376
  }),
13136
13377
  prepareRetry: async (served, signal) => {
@@ -13173,8 +13414,7 @@ function createNativeCustody(options) {
13173
13414
  if (current.assertedAccountIdentity !== served.assertedAccountIdentity) {
13174
13415
  return { retry: false, reason: "account-changed" };
13175
13416
  }
13176
- const replacementReceipt = previousConnectionReceipt(served) && !previousConnectionReceipt(current);
13177
- if (current.fromKeptReceipt || !replacementReceipt && !(current.recordVersion > served.recordVersion)) {
13417
+ if (current.fromKeptReceipt || !(current.recordVersion > served.recordVersion)) {
13178
13418
  return { retry: false, reason: "version-not-newer" };
13179
13419
  }
13180
13420
  if (hosted2)
@@ -13971,7 +14211,387 @@ import {
13971
14211
  writeFile as writeFile2
13972
14212
  } from "node:fs/promises";
13973
14213
  import { tmpdir as tmpdir5 } from "node:os";
13974
- import { join as join13, resolve as resolve11 } from "node:path";
14214
+ import { join as join13, resolve as resolve12 } from "node:path";
14215
+
14216
+ // src/sse.ts
14217
+ import { types as utilTypes2 } from "node:util";
14218
+ var DEFAULT_SSE_MAX_FRAME_BYTES = 8 * 1024 * 1024;
14219
+ var LF = 10;
14220
+ var CR = 13;
14221
+
14222
+ class SseFrameTooLargeError extends Error {
14223
+ code = "SSE_FRAME_TOO_LARGE";
14224
+ maxFrameBytes;
14225
+ constructor(maxFrameBytes) {
14226
+ super(`SSE frame exceeded ${maxFrameBytes} bytes without a terminator`);
14227
+ this.name = "SseFrameTooLargeError";
14228
+ this.maxFrameBytes = maxFrameBytes;
14229
+ }
14230
+ }
14231
+ function readMaxFrameBytes(options) {
14232
+ if (options === undefined)
14233
+ return DEFAULT_SSE_MAX_FRAME_BYTES;
14234
+ if (options === null || typeof options !== "object" || utilTypes2.isProxy(options))
14235
+ throw new TypeError("SSE framer options must be an object");
14236
+ const field = Object.getOwnPropertyDescriptor(options, "maxFrameBytes");
14237
+ if (field === undefined)
14238
+ return DEFAULT_SSE_MAX_FRAME_BYTES;
14239
+ if (!("value" in field))
14240
+ throw new TypeError("SSE framer maxFrameBytes must be a data property");
14241
+ const value = field.value;
14242
+ if (value === undefined)
14243
+ return DEFAULT_SSE_MAX_FRAME_BYTES;
14244
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
14245
+ throw new TypeError("SSE framer maxFrameBytes must be a positive integer");
14246
+ return value;
14247
+ }
14248
+ function createSseFramer(options) {
14249
+ const maxFrameBytes = readMaxFrameBytes(options);
14250
+ let carry = new Uint8Array(0);
14251
+ let carryLength = 0;
14252
+ let carryAtLineStart = true;
14253
+ let pendingCr = false;
14254
+ let pendingBlank = false;
14255
+ let failed = false;
14256
+ const fail = () => {
14257
+ failed = true;
14258
+ carry = new Uint8Array(0);
14259
+ carryLength = 0;
14260
+ throw new SseFrameTooLargeError(maxFrameBytes);
14261
+ };
14262
+ const keep = (bytes, append) => {
14263
+ const needed = (append ? carryLength : 0) + bytes.length;
14264
+ if (needed > maxFrameBytes)
14265
+ fail();
14266
+ if (carry.length < needed) {
14267
+ const grown = new Uint8Array(Math.min(maxFrameBytes, Math.max(needed, carry.length * 2, 1024)));
14268
+ if (append)
14269
+ grown.set(carry.subarray(0, carryLength), 0);
14270
+ carry = grown;
14271
+ }
14272
+ carry.set(bytes, append ? carryLength : 0);
14273
+ carryLength = needed;
14274
+ };
14275
+ const push = (chunk) => {
14276
+ if (failed)
14277
+ throw new SseFrameTooLargeError(maxFrameBytes);
14278
+ if (!utilTypes2.isUint8Array(chunk))
14279
+ throw new TypeError("SSE framer input must be a Uint8Array");
14280
+ const end = chunk.length;
14281
+ if (end === 0)
14282
+ return [];
14283
+ const frames = [];
14284
+ let frameStart = 0;
14285
+ let pos = 0;
14286
+ let line = carryAtLineStart ? 0 : -1;
14287
+ const complete = (frameEnd) => {
14288
+ if (carryLength > 0) {
14289
+ const size = carryLength + frameEnd;
14290
+ if (size > maxFrameBytes)
14291
+ fail();
14292
+ const joined = new Uint8Array(size);
14293
+ joined.set(carry.subarray(0, carryLength), 0);
14294
+ joined.set(chunk.subarray(0, frameEnd), carryLength);
14295
+ carryLength = 0;
14296
+ frames.push(joined);
14297
+ } else {
14298
+ if (frameEnd - frameStart > maxFrameBytes)
14299
+ fail();
14300
+ frames.push(chunk.subarray(frameStart, frameEnd));
14301
+ }
14302
+ frameStart = frameEnd;
14303
+ };
14304
+ if (pendingCr) {
14305
+ pendingCr = false;
14306
+ if (chunk[0] === LF)
14307
+ pos = 1;
14308
+ if (pendingBlank) {
14309
+ pendingBlank = false;
14310
+ complete(pos);
14311
+ }
14312
+ line = pos;
14313
+ }
14314
+ let nextLf = -2;
14315
+ let nextCr = -2;
14316
+ while (pos < end) {
14317
+ if (nextLf !== -1 && nextLf < pos)
14318
+ nextLf = chunk.indexOf(LF, pos);
14319
+ if (nextCr !== -1 && nextCr < pos)
14320
+ nextCr = chunk.indexOf(CR, pos);
14321
+ let terminator;
14322
+ if (nextLf === -1)
14323
+ terminator = nextCr;
14324
+ else if (nextCr === -1)
14325
+ terminator = nextLf;
14326
+ else
14327
+ terminator = Math.min(nextLf, nextCr);
14328
+ if (terminator === -1)
14329
+ break;
14330
+ let terminatorEnd = terminator + 1;
14331
+ if (chunk[terminator] === CR) {
14332
+ if (terminatorEnd === end) {
14333
+ pendingCr = true;
14334
+ pendingBlank = terminator === line;
14335
+ line = end;
14336
+ break;
14337
+ }
14338
+ if (chunk[terminatorEnd] === LF)
14339
+ terminatorEnd += 1;
14340
+ }
14341
+ if (terminator === line)
14342
+ complete(terminatorEnd);
14343
+ line = terminatorEnd;
14344
+ pos = terminatorEnd;
14345
+ }
14346
+ if (frameStart < end) {
14347
+ keep(chunk.subarray(frameStart, end), carryLength > 0);
14348
+ carryAtLineStart = line === end;
14349
+ } else {
14350
+ carryAtLineStart = true;
14351
+ }
14352
+ return frames;
14353
+ };
14354
+ const finish = () => {
14355
+ if (failed)
14356
+ throw new SseFrameTooLargeError(maxFrameBytes);
14357
+ const tail = carryLength > 0 ? carry.slice(0, carryLength) : undefined;
14358
+ carry = new Uint8Array(0);
14359
+ carryLength = 0;
14360
+ carryAtLineStart = true;
14361
+ pendingCr = false;
14362
+ pendingBlank = false;
14363
+ return tail;
14364
+ };
14365
+ return Object.freeze({
14366
+ push,
14367
+ finish,
14368
+ get bufferedBytes() {
14369
+ return carryLength;
14370
+ }
14371
+ });
14372
+ }
14373
+ var frameDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
14374
+ var BYTE_ORDER_MARK = 65279;
14375
+ function readStreamStart(options) {
14376
+ if (options === null || typeof options !== "object" || utilTypes2.isProxy(options))
14377
+ return false;
14378
+ const field = Object.getOwnPropertyDescriptor(options, "streamStart");
14379
+ return field !== undefined && "value" in field && field.value === true;
14380
+ }
14381
+ function decodeSseFrame(frame, options) {
14382
+ const text = frameDecoder.decode(frame);
14383
+ return text.charCodeAt(0) === BYTE_ORDER_MARK && readStreamStart(options) ? text.slice(1) : text;
14384
+ }
14385
+ function parseSseFrame(frame) {
14386
+ const text = typeof frame === "string" ? frame : decodeSseFrame(frame);
14387
+ const result = {};
14388
+ let dataLines;
14389
+ for (const line of text.split(/\r\n|\r|\n/)) {
14390
+ if (line === "" || line.charCodeAt(0) === 58)
14391
+ continue;
14392
+ const colon = line.indexOf(":");
14393
+ const field = colon === -1 ? line : line.slice(0, colon);
14394
+ let value = colon === -1 ? "" : line.slice(colon + 1);
14395
+ if (value.charCodeAt(0) === 32)
14396
+ value = value.slice(1);
14397
+ switch (field) {
14398
+ case "event":
14399
+ result.event = value;
14400
+ break;
14401
+ case "data":
14402
+ if (dataLines)
14403
+ dataLines.push(value);
14404
+ else
14405
+ dataLines = [value];
14406
+ break;
14407
+ case "id":
14408
+ if (!value.includes("\x00"))
14409
+ result.id = value;
14410
+ break;
14411
+ case "retry":
14412
+ if (/^[0-9]+$/.test(value))
14413
+ result.retry = Number(value);
14414
+ break;
14415
+ }
14416
+ }
14417
+ if (dataLines)
14418
+ result.data = dataLines.join(`
14419
+ `);
14420
+ return result;
14421
+ }
14422
+ function isTerminatedSseFrame(frame) {
14423
+ const length = frame.length;
14424
+ if (length === 0)
14425
+ return false;
14426
+ const last = frame[length - 1];
14427
+ if (last !== LF && last !== CR)
14428
+ return false;
14429
+ let before = length - 1;
14430
+ if (last === LF && before > 0 && frame[before - 1] === CR)
14431
+ before -= 1;
14432
+ if (before === 0)
14433
+ return true;
14434
+ const previous = frame[before - 1];
14435
+ return previous === LF || previous === CR;
14436
+ }
14437
+ var ERROR_NEEDLE = Buffer.from("error");
14438
+ var UNICODE_ESCAPE_NEEDLE = Buffer.from("\\u");
14439
+ function isSseCandidateFrame(frame) {
14440
+ const view = Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
14441
+ return view.indexOf(ERROR_NEEDLE) !== -1 || view.indexOf(UNICODE_ESCAPE_NEEDLE) !== -1;
14442
+ }
14443
+
14444
+ // src/stream-completion.ts
14445
+ var timings = new WeakMap;
14446
+ function copyStreamResponseTiming(source, target, sent, timingSource = "physical_fetch") {
14447
+ const timing = timings.get(source);
14448
+ if (timing)
14449
+ timings.set(target, timing);
14450
+ else if (sent !== undefined)
14451
+ timings.set(target, {
14452
+ sent,
14453
+ headers: performance.now(),
14454
+ contentLength: responseHeaders(target.headers)["content-length"],
14455
+ source: timingSource
14456
+ });
14457
+ return target;
14458
+ }
14459
+ function responseHeaders(headers) {
14460
+ const result = {};
14461
+ const rules = {
14462
+ "request-id": /^req_[A-Za-z0-9_-]{1,128}$/,
14463
+ "cf-ray": /^[a-fA-F0-9]{16,32}(?:-[A-Z]{3})?$/,
14464
+ "content-type": /^(?:text\/event-stream|application\/json|text\/plain)(?:;\s*charset=utf-8)?$/i,
14465
+ "content-encoding": /^(?:gzip|br|deflate|identity)$/,
14466
+ "content-length": /^\d{1,16}$/
14467
+ };
14468
+ for (const [name, rule] of Object.entries(rules)) {
14469
+ const value = headers.get(name);
14470
+ if (value !== null && rule.test(value))
14471
+ result[name] = value;
14472
+ }
14473
+ return result;
14474
+ }
14475
+ function safeIncompleteStreamDiagnostics(input) {
14476
+ const count = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0;
14477
+ return {
14478
+ response_headers: responseHeaders({
14479
+ get: (name) => input.response_headers[name] ?? null
14480
+ }),
14481
+ response_bytes: count(input.response_bytes),
14482
+ sse_events: count(input.sse_events),
14483
+ ...input.send_to_headers_ms !== undefined ? { send_to_headers_ms: count(input.send_to_headers_ms) } : {},
14484
+ ...input.timing_source === "physical_fetch" || input.timing_source === "credential_scope" ? { timing_source: input.timing_source } : {},
14485
+ headers_to_eof_ms: count(input.headers_to_eof_ms)
14486
+ };
14487
+ }
14488
+ function createAnthropicStreamCompletion(response) {
14489
+ const framer = createSseFramer();
14490
+ const timing = timings.get(response);
14491
+ const headers = responseHeaders(response.headers);
14492
+ const contentLength = timing?.contentLength;
14493
+ if (contentLength !== undefined)
14494
+ headers["content-length"] = contentLength;
14495
+ const headersAt = timing?.headers ?? performance.now();
14496
+ let bytes = 0;
14497
+ let events = 0;
14498
+ let stopped = false;
14499
+ let failed = false;
14500
+ let streamStart = true;
14501
+ let eofAt;
14502
+ const inspect = (frame) => {
14503
+ const data = parseSseFrame(decodeSseFrame(frame, { streamStart })).data;
14504
+ streamStart = false;
14505
+ if (!data || data === "[DONE]")
14506
+ return;
14507
+ events++;
14508
+ try {
14509
+ const event = JSON.parse(data);
14510
+ if (event?.type === "message_stop")
14511
+ stopped = true;
14512
+ if (event?.type === "error")
14513
+ failed = true;
14514
+ } catch {}
14515
+ };
14516
+ const end = () => {
14517
+ if (eofAt !== undefined)
14518
+ return;
14519
+ eofAt = performance.now();
14520
+ const tail = framer.finish();
14521
+ if (tail && isTerminatedSseFrame(tail))
14522
+ inspect(tail);
14523
+ };
14524
+ return {
14525
+ end,
14526
+ push(chunk) {
14527
+ bytes += chunk.byteLength;
14528
+ for (const frame of framer.push(chunk))
14529
+ inspect(frame);
14530
+ },
14531
+ finish() {
14532
+ end();
14533
+ if (stopped || failed)
14534
+ return;
14535
+ const diagnostics = {
14536
+ response_headers: headers,
14537
+ response_bytes: bytes,
14538
+ sse_events: events,
14539
+ ...timing ? {
14540
+ send_to_headers_ms: Math.max(0, Math.round(timing.headers - timing.sent)),
14541
+ timing_source: timing.source
14542
+ } : {},
14543
+ headers_to_eof_ms: Math.max(0, Math.round((eofAt ?? performance.now()) - headersAt))
14544
+ };
14545
+ logger2.warn("stream", "Anthropic connection closed before message_stop", {
14546
+ ...diagnostics
14547
+ });
14548
+ return Object.assign(new Error("Anthropic connection reset: stream ended before message_stop (ECONNRESET)"), { code: "ECONNRESET", syscall: "anthropic-sse", diagnostics });
14549
+ }
14550
+ };
14551
+ }
14552
+ function guardAnthropicStreamResponse(response, onIncomplete) {
14553
+ if (!response.ok)
14554
+ return response;
14555
+ const completion = createAnthropicStreamCompletion(response);
14556
+ const reader = response.body?.getReader();
14557
+ return copyStreamResponseTiming(response, new Response(new ReadableStream({
14558
+ async pull(controller) {
14559
+ try {
14560
+ const chunk = await reader?.read();
14561
+ if (!chunk || chunk.done) {
14562
+ completion.end();
14563
+ const error = completion.finish();
14564
+ reader?.releaseLock();
14565
+ if (error) {
14566
+ await onIncomplete?.(error.diagnostics);
14567
+ controller.error(error);
14568
+ } else
14569
+ controller.close();
14570
+ return;
14571
+ }
14572
+ completion.push(chunk.value);
14573
+ controller.enqueue(chunk.value);
14574
+ } catch (error) {
14575
+ controller.error(error);
14576
+ await reader?.cancel(error).catch(() => {});
14577
+ reader?.releaseLock();
14578
+ }
14579
+ },
14580
+ async cancel(reason) {
14581
+ try {
14582
+ await reader?.cancel(reason);
14583
+ } finally {
14584
+ reader?.releaseLock();
14585
+ }
14586
+ }
14587
+ }, { highWaterMark: 0 }), {
14588
+ status: response.status,
14589
+ statusText: response.statusText,
14590
+ headers: response.headers
14591
+ }));
14592
+ }
14593
+
14594
+ // src/dump.ts
13975
14595
  var CLAUDE_DUMP_COMMAND_NAME = "claude-dump";
13976
14596
  var DUMP_STATUS_TITLE = "## Claude Dump Status";
13977
14597
  var DUMP_ENABLED_TITLE = "## Claude Dump Enabled";
@@ -14017,7 +14637,7 @@ function getDumpMaxBytes() {
14017
14637
  return Number.isFinite(configured) && configured >= 0 ? Math.floor(configured) : DEFAULT_DUMP_MAX_BYTES;
14018
14638
  }
14019
14639
  function isConfiguredDumpDirectory(path2) {
14020
- return resolve11(path2) === resolve11(getDumpDirectory());
14640
+ return resolve12(path2) === resolve12(getDumpDirectory());
14021
14641
  }
14022
14642
  function isDumpArtifactFileName(name) {
14023
14643
  const stem = name.replace(DUMP_ARTIFACT_SUFFIX_PATTERN, "");
@@ -14074,7 +14694,7 @@ async function sweepDumpDirectory(options) {
14074
14694
  const dumpDirStats = await lstat5(dumpDir);
14075
14695
  if (dumpDirStats.isSymbolicLink())
14076
14696
  return emptyResult;
14077
- const protectedPaths = new Set((options.protectedPaths ?? []).map((path2) => resolve11(path2)));
14697
+ const protectedPaths = new Set((options.protectedPaths ?? []).map((path2) => resolve12(path2)));
14078
14698
  const entries = await readdir2(dumpDir, { withFileTypes: true });
14079
14699
  const files = [];
14080
14700
  await Promise.all(entries.map(async (entry) => {
@@ -14112,7 +14732,7 @@ async function sweepDumpDirectory(options) {
14112
14732
  };
14113
14733
  const partials = files.filter((file) => file.partial).sort((left, right) => left.mtimeMs - right.mtimeMs || left.path.localeCompare(right.path));
14114
14734
  for (const file of partials) {
14115
- if (protectedPaths.has(resolve11(file.path)))
14735
+ if (protectedPaths.has(resolve12(file.path)))
14116
14736
  continue;
14117
14737
  if (now - file.mtimeMs < partialStaleMs)
14118
14738
  continue;
@@ -14136,7 +14756,7 @@ async function sweepDumpDirectory(options) {
14136
14756
  break;
14137
14757
  if (now - group.newestMtimeMs < minAgeMs)
14138
14758
  continue;
14139
- if (group.files.some((file) => protectedPaths.has(resolve11(file.path)))) {
14759
+ if (group.files.some((file) => protectedPaths.has(resolve12(file.path)))) {
14140
14760
  continue;
14141
14761
  }
14142
14762
  for (const file of group.files)
@@ -14519,6 +15139,7 @@ function createDumpResponseObserver(handle, status) {
14519
15139
  let message;
14520
15140
  let complete = false;
14521
15141
  let failed = false;
15142
+ let incomplete;
14522
15143
  const record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
14523
15144
  const replyTextEdges = () => message && !failed && status >= 200 && status < 300 ? [...edges.values()] : undefined;
14524
15145
  const append = (edge, text) => {
@@ -14593,16 +15214,18 @@ function createDumpResponseObserver(handle, status) {
14593
15214
  }
14594
15215
  },
14595
15216
  replyTextEdges,
14596
- fail() {
15217
+ fail(diagnostics) {
14597
15218
  failed = true;
15219
+ incomplete = diagnostics;
14598
15220
  },
14599
15221
  async finish() {
14600
- if (!message)
15222
+ if (!message && !incomplete)
14601
15223
  return;
14602
15224
  await dumpResponseArtifact(handle, {
14603
15225
  status,
14604
15226
  message,
14605
15227
  complete: complete && !failed,
15228
+ incomplete_stream: incomplete,
14606
15229
  ...complete ? { reply_text_edges: replyTextEdges() } : {}
14607
15230
  });
14608
15231
  }
@@ -14628,6 +15251,8 @@ async function dumpResponseArtifact(handle, input) {
14628
15251
  artifact.stop_reason = message.stop_reason;
14629
15252
  if (input.provider_error)
14630
15253
  artifact.provider_error = input.provider_error;
15254
+ if (input.incomplete_stream)
15255
+ artifact.incomplete_stream = safeIncompleteStreamDiagnostics(input.incomplete_stream);
14631
15256
  if (input.reply_text_edges && input.complete !== false && input.status >= 200 && input.status < 300 && !input.provider_error)
14632
15257
  artifact.reply_text_edges = input.reply_text_edges.map(({ index, leading, trailing, chars }) => ({
14633
15258
  index,
@@ -14777,236 +15402,6 @@ function isOpenAIReasoningSignature(value) {
14777
15402
  // src/provider-error.ts
14778
15403
  import { Buffer as Buffer2 } from "node:buffer";
14779
15404
  import { types as utilTypes3 } from "node:util";
14780
-
14781
- // src/sse.ts
14782
- import { types as utilTypes2 } from "node:util";
14783
- var DEFAULT_SSE_MAX_FRAME_BYTES = 8 * 1024 * 1024;
14784
- var LF = 10;
14785
- var CR = 13;
14786
-
14787
- class SseFrameTooLargeError extends Error {
14788
- code = "SSE_FRAME_TOO_LARGE";
14789
- maxFrameBytes;
14790
- constructor(maxFrameBytes) {
14791
- super(`SSE frame exceeded ${maxFrameBytes} bytes without a terminator`);
14792
- this.name = "SseFrameTooLargeError";
14793
- this.maxFrameBytes = maxFrameBytes;
14794
- }
14795
- }
14796
- function readMaxFrameBytes(options) {
14797
- if (options === undefined)
14798
- return DEFAULT_SSE_MAX_FRAME_BYTES;
14799
- if (options === null || typeof options !== "object" || utilTypes2.isProxy(options))
14800
- throw new TypeError("SSE framer options must be an object");
14801
- const field = Object.getOwnPropertyDescriptor(options, "maxFrameBytes");
14802
- if (field === undefined)
14803
- return DEFAULT_SSE_MAX_FRAME_BYTES;
14804
- if (!("value" in field))
14805
- throw new TypeError("SSE framer maxFrameBytes must be a data property");
14806
- const value = field.value;
14807
- if (value === undefined)
14808
- return DEFAULT_SSE_MAX_FRAME_BYTES;
14809
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)
14810
- throw new TypeError("SSE framer maxFrameBytes must be a positive integer");
14811
- return value;
14812
- }
14813
- function createSseFramer(options) {
14814
- const maxFrameBytes = readMaxFrameBytes(options);
14815
- let carry = new Uint8Array(0);
14816
- let carryLength = 0;
14817
- let carryAtLineStart = true;
14818
- let pendingCr = false;
14819
- let pendingBlank = false;
14820
- let failed = false;
14821
- const fail = () => {
14822
- failed = true;
14823
- carry = new Uint8Array(0);
14824
- carryLength = 0;
14825
- throw new SseFrameTooLargeError(maxFrameBytes);
14826
- };
14827
- const keep = (bytes, append) => {
14828
- const needed = (append ? carryLength : 0) + bytes.length;
14829
- if (needed > maxFrameBytes)
14830
- fail();
14831
- if (carry.length < needed) {
14832
- const grown = new Uint8Array(Math.min(maxFrameBytes, Math.max(needed, carry.length * 2, 1024)));
14833
- if (append)
14834
- grown.set(carry.subarray(0, carryLength), 0);
14835
- carry = grown;
14836
- }
14837
- carry.set(bytes, append ? carryLength : 0);
14838
- carryLength = needed;
14839
- };
14840
- const push = (chunk) => {
14841
- if (failed)
14842
- throw new SseFrameTooLargeError(maxFrameBytes);
14843
- if (!utilTypes2.isUint8Array(chunk))
14844
- throw new TypeError("SSE framer input must be a Uint8Array");
14845
- const end = chunk.length;
14846
- if (end === 0)
14847
- return [];
14848
- const frames = [];
14849
- let frameStart = 0;
14850
- let pos = 0;
14851
- let line = carryAtLineStart ? 0 : -1;
14852
- const complete = (frameEnd) => {
14853
- if (carryLength > 0) {
14854
- const size = carryLength + frameEnd;
14855
- if (size > maxFrameBytes)
14856
- fail();
14857
- const joined = new Uint8Array(size);
14858
- joined.set(carry.subarray(0, carryLength), 0);
14859
- joined.set(chunk.subarray(0, frameEnd), carryLength);
14860
- carryLength = 0;
14861
- frames.push(joined);
14862
- } else {
14863
- if (frameEnd - frameStart > maxFrameBytes)
14864
- fail();
14865
- frames.push(chunk.subarray(frameStart, frameEnd));
14866
- }
14867
- frameStart = frameEnd;
14868
- };
14869
- if (pendingCr) {
14870
- pendingCr = false;
14871
- if (chunk[0] === LF)
14872
- pos = 1;
14873
- if (pendingBlank) {
14874
- pendingBlank = false;
14875
- complete(pos);
14876
- }
14877
- line = pos;
14878
- }
14879
- let nextLf = -2;
14880
- let nextCr = -2;
14881
- while (pos < end) {
14882
- if (nextLf !== -1 && nextLf < pos)
14883
- nextLf = chunk.indexOf(LF, pos);
14884
- if (nextCr !== -1 && nextCr < pos)
14885
- nextCr = chunk.indexOf(CR, pos);
14886
- let terminator;
14887
- if (nextLf === -1)
14888
- terminator = nextCr;
14889
- else if (nextCr === -1)
14890
- terminator = nextLf;
14891
- else
14892
- terminator = Math.min(nextLf, nextCr);
14893
- if (terminator === -1)
14894
- break;
14895
- let terminatorEnd = terminator + 1;
14896
- if (chunk[terminator] === CR) {
14897
- if (terminatorEnd === end) {
14898
- pendingCr = true;
14899
- pendingBlank = terminator === line;
14900
- line = end;
14901
- break;
14902
- }
14903
- if (chunk[terminatorEnd] === LF)
14904
- terminatorEnd += 1;
14905
- }
14906
- if (terminator === line)
14907
- complete(terminatorEnd);
14908
- line = terminatorEnd;
14909
- pos = terminatorEnd;
14910
- }
14911
- if (frameStart < end) {
14912
- keep(chunk.subarray(frameStart, end), carryLength > 0);
14913
- carryAtLineStart = line === end;
14914
- } else {
14915
- carryAtLineStart = true;
14916
- }
14917
- return frames;
14918
- };
14919
- const finish = () => {
14920
- if (failed)
14921
- throw new SseFrameTooLargeError(maxFrameBytes);
14922
- const tail = carryLength > 0 ? carry.slice(0, carryLength) : undefined;
14923
- carry = new Uint8Array(0);
14924
- carryLength = 0;
14925
- carryAtLineStart = true;
14926
- pendingCr = false;
14927
- pendingBlank = false;
14928
- return tail;
14929
- };
14930
- return Object.freeze({
14931
- push,
14932
- finish,
14933
- get bufferedBytes() {
14934
- return carryLength;
14935
- }
14936
- });
14937
- }
14938
- var frameDecoder = new TextDecoder("utf-8", { ignoreBOM: true });
14939
- var BYTE_ORDER_MARK = 65279;
14940
- function readStreamStart(options) {
14941
- if (options === null || typeof options !== "object" || utilTypes2.isProxy(options))
14942
- return false;
14943
- const field = Object.getOwnPropertyDescriptor(options, "streamStart");
14944
- return field !== undefined && "value" in field && field.value === true;
14945
- }
14946
- function decodeSseFrame(frame, options) {
14947
- const text = frameDecoder.decode(frame);
14948
- return text.charCodeAt(0) === BYTE_ORDER_MARK && readStreamStart(options) ? text.slice(1) : text;
14949
- }
14950
- function parseSseFrame(frame) {
14951
- const text = typeof frame === "string" ? frame : decodeSseFrame(frame);
14952
- const result = {};
14953
- let dataLines;
14954
- for (const line of text.split(/\r\n|\r|\n/)) {
14955
- if (line === "" || line.charCodeAt(0) === 58)
14956
- continue;
14957
- const colon = line.indexOf(":");
14958
- const field = colon === -1 ? line : line.slice(0, colon);
14959
- let value = colon === -1 ? "" : line.slice(colon + 1);
14960
- if (value.charCodeAt(0) === 32)
14961
- value = value.slice(1);
14962
- switch (field) {
14963
- case "event":
14964
- result.event = value;
14965
- break;
14966
- case "data":
14967
- if (dataLines)
14968
- dataLines.push(value);
14969
- else
14970
- dataLines = [value];
14971
- break;
14972
- case "id":
14973
- if (!value.includes("\x00"))
14974
- result.id = value;
14975
- break;
14976
- case "retry":
14977
- if (/^[0-9]+$/.test(value))
14978
- result.retry = Number(value);
14979
- break;
14980
- }
14981
- }
14982
- if (dataLines)
14983
- result.data = dataLines.join(`
14984
- `);
14985
- return result;
14986
- }
14987
- function isTerminatedSseFrame(frame) {
14988
- const length = frame.length;
14989
- if (length === 0)
14990
- return false;
14991
- const last = frame[length - 1];
14992
- if (last !== LF && last !== CR)
14993
- return false;
14994
- let before = length - 1;
14995
- if (last === LF && before > 0 && frame[before - 1] === CR)
14996
- before -= 1;
14997
- if (before === 0)
14998
- return true;
14999
- const previous = frame[before - 1];
15000
- return previous === LF || previous === CR;
15001
- }
15002
- var ERROR_NEEDLE = Buffer.from("error");
15003
- var UNICODE_ESCAPE_NEEDLE = Buffer.from("\\u");
15004
- function isSseCandidateFrame(frame) {
15005
- const view = Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength);
15006
- return view.indexOf(ERROR_NEEDLE) !== -1 || view.indexOf(UNICODE_ESCAPE_NEEDLE) !== -1;
15007
- }
15008
-
15009
- // src/provider-error.ts
15010
15405
  var PROVIDER_ERROR_REDACTION = "[REDACTED]";
15011
15406
  var PROVIDER_ERROR_WITHHELD_MESSAGE = "Provider error details were withheld because the request attempt has ended";
15012
15407
  var PROVIDER_ERROR_OVERSIZED_MESSAGE = "Provider error body exceeded the redaction size limit and was withheld";
@@ -16185,6 +16580,7 @@ function createProviderErrorRedactor(secrets) {
16185
16580
  }
16186
16581
  var PROVIDER_ERROR_RESPONSE_SCOPE_USED_MESSAGE = "Provider error response scope accepts one response while live";
16187
16582
  function createProviderErrorResponseScope(secrets, mode) {
16583
+ const sentAt = performance.now();
16188
16584
  if (mode !== "event-stream" && mode !== "http")
16189
16585
  throw new TypeError("Provider error response scope mode must be 'event-stream' or 'http'");
16190
16586
  const framing = mode;
@@ -16193,8 +16589,8 @@ function createProviderErrorResponseScope(secrets, mode) {
16193
16589
  wrappedBodies: 0
16194
16590
  };
16195
16591
  let resolveSettled = () => {};
16196
- const settled = new Promise((resolve12) => {
16197
- resolveSettled = resolve12;
16592
+ const settled = new Promise((resolve13) => {
16593
+ resolveSettled = resolve13;
16198
16594
  });
16199
16595
  let retired = false;
16200
16596
  let used = false;
@@ -16229,7 +16625,7 @@ function createProviderErrorResponseScope(secrets, mode) {
16229
16625
  retire("untouched");
16230
16626
  if (!(result instanceof Response))
16231
16627
  throw new TypeError("Provider error redactor expects a Response");
16232
- return result;
16628
+ return copyStreamResponseTiming(response, result, sentAt, "credential_scope");
16233
16629
  },
16234
16630
  redactError(error) {
16235
16631
  return redactErrorWith(error, state);
@@ -17839,7 +18235,7 @@ import { basename as basename8, dirname as dirname15, join as join17 } from "nod
17839
18235
  // src/pool-paths.ts
17840
18236
  import { createHash as createHash17 } from "node:crypto";
17841
18237
  import { realpath as realpath3 } from "node:fs/promises";
17842
- import { basename as basename7, dirname as dirname14, join as join16, resolve as resolve12 } from "node:path";
18238
+ import { basename as basename7, dirname as dirname14, join as join16, resolve as resolve13 } from "node:path";
17843
18239
 
17844
18240
  // src/sticky-routing.ts
17845
18241
  import { createHash as createHash16, randomUUID as randomUUID12 } from "node:crypto";
@@ -18026,7 +18422,7 @@ async function acquirePoolLock(spec, defaults, env) {
18026
18422
  });
18027
18423
  }
18028
18424
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
18029
- await new Promise((resolve12) => setTimeout(resolve12, Math.min(options.retryMs + jitter, remaining)));
18425
+ await new Promise((resolve13) => setTimeout(resolve13, Math.min(options.retryMs + jitter, remaining)));
18030
18426
  }
18031
18427
  }
18032
18428
  function definedOnly(spec) {
@@ -20708,11 +21104,11 @@ class PoolQuotaWriter {
20708
21104
  const left = deadline - performance.now();
20709
21105
  if (left <= 0)
20710
21106
  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);
20711
- await new Promise((resolve12) => {
21107
+ await new Promise((resolve13) => {
20712
21108
  const done = () => {
20713
21109
  clearTimeout(timer);
20714
21110
  this.wake.delete(done);
20715
- resolve12();
21111
+ resolve13();
20716
21112
  };
20717
21113
  const timer = setTimeout(done, left);
20718
21114
  this.wake.add(done);
@@ -22041,7 +22437,7 @@ async function renameWithWindowsSharingRetry(from, to, options = {}, beforeRetry
22041
22437
  return "published";
22042
22438
  }
22043
22439
  const now = options.now ?? (() => performance.now());
22044
- const sleep = options.sleep ?? ((ms) => new Promise((resolve12) => setTimeout(resolve12, ms)));
22440
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve13) => setTimeout(resolve13, ms)));
22045
22441
  const start = now();
22046
22442
  let original;
22047
22443
  try {
@@ -24089,7 +24485,7 @@ class StickySessionRouter {
24089
24485
  if (!wait || performance.now() >= deadline) {
24090
24486
  throw new Error("Timed out acquiring sticky routing state lock");
24091
24487
  }
24092
- await new Promise((resolve12) => setTimeout(resolve12, STICKY_ROUTING_LOCK_POLL_MS));
24488
+ await new Promise((resolve13) => setTimeout(resolve13, STICKY_ROUTING_LOCK_POLL_MS));
24093
24489
  }
24094
24490
  }
24095
24491
  recoverLocalPins() {
@@ -24464,7 +24860,7 @@ function resolveLocalRoutingDestination(host, paths, env) {
24464
24860
  return (host === "opencode" ? env.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE : env.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE) || getStickyRoutingStatePath(paths.config);
24465
24861
  }
24466
24862
  async function canonicalPath(path2) {
24467
- const absolute = resolve12(path2);
24863
+ const absolute = resolve13(path2);
24468
24864
  try {
24469
24865
  return await realpath3(absolute);
24470
24866
  } catch (error) {
@@ -24765,7 +25161,7 @@ class StateLayoutLockStack {
24765
25161
  name: spec.name,
24766
25162
  timeoutMs
24767
25163
  });
24768
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(remaining, POOL_LOCK_DEFAULTS.retryMs + Math.floor(Math.random() * 25))));
25164
+ await new Promise((resolve14) => setTimeout(resolve14, Math.min(remaining, POOL_LOCK_DEFAULTS.retryMs + Math.floor(Math.random() * 25))));
24769
25165
  }
24770
25166
  }
24771
25167
  async assertAll() {
@@ -25433,10 +25829,10 @@ async function linuxIncarnation(pid) {
25433
25829
  }
25434
25830
  }
25435
25831
  function macosIncarnation(pid) {
25436
- return new Promise((resolve13) => {
25832
+ return new Promise((resolve14) => {
25437
25833
  execFile("ps", ["-o", "lstart=", "-p", String(pid)], { env: { ...process.env, TZ: "UTC0" }, timeout: 5000 }, (error, stdout) => {
25438
25834
  const text5 = String(stdout ?? "").trim();
25439
- resolve13(error || !text5 ? null : text5);
25835
+ resolve14(error || !text5 ? null : text5);
25440
25836
  });
25441
25837
  });
25442
25838
  }
@@ -25719,8 +26115,8 @@ function retryInBackground(attempt, options) {
25719
26115
  let timer;
25720
26116
  let closed2 = false;
25721
26117
  let settle = () => {};
25722
- const settled = new Promise((resolve13) => {
25723
- settle = resolve13;
26118
+ const settled = new Promise((resolve14) => {
26119
+ settle = resolve14;
25724
26120
  });
25725
26121
  const schedule2 = () => {
25726
26122
  if (closed2)
@@ -27688,7 +28084,7 @@ function observeMessageThreadResponse(response, prepared) {
27688
28084
  facts.rewritten = true;
27689
28085
  }
27690
28086
  };
27691
- return new Response(new ReadableStream({
28087
+ return copyStreamResponseTiming(response, new Response(new ReadableStream({
27692
28088
  async pull(controller) {
27693
28089
  try {
27694
28090
  const chunk = await reader.read();
@@ -27725,7 +28121,7 @@ function observeMessageThreadResponse(response, prepared) {
27725
28121
  status: response.status,
27726
28122
  statusText: response.statusText,
27727
28123
  headers: response.headers
27728
- });
28124
+ }));
27729
28125
  }
27730
28126
  function placeContinueCache(body, full) {
27731
28127
  const fixed = fixedCacheHolders(body);
@@ -28639,13 +29035,13 @@ function logCommittedNativeAccountAdded(account) {
28639
29035
  }
28640
29036
 
28641
29037
  // src/native-vault-invalidation.ts
28642
- import { resolve as resolve13 } from "node:path";
29038
+ import { resolve as resolve14 } from "node:path";
28643
29039
  var holders = new Set;
28644
29040
  function watchNativeVaultAuthority(holder) {
28645
29041
  const held = {
28646
29042
  ...holder,
28647
- roster: resolve13(holder.roster),
28648
- tokenPath: resolve13(holder.tokenPath)
29043
+ roster: resolve14(holder.roster),
29044
+ tokenPath: resolve14(holder.tokenPath)
28649
29045
  };
28650
29046
  holders.add(held);
28651
29047
  return () => {
@@ -28654,12 +29050,12 @@ function watchNativeVaultAuthority(holder) {
28654
29050
  }
28655
29051
  function retainNativeVaultRoster(path2, roster) {
28656
29052
  for (const holder of holders)
28657
- if (holder.roster === resolve13(path2))
29053
+ if (holder.roster === resolve14(path2))
28658
29054
  holder.retain(roster);
28659
29055
  }
28660
29056
  function closeNativeVaultAuthority(tokenPath) {
28661
29057
  for (const holder of holders)
28662
- if (holder.tokenPath === resolve13(tokenPath) && !holder.isHosted?.())
29058
+ if (holder.tokenPath === resolve14(tokenPath) && !holder.isHosted?.())
28663
29059
  holder.close();
28664
29060
  }
28665
29061
 
@@ -28987,12 +29383,12 @@ async function joinNativePoolWrite(paths, signals, check, onLockEvent) {
28987
29383
  function pause(ms, signals) {
28988
29384
  if (signals.some((signal) => signal.aborted))
28989
29385
  return Promise.resolve();
28990
- return new Promise((resolve14) => {
29386
+ return new Promise((resolve15) => {
28991
29387
  const wake = () => {
28992
29388
  clearTimeout(timer);
28993
29389
  for (const signal of signals)
28994
29390
  signal.removeEventListener("abort", wake);
28995
- resolve14();
29391
+ resolve15();
28996
29392
  };
28997
29393
  const timer = setTimeout(wake, ms);
28998
29394
  for (const signal of signals)
@@ -29248,7 +29644,7 @@ function createNativeRefreshCoordinator(options) {
29248
29644
  name: spec.name,
29249
29645
  timeoutMs: POOL_LOCK_DEFAULTS.timeoutMs
29250
29646
  });
29251
- await new Promise((resolve14) => setTimeout(resolve14, Math.min(POOL_LOCK_DEFAULTS.retryMs, remaining)));
29647
+ await new Promise((resolve15) => setTimeout(resolve15, Math.min(POOL_LOCK_DEFAULTS.retryMs, remaining)));
29252
29648
  }
29253
29649
  }
29254
29650
  async function run(job, request2) {
@@ -30666,13 +31062,13 @@ function createPublisher() {
30666
31062
  pending.set(key, batch);
30667
31063
  let stopWaiting = () => {};
30668
31064
  const result = run(async () => {
30669
- await new Promise((resolve14) => setTimeout(resolve14, 0));
31065
+ await new Promise((resolve15) => setTimeout(resolve15, 0));
30670
31066
  stopWaiting();
30671
31067
  signal?.throwIfAborted();
30672
31068
  pending.delete(key);
30673
31069
  return write(batch.patch);
30674
31070
  });
30675
- batch.result = signal ? new Promise((resolve14, reject) => {
31071
+ batch.result = signal ? new Promise((resolve15, reject) => {
30676
31072
  const abort = () => {
30677
31073
  if (pending.get(key) === batch)
30678
31074
  pending.delete(key);
@@ -30680,7 +31076,7 @@ function createPublisher() {
30680
31076
  };
30681
31077
  stopWaiting = () => signal.removeEventListener("abort", abort);
30682
31078
  signal.addEventListener("abort", abort, { once: true });
30683
- result.then(resolve14, reject).finally(stopWaiting);
31079
+ result.then(resolve15, reject).finally(stopWaiting);
30684
31080
  if (signal.aborted)
30685
31081
  abort();
30686
31082
  }) : result;
@@ -30797,8 +31193,8 @@ async function waitForNativeUsageDrain(work) {
30797
31193
  try {
30798
31194
  await Promise.race([
30799
31195
  work,
30800
- new Promise((resolve14) => {
30801
- timer = setTimeout(resolve14, ADVISORY_SHUTDOWN_GRACE_MS);
31196
+ new Promise((resolve15) => {
31197
+ timer = setTimeout(resolve15, ADVISORY_SHUTDOWN_GRACE_MS);
30802
31198
  })
30803
31199
  ]);
30804
31200
  } finally {
@@ -30830,7 +31226,7 @@ function createNativeUsagePublisher(channel3) {
30830
31226
  hasPending: () => pending.size > 0,
30831
31227
  observe: observe2,
30832
31228
  publish(write) {
30833
- observe2(new Promise((resolve14) => setTimeout(resolve14, 0)).then(() => write(shutdown.signal)));
31229
+ observe2(new Promise((resolve15) => setTimeout(resolve15, 0)).then(() => write(shutdown.signal)));
30834
31230
  },
30835
31231
  drain,
30836
31232
  close() {
@@ -30951,7 +31347,7 @@ class NativeQuotaObservations extends Map {
30951
31347
  }
30952
31348
 
30953
31349
  // src/native-runtime-registry.ts
30954
- import { resolve as resolve14 } from "node:path";
31350
+ import { resolve as resolve15 } from "node:path";
30955
31351
  var identities = new WeakMap;
30956
31352
  var nextIdentity = 0;
30957
31353
  function nativeRuntimeOptionIdentity(value) {
@@ -30981,14 +31377,14 @@ function nativeRuntimeStorageKey(options) {
30981
31377
  "runtime",
30982
31378
  "journal",
30983
31379
  "roster"
30984
- ].map((field) => resolve14(paths[field])),
30985
- resolve14(enrollment.tokenPath),
30986
- resolve14(enrollment.statePath),
30987
- resolve14(connection)
31380
+ ].map((field) => resolve15(paths[field])),
31381
+ resolve15(enrollment.tokenPath),
31382
+ resolve15(enrollment.statePath),
31383
+ resolve15(connection)
30988
31384
  ]);
30989
31385
  }
30990
31386
  function nativeRuntimeConnectionFile(host, env) {
30991
- return resolve14(resolveClaustrumConnectionPath(host === "pi" ? env.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE : undefined, host === "pi" ? {
31387
+ return resolve15(resolveClaustrumConnectionPath(host === "pi" ? env.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE : undefined, host === "pi" ? {
30992
31388
  ...env,
30993
31389
  OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE: undefined
30994
31390
  } : env));
@@ -31463,8 +31859,8 @@ function validateNativeVaultRosterSeed(existing, input) {
31463
31859
  // src/quota-manager.ts
31464
31860
  var nativeSetTimeout = globalThis.setTimeout;
31465
31861
  function pauseOnRealTimer(ms) {
31466
- return new Promise((resolve15) => {
31467
- const id2 = nativeSetTimeout(resolve15, ms);
31862
+ return new Promise((resolve16) => {
31863
+ const id2 = nativeSetTimeout(resolve16, ms);
31468
31864
  if (typeof id2 === "object" && "unref" in id2)
31469
31865
  id2.unref();
31470
31866
  });
@@ -32316,7 +32712,6 @@ function createNativeVaultRuntime(options) {
32316
32712
  } : undefined,
32317
32713
  onConnectionChanged: () => {
32318
32714
  insulaTransportEpoch++;
32319
- closeRosterWatch();
32320
32715
  insula?.release();
32321
32716
  insula = undefined;
32322
32717
  }
@@ -32847,8 +33242,7 @@ function createNativeVaultRuntime(options) {
32847
33242
  return [{ retry: false, reason: "credential-changed" }, next];
32848
33243
  if (next.assertedAccountIdentity !== served.assertedAccountIdentity)
32849
33244
  return [{ retry: false, reason: "account-changed" }, next];
32850
- const replacementReceipt = custody.isPreviousConnectionReceipt?.(served) && !custody.isPreviousConnectionReceipt?.(next);
32851
- if (next.fromKeptReceipt || !replacementReceipt && !(next.recordVersion > served.recordVersion))
33245
+ if (next.fromKeptReceipt || !(next.recordVersion > served.recordVersion))
32852
33246
  return [{ retry: false, reason: "version-not-newer" }, next];
32853
33247
  retryUsed.add(next);
32854
33248
  return [{ retry: true, receipt: next }, next];
@@ -33234,7 +33628,7 @@ function recencyOnly(patch) {
33234
33628
  return keys4.length === 1 && keys4[0] === "lastUsed" && typeof patch.lastUsed === "number";
33235
33629
  }
33236
33630
  function waitFor(pending, signal) {
33237
- return new Promise((resolve15, reject) => {
33631
+ return new Promise((resolve16, reject) => {
33238
33632
  const abort = () => {
33239
33633
  cleanup2();
33240
33634
  reject(signal.reason);
@@ -33243,7 +33637,7 @@ function waitFor(pending, signal) {
33243
33637
  signal.addEventListener("abort", abort, { once: true });
33244
33638
  pending.then((value) => {
33245
33639
  cleanup2();
33246
- signal.aborted ? reject(signal.reason) : resolve15(value);
33640
+ signal.aborted ? reject(signal.reason) : resolve16(value);
33247
33641
  }, (error) => {
33248
33642
  cleanup2();
33249
33643
  reject(error);
@@ -33869,7 +34263,7 @@ class PersistentRelaySession {
33869
34263
  return;
33870
34264
  if (this.connecting)
33871
34265
  return await this.connecting;
33872
- this.connecting = new Promise((resolve15, reject) => {
34266
+ this.connecting = new Promise((resolve16, reject) => {
33873
34267
  const url = toWebSocketUrl(this.config.url, this.config.token);
33874
34268
  const parsed = new URL(url);
33875
34269
  parsed.searchParams.set("affinity", this.affinity);
@@ -33891,7 +34285,7 @@ class PersistentRelaySession {
33891
34285
  if (message.type === "ready") {
33892
34286
  this.timers.clearTimeout(timeout);
33893
34287
  this.serverState = message.state;
33894
- resolve15();
34288
+ resolve16();
33895
34289
  return;
33896
34290
  }
33897
34291
  this.handleMessage(message);
@@ -33943,15 +34337,15 @@ class PersistentRelaySession {
33943
34337
  const sentAt = perfNowMs();
33944
34338
  let resolveDone;
33945
34339
  let rejectDone;
33946
- const done = new Promise((resolve15, reject) => {
33947
- resolveDone = resolve15;
34340
+ const done = new Promise((resolve16, reject) => {
34341
+ resolveDone = resolve16;
33948
34342
  rejectDone = reject;
33949
34343
  });
33950
- const response = new Promise((resolve15, reject) => {
34344
+ const response = new Promise((resolve16, reject) => {
33951
34345
  const pending = {
33952
34346
  payload,
33953
34347
  bodyText,
33954
- resolve: resolve15,
34348
+ resolve: resolve16,
33955
34349
  reject,
33956
34350
  streamDone: false,
33957
34351
  accepted: false,
@@ -35385,7 +35779,7 @@ function createNativeAccountRuntime(options) {
35385
35779
  const { mode, paths: paths2, store: store2 } = await selectedStorage();
35386
35780
  for (let attempt = 0;attempt < 4; attempt++) {
35387
35781
  if (attempt)
35388
- await new Promise((resolve15) => setTimeout(resolve15, 10));
35782
+ await new Promise((resolve16) => setTimeout(resolve16, 10));
35389
35783
  const settings = await store2.readSettings();
35390
35784
  if (settings.status !== "ready")
35391
35785
  throw new NativeRuntimeError("publication-refused");
@@ -37749,8 +38143,8 @@ async function runNativeCustodyActivation(options, hooks = {}) {
37749
38143
  }
37750
38144
  async function commitMode(paths, routingPath, plan, context) {
37751
38145
  let openGate = () => {};
37752
- const gate = new Promise((resolve15) => {
37753
- openGate = resolve15;
38146
+ const gate = new Promise((resolve16) => {
38147
+ openGate = resolve16;
37754
38148
  });
37755
38149
  let leases;
37756
38150
  let scope;
@@ -39487,11 +39881,11 @@ async function refreshForRequest(runtime2, ready) {
39487
39881
  break;
39488
39882
  if (combined.aborted)
39489
39883
  break;
39490
- await new Promise((resolve15) => {
39884
+ await new Promise((resolve16) => {
39491
39885
  const finish = () => {
39492
39886
  clearTimeout(pause2);
39493
39887
  combined.removeEventListener("abort", finish);
39494
- resolve15();
39888
+ resolve16();
39495
39889
  };
39496
39890
  const pause2 = setTimeout(finish, 25);
39497
39891
  combined.addEventListener("abort", finish, { once: true });
@@ -39507,16 +39901,16 @@ async function refreshForRequest(runtime2, ready) {
39507
39901
  function waitForRequest(pending, signal) {
39508
39902
  if (!signal)
39509
39903
  return pending;
39510
- return new Promise((resolve15, reject) => {
39904
+ return new Promise((resolve16, reject) => {
39511
39905
  const abort = () => reject(signal.reason);
39512
39906
  signal.addEventListener("abort", abort, { once: true });
39513
- pending.then(resolve15, reject).finally(() => signal.removeEventListener("abort", abort));
39907
+ pending.then(resolve16, reject).finally(() => signal.removeEventListener("abort", abort));
39514
39908
  if (signal.aborted)
39515
39909
  abort();
39516
39910
  });
39517
39911
  }
39518
39912
  // src/native-vault-connection.ts
39519
- import { dirname as dirname22, join as join24, resolve as resolve16 } from "node:path";
39913
+ import { dirname as dirname22, join as join24, resolve as resolve17 } from "node:path";
39520
39914
  // ../../node_modules/@cortexkit/common-auth/dist/opencode2/integration.js
39521
39915
  var PLACEHOLDER_PREFIX = "common-auth-placeholder";
39522
39916
  var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
@@ -39527,7 +39921,7 @@ function placeholderSecret(integrationID) {
39527
39921
  import { createHash as createHash26 } from "node:crypto";
39528
39922
  import { constants as constants5 } from "node:fs";
39529
39923
  import { lstat as lstat18, mkdir as mkdir15, open as open13, unlink as unlink9 } from "node:fs/promises";
39530
- import { dirname as dirname21, resolve as resolve15 } from "node:path";
39924
+ import { dirname as dirname21, resolve as resolve16 } from "node:path";
39531
39925
  import { setTimeout as sleep } from "node:timers/promises";
39532
39926
 
39533
39927
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/lock.js
@@ -39930,8 +40324,8 @@ function createPiSlot(options, onStep, hooks) {
39930
40324
  if (!provider || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
39931
40325
  throw new PiSlotError("invalid-options");
39932
40326
  }
39933
- const authPath = resolve15(options.authPath);
39934
- const stashPath = resolve15(options.stashPath);
40327
+ const authPath = resolve16(options.authPath);
40328
+ const stashPath = resolve16(options.stashPath);
39935
40329
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
39936
40330
  throw new PiSlotError("invalid-options");
39937
40331
  }
@@ -40069,7 +40463,7 @@ function createPiSlot(options, onStep, hooks) {
40069
40463
  // src/native-vault-connection.ts
40070
40464
  function nativePiAuthSlotPaths(options) {
40071
40465
  return {
40072
- authPath: resolve16(options.authPath),
40466
+ authPath: resolve17(options.authPath),
40073
40467
  stashPath: join24(dirname22(getHostClaustrumEnrollmentPaths("pi", options.env).tokenPath), "pi-auth-slot", "anthropic.json"),
40074
40468
  provider: "anthropic",
40075
40469
  placeholderKey: placeholderSecret("anthropic")
@@ -40193,7 +40587,9 @@ function createAnthropicOAuthFetch(options = {}) {
40193
40587
  const signal = init?.signal !== undefined ? init.signal : input instanceof Request ? input.signal : undefined;
40194
40588
  signal?.throwIfAborted();
40195
40589
  requireAnthropicOAuthOrigin(fetchInputUrl(input), current());
40196
- return fetch(input, { ...init, redirect: "error" });
40590
+ const sentAt = performance.now();
40591
+ const response = await fetch(input, { ...init, redirect: "error" });
40592
+ return copyStreamResponseTiming(response, response, sentAt);
40197
40593
  }, {
40198
40594
  preconnect: (...args) => {
40199
40595
  requireAnthropicOAuthOrigin(String(args[0]), current());
@@ -40206,7 +40602,7 @@ import { createHash as createHash27 } from "node:crypto";
40206
40602
  import { realpathSync as realpathSync3 } from "node:fs";
40207
40603
  import { mkdir as mkdir16, readdir as readdir5, rm as rm9, stat as stat12, writeFile as writeFile6 } from "node:fs/promises";
40208
40604
  import { tmpdir as tmpdir8 } from "node:os";
40209
- import { join as join25, resolve as resolve17 } from "node:path";
40605
+ import { join as join25, resolve as resolve18 } from "node:path";
40210
40606
  var CLAUDE_PRIME_COMMAND_NAME = "claude-prime";
40211
40607
  var PRIME_TICK_MS = 60000;
40212
40608
  var PRIME_DUE_OFFSET_MS = 60000;
@@ -40397,7 +40793,7 @@ function defaultMarkerDir() {
40397
40793
  return join25(tmpdir8(), "opencode-anthropic-auth", "prime");
40398
40794
  }
40399
40795
  function primeStorageFingerprint(storagePath) {
40400
- const absolutePath = resolve17(storagePath);
40796
+ const absolutePath = resolve18(storagePath);
40401
40797
  let canonicalPath2;
40402
40798
  try {
40403
40799
  canonicalPath2 = realpathSync3(absolutePath);
@@ -41502,7 +41898,9 @@ function getRequestGzipLatch(path2) {
41502
41898
  }
41503
41899
  return latch;
41504
41900
  }
41505
- function getRequestGzipLatchPath(accountStoragePath) {
41901
+ function getRequestGzipLatchPath(accountStoragePath, layout = LEGACY_STATE_LAYOUT) {
41902
+ if (layout.kind === "state-home")
41903
+ return stateHomeFilePaths(layout.dir).requestGzip;
41506
41904
  const name = basename10(accountStoragePath);
41507
41905
  const stem = name.endsWith(".json") ? name.slice(0, -5) : name;
41508
41906
  return join27(dirname23(accountStoragePath), `${stem}-request-gzip.json`);
@@ -41740,7 +42138,7 @@ import { basename as basename13, dirname as dirname25, join as join31 } from "no
41740
42138
  // src/layout-fence.ts
41741
42139
  import { open as open14, readdir as readdir7 } from "node:fs/promises";
41742
42140
  import { homedir as homedir6 } from "node:os";
41743
- import { basename as basename11, join as join28, resolve as resolve18 } from "node:path";
42141
+ import { basename as basename11, join as join28, resolve as resolve19 } from "node:path";
41744
42142
  var STATE_PATH_OVERRIDE_VARIABLES = [
41745
42143
  "OPENCODE_ANTHROPIC_AUTH_FILE",
41746
42144
  "OPENCODE_ANTHROPIC_AUTH_STATE_FILE",
@@ -41827,7 +42225,7 @@ function defaultPreNArtifactLocations(env = process.env, home = homedir6()) {
41827
42225
  const rpcOverride = env.OPENCODE_ANTHROPIC_AUTH_RPC_DIR?.trim();
41828
42226
  return {
41829
42227
  rpcRoots: [join28(root, "rpc")],
41830
- rpcDirs: rpcOverride ? [resolve18(rpcOverride)] : [],
42228
+ rpcDirs: rpcOverride ? [resolve19(rpcOverride)] : [],
41831
42229
  cacheKeepDirs: [
41832
42230
  ...new Set([
41833
42231
  getDefaultCacheKeepRegistryDirectory("opencode", env),
@@ -43210,7 +43608,7 @@ async function restoreLegacyLayout(options = {}) {
43210
43608
  // src/state-layout-decision.ts
43211
43609
  var ACCOUNT_FILE2 = "anthropic-auth.json";
43212
43610
  var ACCOUNT_STATE_FILE2 = "anthropic-auth-state.json";
43213
- var RELOCATION_MOVE_ENABLED = false;
43611
+ var RELOCATION_MOVE_ENABLED = true;
43214
43612
  var moveEnabledOverride;
43215
43613
  function setRelocationMoveEnabledForTests(enabled) {
43216
43614
  moveEnabledOverride = enabled;
@@ -43267,6 +43665,49 @@ async function readRecord2(sub) {
43267
43665
  markerUnreadable(sub, error);
43268
43666
  }
43269
43667
  }
43668
+ async function readPreflightCustodyAuthority(host, env) {
43669
+ const authority = await vaultAuthority(getHostClaustrumEnrollmentPaths(host, env), `anthropic-auth-${host}`);
43670
+ return authority === "host" ? "vault" : authority;
43671
+ }
43672
+ async function preflightExistingAuthority(paths, host, env) {
43673
+ if (await readPreflightCustodyAuthority(host, env) !== "local")
43674
+ return;
43675
+ const vault = nativeVaultPaths(paths, LEGACY_STATE_LAYOUT);
43676
+ for (const runtime2 of [paths.runtime, vault.runtime])
43677
+ if (await readRelocationPointer(runtime2))
43678
+ return;
43679
+ for (const dir of new Set(nativeHolderDatasetFiles(paths).map(dirname25)))
43680
+ if (await readConfigDirMarker(dir) || await readStateLayoutMarker(dir))
43681
+ return;
43682
+ await requireNativePoolAuthority(paths);
43683
+ }
43684
+ async function preflightOpenCodeAuthority(configDir, env, home) {
43685
+ if (await readPreflightCustodyAuthority("opencode", env) !== "local")
43686
+ return;
43687
+ if (!isExplicit(env)) {
43688
+ const identity3 = configIdentity(configDir);
43689
+ if (identity3 !== undefined) {
43690
+ const target2 = stateHomeTargetFor(identity3, { env, home });
43691
+ const record12 = await readRecord2(target2.dir);
43692
+ if (record12?.phase === "committed") {
43693
+ const dataset = await resolveRelocationDataset({
43694
+ configDir,
43695
+ identity: identity3,
43696
+ stateRoot: target2.stateRoot,
43697
+ sub: await canonicalPath(target2.dir)
43698
+ });
43699
+ requireRecordMatches2(record12, dataset);
43700
+ await requireNativePoolAuthority(dataset.newPaths);
43701
+ return;
43702
+ }
43703
+ if (!noMoveRecord(record12))
43704
+ return;
43705
+ }
43706
+ }
43707
+ const config = env.OPENCODE_ANTHROPIC_AUTH_FILE?.trim() || join31(configDir, ACCOUNT_FILE2);
43708
+ const state = env.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim() || (config.endsWith(ACCOUNT_FILE2) ? join31(dirname25(config), ACCOUNT_STATE_FILE2) : `${config}.state.json`);
43709
+ await preflightExistingAuthority(await resolveNativePoolPaths(config, state, LEGACY_STATE_LAYOUT), "opencode", env);
43710
+ }
43270
43711
  async function registerHeld(holderFile, paths, kind, identity3, options, ctx) {
43271
43712
  const entry2 = await buildHolderEntry({
43272
43713
  role: options.role,
@@ -43467,6 +43908,8 @@ async function decideOpenCodeStateLayout(options) {
43467
43908
  const home = options.home ?? homedir8();
43468
43909
  const fs3 = options.fs ?? defaultStateLayoutFs();
43469
43910
  const configDir = getOpenCodeConfigDir(env, home);
43911
+ if (options.requireExistingAuthority)
43912
+ await preflightOpenCodeAuthority(configDir, env, home);
43470
43913
  const newContext = () => ({
43471
43914
  fs: fs3,
43472
43915
  stack: new StateLayoutLockStack(options.onLockEvent),
@@ -43796,8 +44239,16 @@ function decisionKey(options) {
43796
44239
  function decideOpenCodeStateLayoutOnce(options) {
43797
44240
  const key = decisionKey(options);
43798
44241
  const known = processDecisions.get(key);
43799
- if (known)
43800
- return known;
44242
+ if (known) {
44243
+ if (!options.requireExistingAuthority)
44244
+ return known;
44245
+ return known.then(async (decision2) => {
44246
+ const env = options.env ?? process.env;
44247
+ const home = options.home ?? homedir8();
44248
+ await preflightOpenCodeAuthority(getOpenCodeConfigDir(env, home), env, home);
44249
+ return decision2;
44250
+ });
44251
+ }
43801
44252
  const decision = decideOpenCodeStateLayout(options);
43802
44253
  processDecisions.set(key, decision);
43803
44254
  decision.catch(() => {
@@ -43810,6 +44261,8 @@ function resetStateLayoutDecisionsForTests() {
43810
44261
  processDecisions.clear();
43811
44262
  }
43812
44263
  async function decidePiStateLayout(options) {
44264
+ if (options.requireExistingAuthority)
44265
+ await preflightExistingAuthority(options.paths, "pi", options.env ?? process.env);
43813
44266
  const registration = await registerNativePoolHolder({
43814
44267
  paths: options.paths,
43815
44268
  role: options.role,
@@ -44286,6 +44739,7 @@ export {
44286
44739
  hasThinkingBindingControls,
44287
44740
  hasReplayableThinkingBlocks,
44288
44741
  hasNoLocalCredential,
44742
+ guardAnthropicStreamResponse,
44289
44743
  getThinkingPrefixMismatchBehavior,
44290
44744
  getStickyRoutingStatePath,
44291
44745
  getScopedQuotaWindowForModel,
@@ -44410,8 +44864,10 @@ export {
44410
44864
  createNativeAccountRuntime,
44411
44865
  createEmptyStorage,
44412
44866
  createDumpResponseObserver,
44867
+ createAnthropicStreamCompletion,
44413
44868
  createAnthropicOAuthFetch,
44414
44869
  countUserPrompts,
44870
+ copyStreamResponseTiming,
44415
44871
  connectVaultHost,
44416
44872
  connectClaustrumEnrollmentClient2 as connectClaustrumEnrollmentClient,
44417
44873
  configuredAnthropicOAuthAccountCount,