@cortexkit/anthropic-auth-core 2.4.12 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { createRequire } from "node:module";
2
2
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
3
3
 
4
- // ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
5
- function isObject(value) {
6
- return typeof value === "object" && value !== null;
7
- }
4
+ // ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/handle.js
8
5
  function routingHandle(sessionId) {
9
6
  const routing = Reflect.get(globalThis, Symbol.for("cortexkit.routing"));
10
7
  if (typeof routing !== "function")
11
8
  return;
12
9
  const handle = routing(sessionId);
13
- return isObject(handle) ? handle : undefined;
10
+ return typeof handle === "object" && handle !== null ? handle : undefined;
11
+ }
12
+
13
+ // ../../node_modules/@cortexkit/common-auth/dist/routing-accessor/index.js
14
+ function isObject(value) {
15
+ return typeof value === "object" && value !== null;
14
16
  }
15
17
  function selectionFor(answer, candidates) {
16
18
  if (!isObject(answer))
@@ -47,7 +49,15 @@ async function askRouting(input) {
47
49
  timer = setTimeout(() => resolve(undefined), deadlineMs);
48
50
  timer.unref();
49
51
  });
50
- const pending = accountFor.call(handle, { provider: input.provider, modelId: input.modelId }, { deadlineMs });
52
+ const request = {
53
+ provider: input.provider,
54
+ modelId: input.modelId
55
+ };
56
+ const cap = input.holdWaitMaxS;
57
+ if (typeof cap === "number" && Number.isFinite(cap)) {
58
+ request.hold_wait_max_s = Math.max(0, Math.floor(cap));
59
+ }
60
+ const pending = accountFor.call(handle, request, { deadlineMs });
51
61
  if (!isObject(pending) || typeof pending.then !== "function")
52
62
  return;
53
63
  const answer = await Promise.race([pending, expired]);
@@ -79,7 +89,7 @@ function reportRouting(input) {
79
89
  const { window, pool } = input;
80
90
  if (window !== "5h" && window !== "7d")
81
91
  return;
82
- if (pool !== undefined && (typeof pool !== "string" || pool.length === 0 || pool.includes(":")))
92
+ if (pool !== undefined && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
83
93
  return;
84
94
  payload = {
85
95
  ...identity,
@@ -462,6 +472,9 @@ class PrivateFileError extends Error {
462
472
  this.reason = detail?.reason;
463
473
  }
464
474
  }
475
+ function isWindowsSharingViolation(error) {
476
+ return windowsPrivateFiles && error instanceof PrivateFileError && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
477
+ }
465
478
  async function privateOperation(path, stage, operation) {
466
479
  try {
467
480
  return await operation();
@@ -812,7 +825,7 @@ class LockOwnershipError extends Error {
812
825
  }
813
826
  }
814
827
  function isChangingLockRead(error, target, name) {
815
- if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.reason !== "io-error" || error.win32Code !== 32 && error.win32Code !== 303 || error.stage !== "read" && error.stage !== "verify")
828
+ if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
816
829
  return false;
817
830
  const path = resolve3(lockPathFor(target, name));
818
831
  return error.path === path || error.path === join2(path, "owner.json");
@@ -1141,36 +1154,84 @@ async function acquireRefreshFileLockWithClock(options) {
1141
1154
  else
1142
1155
  await rm2(path, { recursive: true, force: true }).catch(() => {});
1143
1156
  }
1144
- async function releaseEvictionMarker() {
1145
- if (await ownsEvictionMarker()) {
1146
- await removeLeaseObject(evictPath);
1147
- }
1157
+ function isRetryableRemoval(error, path) {
1158
+ if (!windowsPrivateFiles || !(error instanceof PrivateFileError) || error.stage !== "remove" || error.path !== path)
1159
+ return false;
1160
+ return isWindowsSharingViolation(error) || error.win32Code === undefined && error.reason === undefined && (error.code === "EBUSY" || error.code === "EPERM");
1161
+ }
1162
+ async function removeOwnedLeaseObject(path, stillOwned, deadline = performance.now() + EVICT_TTL + 1000) {
1163
+ let original;
1164
+ let delayMs = 5;
1165
+ while (await stillOwned()) {
1166
+ try {
1167
+ await removeLeaseObject(path);
1168
+ return;
1169
+ } catch (error) {
1170
+ if (!isRetryableRemoval(error, path))
1171
+ throw error;
1172
+ original ??= error;
1173
+ }
1174
+ const remainingMs = deadline - performance.now();
1175
+ if (remainingMs <= 0)
1176
+ throw original;
1177
+ await new Promise((resolve4) => setTimeout(resolve4, Math.min(delayMs, remainingMs)));
1178
+ if (performance.now() >= deadline)
1179
+ throw original;
1180
+ delayMs = Math.min(delayMs * 2, 50);
1181
+ }
1182
+ }
1183
+ async function releaseEvictionMarker(deadline) {
1184
+ let ownedDirectory;
1185
+ await removeOwnedLeaseObject(evictPath, async () => {
1186
+ if (!windowsPrivateFiles)
1187
+ return ownsEvictionMarker();
1188
+ const current = await lstat3(evictPath).catch((error) => {
1189
+ if (error.code !== "ENOENT")
1190
+ throw error;
1191
+ return;
1192
+ });
1193
+ if (!current || ownedDirectory && !sameMarkerDirectory(ownedDirectory, current))
1194
+ return false;
1195
+ if (await ownsEvictionMarker()) {
1196
+ ownedDirectory = current;
1197
+ return true;
1198
+ }
1199
+ if (!ownedDirectory)
1200
+ return false;
1201
+ try {
1202
+ await stat(evictOwnerPath);
1203
+ return false;
1204
+ } catch (error) {
1205
+ if (error.code !== "ENOENT")
1206
+ throw error;
1207
+ return true;
1208
+ }
1209
+ }, deadline);
1148
1210
  }
1149
- async function removeOwnMarkerAfterFailedOwnerWrite(created) {
1211
+ async function removeOwnMarkerAfterFailedOwnerWrite(created, deadline) {
1150
1212
  if (!created)
1151
1213
  return false;
1152
- let current;
1214
+ let stillOurs = false;
1153
1215
  try {
1154
- const st = await lstat3(evictPath);
1155
- current = { dev: st.dev, ino: st.ino, birthtimeMs: st.birthtimeMs };
1156
- } catch {
1157
- return false;
1158
- }
1159
- if (!sameMarkerDirectory(created, current))
1160
- return false;
1161
- try {
1162
- await stat(evictOwnerPath);
1163
- return true;
1164
- } catch (error) {
1165
- if (error.code !== "ENOENT")
1166
- return true;
1167
- }
1168
- try {
1169
- await removeLeaseObject(evictPath);
1216
+ await removeOwnedLeaseObject(evictPath, async () => {
1217
+ stillOurs = false;
1218
+ const st = await lstat3(evictPath).catch(() => {
1219
+ return;
1220
+ });
1221
+ if (!st || !sameMarkerDirectory(created, st))
1222
+ return false;
1223
+ stillOurs = true;
1224
+ try {
1225
+ await stat(evictOwnerPath);
1226
+ return false;
1227
+ } catch (error) {
1228
+ return error.code === "ENOENT";
1229
+ }
1230
+ }, deadline);
1170
1231
  } catch {}
1171
- return true;
1232
+ return stillOurs;
1172
1233
  }
1173
- async function tryAcquireEvictionMarker() {
1234
+ async function tryAcquireEvictionMarker(deadline) {
1174
1235
  if (windowsPrivateFiles)
1175
1236
  await createPrivateDirectoryExclusive(evictPath);
1176
1237
  else
@@ -1194,11 +1255,11 @@ async function acquireRefreshFileLockWithClock(options) {
1194
1255
  else
1195
1256
  await createExclusiveText(evictOwnerPath, bytes);
1196
1257
  } catch (error) {
1197
- const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created);
1258
+ const stillOurs = await removeOwnMarkerAfterFailedOwnerWrite(created, deadline);
1198
1259
  if (isLostMarkerRaceError(error) && !stillOurs)
1199
1260
  return false;
1200
1261
  try {
1201
- await releaseEvictionMarker();
1262
+ await releaseEvictionMarker(deadline);
1202
1263
  } catch {}
1203
1264
  throw error;
1204
1265
  }
@@ -1206,7 +1267,7 @@ async function acquireRefreshFileLockWithClock(options) {
1206
1267
  await options.onStep("eviction-marker-acquired");
1207
1268
  return true;
1208
1269
  }
1209
- async function recoverStaleEvictionMarker() {
1270
+ async function recoverStaleEvictionMarker(deadline) {
1210
1271
  let evictStat;
1211
1272
  try {
1212
1273
  evictStat = await stat(evictPath);
@@ -1251,12 +1312,22 @@ async function acquireRefreshFileLockWithClock(options) {
1251
1312
  }
1252
1313
  if (options.onStep)
1253
1314
  await options.onStep("stale-marker-claimed");
1254
- await removeLeaseObject(claimedPath);
1315
+ const claimedIdentity = windowsPrivateFiles ? await lstat3(claimedPath) : undefined;
1316
+ await removeOwnedLeaseObject(claimedPath, async () => {
1317
+ if (!claimedIdentity)
1318
+ return true;
1319
+ const current = await lstat3(claimedPath).catch((error) => {
1320
+ if (error.code !== "ENOENT")
1321
+ throw error;
1322
+ return;
1323
+ });
1324
+ return !!current && sameMarkerDirectory(claimedIdentity, current);
1325
+ }, deadline);
1255
1326
  return "recovered";
1256
1327
  }
1257
- async function withEvictionMarker(action) {
1328
+ async function withEvictionMarker(action, deadline) {
1258
1329
  try {
1259
- if (!await tryAcquireEvictionMarker())
1330
+ if (!await tryAcquireEvictionMarker(deadline))
1260
1331
  return false;
1261
1332
  } catch (error) {
1262
1333
  if (error.code === "EEXIST") {
@@ -1273,11 +1344,23 @@ async function acquireRefreshFileLockWithClock(options) {
1273
1344
  }
1274
1345
  throw error;
1275
1346
  }
1347
+ let actionFailed = false;
1348
+ let actionError;
1276
1349
  try {
1277
1350
  await action();
1278
- } finally {
1279
- await releaseEvictionMarker();
1351
+ } catch (error) {
1352
+ actionFailed = true;
1353
+ actionError = error;
1354
+ }
1355
+ try {
1356
+ await releaseEvictionMarker(deadline);
1357
+ } catch (error) {
1358
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
1359
+ throw actionError;
1360
+ throw error;
1280
1361
  }
1362
+ if (actionFailed)
1363
+ throw actionError;
1281
1364
  return true;
1282
1365
  }
1283
1366
  async function relinquishLockAfterMarkerLoss() {
@@ -1511,6 +1594,7 @@ async function acquireRefreshFileLockWithClock(options) {
1511
1594
  await renewalInFlight;
1512
1595
  const deadline = performance.now() + EVICT_TTL + 1000;
1513
1596
  let delayMs = 5;
1597
+ let removalError;
1514
1598
  for (;; ) {
1515
1599
  try {
1516
1600
  let removalConfirmed = false;
@@ -1535,7 +1619,7 @@ async function acquireRefreshFileLockWithClock(options) {
1535
1619
  return;
1536
1620
  await removeLeaseObject(lockPath);
1537
1621
  removalConfirmed = true;
1538
- });
1622
+ }, deadline);
1539
1623
  if (markerAcquired) {
1540
1624
  if (windowsPrivateFiles && !removalConfirmed)
1541
1625
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -1546,20 +1630,25 @@ async function acquireRefreshFileLockWithClock(options) {
1546
1630
  }
1547
1631
  if (signal?.aborted)
1548
1632
  return;
1549
- await recoverStaleEvictionMarker();
1633
+ await recoverStaleEvictionMarker(deadline);
1550
1634
  } catch (error) {
1551
- if (windowsPrivateFiles)
1552
- throw error;
1553
- return;
1635
+ if (!isRetryableRemoval(error, lockPath)) {
1636
+ if (windowsPrivateFiles)
1637
+ throw error;
1638
+ return;
1639
+ }
1640
+ removalError ??= error;
1554
1641
  }
1555
1642
  const remainingMs = deadline - performance.now();
1556
1643
  if (remainingMs <= 0)
1557
1644
  break;
1558
1645
  await new Promise((resolve4) => setTimeout(resolve4, Math.min(delayMs, remainingMs)));
1646
+ if (windowsPrivateFiles && performance.now() >= deadline)
1647
+ break;
1559
1648
  delayMs = Math.min(delayMs * 2, 50);
1560
1649
  }
1561
1650
  if (windowsPrivateFiles)
1562
- throw new PrivateFileError(lockPath, "release-not-confirmed", {
1651
+ throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
1563
1652
  code: "ETIMEDOUT"
1564
1653
  });
1565
1654
  }
@@ -4571,6 +4660,102 @@ async function exchange(input, verifier, redirectUri, expectedState) {
4571
4660
  return exchangeCode(callback, verifier, redirectUri);
4572
4661
  }
4573
4662
 
4663
+ // src/routing.ts
4664
+ var CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
4665
+ var ROUTING_MODES = [
4666
+ "main-first",
4667
+ "fallback-first",
4668
+ "sticky-balanced"
4669
+ ];
4670
+ var DEFAULT_ROUTING_MODE = "main-first";
4671
+ var MAX_SAME_ACCOUNT_WAITS = ["0", "15", "max"];
4672
+ var DEFAULT_MAX_SAME_ACCOUNT_WAIT = "15";
4673
+ function getMaxSameAccountWait(storage) {
4674
+ const value = storage?.routing?.maxSameAccountWait;
4675
+ return MAX_SAME_ACCOUNT_WAITS.includes(value) ? value : DEFAULT_MAX_SAME_ACCOUNT_WAIT;
4676
+ }
4677
+ var ROUTING_USAGE = "Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";
4678
+ function normalizeRoutingMode(value) {
4679
+ return typeof value === "string" && ROUTING_MODES.includes(value) ? value : DEFAULT_ROUTING_MODE;
4680
+ }
4681
+ function getRoutingMode(storage) {
4682
+ return normalizeRoutingMode(storage?.routing?.mode);
4683
+ }
4684
+ function parseRoutingCommandAction(argumentsText) {
4685
+ const tokens = argumentsText.trim().toLowerCase().split(/\s+/).filter(Boolean);
4686
+ if (tokens.length === 0)
4687
+ return { type: "status" };
4688
+ if (tokens.length === 1 && tokens[0] === "reset")
4689
+ return { type: "reset" };
4690
+ if (tokens.length === 1 && ROUTING_MODES.includes(tokens[0])) {
4691
+ return { type: "mode", mode: tokens[0] };
4692
+ }
4693
+ if (tokens.length === 2 && tokens[0] === "mode" && ROUTING_MODES.includes(tokens[1])) {
4694
+ return { type: "mode", mode: tokens[1] };
4695
+ }
4696
+ return { type: "usage" };
4697
+ }
4698
+ function routingDescription(mode) {
4699
+ if (mode === "fallback-first") {
4700
+ return "Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";
4701
+ }
4702
+ if (mode === "sticky-balanced") {
4703
+ return "Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";
4704
+ }
4705
+ return "Try the main account first. Use fallback accounts only when quota policy or fallback errors require it.";
4706
+ }
4707
+ function buildRoutingStatusSummary(input) {
4708
+ const mode = input?.mode ?? DEFAULT_ROUTING_MODE;
4709
+ return [
4710
+ "## Claude Routing Status",
4711
+ "",
4712
+ `- Mode: \`${mode}\``,
4713
+ `- Longest wait on the same account: \`${input?.maxSameAccountWait ?? DEFAULT_MAX_SAME_ACCOUNT_WAIT}\``,
4714
+ `- Behavior: ${routingDescription(mode)}`,
4715
+ "",
4716
+ ROUTING_USAGE
4717
+ ].join(`
4718
+ `);
4719
+ }
4720
+ function executeRoutingCommand(input) {
4721
+ const action = parseRoutingCommandAction(input.argumentsText);
4722
+ const mode = input.mode ?? DEFAULT_ROUTING_MODE;
4723
+ const maxSameAccountWait = input.maxSameAccountWait;
4724
+ if (action.type === "status")
4725
+ return buildRoutingStatusSummary({ mode, maxSameAccountWait });
4726
+ if (action.type === "mode") {
4727
+ return [
4728
+ "## Claude Routing Updated",
4729
+ "",
4730
+ `Mode updated to \`${action.mode}\`.`,
4731
+ "",
4732
+ ...buildRoutingStatusSummary({ mode: action.mode, maxSameAccountWait }).split(`
4733
+ `).slice(2)
4734
+ ].join(`
4735
+ `);
4736
+ }
4737
+ if (action.type === "reset") {
4738
+ return [
4739
+ "## Claude Routing Assignment Reset",
4740
+ "",
4741
+ "The current session will be assigned again on its next request.",
4742
+ "",
4743
+ ...buildRoutingStatusSummary({ mode, maxSameAccountWait }).split(`
4744
+ `).slice(2)
4745
+ ].join(`
4746
+ `);
4747
+ }
4748
+ return [
4749
+ "## Claude Routing Usage",
4750
+ "",
4751
+ ROUTING_USAGE,
4752
+ "",
4753
+ ...buildRoutingStatusSummary({ mode, maxSameAccountWait }).split(`
4754
+ `).slice(2)
4755
+ ].join(`
4756
+ `);
4757
+ }
4758
+
4574
4759
  // src/accounts.ts
4575
4760
  var setRefreshLockRenewalTimeout2 = globalThis.setTimeout.bind(globalThis);
4576
4761
  var clearRefreshLockRenewalTimeout2 = globalThis.clearTimeout.bind(globalThis);
@@ -5261,34 +5446,75 @@ function killswitchPassesPolicy(quota, storage, accountId, modelId) {
5261
5446
  return !failClosedOnUnknownQuota(storage);
5262
5447
  return true;
5263
5448
  }
5264
- function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId) {
5449
+ function quotaRefusalTiming(input) {
5450
+ const now = input.now ?? Date.now();
5451
+ const maxAge = getQuotaCheckIntervalMs(input.storage ?? null);
5452
+ const fresh = (window) => Boolean(window && Number.isFinite(window.checkedAt) && window.checkedAt <= now && now - window.checkedAt < maxAge);
5265
5453
  const resetTimes = [];
5266
- const allQuotas = [mainQuota, ...fallbackAccounts.map((a) => a.quota)];
5267
- for (const quota of allQuotas) {
5268
- if (scopedModelId) {
5269
- const scopedWindow = getScopedQuotaWindowForModel(quota, scopedModelId);
5270
- const resetStr = scopedWindow?.resetsAt;
5271
- if (!resetStr)
5454
+ const storage = input.storage ?? null;
5455
+ const modelId = input.modelId ?? input.scopedModelId;
5456
+ const floors = quotaEnabled(storage) ? getQuotaMinimumRemainingThresholds(storage) : { five_hour: 0, seven_day: 0 };
5457
+ for (const { quota, accountIdentity, accountId } of input.readings) {
5458
+ if (!accountIdentity || quota?.accountIdentity !== accountIdentity)
5459
+ continue;
5460
+ const killswitch = isKillswitchEnabled(storage) ? getKillswitchThresholdsForAccount(storage, accountId === "main" ? undefined : accountId) : { five_hour: 0, seven_day: 0, scoped: 0 };
5461
+ const scoped = getScopedQuotaWindowForModel(quota, modelId);
5462
+ if (!quotaSnapshotHasStandardWindows(quota) || !fresh(quota.seven_day) || !quotaSnapshotOmitsFiveHour(quota) && !fresh(quota.five_hour) || scoped && !fresh(scoped) || modelId && killswitch.scoped > 0 && quota.scoped === undefined)
5463
+ continue;
5464
+ const blockers = [];
5465
+ let unknown = false;
5466
+ for (const key of ["five_hour", "seven_day"]) {
5467
+ if (key === "five_hour" && quotaSnapshotOmitsFiveHour(quota))
5272
5468
  continue;
5273
- const resetTime = Date.parse(resetStr);
5274
- if (Number.isFinite(resetTime) && resetTime > now) {
5275
- resetTimes.push(resetTime);
5469
+ const window = quota[key];
5470
+ if (!window || !Number.isFinite(window.remainingPercent)) {
5471
+ unknown = true;
5472
+ break;
5276
5473
  }
5277
- } else {
5278
- for (const key of ["five_hour", "seven_day"]) {
5279
- const resetStr = quota?.[key]?.resetsAt;
5280
- if (!resetStr)
5281
- continue;
5282
- const resetTime = Date.parse(resetStr);
5283
- if (Number.isFinite(resetTime) && resetTime > now) {
5284
- resetTimes.push(resetTime);
5285
- }
5474
+ if (window.remainingPercent <= 0 || window.remainingPercent < Math.max(floors[key], killswitch[key]))
5475
+ blockers.push(window);
5476
+ }
5477
+ if (scoped) {
5478
+ if (!Number.isFinite(scoped.remainingPercent))
5479
+ unknown = true;
5480
+ else if (scoped.remainingPercent <= killswitch.scoped)
5481
+ blockers.push(scoped);
5482
+ }
5483
+ let usableAt;
5484
+ for (const window of blockers) {
5485
+ const resetAt2 = Date.parse(window?.resetsAt ?? "");
5486
+ if (!Number.isFinite(resetAt2) || resetAt2 <= now) {
5487
+ unknown = true;
5488
+ break;
5286
5489
  }
5490
+ usableAt = Math.max(usableAt ?? resetAt2, resetAt2);
5287
5491
  }
5492
+ if (!unknown && usableAt !== undefined)
5493
+ resetTimes.push(usableAt);
5288
5494
  }
5289
- if (!resetTimes.length)
5290
- return 300;
5291
- return Math.max(1, Math.ceil((Math.min(...resetTimes) - now) / 1000)) + 60;
5495
+ const resetAt = resetTimes.length ? Math.min(...resetTimes) : undefined;
5496
+ const wait = getMaxSameAccountWait(input.storage ?? null);
5497
+ const ttlMs = input.sessionTtlMs && input.sessionTtlMs > 0 && Number.isFinite(input.sessionTtlMs) ? input.sessionTtlMs : 300000;
5498
+ const capMs = wait === "max" ? ttlMs : Number(wait) * 60000;
5499
+ return {
5500
+ resetAt,
5501
+ retryAfterSeconds: wait === "0" ? undefined : Math.max(1, Math.ceil(Math.min(resetAt === undefined ? 300000 : resetAt - now, capMs) / 1000))
5502
+ };
5503
+ }
5504
+ function killswitchRetryAfterSeconds(mainQuota, fallbackAccounts, now, scopedModelId, options) {
5505
+ return quotaRefusalTiming({
5506
+ ...options,
5507
+ now,
5508
+ scopedModelId,
5509
+ readings: [
5510
+ {
5511
+ quota: mainQuota,
5512
+ accountIdentity: options?.mainAccountIdentity,
5513
+ accountId: "main"
5514
+ },
5515
+ ...fallbackAccounts
5516
+ ]
5517
+ }).retryAfterSeconds ?? 0;
5292
5518
  }
5293
5519
  function getKillswitchConfig(storage) {
5294
5520
  return storage?.killswitch ?? { enabled: false };
@@ -6844,6 +7070,7 @@ function bodyStructureSummary(bodyText) {
6844
7070
  parseable: true,
6845
7071
  model: typeof parsed.model === "string" ? parsed.model : undefined,
6846
7072
  stream: parsed.stream,
7073
+ thread: parsed.thread,
6847
7074
  systemCount: system.length,
6848
7075
  messagesCount: messages.length,
6849
7076
  systemHash: hashJson(system),
@@ -6891,7 +7118,9 @@ async function dumpRequest(input) {
6891
7118
  try {
6892
7119
  await mkdir6(dumpDir, { recursive: true });
6893
7120
  const previousBodyText = input.previousBodyText ?? await loadLatestDumpBody(input);
7121
+ const bodySummary = bodyStructureSummary(input.bodyText);
6894
7122
  const metadata = {
7123
+ thread: "thread" in bodySummary ? bodySummary.thread : undefined,
6895
7124
  id,
6896
7125
  createdAt: new Date().toISOString(),
6897
7126
  session: shortAffinity(affinity),
@@ -6906,7 +7135,7 @@ async function dumpRequest(input) {
6906
7135
  relayBytes: input.relayBytes,
6907
7136
  bodyHash: hashText(input.bodyText),
6908
7137
  diff: diffSummary(previousBodyText, input.bodyText),
6909
- body: bodyStructureSummary(input.bodyText),
7138
+ body: bodySummary,
6910
7139
  files
6911
7140
  };
6912
7141
  const writes = [
@@ -7778,7 +8007,7 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
7778
8007
  }
7779
8008
 
7780
8009
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7781
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
8010
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
7782
8011
  // ../../node_modules/@cortexkit/common-auth/dist/logger/engine.js
7783
8012
  import { appendFileSync as appendFileSync2, chmodSync, existsSync as existsSync3, renameSync as renameSync2, statSync as statSync4 } from "node:fs";
7784
8013
  import { open as open5 } from "node:fs/promises";
@@ -8088,7 +8317,7 @@ function combineAbortSignals(signals) {
8088
8317
 
8089
8318
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8090
8319
  import { channel } from "node:diagnostics_channel";
8091
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8320
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
8092
8321
 
8093
8322
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
8094
8323
  var CUSTODY_PLACEHOLDER_PREFIX = "claustrum-tombstone:v1:";
@@ -8131,6 +8360,134 @@ async function drainShutdown(pending, onTimeout) {
8131
8360
  }
8132
8361
  }
8133
8362
 
8363
+ // ../../node_modules/@cortexkit/common-auth/dist/claustrum/usage.js
8364
+ import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8365
+ function plain(value) {
8366
+ return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
8367
+ }
8368
+
8369
+ class ScopedUsageReporter {
8370
+ options;
8371
+ #queue = new Map;
8372
+ #latest = new Map;
8373
+ #errors = new Set;
8374
+ #timer;
8375
+ #running;
8376
+ #closing = false;
8377
+ #stopped = false;
8378
+ #dropped = 0;
8379
+ constructor(options) {
8380
+ this.options = options;
8381
+ }
8382
+ state() {
8383
+ return {
8384
+ pending: this.#queue.size,
8385
+ inFlight: this.#running !== undefined,
8386
+ dropped: this.#dropped
8387
+ };
8388
+ }
8389
+ report(credentialId, reading) {
8390
+ if (this.#closing || !this.options.client.reportUsageScoped)
8391
+ return;
8392
+ try {
8393
+ if (!this.options.owns(credentialId)) {
8394
+ this.#dropped++;
8395
+ return;
8396
+ }
8397
+ if (!plain(reading) || "credentialId" in reading || "vouched" in reading)
8398
+ throw new Error("invalid reading");
8399
+ const json = JSON.stringify(reading);
8400
+ if (Buffer.byteLength(json, "utf8") > 15360)
8401
+ throw new Error("oversized reading");
8402
+ const copy = JSON.parse(json);
8403
+ if (!plain(copy) || "credentialId" in copy || "vouched" in copy || typeof copy.observedAtMs !== "number" || !Number.isFinite(copy.observedAtMs))
8404
+ throw new Error("invalid reading");
8405
+ if (copy.observedAtMs <= (this.#latest.get(credentialId) ?? -Infinity)) {
8406
+ this.#dropped++;
8407
+ return;
8408
+ }
8409
+ if (this.#queue.has(credentialId))
8410
+ this.#dropped++;
8411
+ this.#latest.set(credentialId, copy.observedAtMs);
8412
+ this.#queue.set(credentialId, copy);
8413
+ if (!this.#timer && !this.#running) {
8414
+ this.#timer = this.options.setTimeout(() => {
8415
+ this.#timer = undefined;
8416
+ this.#flush();
8417
+ }, 1000);
8418
+ this.#timer.unref?.();
8419
+ }
8420
+ } catch {
8421
+ this.#dropped++;
8422
+ }
8423
+ }
8424
+ forget(credentialId) {
8425
+ if (this.#queue.delete(credentialId))
8426
+ this.#dropped++;
8427
+ this.#latest.delete(credentialId);
8428
+ }
8429
+ #flush() {
8430
+ if (this.#running || !this.#queue.size || this.#stopped)
8431
+ return this.#running;
8432
+ const running = Promise.resolve().then(async () => {
8433
+ while (!this.#stopped && this.#queue.size) {
8434
+ const entry = this.#queue.entries().next().value;
8435
+ if (!entry)
8436
+ break;
8437
+ const [credentialId, reading] = entry;
8438
+ this.#queue.delete(credentialId);
8439
+ try {
8440
+ const enrollmentToken = await this.options.token();
8441
+ if (this.#stopped || !this.options.owns(credentialId)) {
8442
+ if (!this.#stopped)
8443
+ this.#dropped++;
8444
+ continue;
8445
+ }
8446
+ await this.options.client.reportUsageScoped?.({
8447
+ credentialId,
8448
+ reading,
8449
+ enrollmentToken
8450
+ });
8451
+ } catch (error) {
8452
+ if (!this.#stopped)
8453
+ this.#dropped++;
8454
+ this.#log(error);
8455
+ }
8456
+ }
8457
+ });
8458
+ this.#running = running;
8459
+ running.finally(() => {
8460
+ this.#running = undefined;
8461
+ });
8462
+ return running;
8463
+ }
8464
+ #log(error) {
8465
+ let code = "transport_error";
8466
+ try {
8467
+ if (error instanceof ClaustrumCredentialError3)
8468
+ code = /^[a-z][a-z0-9_]{0,63}$/.test(error.code) ? error.code : code;
8469
+ if (this.#errors.has(code))
8470
+ return;
8471
+ this.#errors.add(code);
8472
+ this.options.logger.debug("claustrum usage report dropped", { code });
8473
+ } catch {}
8474
+ }
8475
+ close() {
8476
+ this.#closing = true;
8477
+ if (this.#timer)
8478
+ this.options.clearTimeout(this.#timer);
8479
+ this.#timer = undefined;
8480
+ return this.#flush();
8481
+ }
8482
+ drop() {
8483
+ this.#stopped = true;
8484
+ this.#dropped += this.#queue.size + (this.#running ? 1 : 0);
8485
+ this.#running = undefined;
8486
+ this.#queue.clear();
8487
+ this.#latest.clear();
8488
+ }
8489
+ }
8490
+
8134
8491
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8135
8492
  function isScopedCredentialRotation(served, current) {
8136
8493
  return current !== undefined && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
@@ -8147,6 +8504,12 @@ function scopedRetryReason(served, current) {
8147
8504
  return "rotated";
8148
8505
  }
8149
8506
  var defaultLogger = createLogger("claustrum");
8507
+ function checkedEnrollmentToken(value) {
8508
+ if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
8509
+ throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
8510
+ }
8511
+ return value.token;
8512
+ }
8150
8513
  var phaseDiagnostics = channel("common-auth.claustrum.phases");
8151
8514
  function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
8152
8515
  const retry = isScopedCredentialRotation(served, current);
@@ -8261,6 +8624,8 @@ class ClaustrumScopedCustody {
8261
8624
  #reports = new WeakMap;
8262
8625
  #kept = new Map;
8263
8626
  #keptAttempts = new WeakMap;
8627
+ #usage;
8628
+ #usageServed = new Map;
8264
8629
  #setTimeout;
8265
8630
  #clearTimeout;
8266
8631
  #outage = false;
@@ -8274,6 +8639,7 @@ class ClaustrumScopedCustody {
8274
8639
  #watches = new Set;
8275
8640
  #tokenReads = new Set;
8276
8641
  #warnShutdown;
8642
+ #onDrainTimeout;
8277
8643
  #disposing;
8278
8644
  constructor(options) {
8279
8645
  const tokenPath = options.tokenPath;
@@ -8293,12 +8659,20 @@ class ClaustrumScopedCustody {
8293
8659
  this.#warnShutdown = shutdownWarning(this.#logger);
8294
8660
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
8295
8661
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
8662
+ this.#usage = new ScopedUsageReporter({
8663
+ client: this.#client,
8664
+ owns: (id) => this.#usageServed.has(id),
8665
+ token: async () => checkedEnrollmentToken(await this.#readToken()),
8666
+ logger: this.#logger,
8667
+ setTimeout: this.#setTimeout,
8668
+ clearTimeout: this.#clearTimeout
8669
+ });
8296
8670
  }
8297
8671
  transportLost(error) {
8298
8672
  if (this.#closed || this.#outage)
8299
8673
  return;
8300
8674
  this.#outage = true;
8301
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError;
8675
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError;
8302
8676
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
8303
8677
  this.#scheduleProbe();
8304
8678
  }
@@ -8366,10 +8740,7 @@ class ClaustrumScopedCustody {
8366
8740
  });
8367
8741
  }
8368
8742
  this.#check(signal);
8369
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
8370
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
8371
- }
8372
- return value.token;
8743
+ return checkedEnrollmentToken(value);
8373
8744
  }
8374
8745
  async#call(operation, signal) {
8375
8746
  this.#check(signal);
@@ -8393,7 +8764,7 @@ class ClaustrumScopedCustody {
8393
8764
  this.transportLost(error);
8394
8765
  else
8395
8766
  this.reachable();
8396
- if (error instanceof ClaustrumCredentialError3)
8767
+ if (error instanceof ClaustrumCredentialError4)
8397
8768
  throw error;
8398
8769
  if (classifyVaultFailure(error) === "unreachable")
8399
8770
  throw new ClaustrumUnreachableError;
@@ -8417,6 +8788,7 @@ class ClaustrumScopedCustody {
8417
8788
  token = await this.#token(signal);
8418
8789
  } catch (error) {
8419
8790
  this.#kept.clear();
8791
+ this.#clearUsageOwnership();
8420
8792
  throw error;
8421
8793
  }
8422
8794
  if (phaseDiagnostics.hasSubscribers)
@@ -8512,10 +8884,18 @@ class ClaustrumScopedCustody {
8512
8884
  else {
8513
8885
  this.reachable();
8514
8886
  this.#kept.clear();
8887
+ this.#clearUsageOwnership();
8515
8888
  }
8516
8889
  }
8517
8890
  forget(credentialId) {
8518
8891
  this.#kept.delete(credentialId);
8892
+ this.#usageServed.delete(credentialId);
8893
+ this.#usage.forget(credentialId);
8894
+ }
8895
+ #clearUsageOwnership() {
8896
+ for (const id of this.#usageServed.keys())
8897
+ this.#usage.forget(id);
8898
+ this.#usageServed.clear();
8519
8899
  }
8520
8900
  retain(identities) {
8521
8901
  const current = new Map(identities.map((identity2) => [identity2.credentialId, identity2]));
@@ -8524,6 +8904,11 @@ class ClaustrumScopedCustody {
8524
8904
  if (!identity2?.enabled || identity2.state !== "active" || identity2.credentialType !== kept.attempt.credentialType || identity2.accountIdentity !== kept.attempt.expectedAccountIdentity)
8525
8905
  this.forget(id);
8526
8906
  }
8907
+ for (const [id, served] of this.#usageServed) {
8908
+ const identity2 = current.get(id);
8909
+ if (!identity2?.enabled || identity2.state !== "active" || identity2.credentialType !== served.credentialType || identity2.accountIdentity !== served.accountIdentity)
8910
+ this.forget(id);
8911
+ }
8527
8912
  }
8528
8913
  keptReceiptState() {
8529
8914
  let since = null;
@@ -8553,6 +8938,7 @@ class ClaustrumScopedCustody {
8553
8938
  token = await this.#token(signal);
8554
8939
  } catch (error) {
8555
8940
  this.#kept.clear();
8941
+ this.#clearUsageOwnership();
8556
8942
  throw error;
8557
8943
  }
8558
8944
  if (this.#outage && kept) {
@@ -8562,6 +8948,7 @@ class ClaustrumScopedCustody {
8562
8948
  try {
8563
8949
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
8564
8950
  this.#kept.set(credentialId, { attempt, routeId, since: null });
8951
+ this.#usageServed.set(credentialId, { ...identity2 });
8565
8952
  return attempt;
8566
8953
  } catch (error) {
8567
8954
  this.#check(signal);
@@ -8714,6 +9101,16 @@ class ClaustrumScopedCustody {
8714
9101
  }
8715
9102
  };
8716
9103
  }
9104
+ reportUsage(input) {
9105
+ if (this.#closed)
9106
+ return;
9107
+ try {
9108
+ this.#usage.report(input.credentialId, input.reading);
9109
+ } catch {}
9110
+ }
9111
+ usageReportState() {
9112
+ return this.#usage.state();
9113
+ }
8717
9114
  close() {
8718
9115
  if (this.#closed)
8719
9116
  return;
@@ -8725,11 +9122,22 @@ class ClaustrumScopedCustody {
8725
9122
  watch.stop();
8726
9123
  this.#watches.clear();
8727
9124
  this.#kept.clear();
8728
- this.#client.close();
9125
+ const usage = this.#usage.close();
9126
+ if (usage) {
9127
+ this.#tokenReads.add(usage);
9128
+ usage.then(() => this.#tokenReads.delete(usage));
9129
+ } else
9130
+ this.#client.close();
9131
+ this.#disposing = drainShutdown(this.#tokenReads, (count) => (this.#onDrainTimeout ?? this.#warnShutdown)(count)).finally(() => {
9132
+ this.#usage.drop();
9133
+ this.#usageServed.clear();
9134
+ if (usage)
9135
+ this.#client.close();
9136
+ });
8729
9137
  }
8730
9138
  async dispose(onTimeout = this.#warnShutdown) {
9139
+ this.#onDrainTimeout = onTimeout;
8731
9140
  this.close();
8732
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
8733
9141
  await this.#disposing;
8734
9142
  }
8735
9143
  }
@@ -9470,6 +9878,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
9470
9878
  return {
9471
9879
  version: 1,
9472
9880
  view: inventory.view,
9881
+ ...previous?.limits !== undefined && { limits: previous.limits },
9473
9882
  complete,
9474
9883
  ...!complete && {
9475
9884
  rejected: inventory.skipped.map((record2) => ({
@@ -9544,6 +9953,7 @@ function decodeRoster(value) {
9544
9953
  ...typeof value.view === "string" && { view: value.view },
9545
9954
  complete: value.complete !== false,
9546
9955
  ...rejected && { rejected },
9956
+ ...value.limits !== undefined && { limits: value.limits },
9547
9957
  rows,
9548
9958
  declined
9549
9959
  };
@@ -10591,6 +11001,27 @@ class ClaustrumConsumer {
10591
11001
  combined.dispose();
10592
11002
  }
10593
11003
  }
11004
+ reportUsage(input) {
11005
+ if (this.#shutdown.signal.aborted)
11006
+ return;
11007
+ try {
11008
+ const row = this.#roster?.rows.find((row2) => row2.routeId === input.routeId);
11009
+ if (!row?.enabled || row.state !== "active" || row.credentialId !== input.credentialId && !row.aliases?.includes(input.credentialId))
11010
+ return;
11011
+ if (this.#hub) {
11012
+ if (this.#lease && this.#hub.leaseLive(this.#lease))
11013
+ this.#lease.custody.reportUsage(input);
11014
+ } else
11015
+ this.#custody?.reportUsage(input);
11016
+ } catch {}
11017
+ }
11018
+ usageReportState() {
11019
+ try {
11020
+ return (this.#hub ? this.#lease?.custody : this.#custody)?.usageReportState() ?? { pending: 0, inFlight: false, dropped: 0 };
11021
+ } catch {
11022
+ return { pending: 0, inFlight: false, dropped: 0 };
11023
+ }
11024
+ }
10594
11025
  async reportFailure(attempt, status, source) {
10595
11026
  this.#assertOpen();
10596
11027
  if (this.#hub) {
@@ -11125,6 +11556,14 @@ class ClaustrumDiscoveryHub {
11125
11556
  check();
11126
11557
  return custody.reportFailure(attempt, status, source);
11127
11558
  },
11559
+ reportUsage: (input) => {
11560
+ if (!state.released && !generation.ended)
11561
+ custody.reportUsage(input);
11562
+ },
11563
+ usageReportState: () => {
11564
+ check();
11565
+ return custody.usageReportState();
11566
+ },
11128
11567
  forget: (credentialId) => {
11129
11568
  check();
11130
11569
  custody.forget(credentialId);
@@ -11605,7 +12044,7 @@ import {
11605
12044
  resolve as resolve11
11606
12045
  } from "node:path";
11607
12046
  import {
11608
- ClaustrumCredentialError as ClaustrumCredentialError5,
12047
+ ClaustrumCredentialError as ClaustrumCredentialError6,
11609
12048
  ClaustrumClient as ClaustrumWireClient2,
11610
12049
  writeEnrollmentTokenFile as writeEnrollmentTokenFile3
11611
12050
  } from "@cortexkit/claustrum-client";
@@ -12359,7 +12798,7 @@ class ClaustrumEnrollmentManager2 {
12359
12798
  };
12360
12799
  await writeStateAtomic2(this.#paths.statePath, state, () => lock.assertOwned());
12361
12800
  } catch (error) {
12362
- if (error instanceof ClaustrumCredentialError5) {
12801
+ if (error instanceof ClaustrumCredentialError6) {
12363
12802
  if (!TERMINAL_ENROLLMENT_CODES2.has(error.code) && (error.code === "pending_queue_full" || error.action === "retry")) {
12364
12803
  return {
12365
12804
  state: "pending",
@@ -12415,7 +12854,7 @@ class ClaustrumEnrollmentManager2 {
12415
12854
  await writeStateAtomic2(this.#paths.statePath, approved, () => lock.assertOwned());
12416
12855
  return statusFromState2(approved);
12417
12856
  } catch (error) {
12418
- if (!(error instanceof ClaustrumCredentialError5))
12857
+ if (!(error instanceof ClaustrumCredentialError6))
12419
12858
  throw error;
12420
12859
  if (!TERMINAL_ENROLLMENT_CODES2.has(error.code) && error.action === "retry") {
12421
12860
  return {
@@ -12544,7 +12983,7 @@ function createNativeCustody(options) {
12544
12983
  return await operation(owned);
12545
12984
  } catch (error) {
12546
12985
  check();
12547
- if (error instanceof ClaustrumCredentialError4 && error.code === "enrollment_revoked")
12986
+ if (error instanceof ClaustrumCredentialError5 && error.code === "enrollment_revoked")
12548
12987
  revoked = true;
12549
12988
  if (error instanceof NativeCustodyError)
12550
12989
  throw new ClaustrumConsumerError(error.code, "Native custody operation refused");
@@ -12713,7 +13152,7 @@ function createNativeCustody(options) {
12713
13152
  onMode: watchOptions.onMode,
12714
13153
  onRefused: (error) => {
12715
13154
  watchOptions.onRefused?.(error);
12716
- if (error instanceof ClaustrumCredentialError4 && error.code === "enrollment_revoked")
13155
+ if (error instanceof ClaustrumCredentialError5 && error.code === "enrollment_revoked")
12717
13156
  custody.close();
12718
13157
  },
12719
13158
  onError: watchOptions.onError
@@ -14460,10 +14899,16 @@ async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
14460
14899
  } catch {
14461
14900
  return { ok: false, reason: "body is not valid JSON" };
14462
14901
  }
14902
+ if (isRecord9(body.thread) && body.thread.type === "continue")
14903
+ return {
14904
+ ok: false,
14905
+ reason: "a thread continuation is not a full cache prefix"
14906
+ };
14463
14907
  if (!hasExplicitCacheControl(body)) {
14464
14908
  return { ok: false, reason: "body has no explicit cache breakpoints" };
14465
14909
  }
14466
14910
  const warm = structuredClone(body);
14911
+ delete warm.thread;
14467
14912
  stripBillingLineageFromBody(warm);
14468
14913
  warm.max_tokens = 0;
14469
14914
  delete warm.stream;
@@ -14743,6 +15188,13 @@ class CacheKeepManager {
14743
15188
  if (bodyBytes > CACHE_KEEP_MAX_BODY_BYTES) {
14744
15189
  return refuse("body exceeds cachekeep memory budget", "body-budget");
14745
15190
  }
15191
+ if (input.bodyText.includes('"thread"')) {
15192
+ try {
15193
+ const body = JSON.parse(input.bodyText);
15194
+ if (body.thread)
15195
+ return refuse("thread wire bodies are not full stateless cache prefixes", "message-thread-wire-body");
15196
+ } catch {}
15197
+ }
14746
15198
  const window = getCacheKeepWindow(input.storage);
14747
15199
  if (!isCacheKeepActiveNow(input.storage, new Date(now))) {
14748
15200
  return refuse("outside configured schedule", "outside-schedule");
@@ -15217,24 +15669,32 @@ function recordIdentityIn(tx, id, identity2) {
15217
15669
  raw.accountId = identity2;
15218
15670
  return disableIdentityDuplicates(tx, identity2);
15219
15671
  }
15220
- // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
15221
- import { setTimeout as snapshotDelay } from "node:timers/promises";
15222
-
15223
15672
  // ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
15224
15673
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
15225
15674
  var insideHook = new AsyncLocalStorage3;
15675
+ var insideCodec = new AsyncLocalStorage3;
15226
15676
  function assertNotInsideHook(operation) {
15227
15677
  if (insideHook.getStore() !== undefined)
15228
15678
  throw new PoolReentryError(operation);
15229
15679
  }
15230
- function runInsideHook(operation, fn) {
15231
- return insideHook.run(operation, async () => await fn());
15680
+ function assertLimitsWriteAllowed() {
15681
+ if (insideHook.getStore()?.storeLocksReleased === false || insideCodec.getStore())
15682
+ throw new PoolReentryError("updateLimitsNamespace");
15683
+ }
15684
+ function runInsideCodec(fn) {
15685
+ return insideCodec.run(true, fn);
15686
+ }
15687
+ function runInsideHook(operation, fn, storeLocksReleased = false) {
15688
+ return insideHook.run({
15689
+ operation,
15690
+ storeLocksReleased: storeLocksReleased && insideHook.getStore()?.storeLocksReleased !== false
15691
+ }, async () => await fn());
15232
15692
  }
15233
15693
  async function callFailureHook(operation, hook, rowId, error, logger3) {
15234
15694
  if (!hook)
15235
15695
  return;
15236
15696
  try {
15237
- await runInsideHook(operation, () => hook(rowId, error));
15697
+ await runInsideHook(operation, () => hook(rowId, error), true);
15238
15698
  } catch (hookError) {
15239
15699
  logger3?.warn("store failure hook threw; the original failure stands", {
15240
15700
  operation,
@@ -15244,6 +15704,9 @@ async function callFailureHook(operation, hook, rowId, error, logger3) {
15244
15704
  }
15245
15705
  }
15246
15706
 
15707
+ // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
15708
+ import { setTimeout as snapshotDelay } from "node:timers/promises";
15709
+
15247
15710
  // ../../node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
15248
15711
  var POOL_LOCK_DEFAULTS = Object.freeze({
15249
15712
  ttlMs: 1e4,
@@ -15467,7 +15930,7 @@ function stampFor(credential, credentialEpoch, binding, options = {}) {
15467
15930
  };
15468
15931
  }
15469
15932
  function providerStateDigest(codec, value) {
15470
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
15933
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
15471
15934
  return createHash10("sha256").update(`provider-state\x00${JSON.stringify(bound ?? null)}`).digest("hex");
15472
15935
  }
15473
15936
  function boundProviderStateDigest(account, credential, credentialEpoch, identity2) {
@@ -15634,8 +16097,8 @@ function parseEntry(raw, codec) {
15634
16097
  return;
15635
16098
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
15636
16099
  return;
15637
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
15638
- if ("quota" in raw && !codec.validate(quota))
16100
+ const quota = "quota" in raw && codec.decode ? runInsideCodec(() => codec.decode?.(raw.quota)) : raw.quota;
16101
+ if ("quota" in raw && !runInsideCodec(() => codec.validate(quota)))
15639
16102
  return;
15640
16103
  if ("staged" in raw && !parseReservation(raw.staged))
15641
16104
  return;
@@ -15807,7 +16270,7 @@ function providerStateFields(account, credential, credentialEpoch, identity2, co
15807
16270
  if (digest === undefined)
15808
16271
  return { providerStateDropped: "uncovered" };
15809
16272
  const value = account[PROVIDER_STATE_KEY];
15810
- if (!codec?.validate(value))
16273
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
15811
16274
  return { providerStateDropped: "invalid" };
15812
16275
  if (providerStateDigest(codec, value) !== digest)
15813
16276
  return { providerStateDropped: "uncovered" };
@@ -16505,8 +16968,8 @@ function assertQuotaRow(id, attribution, row) {
16505
16968
  });
16506
16969
  }
16507
16970
  function mergedQuota(ctx, id, stored, observation) {
16508
- const merged = ctx.codec.merge(stored, observation);
16509
- if (!ctx.codec.validate(merged))
16971
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
16972
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
16510
16973
  throw refusal("pull", id, "invalid-quota", "the quota codec rejected the merged map");
16511
16974
  return merged;
16512
16975
  }
@@ -16534,6 +16997,38 @@ async function recordQuota(rt, id, attribution, observation) {
16534
16997
  }
16535
16998
  }
16536
16999
 
17000
+ // ../../node_modules/@cortexkit/common-auth/dist/store/limits-namespace.js
17001
+ async function updatePoolLimitsNamespace(rt, mutator) {
17002
+ assertLimitsWriteAllowed();
17003
+ const { ctx } = rt;
17004
+ await runOperation(ctx, "updateLimitsNamespace", undefined, undefined, async (locks, progress) => {
17005
+ for (const spec of ctx.storeLocks)
17006
+ await locks.acquire(spec);
17007
+ const result = await readPool(ctx);
17008
+ if (result.status !== "ready")
17009
+ throw notReadyError(result, "updateLimitsNamespace", undefined);
17010
+ const rows = result.rows.map(({ id, credentialEpoch, identity: identity2 }) => ({
17011
+ id,
17012
+ credentialEpoch,
17013
+ identity: identity2
17014
+ }));
17015
+ const envelope = await runInsideHook("updateLimitsNamespace", () => mutator(structuredClone(result.config.commonAuthLimits), rows));
17016
+ const config = { ...result.config, commonAuthLimits: envelope };
17017
+ const info = {
17018
+ operation: "updateLimitsNamespace",
17019
+ rowId: undefined
17020
+ };
17021
+ await writeJsonAtomic(ctx.configPath, config, {
17022
+ beforeRename: async () => {
17023
+ await ctx.onStep?.("before-config-write", info);
17024
+ await locks.assertAll();
17025
+ }
17026
+ });
17027
+ progress.writes++;
17028
+ await ctx.onStep?.("after-config-write", info);
17029
+ });
17030
+ }
17031
+
16537
17032
  // ../../node_modules/@cortexkit/common-auth/dist/store/provider-state.js
16538
17033
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
16539
17034
  if (!codec)
@@ -16547,7 +17042,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
16547
17042
  }
16548
17043
  if (normalized === undefined)
16549
17044
  throw refusal(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
16550
- if (!codec.validate(normalized))
17045
+ if (!runInsideCodec(() => codec.validate(normalized)))
16551
17046
  throw refusal(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
16552
17047
  return normalized;
16553
17048
  }
@@ -16556,18 +17051,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
16556
17051
  return { kind: "set", value: incoming };
16557
17052
  return {
16558
17053
  kind: "set",
16559
- value: acceptProviderState(codec, operation, id, codec.merge(structuredClone(onDisk), structuredClone(incoming)), "the merged provider state")
17054
+ value: acceptProviderState(codec, operation, id, runInsideCodec(() => codec.merge?.(structuredClone(onDisk), structuredClone(incoming))), "the merged provider state")
16560
17055
  };
16561
17056
  }
16562
17057
  function replacementProviderState(codec, row, credentialEpoch, identity2, incoming) {
16563
17058
  const hook = codec?.onReplace;
16564
- const next = hook ? hook(row.providerState === undefined ? undefined : structuredClone(row.providerState), {
17059
+ const next = hook ? runInsideCodec(() => hook(row.providerState === undefined ? undefined : structuredClone(row.providerState), {
16565
17060
  id: row.id,
16566
17061
  credentialEpoch,
16567
17062
  ...row.identity !== undefined ? { previousIdentity: row.identity } : {},
16568
17063
  ...identity2 !== undefined ? { identity: identity2 } : {},
16569
17064
  ...incoming !== undefined ? { incoming: structuredClone(incoming) } : {}
16570
- }) : incoming;
17065
+ })) : incoming;
16571
17066
  if (next === undefined)
16572
17067
  return { kind: "clear" };
16573
17068
  if (!hook)
@@ -18295,7 +18790,7 @@ async function refreshRow(rt, id, provider, options = {}) {
18295
18790
  if (options.onPersisted) {
18296
18791
  try {
18297
18792
  const persisted = options.onPersisted;
18298
- await runInsideHook("refresh", () => persisted(id, commit.stored));
18793
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
18299
18794
  } catch (cause) {
18300
18795
  throw new PoolOperationError({
18301
18796
  operation: "refresh",
@@ -18343,7 +18838,7 @@ function defineKey(target, key, value) {
18343
18838
  function composeConfig(config, next) {
18344
18839
  const out = {};
18345
18840
  for (const [key, value] of Object.entries(config)) {
18346
- if (POOL_OWNED_KEYS.includes(key))
18841
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
18347
18842
  defineKey(out, key, value);
18348
18843
  else if (Object.hasOwn(next, key))
18349
18844
  defineKey(out, key, next[key]);
@@ -18396,9 +18891,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
18396
18891
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
18397
18892
  if (owned.length > 0)
18398
18893
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
18399
- if (isDeepStrictEqual(next, current))
18400
- return { settings: current, outcome: "unchanged" };
18894
+ if (Object.hasOwn(next, "commonAuthLimits") && (!Object.hasOwn(current, "commonAuthLimits") || !isDeepStrictEqual(next.commonAuthLimits, current.commonAuthLimits)))
18895
+ throw settingsRefusal("settings cannot alter commonAuthLimits; use updateLimitsNamespace");
18401
18896
  const config = composeConfig(result.config, next);
18897
+ if (isDeepStrictEqual(settingsOf(config), current))
18898
+ return { settings: current, outcome: "unchanged" };
18402
18899
  const info = { operation: "updateSettings", rowId: undefined };
18403
18900
  await writeJsonAtomic(ctx.configPath, config, {
18404
18901
  beforeRename: async () => {
@@ -18515,6 +19012,7 @@ function openPoolStore(options) {
18515
19012
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
18516
19013
  readSettings: () => readPoolSettings(rt),
18517
19014
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
19015
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
18518
19016
  recordIdentity: (id, identity2, attribution, callOptions) => recordRowIdentity(rt, id, identity2, attribution, callOptions),
18519
19017
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
18520
19018
  recordQuota: record2,
@@ -20123,7 +20621,7 @@ function pick(source2, keys4) {
20123
20621
  return Object.fromEntries(keys4.filter((key) => Object.hasOwn(source2, key)).map((key) => [key, source2[key]]));
20124
20622
  }
20125
20623
  var settingFields = {
20126
- routing: ["mode"],
20624
+ routing: ["mode", "maxSameAccountWait"],
20127
20625
  refresh: ["enabled", "intervalMinutes", "refreshBeforeExpiryMinutes"],
20128
20626
  quota: [
20129
20627
  "enabled",
@@ -20150,6 +20648,7 @@ function validateNativeMigrationSettings(settings) {
20150
20648
  const threshold = (value) => record6(value) && Object.entries(value).every(([key, amount]) => ["five_hour", "seven_day", "5h", "1w", "scoped"].includes(key) && typeof amount === "number" && Number.isFinite(amount) && amount >= 0 && amount <= 100);
20151
20649
  const enums = {
20152
20650
  "routing.mode": ["main-first", "fallback-first", "sticky-balanced"],
20651
+ "routing.maxSameAccountWait": ["0", "15", "max"],
20153
20652
  "claudeCache.mode": CACHE_1H_MODES,
20154
20653
  "logging.level": ["debug", "info", "warn", "error", "trace"],
20155
20654
  "thinkingBinding.prefixMismatchBehavior": [
@@ -20577,7 +21076,7 @@ async function nativeVaultFileAbsent(path2) {
20577
21076
  }
20578
21077
  }
20579
21078
  var preferenceFields = {
20580
- routing: ["mode"],
21079
+ routing: ["mode", "maxSameAccountWait"],
20581
21080
  claudeCache: ["enabled", "mode"],
20582
21081
  cacheKeep: ["enabled", "always", "startHour", "endHour", "subagents"],
20583
21082
  quota: [
@@ -20816,9 +21315,84 @@ function mergeHeaderQuotaSnapshot(existing, incoming) {
20816
21315
  };
20817
21316
  }
20818
21317
 
21318
+ // src/quota-refusal.ts
21319
+ var details = new WeakMap;
21320
+ var quotaRefusalDetails = (response) => details.get(response);
21321
+ function createQuotaRefusalResponse(reason, timing, _now) {
21322
+ const reset = timing.resetAt === undefined ? "Reset time is unknown." : `Reset at ${new Intl.DateTimeFormat("en-US", {
21323
+ month: "long",
21324
+ day: "numeric",
21325
+ hour: "2-digit",
21326
+ minute: "2-digit",
21327
+ timeZoneName: "short"
21328
+ }).format(timing.resetAt)}.`;
21329
+ const seconds = timing.retryAfterSeconds;
21330
+ const retry = seconds === undefined ? "" : ` Retry in ${Math.floor(seconds / 60)}m ${seconds % 60}s.`;
21331
+ const response = new Response(JSON.stringify({
21332
+ type: "error",
21333
+ error: {
21334
+ type: timing.retryAfterSeconds === undefined ? "FAILED_PRECONDITION" : "rate_limit_error",
21335
+ message: `${reason}${retry} ${reset}`
21336
+ }
21337
+ }), {
21338
+ status: timing.retryAfterSeconds === undefined ? 412 : 429,
21339
+ headers: {
21340
+ "content-type": "application/json",
21341
+ ...timing.retryAfterSeconds === undefined ? {} : { "retry-after": String(timing.retryAfterSeconds) }
21342
+ }
21343
+ });
21344
+ details.set(response, { reason, timing });
21345
+ return response;
21346
+ }
21347
+
21348
+ // src/session-cache-activity.ts
21349
+ var PROMPT_CACHE_DEFAULT_TTL_MS = 5 * 60000;
21350
+ var PROMPT_CACHE_1H_TTL_MS = 60 * 60000;
21351
+
21352
+ class SessionCacheActivity {
21353
+ maxSessions;
21354
+ entries = new Map;
21355
+ constructor(maxSessions = 4096) {
21356
+ this.maxSessions = maxSessions;
21357
+ }
21358
+ record(sessionId, accountId, ttlMs, lastAcceptedAt = Date.now()) {
21359
+ this.entries.delete(sessionId);
21360
+ this.entries.set(sessionId, {
21361
+ accountId,
21362
+ lastAcceptedAt,
21363
+ ttlMs: ttlMs && Number.isFinite(ttlMs) && ttlMs > 0 ? ttlMs : PROMPT_CACHE_DEFAULT_TTL_MS
21364
+ });
21365
+ if (this.entries.size > this.maxSessions) {
21366
+ const oldest = this.entries.keys().next().value;
21367
+ if (oldest !== undefined)
21368
+ this.entries.delete(oldest);
21369
+ }
21370
+ }
21371
+ holdUntil(sessionId, accountId, now = Date.now(), maxWait = "15") {
21372
+ if (!sessionId)
21373
+ return;
21374
+ const activity = this.entries.get(sessionId);
21375
+ if (!activity || activity.accountId !== accountId)
21376
+ return;
21377
+ return Math.min(activity.lastAcceptedAt + activity.ttlMs, maxWait === "max" ? Infinity : now + Number(maxWait) * 60000);
21378
+ }
21379
+ recordPrewarm(sessionId, accountId, acceptedAt = Date.now()) {
21380
+ const activity = this.entries.get(sessionId);
21381
+ if (activity && activity.accountId !== accountId)
21382
+ return;
21383
+ this.record(sessionId, accountId, PROMPT_CACHE_1H_TTL_MS, acceptedAt);
21384
+ }
21385
+ forget(sessionId) {
21386
+ this.entries.delete(sessionId);
21387
+ }
21388
+ ttlMs(sessionId) {
21389
+ return sessionId && this.entries.get(sessionId)?.ttlMs || PROMPT_CACHE_DEFAULT_TTL_MS;
21390
+ }
21391
+ }
21392
+ var sessionCacheActivity = new SessionCacheActivity;
21393
+
20819
21394
  // src/sticky-routing.ts
20820
21395
  var STICKY_ROUTING_MAIN_ACCOUNT_ID = "main";
20821
- var STICKY_ROUTING_SHORT_RESET_GRACE_MS = 15 * 60000;
20822
21396
  var STICKY_ROUTING_ASSIGNMENT_TTL_MS = 7 * 24 * 60 * 60000;
20823
21397
  var STICKY_ROUTING_TOUCH_INTERVAL_MS = 60 * 60000;
20824
21398
  var STICKY_ROUTING_LOCK_TTL_MS = 1e4;
@@ -20826,6 +21400,35 @@ var STICKY_ROUTING_LOCK_WAIT_MS = 5000;
20826
21400
  var STICKY_ROUTING_LOCK_POLL_MS = 10;
20827
21401
  var STICKY_ROUTING_MAX_ASSIGNMENTS = 4096;
20828
21402
  var MIN_WEIGHT = 0.000001;
21403
+ var MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES = 2;
21404
+
21405
+ class StickyQuotaRetryCounter {
21406
+ maxSessions;
21407
+ sessions = new Map;
21408
+ constructor(maxSessions = STICKY_ROUTING_MAX_ASSIGNMENTS) {
21409
+ this.maxSessions = maxSessions;
21410
+ }
21411
+ retain(sessionId, turnId, accountId) {
21412
+ let entry2 = this.sessions.get(sessionId);
21413
+ if (entry2?.turnId !== turnId || entry2.accountId !== accountId) {
21414
+ this.sessions.delete(sessionId);
21415
+ if (this.sessions.size >= this.maxSessions) {
21416
+ const oldest = this.sessions.keys().next().value;
21417
+ if (oldest !== undefined)
21418
+ this.sessions.delete(oldest);
21419
+ }
21420
+ entry2 = { turnId, accountId, retains: 0 };
21421
+ this.sessions.set(sessionId, entry2);
21422
+ }
21423
+ if (entry2.retains >= MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES)
21424
+ return false;
21425
+ entry2.retains++;
21426
+ return true;
21427
+ }
21428
+ clear(sessionId) {
21429
+ this.sessions.delete(sessionId);
21430
+ }
21431
+ }
20829
21432
  function createStickyNoRouteResponse(input) {
20830
21433
  const modelId = input.modelId;
20831
21434
  const modelName = modelId ? input.routeQuotas.map((quota2) => getScopedQuotaWindowForModel(quota2, modelId)).find(Boolean)?.modelName : undefined;
@@ -20849,23 +21452,21 @@ function createStickyNoRouteResponse(input) {
20849
21452
  });
20850
21453
  }
20851
21454
  const scopedBlocked = Boolean(modelId && input.routeQuotas.length > 0 && input.routeQuotas.every((quota2) => !quotaSnapshotPassesModelScope(quota2, modelId)));
20852
- const [firstQuota, ...remainingQuotas] = input.routeQuotas;
20853
- const retryAfter = killswitchRetryAfterSeconds(firstQuota, remainingQuotas.map((quota2) => ({ quota: quota2 })), input.now ?? Date.now(), scopedBlocked ? modelId : undefined);
20854
- const minutes = Math.floor(retryAfter / 60);
20855
- const seconds = retryAfter % 60;
21455
+ const now = input.now ?? Date.now();
21456
+ const timing = quotaRefusalTiming({
21457
+ readings: input.routeQuotas.map((quota2, index) => ({
21458
+ quota: quota2,
21459
+ accountIdentity: input.routeIdentities?.[index],
21460
+ accountId: input.routeAccountIds?.[index]
21461
+ })),
21462
+ storage: input.storage,
21463
+ modelId,
21464
+ now,
21465
+ sessionTtlMs: sessionCacheActivity.ttlMs(input.sessionId)
21466
+ });
20856
21467
  const limitNames = input.vaultPolicyLimits?.map((limit) => limit === "model-scoped" ? `${modelName ?? "Model"} scoped limit` : limit === "killswitch" ? "killswitch limit" : "quota floor");
20857
21468
  const reason = limitNames ? `No vault account currently satisfies quota policy: ${limitNames.join(", ")}. Open /claude → Killswitch / Quota to change these limits.` : scopedBlocked && modelName ? `${modelName} weekly limit reached, no routable OAuth accounts.` : "No OAuth account currently satisfies sticky-balanced quota policy.";
20858
- const message = `${reason} Retry in ${minutes}m ${seconds}s.`;
20859
- return new Response(JSON.stringify({
20860
- type: "error",
20861
- error: { type: "rate_limit_error", message }
20862
- }), {
20863
- status: 429,
20864
- headers: {
20865
- "content-type": "application/json",
20866
- "retry-after": String(retryAfter)
20867
- }
20868
- });
21469
+ return createQuotaRefusalResponse(reason, timing, now);
20869
21470
  }
20870
21471
  function isRecord11(value) {
20871
21472
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -21050,6 +21651,10 @@ function stickyRouteKnownFableExhausted(candidate, storage, now = Date.now()) {
21050
21651
  }
21051
21652
  function decideStickyQuotaFailure(input) {
21052
21653
  const now = input.now ?? Date.now();
21654
+ const retain = (reason) => {
21655
+ const scope = input.unconfirmedRetry;
21656
+ return scope && !scope.counter.retain(scope.sessionId, scope.turnId, scope.accountId) ? { action: "migrate", reason: "unconfirmed-retry-limit" } : { action: "retain", reason };
21657
+ };
21053
21658
  let reading2 = knownQuota(input.quota);
21054
21659
  const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, now) : undefined;
21055
21660
  if (reading2 && input.responseHeaders) {
@@ -21061,7 +21666,7 @@ function decideStickyQuotaFailure(input) {
21061
21666
  }
21062
21667
  const quota2 = reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
21063
21668
  if (!quota2)
21064
- return { action: "retain", reason: "unknown" };
21669
+ return retain("unknown");
21065
21670
  let blocking;
21066
21671
  for (const [reason, window2] of [
21067
21672
  ["model-scoped", getScopedQuotaWindowForModel(quota2, input.modelId)],
@@ -21077,8 +21682,9 @@ function decideStickyQuotaFailure(input) {
21077
21682
  blocking = { resetAt, reason };
21078
21683
  }
21079
21684
  if (!blocking)
21080
- return { action: "retain", reason: "not-exhausted" };
21081
- if (blocking.resetAt - now <= STICKY_ROUTING_SHORT_RESET_GRACE_MS) {
21685
+ return retain("not-exhausted");
21686
+ const jitterMs = input.sessionId ? (stickyRetryAfterWithJitter(input.sessionId, 1) - 1) * 1000 : 0;
21687
+ if (input.holdUntil !== undefined && blocking.resetAt + jitterMs <= input.holdUntil) {
21082
21688
  return {
21083
21689
  action: "hold",
21084
21690
  reason: `${blocking.reason}-short-reset`,
@@ -23826,6 +24432,794 @@ function executeLoggingCommand(input) {
23826
24432
  ].join(`
23827
24433
  `);
23828
24434
  }
24435
+ // src/message-threads.ts
24436
+ import { createHash as createHash20 } from "node:crypto";
24437
+ var MESSAGE_THREADS_BETA = "message-threads-2026-08-12";
24438
+ var MAX_AGE_MS = 5 * 60000;
24439
+ var MAX_SESSIONS = 2048;
24440
+ var MAX_MESSAGE_HASHES = 131072;
24441
+ function hash3(value) {
24442
+ return createHash20("sha256").update(JSON.stringify(value)).digest("hex");
24443
+ }
24444
+ function normalizedReplyName(name) {
24445
+ const bare = name.startsWith("mcp_") ? name.slice(4) : name;
24446
+ return `${bare.charAt(0).toUpperCase()}${bare.slice(1)}`;
24447
+ }
24448
+ function replyToolNameResolver(input) {
24449
+ let exact;
24450
+ let aliases;
24451
+ return (value) => {
24452
+ if (typeof value !== "string" || !value)
24453
+ return;
24454
+ if (input.replyToolNames) {
24455
+ const target2 = input.replyToolNames.get(value);
24456
+ return typeof target2 === "string" ? target2 : undefined;
24457
+ }
24458
+ if (!exact || !aliases) {
24459
+ exact = new Map;
24460
+ aliases = new Map;
24461
+ const tools = Array.isArray(input.body.tools) ? input.body.tools : [];
24462
+ for (const [index, tool] of tools.entries()) {
24463
+ if (!isBody(tool) || typeof tool.name !== "string")
24464
+ continue;
24465
+ const name = normalizedReplyName(tool.name);
24466
+ const target2 = `${index}:${name}`;
24467
+ exact.set(tool.name, exact.has(tool.name) ? null : target2);
24468
+ aliases.set(name, aliases.has(name) ? null : target2);
24469
+ }
24470
+ }
24471
+ const target = exact.has(value) ? exact.get(value) : aliases.get(normalizedReplyName(value));
24472
+ return typeof target === "string" ? target : undefined;
24473
+ };
24474
+ }
24475
+ var MAX_REPLY_INPUT_CHARS = 1048576;
24476
+ function hasOnlyTextFields(block) {
24477
+ return Object.keys(block).every((key) => key === "type" || key === "text" || key === "cache_control");
24478
+ }
24479
+
24480
+ class ReplyFingerprint {
24481
+ normalizeToolName;
24482
+ open = new Map;
24483
+ seen = new Set;
24484
+ tools = new Map;
24485
+ layout = new Map;
24486
+ textBlocks = new Map;
24487
+ signatures = new Map;
24488
+ text = createHash20("sha256");
24489
+ committedText = this.text.copy();
24490
+ hasText = false;
24491
+ activeText;
24492
+ lastText = -1;
24493
+ inputChars = 0;
24494
+ invalid = false;
24495
+ constructor(normalizeToolName) {
24496
+ this.normalizeToolName = normalizeToolName;
24497
+ }
24498
+ appendText(value) {
24499
+ const part = this.hasText ? value : value.trimStart();
24500
+ const visible = part.trimEnd();
24501
+ if (visible) {
24502
+ this.text.update(visible);
24503
+ this.committedText = this.text.copy();
24504
+ this.hasText = true;
24505
+ }
24506
+ if (this.hasText)
24507
+ this.text.update(part.slice(visible.length));
24508
+ }
24509
+ appendBlockText(state, value) {
24510
+ state.text ??= createHash20("sha256");
24511
+ state.committedText ??= state.text.copy();
24512
+ const part = state.textHasContent ? value : value.trimStart();
24513
+ const visible = part.trimEnd();
24514
+ if (visible) {
24515
+ state.committedText = state.text.copy().update(visible);
24516
+ state.textHasContent = true;
24517
+ }
24518
+ state.text.update(part);
24519
+ this.appendText(value);
24520
+ }
24521
+ start(index, block) {
24522
+ if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || !isBody(block) || typeof block.type !== "string" || this.seen.has(index)) {
24523
+ this.invalid = true;
24524
+ return;
24525
+ }
24526
+ if (block.type === "text" && !hasOnlyTextFields(block)) {
24527
+ this.invalid = true;
24528
+ return;
24529
+ }
24530
+ this.seen.add(index);
24531
+ const state = {
24532
+ type: block.type,
24533
+ signatureLength: 0,
24534
+ textHasContent: false
24535
+ };
24536
+ if (!["text", "tool_use", "thinking", "redacted_thinking"].includes(block.type))
24537
+ this.invalid = true;
24538
+ if (block.type === "text") {
24539
+ if (this.activeText !== undefined || index < this.lastText)
24540
+ this.invalid = true;
24541
+ this.activeText = index;
24542
+ this.lastText = index;
24543
+ const text5 = typeof block.text === "string" ? block.text : "";
24544
+ this.appendBlockText(state, text5);
24545
+ }
24546
+ if (block.type === "tool_use") {
24547
+ if (typeof block.id !== "string" || !block.id)
24548
+ this.invalid = true;
24549
+ else
24550
+ state.id = block.id;
24551
+ state.name = this.normalizeToolName(block.name);
24552
+ if (!state.name)
24553
+ this.invalid = true;
24554
+ state.input = block.input;
24555
+ }
24556
+ if (block.type === "thinking" || block.type === "redacted_thinking") {
24557
+ state.signature = createHash20("sha256");
24558
+ const signature = block.type === "redacted_thinking" ? block.data : block.signature;
24559
+ if (typeof signature === "string") {
24560
+ state.signature.update(signature);
24561
+ state.signatureLength += signature.length;
24562
+ }
24563
+ }
24564
+ this.open.set(index, state);
24565
+ }
24566
+ delta(index, delta) {
24567
+ const state = typeof index === "number" ? this.open.get(index) : undefined;
24568
+ if (!state || !isBody(delta) || delta.type === "citations_delta") {
24569
+ this.invalid = true;
24570
+ return;
24571
+ }
24572
+ if (this.invalid)
24573
+ return;
24574
+ if (delta.type === "text_delta") {
24575
+ if (state.type !== "text" || this.activeText !== index || typeof delta.text !== "string")
24576
+ this.invalid = true;
24577
+ else {
24578
+ this.appendBlockText(state, delta.text);
24579
+ }
24580
+ }
24581
+ if (delta.type === "signature_delta") {
24582
+ if (!state.signature || typeof delta.signature !== "string")
24583
+ this.invalid = true;
24584
+ else {
24585
+ state.signature.update(delta.signature);
24586
+ state.signatureLength += delta.signature.length;
24587
+ }
24588
+ }
24589
+ if (delta.type === "input_json_delta") {
24590
+ if (state.type !== "tool_use" || typeof delta.partial_json !== "string")
24591
+ this.invalid = true;
24592
+ else if (this.inputChars + delta.partial_json.length > MAX_REPLY_INPUT_CHARS) {
24593
+ this.inputChars -= state.inputJson?.length ?? 0;
24594
+ state.inputJson = "";
24595
+ this.invalid = true;
24596
+ } else {
24597
+ this.inputChars += delta.partial_json.length;
24598
+ state.inputJson = (state.inputJson ?? "") + delta.partial_json;
24599
+ }
24600
+ }
24601
+ }
24602
+ stop(index) {
24603
+ const state = typeof index === "number" ? this.open.get(index) : undefined;
24604
+ if (!state || typeof index !== "number") {
24605
+ this.invalid = true;
24606
+ return;
24607
+ }
24608
+ this.open.delete(index);
24609
+ if (this.invalid)
24610
+ return;
24611
+ this.layout.set(index, {
24612
+ type: state.type,
24613
+ ...state.type === "text" ? { text: state.textHasContent ? "_" : "" } : {}
24614
+ });
24615
+ if (state.type === "text") {
24616
+ this.activeText = undefined;
24617
+ if (state.committedText)
24618
+ this.textBlocks.set(index, state.committedText.digest("hex"));
24619
+ }
24620
+ if (state.signature) {
24621
+ if (!state.signatureLength)
24622
+ this.invalid = true;
24623
+ this.signatures.set(index, [state.type, state.signature.digest("hex")]);
24624
+ }
24625
+ if (state.type === "tool_use") {
24626
+ this.inputChars -= state.inputJson?.length ?? 0;
24627
+ try {
24628
+ const input = state.inputJson?.trim() ? JSON.parse(state.inputJson) : state.input;
24629
+ if (!state.id || !state.name || input === undefined)
24630
+ this.invalid = true;
24631
+ else
24632
+ this.tools.set(index, [
24633
+ state.id,
24634
+ state.name,
24635
+ hash3(canonicalValue(input))
24636
+ ]);
24637
+ } catch {
24638
+ this.invalid = true;
24639
+ }
24640
+ }
24641
+ }
24642
+ digest() {
24643
+ if (this.invalid || this.open.size)
24644
+ return;
24645
+ const ordered = [...this.layout].sort(([a], [b]) => a - b);
24646
+ const kept = withoutTrailingToolWhitespace(ordered.map(([, block]) => block));
24647
+ return hash3({
24648
+ blocks: kept.map((block) => block.type),
24649
+ texts: ordered.slice(0, kept.length).filter(([, block]) => block.type === "text").map(([index]) => this.textBlocks.get(index)),
24650
+ tools: [...this.tools].sort(([a], [b]) => a - b).map(([, tool]) => tool),
24651
+ signatures: [...this.signatures].sort(([a], [b]) => a - b).map(([, signature]) => signature),
24652
+ text: this.committedText.copy().digest("hex")
24653
+ });
24654
+ }
24655
+ }
24656
+ function assistantReplyFingerprint(message, normalizeToolName) {
24657
+ if (!isBody(message) || message.role !== "assistant")
24658
+ return;
24659
+ const content = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content;
24660
+ if (!Array.isArray(content))
24661
+ return;
24662
+ const reply = new ReplyFingerprint(normalizeToolName);
24663
+ for (const [index, block] of content.entries()) {
24664
+ reply.start(index, block);
24665
+ reply.stop(index);
24666
+ }
24667
+ return reply.digest();
24668
+ }
24669
+ function canonicalValue(value) {
24670
+ if (Array.isArray(value))
24671
+ return value.map(canonicalValue);
24672
+ if (value && typeof value === "object") {
24673
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonicalValue(item)]));
24674
+ }
24675
+ return value;
24676
+ }
24677
+ function isBody(value) {
24678
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
24679
+ }
24680
+ function withoutOwnCache(value) {
24681
+ if (!isBody(value))
24682
+ return value;
24683
+ const copy = { ...value };
24684
+ delete copy.cache_control;
24685
+ return copy;
24686
+ }
24687
+ function withoutContentCache(content) {
24688
+ if (!Array.isArray(content))
24689
+ return content;
24690
+ return content.map((block) => {
24691
+ const copy = withoutOwnCache(block);
24692
+ if (isBody(copy) && copy.type === "tool_result")
24693
+ copy.content = withoutContentCache(copy.content);
24694
+ return copy;
24695
+ });
24696
+ }
24697
+ function withoutTrailingToolWhitespace(content) {
24698
+ if (!content.some((block) => isBody(block) && block.type === "tool_use"))
24699
+ return content;
24700
+ let end = content.length;
24701
+ while (end > 0) {
24702
+ const block = content[end - 1];
24703
+ if (!isBody(block) || block.type !== "text" || typeof block.text !== "string" || !hasOnlyTextFields(block) || block.text.trim())
24704
+ break;
24705
+ end--;
24706
+ }
24707
+ return end === content.length ? content : content.slice(0, end);
24708
+ }
24709
+ function withoutMessageCache(message) {
24710
+ if (!isBody(message))
24711
+ return message;
24712
+ let content = withoutContentCache(message.content);
24713
+ if (message.role === "assistant" && Array.isArray(content))
24714
+ content = withoutTrailingToolWhitespace(content);
24715
+ if (message.role === "user" && Array.isArray(content) && content.length === 1) {
24716
+ const block = content[0];
24717
+ if (isBody(block) && block.type === "text" && typeof block.text === "string" && Object.keys(block).every((key) => key === "type" || key === "text"))
24718
+ content = block.text;
24719
+ }
24720
+ return { ...message, content };
24721
+ }
24722
+ function contentCacheHolders(content) {
24723
+ if (!Array.isArray(content))
24724
+ return [];
24725
+ const holders = [];
24726
+ for (const block of content) {
24727
+ if (!isBody(block))
24728
+ continue;
24729
+ if (block.cache_control)
24730
+ holders.push(block);
24731
+ if (block.type === "tool_result")
24732
+ holders.push(...contentCacheHolders(block.content));
24733
+ }
24734
+ return holders;
24735
+ }
24736
+ function messageCacheHolders(messages) {
24737
+ if (!Array.isArray(messages))
24738
+ return [];
24739
+ return messages.flatMap((message) => isBody(message) ? contentCacheHolders(message.content) : []);
24740
+ }
24741
+ function fixedCacheHolders(body) {
24742
+ return [body.system, body.tools].flatMap((items) => Array.isArray(items) ? items.filter((item) => isBody(item) && Boolean(item.cache_control)) : []);
24743
+ }
24744
+ function fixedThreadFingerprint(input) {
24745
+ const { body } = input;
24746
+ const system = Array.isArray(body.system) ? body.system.filter((block) => !(typeof block?.text === "string" && block.text.startsWith("x-anthropic-billing-header:"))) : body.system;
24747
+ const fixed = Object.fromEntries([
24748
+ "model",
24749
+ "thinking",
24750
+ "output_config",
24751
+ "tool_choice",
24752
+ "context_management"
24753
+ ].map((key) => [key, body[key]]));
24754
+ return hash3(canonicalValue({
24755
+ ...fixed,
24756
+ tools: JSON.stringify(body.tools),
24757
+ system: JSON.stringify(system),
24758
+ cache_control: JSON.stringify(body.cache_control),
24759
+ fallbacks: JSON.stringify(body.fallbacks),
24760
+ betas: input.betas
24761
+ }));
24762
+ }
24763
+ function messageThreadSnapshot(input, identity3 = hash3([input.account, input.credential]), fingerprint = fixedThreadFingerprint(input)) {
24764
+ const messages = (Array.isArray(input.body.messages) ? input.body.messages : []).map((message) => hash3(canonicalValue(withoutMessageCache(message))));
24765
+ return { identity: identity3, fingerprint, messages, prefix: hash3(messages) };
24766
+ }
24767
+ function canContinueFrom(anchor, input, identity3, now) {
24768
+ if (!anchor || !identity3 || anchor.identity !== identity3 || now < anchor.completedAt || now - anchor.completedAt >= MAX_AGE_MS)
24769
+ return false;
24770
+ const messages = Array.isArray(input.body.messages) ? input.body.messages : [];
24771
+ return messages.length >= anchor.messages.length + 2 && messages[anchor.messages.length]?.role === "assistant" && !messages.slice(anchor.messages.length + 1).some((message) => message?.role === "assistant") && assistantReplyFingerprint(messages[anchor.messages.length], replyToolNameResolver(input)) === anchor.replyFingerprint;
24772
+ }
24773
+ function decideMessageThread(anchor, input, snapshot, now) {
24774
+ if (!canContinueFrom(anchor, input, snapshot.identity, now) || anchor.fingerprint !== snapshot.fingerprint || hash3(snapshot.messages.slice(0, anchor.messages.length)) !== anchor.prefix)
24775
+ return { type: "create" };
24776
+ const messages = Array.isArray(input.body.messages) ? input.body.messages : [];
24777
+ return {
24778
+ type: "continue",
24779
+ previousMessageId: anchor.messageId,
24780
+ deltaMessages: messages.slice(anchor.messages.length + 1)
24781
+ };
24782
+ }
24783
+
24784
+ class MessageThreadTracker {
24785
+ capacity;
24786
+ now;
24787
+ hashBudget;
24788
+ sessions = new Map;
24789
+ messageHashes = 0;
24790
+ constructor(capacity = MAX_SESSIONS, now = Date.now, hashBudget = MAX_MESSAGE_HASHES) {
24791
+ this.capacity = capacity;
24792
+ this.now = now;
24793
+ this.hashBudget = hashBudget;
24794
+ }
24795
+ forget(session) {
24796
+ this.messageHashes -= this.sessions.get(session)?.anchor?.messages.length ?? 0;
24797
+ this.sessions.delete(session);
24798
+ }
24799
+ prune() {
24800
+ while (this.sessions.size > this.capacity || this.messageHashes > this.hashBudget) {
24801
+ const oldest = this.sessions.keys().next().value;
24802
+ if (oldest === undefined)
24803
+ break;
24804
+ this.forget(oldest);
24805
+ }
24806
+ }
24807
+ failureFor(session, token2) {
24808
+ return () => {
24809
+ if (this.sessions.get(session)?.token === token2)
24810
+ this.forget(session);
24811
+ };
24812
+ }
24813
+ prepare(input) {
24814
+ const normalizeToolName = replyToolNameResolver(input);
24815
+ const previous = this.sessions.get(input.session);
24816
+ const anchor = previous?.anchor;
24817
+ const now = this.now();
24818
+ const identity3 = anchor && now >= anchor.completedAt && now - anchor.completedAt < MAX_AGE_MS ? hash3([input.account, input.credential]) : undefined;
24819
+ let snapshot;
24820
+ if (canContinueFrom(anchor, input, identity3, now)) {
24821
+ const fingerprint = fixedThreadFingerprint(input);
24822
+ if (fingerprint === anchor.fingerprint)
24823
+ snapshot = messageThreadSnapshot(input, identity3, fingerprint);
24824
+ }
24825
+ const decision = snapshot ? decideMessageThread(anchor, input, snapshot, now) : { type: "create" };
24826
+ const token2 = {};
24827
+ this.forget(input.session);
24828
+ this.sessions.set(input.session, { token: token2 });
24829
+ this.prune();
24830
+ const fail = this.failureFor(input.session, token2);
24831
+ let body;
24832
+ const outgoingBody = () => {
24833
+ if (body)
24834
+ return body;
24835
+ const full = input.body;
24836
+ body = {
24837
+ ...full,
24838
+ thread: decision.type === "create" ? { type: "create" } : {
24839
+ type: "continue",
24840
+ previous_message_id: decision.previousMessageId
24841
+ }
24842
+ };
24843
+ if (decision.type === "continue") {
24844
+ Object.assign(body, { messages: decision.deltaMessages });
24845
+ placeContinueCache(body, full);
24846
+ Object.assign(body, {
24847
+ diagnostics: {
24848
+ ...isBody(body.diagnostics) ? body.diagnostics : {},
24849
+ previous_message_id: decision.previousMessageId
24850
+ }
24851
+ });
24852
+ }
24853
+ return body;
24854
+ };
24855
+ return {
24856
+ decision,
24857
+ get body() {
24858
+ return outgoingBody();
24859
+ },
24860
+ normalizeToolName,
24861
+ fail,
24862
+ complete: (facts) => {
24863
+ const current = this.sessions.get(input.session);
24864
+ if (current?.token !== token2 || current.anchor)
24865
+ return;
24866
+ if (!facts.messageId || !facts.stopped || !facts.stopReason || facts.stopReason === "refusal" || facts.refusal || facts.fallback || facts.rewritten || Array.isArray(input.body.messages) && input.body.messages.length > this.hashBudget) {
24867
+ fail();
24868
+ return;
24869
+ }
24870
+ const replyFingerprint = facts.replyFingerprint ?? assistantReplyFingerprint(facts.reply, normalizeToolName);
24871
+ if (!replyFingerprint) {
24872
+ fail();
24873
+ return;
24874
+ }
24875
+ const completedAt = this.now();
24876
+ const completedSnapshot = snapshot ?? messageThreadSnapshot(input, identity3);
24877
+ this.messageHashes += completedSnapshot.messages.length;
24878
+ this.sessions.set(input.session, {
24879
+ token: token2,
24880
+ anchor: {
24881
+ ...completedSnapshot,
24882
+ messageId: facts.messageId,
24883
+ completedAt,
24884
+ replyFingerprint
24885
+ }
24886
+ });
24887
+ this.prune();
24888
+ }
24889
+ };
24890
+ }
24891
+ }
24892
+ function observeMessageThreadResponse(response, prepared) {
24893
+ if (!response.ok || !response.body) {
24894
+ prepared.fail();
24895
+ return response;
24896
+ }
24897
+ const reader = response.body.getReader();
24898
+ const framer = createSseFramer();
24899
+ const facts = { stopped: false };
24900
+ const reply = new ReplyFingerprint(prepared.normalizeToolName ?? (() => {
24901
+ return;
24902
+ }));
24903
+ let inspecting = true;
24904
+ let streamStart = true;
24905
+ const parse3 = (frame) => {
24906
+ const data = parseSseFrame(decodeSseFrame(frame, { streamStart })).data;
24907
+ streamStart = false;
24908
+ if (!data || data === "[DONE]")
24909
+ return;
24910
+ try {
24911
+ const event = JSON.parse(data);
24912
+ if (event.type === "message_start") {
24913
+ if (typeof event.message?.id === "string")
24914
+ facts.messageId = event.message.id;
24915
+ if (Array.isArray(event.message?.content)) {
24916
+ for (const [index, block] of event.message.content.entries()) {
24917
+ reply.start(index, block);
24918
+ reply.stop(index);
24919
+ }
24920
+ }
24921
+ }
24922
+ if (event.type === "content_block_start")
24923
+ reply.start(event.index, event.content_block);
24924
+ if (event.type === "content_block_delta")
24925
+ reply.delta(event.index, event.delta);
24926
+ if (event.type === "content_block_stop")
24927
+ reply.stop(event.index);
24928
+ const stop = event.delta?.stop_reason ?? event.message?.stop_reason;
24929
+ if (typeof stop === "string")
24930
+ facts.stopReason = stop;
24931
+ if (stop === "refusal" || event.content_block?.type === "refusal")
24932
+ facts.refusal = true;
24933
+ if (event.content_block?.type === "fallback" || [event.usage, event.message?.usage].some((usage) => usage?.iterations?.some((iteration) => iteration.type === "fallback_message")))
24934
+ facts.fallback = true;
24935
+ if (event.type === "message_stop")
24936
+ facts.stopped = true;
24937
+ if (event.type === "error")
24938
+ facts.rewritten = true;
24939
+ } catch {
24940
+ facts.rewritten = true;
24941
+ }
24942
+ };
24943
+ return new Response(new ReadableStream({
24944
+ async pull(controller) {
24945
+ try {
24946
+ const chunk = await reader.read();
24947
+ if (chunk.done) {
24948
+ if (inspecting && framer.finish())
24949
+ facts.rewritten = true;
24950
+ if (inspecting) {
24951
+ facts.replyFingerprint = reply.digest();
24952
+ prepared.complete(facts);
24953
+ }
24954
+ controller.close();
24955
+ return;
24956
+ }
24957
+ if (inspecting) {
24958
+ try {
24959
+ for (const frame of framer.push(chunk.value))
24960
+ parse3(frame);
24961
+ } catch {
24962
+ inspecting = false;
24963
+ prepared.fail();
24964
+ }
24965
+ }
24966
+ controller.enqueue(chunk.value);
24967
+ } catch (error) {
24968
+ prepared.fail();
24969
+ controller.error(error);
24970
+ }
24971
+ },
24972
+ cancel(reason) {
24973
+ prepared.fail();
24974
+ return reader.cancel(reason);
24975
+ }
24976
+ }, { highWaterMark: 0 }), {
24977
+ status: response.status,
24978
+ statusText: response.statusText,
24979
+ headers: response.headers
24980
+ });
24981
+ }
24982
+ function placeContinueCache(body, full) {
24983
+ const fixed = fixedCacheHolders(body);
24984
+ let remaining = Math.max(0, 4 - fixed.length - (body.cache_control ? 1 : 0));
24985
+ const messages = structuredClone(body.messages);
24986
+ body.messages = messages;
24987
+ const last = messages.findLast((message) => message.role !== "system");
24988
+ const selected = new Set(contentCacheHolders(last?.content));
24989
+ const fullMessages = Array.isArray(full.messages) ? full.messages.filter((message) => isBody(message) && message.role !== "system") : [];
24990
+ const template = contentCacheHolders(last?.content).at(-1)?.cache_control ?? messageCacheHolders(fullMessages).at(-1)?.cache_control;
24991
+ if (last && remaining > 0 && template && typeof last.content === "string") {
24992
+ last.content = [{ type: "text", text: last.content }];
24993
+ }
24994
+ const lastBlock = Array.isArray(last?.content) ? last.content.at(-1) : undefined;
24995
+ const cacheableLastBlock = isBody(lastBlock) ? lastBlock : undefined;
24996
+ const lastControl = cacheableLastBlock?.cache_control ?? template;
24997
+ let reserved;
24998
+ if (cacheableLastBlock && lastControl && remaining > 0) {
24999
+ cacheableLastBlock.cache_control = lastControl;
25000
+ reserved = cacheableLastBlock;
25001
+ remaining--;
25002
+ }
25003
+ for (const holder of messageCacheHolders(messages)) {
25004
+ if (holder === reserved)
25005
+ continue;
25006
+ if (selected.has(holder) && remaining > 0)
25007
+ remaining--;
25008
+ else
25009
+ delete holder.cache_control;
25010
+ }
25011
+ }
25012
+ function messageThreadBetas(headers) {
25013
+ const betas = (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter((beta) => beta && beta !== MESSAGE_THREADS_BETA);
25014
+ betas.push(MESSAGE_THREADS_BETA);
25015
+ headers.set("anthropic-beta", betas.join(","));
25016
+ return betas;
25017
+ }
25018
+ async function readThreadError(response) {
25019
+ if (response.status !== 400 && response.status !== 404)
25020
+ return;
25021
+ const reader = response.clone().body?.getReader();
25022
+ if (!reader)
25023
+ return;
25024
+ let text5 = "";
25025
+ let remaining = 16384;
25026
+ const decoder = new TextDecoder;
25027
+ try {
25028
+ while (remaining > 0) {
25029
+ const chunk = await reader.read();
25030
+ if (chunk.done)
25031
+ break;
25032
+ remaining -= chunk.value.byteLength;
25033
+ if (remaining < 0)
25034
+ return;
25035
+ text5 += decoder.decode(chunk.value, { stream: true });
25036
+ }
25037
+ const body = JSON.parse(text5);
25038
+ return isBody(body?.error) ? body.error : undefined;
25039
+ } catch {
25040
+ return;
25041
+ } finally {
25042
+ reader.cancel().catch(() => {});
25043
+ }
25044
+ }
25045
+ async function isMessageThreadRejection(response) {
25046
+ const error = await readThreadError(response);
25047
+ const code = isBody(error?.details) ? error.details.error_code : undefined;
25048
+ return response.status === 404 ? error?.type === "not_found_error" && code === "thread_not_found" : response.status === 400 && error?.type === "invalid_request_error" && [
25049
+ "thread_fingerprint_mismatch",
25050
+ "thread_already_continued",
25051
+ "thread_continue_in_flight",
25052
+ "thread_unsupported_request"
25053
+ ].includes(code);
25054
+ }
25055
+ async function isThreadCreateRejection(response) {
25056
+ if (response.status !== 400)
25057
+ return false;
25058
+ const error = await readThreadError(response);
25059
+ const code = isBody(error?.details) ? error.details.error_code : undefined;
25060
+ if (typeof code === "string" && code.startsWith("thread_"))
25061
+ return true;
25062
+ const message = typeof error?.message === "string" ? error.message : "";
25063
+ return message.includes(MESSAGE_THREADS_BETA) || /(?:^|\W)thread\s*[:.]|["'`]thread["'`]|(?:field|parameter|property|argument|input)s?\s*[:=]?\s+thread\b|^\s*thread\s+(?:is|was)\b/i.test(message);
25064
+ }
25065
+ var disabledThreadAccounts = new Set;
25066
+ function removeThreadBeta(headers) {
25067
+ const kept = (headers.get("anthropic-beta") ?? "").split(",").map((beta) => beta.trim()).filter((beta) => beta && beta !== MESSAGE_THREADS_BETA);
25068
+ if (kept.length)
25069
+ headers.set("anthropic-beta", kept.join(","));
25070
+ else
25071
+ headers.delete("anthropic-beta");
25072
+ }
25073
+ function disableThreadsForAccount(key) {
25074
+ if (disabledThreadAccounts.has(key))
25075
+ return;
25076
+ disabledThreadAccounts.add(key);
25077
+ logger.warn("message-threads", "Anthropic rejected message threads; using full stateless requests for this account until restart", { account: hash3(key).slice(0, 12) });
25078
+ }
25079
+ function ignoreThreadFailure() {}
25080
+ function threadFailureState(initial) {
25081
+ const state = { current: initial };
25082
+ return {
25083
+ replace: (fail) => {
25084
+ state.current = fail;
25085
+ },
25086
+ fail: () => state.current()
25087
+ };
25088
+ }
25089
+ function serializedCreate(text5, full) {
25090
+ if (/"thread"\s*:/.test(text5) && Object.hasOwn(full(), "thread"))
25091
+ return JSON.stringify({ ...full(), thread: { type: "create" } });
25092
+ const compactEnd = text5.trimEnd();
25093
+ if (!compactEnd.startsWith("{") && !compactEnd.trimStart().startsWith("{") || !compactEnd.endsWith("}"))
25094
+ throw new SyntaxError("Message request must be a JSON object");
25095
+ const prefix = compactEnd.slice(0, -1);
25096
+ return `${prefix}${prefix.trimEnd().endsWith("{") ? "" : ","}"thread":{"type":"create"}}${text5.slice(compactEnd.length)}`;
25097
+ }
25098
+ function serializedStateless(text5, full) {
25099
+ if (!/"thread"\s*:/.test(text5) || !Object.hasOwn(full(), "thread"))
25100
+ return text5;
25101
+ const body = { ...full() };
25102
+ delete body.thread;
25103
+ return JSON.stringify(body);
25104
+ }
25105
+ async function prepareMessageThreadRequest(tracker, input) {
25106
+ const fullText = input.bodyText;
25107
+ let full;
25108
+ const fullBody = () => full ??= JSON.parse(fullText);
25109
+ const accountKey = input.account;
25110
+ let threading = !disabledThreadAccounts.has(accountKey);
25111
+ const betas = threading ? messageThreadBetas(input.headers) : [];
25112
+ const prepareForSession = (credential3) => tracker.prepare({
25113
+ account: input.account,
25114
+ credential: credential3,
25115
+ session: input.session ?? "",
25116
+ betas,
25117
+ replyToolNames: input.replyToolNames,
25118
+ get body() {
25119
+ return fullBody();
25120
+ }
25121
+ });
25122
+ if (!threading) {
25123
+ removeThreadBeta(input.headers);
25124
+ if (input.session)
25125
+ tracker.forget(input.session);
25126
+ }
25127
+ let prepared = threading && input.session ? prepareForSession(input.credential) : {
25128
+ decision: { type: "create" },
25129
+ get body() {
25130
+ return threading ? { ...fullBody(), thread: { type: "create" } } : fullBody();
25131
+ },
25132
+ complete: () => {},
25133
+ normalizeToolName: () => {
25134
+ return;
25135
+ },
25136
+ fail: ignoreThreadFailure
25137
+ };
25138
+ const failure = threadFailureState(prepared.fail);
25139
+ const outgoing = threading ? prepared.decision.type === "continue" ? JSON.stringify(prepared.body) : serializedCreate(fullText, fullBody) : serializedStateless(fullText, fullBody);
25140
+ let bodyText = await signRequestBody(outgoing);
25141
+ let recovered = false;
25142
+ let credential2 = input.credential;
25143
+ const mayResend = async (rejected, authorize2) => {
25144
+ const result = await authorize2?.(rejected);
25145
+ if (result === false)
25146
+ return false;
25147
+ if (result && typeof result === "object")
25148
+ credential2 = result.credential;
25149
+ return true;
25150
+ };
25151
+ const latchStateless = () => {
25152
+ disableThreadsForAccount(accountKey);
25153
+ threading = false;
25154
+ removeThreadBeta(input.headers);
25155
+ };
25156
+ const prepareStateless = async () => {
25157
+ prepared.fail();
25158
+ latchStateless();
25159
+ bodyText = await signRequestBody(serializedStateless(fullText, fullBody));
25160
+ };
25161
+ return {
25162
+ get bodyText() {
25163
+ return bodyText;
25164
+ },
25165
+ fail: failure.fail,
25166
+ observe: (response) => {
25167
+ if (!threading || !input.session || disabledThreadAccounts.has(accountKey)) {
25168
+ prepared.fail();
25169
+ return response;
25170
+ }
25171
+ return observeMessageThreadResponse(response, {
25172
+ fail: failure.fail,
25173
+ normalizeToolName: prepared.normalizeToolName,
25174
+ complete: (facts) => {
25175
+ if (input.signal?.aborted)
25176
+ prepared.fail();
25177
+ else
25178
+ prepared.complete(facts);
25179
+ }
25180
+ });
25181
+ },
25182
+ async recover(response, send, beforeResend) {
25183
+ if (!threading || recovered)
25184
+ return response;
25185
+ const rejectedCreate = prepared.decision.type === "create" && await isThreadCreateRejection(response);
25186
+ const rejectedContinue = prepared.decision.type === "continue" && await isMessageThreadRejection(response);
25187
+ if (!rejectedCreate && !rejectedContinue)
25188
+ return response;
25189
+ recovered = true;
25190
+ if (!await mayResend(response, beforeResend)) {
25191
+ prepared.fail();
25192
+ if (rejectedCreate)
25193
+ latchStateless();
25194
+ return response;
25195
+ }
25196
+ prepared.fail();
25197
+ response.body?.cancel().catch(() => {});
25198
+ if (rejectedCreate || disabledThreadAccounts.has(accountKey)) {
25199
+ await prepareStateless();
25200
+ return send(bodyText);
25201
+ }
25202
+ if (input.session) {
25203
+ tracker.forget(input.session);
25204
+ prepared = prepareForSession(credential2);
25205
+ failure.replace(prepared.fail);
25206
+ }
25207
+ bodyText = await signRequestBody(serializedCreate(fullText, fullBody));
25208
+ const created = await send(bodyText);
25209
+ if (await isThreadCreateRejection(created)) {
25210
+ if (!await mayResend(created, beforeResend)) {
25211
+ prepared.fail();
25212
+ latchStateless();
25213
+ return created;
25214
+ }
25215
+ created.body?.cancel().catch(() => {});
25216
+ await prepareStateless();
25217
+ return send(bodyText);
25218
+ }
25219
+ return created;
25220
+ }
25221
+ };
25222
+ }
23829
25223
  // src/mid-conversation-output-config.ts
23830
25224
  function isRecord14(value) {
23831
25225
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -24149,7 +25543,7 @@ function nativeVaultPrimaryRow(roster, pin) {
24149
25543
  return roster?.rows.find((row) => row.routeId === pin.routeId && row.accountIdentity === pin.accountIdentity && (row.credentialId === pin.credentialId || row.aliases?.includes(pin.credentialId)));
24150
25544
  }
24151
25545
  var settingFields2 = {
24152
- routing: ["mode"],
25546
+ routing: ["mode", "maxSameAccountWait"],
24153
25547
  refresh: ["enabled", "intervalMinutes", "refreshBeforeExpiryMinutes"],
24154
25548
  quota: [
24155
25549
  "enabled",
@@ -24735,7 +26129,7 @@ function createNativeLocalRuntimeReaders(options) {
24735
26129
  }
24736
26130
 
24737
26131
  // src/native-refresh-coordinator.ts
24738
- import { createHash as createHash20 } from "node:crypto";
26132
+ import { createHash as createHash21 } from "node:crypto";
24739
26133
 
24740
26134
  // src/native-transient-account.ts
24741
26135
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -24837,7 +26231,7 @@ function pause(ms, signals) {
24837
26231
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
24838
26232
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
24839
26233
  function nativeAccountProviderLock(paths, identity3) {
24840
- const key = createHash20("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
26234
+ const key = createHash21("sha256").update(JSON.stringify([paths.storageId, identity3])).digest("hex");
24841
26235
  return {
24842
26236
  path: paths.state,
24843
26237
  name: `native-account-provider-${key}`,
@@ -25637,7 +27031,7 @@ function createNativeRefreshCoordinator(options) {
25637
27031
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
25638
27032
 
25639
27033
  // src/migration-source.ts
25640
- import { createHash as createHash21 } from "node:crypto";
27034
+ import { createHash as createHash22 } from "node:crypto";
25641
27035
  import { constants as constants3 } from "node:fs";
25642
27036
  import { lstat as lstat13, open as open10 } from "node:fs/promises";
25643
27037
  class NativeMigrationSourceError extends Error {
@@ -25736,7 +27130,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
25736
27130
  return sourceSnapshot({
25737
27131
  role,
25738
27132
  path: path2,
25739
- digest: createHash21("sha256").update(content).digest("hex"),
27133
+ digest: createHash22("sha256").update(content).digest("hex"),
25740
27134
  data: freezeJson(data),
25741
27135
  metadata: Object.freeze({
25742
27136
  uid: Number(before.uid),
@@ -28886,7 +30280,7 @@ function leaseNativeVaultRuntime(use, close) {
28886
30280
 
28887
30281
  // src/relay.ts
28888
30282
  import { Buffer as Buffer3 } from "node:buffer";
28889
- import { createHash as createHash22, randomBytes as randomBytes5 } from "node:crypto";
30283
+ import { createHash as createHash23, randomBytes as randomBytes5 } from "node:crypto";
28890
30284
  var WEBSOCKET_RELAY_URL = /^wss?:\/\//i;
28891
30285
  function effectiveRelayTransport(stored, url) {
28892
30286
  if (stored === "http" || stored === "websocket")
@@ -29037,7 +30431,7 @@ function generateRelayToken() {
29037
30431
  return randomBytes5(32).toString("base64url");
29038
30432
  }
29039
30433
  function hashBody(body) {
29040
- return `sha256:${createHash22("sha256").update(body).digest("hex")}`;
30434
+ return `sha256:${createHash23("sha256").update(body).digest("hex")}`;
29041
30435
  }
29042
30436
  function createStringPatch(previous, next) {
29043
30437
  let start = 0;
@@ -29082,6 +30476,8 @@ function createRelayPatch(previous, next) {
29082
30476
  };
29083
30477
  const previousWithNextCch = replaceRange(previous, previousCch.start, previousCch.end, nextCch.token);
29084
30478
  const tailPatch = createStringPatch(previousWithNextCch, next);
30479
+ if (tailPatch.start < cchPatch.start + cchPatch.deleteCount)
30480
+ return createStringPatch(previous, next);
29085
30481
  return isNoopPatch(tailPatch) ? cchPatch : [cchPatch, tailPatch];
29086
30482
  }
29087
30483
  return createStringPatch(previous, next);
@@ -31809,7 +33205,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
31809
33205
  }
31810
33206
 
31811
33207
  // src/native-migration.ts
31812
- import { createHash as createHash23 } from "node:crypto";
33208
+ import { createHash as createHash24 } from "node:crypto";
31813
33209
  import { lstat as lstat15, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
31814
33210
  import { dirname as dirname19, isAbsolute as isAbsolute7 } from "node:path";
31815
33211
  class NativeMigrationError extends Error {
@@ -32189,7 +33585,7 @@ function routingBytes(captured) {
32189
33585
  `;
32190
33586
  }
32191
33587
  function bytesDigest(bytes) {
32192
- return bytes === undefined ? null : createHash23("sha256").update(bytes).digest("hex");
33588
+ return bytes === undefined ? null : createHash24("sha256").update(bytes).digest("hex");
32193
33589
  }
32194
33590
  function expectedAuth(input, snapshot) {
32195
33591
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -33589,6 +34985,21 @@ var actions = Object.freeze([
33589
34985
  label: "Reset routing session",
33590
34986
  parameters: []
33591
34987
  },
34988
+ {
34989
+ ...ordinary,
34990
+ id: "routing-max-same-account-wait",
34991
+ command: "routing",
34992
+ group: "Routing",
34993
+ label: "Longest wait on the same account",
34994
+ parameters: [
34995
+ {
34996
+ id: "maxSameAccountWait",
34997
+ kind: "choice",
34998
+ required: true,
34999
+ choices: ["0", "15", "max"]
35000
+ }
35001
+ ]
35002
+ },
33592
35003
  {
33593
35004
  ...ordinary,
33594
35005
  id: "killswitch-on",
@@ -34620,10 +36031,17 @@ function knob(parameter) {
34620
36031
  return {
34621
36032
  kind: "choice",
34622
36033
  id: parameter.id,
34623
- label: parameter.id,
36034
+ label: parameter.id === "maxSameAccountWait" ? "Longest wait on the same account" : parameter.id,
34624
36035
  choices: [
34625
36036
  ...!parameter.required ? [{ value: "", label: "Default" }] : [],
34626
- ...parameter.choices.map((value) => ({ value, label: value }))
36037
+ ...parameter.choices.map((value) => ({
36038
+ value,
36039
+ label: parameter.id === "maxSameAccountWait" ? {
36040
+ "0": "Don't wait",
36041
+ "15": "15 minutes",
36042
+ max: "Until the cache expires"
36043
+ }[value] : value
36044
+ }))
34627
36045
  ]
34628
36046
  };
34629
36047
  case "number":
@@ -35029,11 +36447,8 @@ var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
35029
36447
  function placeholderSecret(integrationID) {
35030
36448
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
35031
36449
  }
35032
-
35033
- // ../../node_modules/@cortexkit/common-auth/dist/opencode2/install.js
35034
- var MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
35035
36450
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
35036
- import { createHash as createHash24 } from "node:crypto";
36451
+ import { createHash as createHash25 } from "node:crypto";
35037
36452
  import { constants as constants4 } from "node:fs";
35038
36453
  import { lstat as lstat16, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
35039
36454
  import { dirname as dirname20, resolve as resolve15 } from "node:path";
@@ -35312,7 +36727,7 @@ function canonical(value) {
35312
36727
  return JSON.stringify(value);
35313
36728
  }
35314
36729
  function digest2(value) {
35315
- return createHash24("sha256").update(canonical(value)).digest("hex");
36730
+ return createHash25("sha256").update(canonical(value)).digest("hex");
35316
36731
  }
35317
36732
  function code(error) {
35318
36733
  return object2(error) ? error.code : undefined;
@@ -35627,6 +37042,10 @@ function createNativeVaultNoRouteResponse(input) {
35627
37042
  return createStickyNoRouteResponse({
35628
37043
  routeQuotas: active2.flatMap((account) => account.quota ? [account.quota] : []),
35629
37044
  modelId,
37045
+ routeIdentities: active2.filter((account) => account.quota).map((account) => account.accountIdentity),
37046
+ routeAccountIds: active2.filter((account) => account.quota).map((account) => account.id),
37047
+ storage: snapshot.policyStorage,
37048
+ sessionId: input.sessionId,
35630
37049
  vaultPolicyLimits: [...limits]
35631
37050
  });
35632
37051
  }
@@ -35635,7 +37054,7 @@ class NativeVaultQuotaPolicyError extends Error {
35635
37054
  response;
35636
37055
  body;
35637
37056
  kind = "quota-policy";
35638
- status = 429;
37057
+ status;
35639
37058
  headers;
35640
37059
  retryAfter;
35641
37060
  constructor(response, body) {
@@ -35643,6 +37062,7 @@ class NativeVaultQuotaPolicyError extends Error {
35643
37062
  this.response = response;
35644
37063
  this.body = body;
35645
37064
  this.name = "NativeVaultQuotaPolicyError";
37065
+ this.status = response.status;
35646
37066
  this.headers = new Headers(response.headers);
35647
37067
  this.retryAfter = Number(this.headers.get("retry-after"));
35648
37068
  }
@@ -35704,7 +37124,7 @@ function createAnthropicOAuthFetch(options = {}) {
35704
37124
  });
35705
37125
  }
35706
37126
  // src/prime.ts
35707
- import { createHash as createHash25 } from "node:crypto";
37127
+ import { createHash as createHash26 } from "node:crypto";
35708
37128
  import { realpathSync as realpathSync3 } from "node:fs";
35709
37129
  import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat11, writeFile as writeFile5 } from "node:fs/promises";
35710
37130
  import { tmpdir as tmpdir7 } from "node:os";
@@ -35908,7 +37328,7 @@ function primeStorageFingerprint(storagePath) {
35908
37328
  throw error;
35909
37329
  canonicalPath2 = absolutePath;
35910
37330
  }
35911
- return createHash25("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37331
+ return createHash26("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
35912
37332
  }
35913
37333
  function primeMarkerNamespaceDir(markerDir, storagePath) {
35914
37334
  return join24(markerDir, primeStorageFingerprint(storagePath));
@@ -37109,9 +38529,9 @@ var TRAILING_ASSISTANT_HISTORY_MESSAGE = "Cannot send this request: the history
37109
38529
  class TrailingAssistantHistoryError extends Error {
37110
38530
  details;
37111
38531
  check = "meaningful_trailing_assistant";
37112
- constructor(details) {
38532
+ constructor(details2) {
37113
38533
  super(TRAILING_ASSISTANT_HISTORY_MESSAGE);
37114
- this.details = details;
38534
+ this.details = details2;
37115
38535
  this.name = "TrailingAssistantHistoryError";
37116
38536
  }
37117
38537
  }
@@ -37175,93 +38595,6 @@ function stripEmptyTrailingAssistantMessages(messages) {
37175
38595
  messages.length -= removed;
37176
38596
  return removed;
37177
38597
  }
37178
- // src/routing.ts
37179
- var CLAUDE_ROUTING_COMMAND_NAME = "claude-routing";
37180
- var ROUTING_MODES = [
37181
- "main-first",
37182
- "fallback-first",
37183
- "sticky-balanced"
37184
- ];
37185
- var DEFAULT_ROUTING_MODE = "main-first";
37186
- var ROUTING_USAGE = "Usage: `/claude-routing`, `/claude-routing main-first`, `/claude-routing fallback-first`, `/claude-routing sticky-balanced`, or `/claude-routing reset`.";
37187
- function normalizeRoutingMode(value) {
37188
- return typeof value === "string" && ROUTING_MODES.includes(value) ? value : DEFAULT_ROUTING_MODE;
37189
- }
37190
- function getRoutingMode(storage) {
37191
- return normalizeRoutingMode(storage?.routing?.mode);
37192
- }
37193
- function parseRoutingCommandAction(argumentsText) {
37194
- const tokens = argumentsText.trim().toLowerCase().split(/\s+/).filter(Boolean);
37195
- if (tokens.length === 0)
37196
- return { type: "status" };
37197
- if (tokens.length === 1 && tokens[0] === "reset")
37198
- return { type: "reset" };
37199
- if (tokens.length === 1 && ROUTING_MODES.includes(tokens[0])) {
37200
- return { type: "mode", mode: tokens[0] };
37201
- }
37202
- if (tokens.length === 2 && tokens[0] === "mode" && ROUTING_MODES.includes(tokens[1])) {
37203
- return { type: "mode", mode: tokens[1] };
37204
- }
37205
- return { type: "usage" };
37206
- }
37207
- function routingDescription(mode) {
37208
- if (mode === "fallback-first") {
37209
- return "Try usable fallback accounts before the main account. If no fallback succeeds, try the main account.";
37210
- }
37211
- if (mode === "sticky-balanced") {
37212
- return "Assign each session to a quota-weighted OAuth account, keep it sticky across transient failures, and migrate only for confirmed long-lived exhaustion or permanent account failure.";
37213
- }
37214
- return "Try the main account first. Use fallback accounts only when quota policy or fallback errors require it.";
37215
- }
37216
- function buildRoutingStatusSummary(input) {
37217
- const mode = input?.mode ?? DEFAULT_ROUTING_MODE;
37218
- return [
37219
- "## Claude Routing Status",
37220
- "",
37221
- `- Mode: \`${mode}\``,
37222
- `- Behavior: ${routingDescription(mode)}`,
37223
- "",
37224
- ROUTING_USAGE
37225
- ].join(`
37226
- `);
37227
- }
37228
- function executeRoutingCommand(input) {
37229
- const action = parseRoutingCommandAction(input.argumentsText);
37230
- const mode = input.mode ?? DEFAULT_ROUTING_MODE;
37231
- if (action.type === "status")
37232
- return buildRoutingStatusSummary({ mode });
37233
- if (action.type === "mode") {
37234
- return [
37235
- "## Claude Routing Updated",
37236
- "",
37237
- `Mode updated to \`${action.mode}\`.`,
37238
- "",
37239
- ...buildRoutingStatusSummary({ mode: action.mode }).split(`
37240
- `).slice(2)
37241
- ].join(`
37242
- `);
37243
- }
37244
- if (action.type === "reset") {
37245
- return [
37246
- "## Claude Routing Assignment Reset",
37247
- "",
37248
- "The current session will be assigned again on its next request.",
37249
- "",
37250
- ...buildRoutingStatusSummary({ mode }).split(`
37251
- `).slice(2)
37252
- ].join(`
37253
- `);
37254
- }
37255
- return [
37256
- "## Claude Routing Usage",
37257
- "",
37258
- ROUTING_USAGE,
37259
- "",
37260
- ...buildRoutingStatusSummary({ mode }).split(`
37261
- `).slice(2)
37262
- ].join(`
37263
- `);
37264
- }
37265
38598
  // src/start.ts
37266
38599
  var CLAUDE_START_COMMAND_NAME = "claude-start";
37267
38600
  var START_STATUS_TITLE = "## Claude Lane Start Status";
@@ -39536,6 +40869,7 @@ export {
39536
40869
  setCache1hMode,
39537
40870
  setCache1hEnabled,
39538
40871
  setBounded,
40872
+ sessionCacheActivity,
39539
40873
  sendsPerTurnControlBeta,
39540
40874
  sendWithRequestGzip,
39541
40875
  sendViaRelay,
@@ -39599,6 +40933,8 @@ export {
39599
40933
  quotaSnapshotModelScopeIsExhausted,
39600
40934
  quotaSnapshotHasStandardWindows,
39601
40935
  quotaSnapshotCheckedAt,
40936
+ quotaRefusalTiming,
40937
+ quotaRefusalDetails,
39602
40938
  quotaFieldSource,
39603
40939
  quotaExhaustionFromHeaders,
39604
40940
  quotaDisplayProjection,
@@ -39616,6 +40952,7 @@ export {
39616
40952
  primeEligibilityReasonLabel,
39617
40953
  primeAccountMarkerDir,
39618
40954
  prepareNativeMigration,
40955
+ prepareMessageThreadRequest,
39619
40956
  pinsEffortOnEveryRequest,
39620
40957
  parseSseFrame,
39621
40958
  parseRoutingCommandAction,
@@ -39636,12 +40973,14 @@ export {
39636
40973
  orderClaudeCodeBody,
39637
40974
  openNativePiAuthSlot,
39638
40975
  openCodeHolderKind,
40976
+ observeMessageThreadResponse,
39639
40977
  oauthProfileMatchesIdentity,
39640
40978
  oauthProfileIsFresh,
39641
40979
  normalizeQuotaHeaders,
39642
40980
  normalizeKillswitchThresholds,
39643
40981
  normalizeAnthropicModelId,
39644
40982
  normalizeAdaptiveEffort,
40983
+ nativeVaultRuntimeKey,
39645
40984
  nativeSettingsRecord,
39646
40985
  nativeRuntimeOptionIdentity,
39647
40986
  nativeRelocationRuntimePaths,
@@ -39661,6 +41000,8 @@ export {
39661
41000
  nativeAccountPolicy,
39662
41001
  nativeAccountCanServe,
39663
41002
  migrateStickyRoutingState,
41003
+ messageThreadSnapshot,
41004
+ messageThreadBetas,
39664
41005
  mergeNativeSettingsSection,
39665
41006
  mergeMainRefreshErrorClearedAt,
39666
41007
  mergeMainQuotaErrorClearedAt,
@@ -39690,6 +41031,7 @@ export {
39690
41031
  isOAuthAccount,
39691
41032
  isNativeTransientAccountError,
39692
41033
  isNativeLocalCredentialValidation,
41034
+ isMessageThreadRejection,
39693
41035
  isKillswitchEnabled,
39694
41036
  isFastModeSupportedModel,
39695
41037
  isFastModePersistentlyEnabled,
@@ -39743,6 +41085,7 @@ export {
39743
41085
  getPersistedLogLevel,
39744
41086
  getOpenCodeConfigDir,
39745
41087
  getNativeMenuModel,
41088
+ getMaxSameAccountWait,
39746
41089
  getLogLevel,
39747
41090
  getLogFilePath,
39748
41091
  getKillswitchThresholdsForAccount,
@@ -39820,6 +41163,7 @@ export {
39820
41163
  decidePiStateLayout,
39821
41164
  decideOpenCodeStateLayoutOnce,
39822
41165
  decideOpenCodeStateLayout,
41166
+ decideMessageThread,
39823
41167
  custodyTombstoneOAuth,
39824
41168
  custodyTombstoneKey,
39825
41169
  custodyStatusLabel,
@@ -39828,6 +41172,8 @@ export {
39828
41172
  createStickyNoRouteResponse,
39829
41173
  createSseFramer,
39830
41174
  createRelocationGuard,
41175
+ createRelayPatch,
41176
+ createQuotaRefusalResponse,
39831
41177
  createProviderErrorResponseScope,
39832
41178
  createProviderErrorRedactor,
39833
41179
  createProcessFence,
@@ -39907,10 +41253,11 @@ export {
39907
41253
  THINKING_BINDING_CONTROLS_BETA,
39908
41254
  TEXT_REPLACEMENTS,
39909
41255
  StickySessionRouter,
41256
+ StickyQuotaRetryCounter,
39910
41257
  StateLayoutRefusalError,
39911
41258
  StateLayoutFileError,
39912
41259
  SseFrameTooLargeError,
39913
- STICKY_ROUTING_SHORT_RESET_GRACE_MS,
41260
+ SessionCacheActivity,
39914
41261
  STICKY_ROUTING_MAIN_ACCOUNT_ID,
39915
41262
  STICKY_ROUTING_ASSIGNMENT_TTL_MS,
39916
41263
  STATE_LAYOUT_REFUSAL_PUBLIC_MESSAGES,
@@ -39935,6 +41282,8 @@ export {
39935
41282
  QUOTA_HEADER_FEED_LEASE_MS,
39936
41283
  QUOTA_FIELD_NAMES,
39937
41284
  PrimeManager,
41285
+ PROMPT_CACHE_DEFAULT_TTL_MS,
41286
+ PROMPT_CACHE_1H_TTL_MS,
39938
41287
  PROFILE_TTL_MS,
39939
41288
  PRODUCTION_CLAUSTRUM_CONNECTION_FILE_NAME,
39940
41289
  PRIVATE_FILES_UNAVAILABLE_MESSAGE,
@@ -39962,6 +41311,10 @@ export {
39962
41311
  NativeCustodyActivationError,
39963
41312
  NativeAccountRefusal,
39964
41313
  NATIVE_VAULT_NO_ACCOUNT_MESSAGE,
41314
+ MessageThreadTracker,
41315
+ MESSAGE_THREADS_BETA,
41316
+ MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES,
41317
+ MAX_SAME_ACCOUNT_WAITS,
39965
41318
  LOGGING_LEVELS,
39966
41319
  LEGACY_STATE_LAYOUT,
39967
41320
  KILLSWITCH_COMMAND_NAME,
@@ -39977,6 +41330,7 @@ export {
39977
41330
  FALLBACK_BACKGROUND_TICK_MS,
39978
41331
  DEFAULT_SSE_MAX_FRAME_BYTES,
39979
41332
  DEFAULT_ROUTING_MODE,
41333
+ DEFAULT_MAX_SAME_ACCOUNT_WAIT,
39980
41334
  DEFAULT_KILLSWITCH_THRESHOLDS,
39981
41335
  DEFAULT_CACHE_1H_MODE,
39982
41336
  CustodyTombstoneRefreshError,