@cortexkit/anthropic-auth-core 2.4.13 → 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;
1153
- 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;
1214
+ let stillOurs = false;
1161
1215
  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;
1280
1354
  }
1355
+ try {
1356
+ await releaseEvictionMarker(deadline);
1357
+ } catch (error) {
1358
+ if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
1359
+ throw actionError;
1360
+ throw error;
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
  }
@@ -6981,6 +7070,7 @@ function bodyStructureSummary(bodyText) {
6981
7070
  parseable: true,
6982
7071
  model: typeof parsed.model === "string" ? parsed.model : undefined,
6983
7072
  stream: parsed.stream,
7073
+ thread: parsed.thread,
6984
7074
  systemCount: system.length,
6985
7075
  messagesCount: messages.length,
6986
7076
  systemHash: hashJson(system),
@@ -7028,7 +7118,9 @@ async function dumpRequest(input) {
7028
7118
  try {
7029
7119
  await mkdir6(dumpDir, { recursive: true });
7030
7120
  const previousBodyText = input.previousBodyText ?? await loadLatestDumpBody(input);
7121
+ const bodySummary = bodyStructureSummary(input.bodyText);
7031
7122
  const metadata = {
7123
+ thread: "thread" in bodySummary ? bodySummary.thread : undefined,
7032
7124
  id,
7033
7125
  createdAt: new Date().toISOString(),
7034
7126
  session: shortAffinity(affinity),
@@ -7043,7 +7135,7 @@ async function dumpRequest(input) {
7043
7135
  relayBytes: input.relayBytes,
7044
7136
  bodyHash: hashText(input.bodyText),
7045
7137
  diff: diffSummary(previousBodyText, input.bodyText),
7046
- body: bodyStructureSummary(input.bodyText),
7138
+ body: bodySummary,
7047
7139
  files
7048
7140
  };
7049
7141
  const writes = [
@@ -7915,7 +8007,7 @@ function acquireInsulaQuotaSource(transport, tokenPath) {
7915
8007
  }
7916
8008
 
7917
8009
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/index.js
7918
- import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
8010
+ import { ClaustrumCredentialError as ClaustrumCredentialError5 } from "@cortexkit/claustrum-client";
7919
8011
  // ../../node_modules/@cortexkit/common-auth/dist/logger/engine.js
7920
8012
  import { appendFileSync as appendFileSync2, chmodSync, existsSync as existsSync3, renameSync as renameSync2, statSync as statSync4 } from "node:fs";
7921
8013
  import { open as open5 } from "node:fs/promises";
@@ -8225,7 +8317,7 @@ function combineAbortSignals(signals) {
8225
8317
 
8226
8318
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8227
8319
  import { channel } from "node:diagnostics_channel";
8228
- import { ClaustrumCredentialError as ClaustrumCredentialError3 } from "@cortexkit/claustrum-client";
8320
+ import { ClaustrumCredentialError as ClaustrumCredentialError4 } from "@cortexkit/claustrum-client";
8229
8321
 
8230
8322
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/host-slot.js
8231
8323
  var CUSTODY_PLACEHOLDER_PREFIX = "claustrum-tombstone:v1:";
@@ -8268,6 +8360,134 @@ async function drainShutdown(pending, onTimeout) {
8268
8360
  }
8269
8361
  }
8270
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
+
8271
8491
  // ../../node_modules/@cortexkit/common-auth/dist/claustrum/custody.js
8272
8492
  function isScopedCredentialRotation(served, current) {
8273
8493
  return current !== undefined && !current.fromKeptReceipt && !served.fromKeptReceipt && current.credentialId === served.credentialId && current.accountIdentity === served.accountIdentity && current.recordVersion !== served.recordVersion;
@@ -8284,6 +8504,12 @@ function scopedRetryReason(served, current) {
8284
8504
  return "rotated";
8285
8505
  }
8286
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
+ }
8287
8513
  var phaseDiagnostics = channel("common-auth.claustrum.phases");
8288
8514
  function decideScopedRetryAfter401(site, served, current, logger2 = defaultLogger) {
8289
8515
  const retry = isScopedCredentialRotation(served, current);
@@ -8398,6 +8624,8 @@ class ClaustrumScopedCustody {
8398
8624
  #reports = new WeakMap;
8399
8625
  #kept = new Map;
8400
8626
  #keptAttempts = new WeakMap;
8627
+ #usage;
8628
+ #usageServed = new Map;
8401
8629
  #setTimeout;
8402
8630
  #clearTimeout;
8403
8631
  #outage = false;
@@ -8411,6 +8639,7 @@ class ClaustrumScopedCustody {
8411
8639
  #watches = new Set;
8412
8640
  #tokenReads = new Set;
8413
8641
  #warnShutdown;
8642
+ #onDrainTimeout;
8414
8643
  #disposing;
8415
8644
  constructor(options) {
8416
8645
  const tokenPath = options.tokenPath;
@@ -8430,12 +8659,20 @@ class ClaustrumScopedCustody {
8430
8659
  this.#warnShutdown = shutdownWarning(this.#logger);
8431
8660
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
8432
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
+ });
8433
8670
  }
8434
8671
  transportLost(error) {
8435
8672
  if (this.#closed || this.#outage)
8436
8673
  return;
8437
8674
  this.#outage = true;
8438
- this.#outageError = error instanceof ClaustrumCredentialError3 ? error : new ClaustrumUnreachableError;
8675
+ this.#outageError = error instanceof ClaustrumCredentialError4 ? error : new ClaustrumUnreachableError;
8439
8676
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
8440
8677
  this.#scheduleProbe();
8441
8678
  }
@@ -8503,10 +8740,7 @@ class ClaustrumScopedCustody {
8503
8740
  });
8504
8741
  }
8505
8742
  this.#check(signal);
8506
- if (!/^[0-9a-f]{64}$/.test(value.token) || !Number.isSafeInteger(value.token_generation) || value.token_generation < 1) {
8507
- throw new ClaustrumConsumerError("invalid-token", "Invalid Claustrum enrollment token");
8508
- }
8509
- return value.token;
8743
+ return checkedEnrollmentToken(value);
8510
8744
  }
8511
8745
  async#call(operation, signal) {
8512
8746
  this.#check(signal);
@@ -8530,7 +8764,7 @@ class ClaustrumScopedCustody {
8530
8764
  this.transportLost(error);
8531
8765
  else
8532
8766
  this.reachable();
8533
- if (error instanceof ClaustrumCredentialError3)
8767
+ if (error instanceof ClaustrumCredentialError4)
8534
8768
  throw error;
8535
8769
  if (classifyVaultFailure(error) === "unreachable")
8536
8770
  throw new ClaustrumUnreachableError;
@@ -8554,6 +8788,7 @@ class ClaustrumScopedCustody {
8554
8788
  token = await this.#token(signal);
8555
8789
  } catch (error) {
8556
8790
  this.#kept.clear();
8791
+ this.#clearUsageOwnership();
8557
8792
  throw error;
8558
8793
  }
8559
8794
  if (phaseDiagnostics.hasSubscribers)
@@ -8649,10 +8884,18 @@ class ClaustrumScopedCustody {
8649
8884
  else {
8650
8885
  this.reachable();
8651
8886
  this.#kept.clear();
8887
+ this.#clearUsageOwnership();
8652
8888
  }
8653
8889
  }
8654
8890
  forget(credentialId) {
8655
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();
8656
8899
  }
8657
8900
  retain(identities) {
8658
8901
  const current = new Map(identities.map((identity2) => [identity2.credentialId, identity2]));
@@ -8661,6 +8904,11 @@ class ClaustrumScopedCustody {
8661
8904
  if (!identity2?.enabled || identity2.state !== "active" || identity2.credentialType !== kept.attempt.credentialType || identity2.accountIdentity !== kept.attempt.expectedAccountIdentity)
8662
8905
  this.forget(id);
8663
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
+ }
8664
8912
  }
8665
8913
  keptReceiptState() {
8666
8914
  let since = null;
@@ -8690,6 +8938,7 @@ class ClaustrumScopedCustody {
8690
8938
  token = await this.#token(signal);
8691
8939
  } catch (error) {
8692
8940
  this.#kept.clear();
8941
+ this.#clearUsageOwnership();
8693
8942
  throw error;
8694
8943
  }
8695
8944
  if (this.#outage && kept) {
@@ -8699,6 +8948,7 @@ class ClaustrumScopedCustody {
8699
8948
  try {
8700
8949
  const attempt = await this.#authorizeFresh({ credentialId, credentialType, accountIdentity }, token, signal);
8701
8950
  this.#kept.set(credentialId, { attempt, routeId, since: null });
8951
+ this.#usageServed.set(credentialId, { ...identity2 });
8702
8952
  return attempt;
8703
8953
  } catch (error) {
8704
8954
  this.#check(signal);
@@ -8851,6 +9101,16 @@ class ClaustrumScopedCustody {
8851
9101
  }
8852
9102
  };
8853
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
+ }
8854
9114
  close() {
8855
9115
  if (this.#closed)
8856
9116
  return;
@@ -8862,11 +9122,22 @@ class ClaustrumScopedCustody {
8862
9122
  watch.stop();
8863
9123
  this.#watches.clear();
8864
9124
  this.#kept.clear();
8865
- 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
+ });
8866
9137
  }
8867
9138
  async dispose(onTimeout = this.#warnShutdown) {
9139
+ this.#onDrainTimeout = onTimeout;
8868
9140
  this.close();
8869
- this.#disposing ??= drainShutdown(this.#tokenReads, onTimeout);
8870
9141
  await this.#disposing;
8871
9142
  }
8872
9143
  }
@@ -9607,6 +9878,7 @@ function projectVaultRoster(previous, inventory, options = {}) {
9607
9878
  return {
9608
9879
  version: 1,
9609
9880
  view: inventory.view,
9881
+ ...previous?.limits !== undefined && { limits: previous.limits },
9610
9882
  complete,
9611
9883
  ...!complete && {
9612
9884
  rejected: inventory.skipped.map((record2) => ({
@@ -9681,6 +9953,7 @@ function decodeRoster(value) {
9681
9953
  ...typeof value.view === "string" && { view: value.view },
9682
9954
  complete: value.complete !== false,
9683
9955
  ...rejected && { rejected },
9956
+ ...value.limits !== undefined && { limits: value.limits },
9684
9957
  rows,
9685
9958
  declined
9686
9959
  };
@@ -10728,6 +11001,27 @@ class ClaustrumConsumer {
10728
11001
  combined.dispose();
10729
11002
  }
10730
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
+ }
10731
11025
  async reportFailure(attempt, status, source) {
10732
11026
  this.#assertOpen();
10733
11027
  if (this.#hub) {
@@ -11262,6 +11556,14 @@ class ClaustrumDiscoveryHub {
11262
11556
  check();
11263
11557
  return custody.reportFailure(attempt, status, source);
11264
11558
  },
11559
+ reportUsage: (input) => {
11560
+ if (!state.released && !generation.ended)
11561
+ custody.reportUsage(input);
11562
+ },
11563
+ usageReportState: () => {
11564
+ check();
11565
+ return custody.usageReportState();
11566
+ },
11265
11567
  forget: (credentialId) => {
11266
11568
  check();
11267
11569
  custody.forget(credentialId);
@@ -11742,7 +12044,7 @@ import {
11742
12044
  resolve as resolve11
11743
12045
  } from "node:path";
11744
12046
  import {
11745
- ClaustrumCredentialError as ClaustrumCredentialError5,
12047
+ ClaustrumCredentialError as ClaustrumCredentialError6,
11746
12048
  ClaustrumClient as ClaustrumWireClient2,
11747
12049
  writeEnrollmentTokenFile as writeEnrollmentTokenFile3
11748
12050
  } from "@cortexkit/claustrum-client";
@@ -12496,7 +12798,7 @@ class ClaustrumEnrollmentManager2 {
12496
12798
  };
12497
12799
  await writeStateAtomic2(this.#paths.statePath, state, () => lock.assertOwned());
12498
12800
  } catch (error) {
12499
- if (error instanceof ClaustrumCredentialError5) {
12801
+ if (error instanceof ClaustrumCredentialError6) {
12500
12802
  if (!TERMINAL_ENROLLMENT_CODES2.has(error.code) && (error.code === "pending_queue_full" || error.action === "retry")) {
12501
12803
  return {
12502
12804
  state: "pending",
@@ -12552,7 +12854,7 @@ class ClaustrumEnrollmentManager2 {
12552
12854
  await writeStateAtomic2(this.#paths.statePath, approved, () => lock.assertOwned());
12553
12855
  return statusFromState2(approved);
12554
12856
  } catch (error) {
12555
- if (!(error instanceof ClaustrumCredentialError5))
12857
+ if (!(error instanceof ClaustrumCredentialError6))
12556
12858
  throw error;
12557
12859
  if (!TERMINAL_ENROLLMENT_CODES2.has(error.code) && error.action === "retry") {
12558
12860
  return {
@@ -12681,7 +12983,7 @@ function createNativeCustody(options) {
12681
12983
  return await operation(owned);
12682
12984
  } catch (error) {
12683
12985
  check();
12684
- if (error instanceof ClaustrumCredentialError4 && error.code === "enrollment_revoked")
12986
+ if (error instanceof ClaustrumCredentialError5 && error.code === "enrollment_revoked")
12685
12987
  revoked = true;
12686
12988
  if (error instanceof NativeCustodyError)
12687
12989
  throw new ClaustrumConsumerError(error.code, "Native custody operation refused");
@@ -12850,7 +13152,7 @@ function createNativeCustody(options) {
12850
13152
  onMode: watchOptions.onMode,
12851
13153
  onRefused: (error) => {
12852
13154
  watchOptions.onRefused?.(error);
12853
- if (error instanceof ClaustrumCredentialError4 && error.code === "enrollment_revoked")
13155
+ if (error instanceof ClaustrumCredentialError5 && error.code === "enrollment_revoked")
12854
13156
  custody.close();
12855
13157
  },
12856
13158
  onError: watchOptions.onError
@@ -14597,10 +14899,16 @@ async function buildCacheKeepPrewarmBody(bodyText, options = {}) {
14597
14899
  } catch {
14598
14900
  return { ok: false, reason: "body is not valid JSON" };
14599
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
+ };
14600
14907
  if (!hasExplicitCacheControl(body)) {
14601
14908
  return { ok: false, reason: "body has no explicit cache breakpoints" };
14602
14909
  }
14603
14910
  const warm = structuredClone(body);
14911
+ delete warm.thread;
14604
14912
  stripBillingLineageFromBody(warm);
14605
14913
  warm.max_tokens = 0;
14606
14914
  delete warm.stream;
@@ -14880,6 +15188,13 @@ class CacheKeepManager {
14880
15188
  if (bodyBytes > CACHE_KEEP_MAX_BODY_BYTES) {
14881
15189
  return refuse("body exceeds cachekeep memory budget", "body-budget");
14882
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
+ }
14883
15198
  const window = getCacheKeepWindow(input.storage);
14884
15199
  if (!isCacheKeepActiveNow(input.storage, new Date(now))) {
14885
15200
  return refuse("outside configured schedule", "outside-schedule");
@@ -15354,24 +15669,32 @@ function recordIdentityIn(tx, id, identity2) {
15354
15669
  raw.accountId = identity2;
15355
15670
  return disableIdentityDuplicates(tx, identity2);
15356
15671
  }
15357
- // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
15358
- import { setTimeout as snapshotDelay } from "node:timers/promises";
15359
-
15360
15672
  // ../../node_modules/@cortexkit/common-auth/dist/store/hooks.js
15361
15673
  import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
15362
15674
  var insideHook = new AsyncLocalStorage3;
15675
+ var insideCodec = new AsyncLocalStorage3;
15363
15676
  function assertNotInsideHook(operation) {
15364
15677
  if (insideHook.getStore() !== undefined)
15365
15678
  throw new PoolReentryError(operation);
15366
15679
  }
15367
- function runInsideHook(operation, fn) {
15368
- 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());
15369
15692
  }
15370
15693
  async function callFailureHook(operation, hook, rowId, error, logger3) {
15371
15694
  if (!hook)
15372
15695
  return;
15373
15696
  try {
15374
- await runInsideHook(operation, () => hook(rowId, error));
15697
+ await runInsideHook(operation, () => hook(rowId, error), true);
15375
15698
  } catch (hookError) {
15376
15699
  logger3?.warn("store failure hook threw; the original failure stands", {
15377
15700
  operation,
@@ -15381,6 +15704,9 @@ async function callFailureHook(operation, hook, rowId, error, logger3) {
15381
15704
  }
15382
15705
  }
15383
15706
 
15707
+ // ../../node_modules/@cortexkit/common-auth/dist/store/mutate.js
15708
+ import { setTimeout as snapshotDelay } from "node:timers/promises";
15709
+
15384
15710
  // ../../node_modules/@cortexkit/common-auth/dist/store/refresh-lock.js
15385
15711
  var POOL_LOCK_DEFAULTS = Object.freeze({
15386
15712
  ttlMs: 1e4,
@@ -15604,7 +15930,7 @@ function stampFor(credential, credentialEpoch, binding, options = {}) {
15604
15930
  };
15605
15931
  }
15606
15932
  function providerStateDigest(codec, value) {
15607
- const bound = codec?.credentialBound ? codec.credentialBound(value) : value;
15933
+ const bound = codec?.credentialBound ? runInsideCodec(() => codec.credentialBound?.(value)) : value;
15608
15934
  return createHash10("sha256").update(`provider-state\x00${JSON.stringify(bound ?? null)}`).digest("hex");
15609
15935
  }
15610
15936
  function boundProviderStateDigest(account, credential, credentialEpoch, identity2) {
@@ -15771,8 +16097,8 @@ function parseEntry(raw, codec) {
15771
16097
  return;
15772
16098
  if ("disabledReason" in raw && typeof raw.disabledReason !== "string")
15773
16099
  return;
15774
- const quota = "quota" in raw && codec.decode ? codec.decode(raw.quota) : raw.quota;
15775
- 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)))
15776
16102
  return;
15777
16103
  if ("staged" in raw && !parseReservation(raw.staged))
15778
16104
  return;
@@ -15944,7 +16270,7 @@ function providerStateFields(account, credential, credentialEpoch, identity2, co
15944
16270
  if (digest === undefined)
15945
16271
  return { providerStateDropped: "uncovered" };
15946
16272
  const value = account[PROVIDER_STATE_KEY];
15947
- if (!codec?.validate(value))
16273
+ if (!codec || !runInsideCodec(() => codec.validate(value)))
15948
16274
  return { providerStateDropped: "invalid" };
15949
16275
  if (providerStateDigest(codec, value) !== digest)
15950
16276
  return { providerStateDropped: "uncovered" };
@@ -16642,8 +16968,8 @@ function assertQuotaRow(id, attribution, row) {
16642
16968
  });
16643
16969
  }
16644
16970
  function mergedQuota(ctx, id, stored, observation) {
16645
- const merged = ctx.codec.merge(stored, observation);
16646
- if (!ctx.codec.validate(merged))
16971
+ const merged = runInsideCodec(() => ctx.codec.merge(stored, observation));
16972
+ if (!runInsideCodec(() => ctx.codec.validate(merged)))
16647
16973
  throw refusal("pull", id, "invalid-quota", "the quota codec rejected the merged map");
16648
16974
  return merged;
16649
16975
  }
@@ -16671,6 +16997,38 @@ async function recordQuota(rt, id, attribution, observation) {
16671
16997
  }
16672
16998
  }
16673
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
+
16674
17032
  // ../../node_modules/@cortexkit/common-auth/dist/store/provider-state.js
16675
17033
  function acceptProviderState(codec, operation, id, value, what = "the provider state") {
16676
17034
  if (!codec)
@@ -16684,7 +17042,7 @@ function acceptProviderState(codec, operation, id, value, what = "the provider s
16684
17042
  }
16685
17043
  if (normalized === undefined)
16686
17044
  throw refusal(operation, id, "invalid-provider-state", `${what} cannot be stored as JSON`);
16687
- if (!codec.validate(normalized))
17045
+ if (!runInsideCodec(() => codec.validate(normalized)))
16688
17046
  throw refusal(operation, id, "invalid-provider-state", `the provider-state codec rejected ${what}`);
16689
17047
  return normalized;
16690
17048
  }
@@ -16693,18 +17051,18 @@ function mergedProviderState(codec, operation, id, onDisk, incoming) {
16693
17051
  return { kind: "set", value: incoming };
16694
17052
  return {
16695
17053
  kind: "set",
16696
- 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")
16697
17055
  };
16698
17056
  }
16699
17057
  function replacementProviderState(codec, row, credentialEpoch, identity2, incoming) {
16700
17058
  const hook = codec?.onReplace;
16701
- const next = hook ? hook(row.providerState === undefined ? undefined : structuredClone(row.providerState), {
17059
+ const next = hook ? runInsideCodec(() => hook(row.providerState === undefined ? undefined : structuredClone(row.providerState), {
16702
17060
  id: row.id,
16703
17061
  credentialEpoch,
16704
17062
  ...row.identity !== undefined ? { previousIdentity: row.identity } : {},
16705
17063
  ...identity2 !== undefined ? { identity: identity2 } : {},
16706
17064
  ...incoming !== undefined ? { incoming: structuredClone(incoming) } : {}
16707
- }) : incoming;
17065
+ })) : incoming;
16708
17066
  if (next === undefined)
16709
17067
  return { kind: "clear" };
16710
17068
  if (!hook)
@@ -18432,7 +18790,7 @@ async function refreshRow(rt, id, provider, options = {}) {
18432
18790
  if (options.onPersisted) {
18433
18791
  try {
18434
18792
  const persisted = options.onPersisted;
18435
- await runInsideHook("refresh", () => persisted(id, commit.stored));
18793
+ await runInsideHook("refresh", () => persisted(id, commit.stored), true);
18436
18794
  } catch (cause) {
18437
18795
  throw new PoolOperationError({
18438
18796
  operation: "refresh",
@@ -18480,7 +18838,7 @@ function defineKey(target, key, value) {
18480
18838
  function composeConfig(config, next) {
18481
18839
  const out = {};
18482
18840
  for (const [key, value] of Object.entries(config)) {
18483
- if (POOL_OWNED_KEYS.includes(key))
18841
+ if (POOL_OWNED_KEYS.includes(key) || key === "commonAuthLimits")
18484
18842
  defineKey(out, key, value);
18485
18843
  else if (Object.hasOwn(next, key))
18486
18844
  defineKey(out, key, next[key]);
@@ -18533,9 +18891,11 @@ async function updatePoolSettings(rt, mutator, options = {}) {
18533
18891
  const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
18534
18892
  if (owned.length > 0)
18535
18893
  throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
18536
- if (isDeepStrictEqual(next, current))
18537
- 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");
18538
18896
  const config = composeConfig(result.config, next);
18897
+ if (isDeepStrictEqual(settingsOf(config), current))
18898
+ return { settings: current, outcome: "unchanged" };
18539
18899
  const info = { operation: "updateSettings", rowId: undefined };
18540
18900
  await writeJsonAtomic(ctx.configPath, config, {
18541
18901
  beforeRename: async () => {
@@ -18652,6 +19012,7 @@ function openPoolStore(options) {
18652
19012
  reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
18653
19013
  readSettings: () => readPoolSettings(rt),
18654
19014
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
19015
+ updateLimitsNamespace: (mutator) => updatePoolLimitsNamespace(rt, mutator),
18655
19016
  recordIdentity: (id, identity2, attribution, callOptions) => recordRowIdentity(rt, id, identity2, attribution, callOptions),
18656
19017
  refresh: (id, provider, callOptions) => refreshRow(rt, id, provider, callOptions),
18657
19018
  recordQuota: record2,
@@ -21039,6 +21400,35 @@ var STICKY_ROUTING_LOCK_WAIT_MS = 5000;
21039
21400
  var STICKY_ROUTING_LOCK_POLL_MS = 10;
21040
21401
  var STICKY_ROUTING_MAX_ASSIGNMENTS = 4096;
21041
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
+ }
21042
21432
  function createStickyNoRouteResponse(input) {
21043
21433
  const modelId = input.modelId;
21044
21434
  const modelName = modelId ? input.routeQuotas.map((quota2) => getScopedQuotaWindowForModel(quota2, modelId)).find(Boolean)?.modelName : undefined;
@@ -21261,6 +21651,10 @@ function stickyRouteKnownFableExhausted(candidate, storage, now = Date.now()) {
21261
21651
  }
21262
21652
  function decideStickyQuotaFailure(input) {
21263
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
+ };
21264
21658
  let reading2 = knownQuota(input.quota);
21265
21659
  const confirmed = input.responseHeaders ? quotaExhaustionFromHeaders(input.responseHeaders, input.modelId, now) : undefined;
21266
21660
  if (reading2 && input.responseHeaders) {
@@ -21272,7 +21666,7 @@ function decideStickyQuotaFailure(input) {
21272
21666
  }
21273
21667
  const quota2 = reading2 || confirmed && Object.keys(confirmed).length ? { ...reading2, ...confirmed } : undefined;
21274
21668
  if (!quota2)
21275
- return { action: "retain", reason: "unknown" };
21669
+ return retain("unknown");
21276
21670
  let blocking;
21277
21671
  for (const [reason, window2] of [
21278
21672
  ["model-scoped", getScopedQuotaWindowForModel(quota2, input.modelId)],
@@ -21288,7 +21682,7 @@ function decideStickyQuotaFailure(input) {
21288
21682
  blocking = { resetAt, reason };
21289
21683
  }
21290
21684
  if (!blocking)
21291
- return { action: "retain", reason: "not-exhausted" };
21685
+ return retain("not-exhausted");
21292
21686
  const jitterMs = input.sessionId ? (stickyRetryAfterWithJitter(input.sessionId, 1) - 1) * 1000 : 0;
21293
21687
  if (input.holdUntil !== undefined && blocking.resetAt + jitterMs <= input.holdUntil) {
21294
21688
  return {
@@ -24038,6 +24432,794 @@ function executeLoggingCommand(input) {
24038
24432
  ].join(`
24039
24433
  `);
24040
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
+ }
24041
25223
  // src/mid-conversation-output-config.ts
24042
25224
  function isRecord14(value) {
24043
25225
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -24947,7 +26129,7 @@ function createNativeLocalRuntimeReaders(options) {
24947
26129
  }
24948
26130
 
24949
26131
  // src/native-refresh-coordinator.ts
24950
- import { createHash as createHash20 } from "node:crypto";
26132
+ import { createHash as createHash21 } from "node:crypto";
24951
26133
 
24952
26134
  // src/native-transient-account.ts
24953
26135
  var TRANSIENT_ACCOUNT_MESSAGE = "Anthropic account update in progress; retry the request";
@@ -25049,7 +26231,7 @@ function pause(ms, signals) {
25049
26231
  var NATIVE_REFRESH_MAX_ATTEMPTS = 3;
25050
26232
  var NATIVE_REFRESH_JOIN_BUDGET_MS = 2000;
25051
26233
  function nativeAccountProviderLock(paths, identity3) {
25052
- 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");
25053
26235
  return {
25054
26236
  path: paths.state,
25055
26237
  name: `native-account-provider-${key}`,
@@ -25849,7 +27031,7 @@ function createNativeRefreshCoordinator(options) {
25849
27031
  import { isAbsolute as isAbsolute5, normalize, parse as parse3, sep } from "node:path";
25850
27032
 
25851
27033
  // src/migration-source.ts
25852
- import { createHash as createHash21 } from "node:crypto";
27034
+ import { createHash as createHash22 } from "node:crypto";
25853
27035
  import { constants as constants3 } from "node:fs";
25854
27036
  import { lstat as lstat13, open as open10 } from "node:fs/promises";
25855
27037
  class NativeMigrationSourceError extends Error {
@@ -25948,7 +27130,7 @@ async function readNativeMigrationSource(role, path2, hooks = {}) {
25948
27130
  return sourceSnapshot({
25949
27131
  role,
25950
27132
  path: path2,
25951
- digest: createHash21("sha256").update(content).digest("hex"),
27133
+ digest: createHash22("sha256").update(content).digest("hex"),
25952
27134
  data: freezeJson(data),
25953
27135
  metadata: Object.freeze({
25954
27136
  uid: Number(before.uid),
@@ -29098,7 +30280,7 @@ function leaseNativeVaultRuntime(use, close) {
29098
30280
 
29099
30281
  // src/relay.ts
29100
30282
  import { Buffer as Buffer3 } from "node:buffer";
29101
- import { createHash as createHash22, randomBytes as randomBytes5 } from "node:crypto";
30283
+ import { createHash as createHash23, randomBytes as randomBytes5 } from "node:crypto";
29102
30284
  var WEBSOCKET_RELAY_URL = /^wss?:\/\//i;
29103
30285
  function effectiveRelayTransport(stored, url) {
29104
30286
  if (stored === "http" || stored === "websocket")
@@ -29249,7 +30431,7 @@ function generateRelayToken() {
29249
30431
  return randomBytes5(32).toString("base64url");
29250
30432
  }
29251
30433
  function hashBody(body) {
29252
- return `sha256:${createHash22("sha256").update(body).digest("hex")}`;
30434
+ return `sha256:${createHash23("sha256").update(body).digest("hex")}`;
29253
30435
  }
29254
30436
  function createStringPatch(previous, next) {
29255
30437
  let start = 0;
@@ -29294,6 +30476,8 @@ function createRelayPatch(previous, next) {
29294
30476
  };
29295
30477
  const previousWithNextCch = replaceRange(previous, previousCch.start, previousCch.end, nextCch.token);
29296
30478
  const tailPatch = createStringPatch(previousWithNextCch, next);
30479
+ if (tailPatch.start < cchPatch.start + cchPatch.deleteCount)
30480
+ return createStringPatch(previous, next);
29297
30481
  return isNoopPatch(tailPatch) ? cchPatch : [cchPatch, tailPatch];
29298
30482
  }
29299
30483
  return createStringPatch(previous, next);
@@ -32021,7 +33205,7 @@ async function writeNativeHostAuth(input, hooks = {}) {
32021
33205
  }
32022
33206
 
32023
33207
  // src/native-migration.ts
32024
- import { createHash as createHash23 } from "node:crypto";
33208
+ import { createHash as createHash24 } from "node:crypto";
32025
33209
  import { lstat as lstat15, mkdir as mkdir12, unlink as unlink8 } from "node:fs/promises";
32026
33210
  import { dirname as dirname19, isAbsolute as isAbsolute7 } from "node:path";
32027
33211
  class NativeMigrationError extends Error {
@@ -32401,7 +33585,7 @@ function routingBytes(captured) {
32401
33585
  `;
32402
33586
  }
32403
33587
  function bytesDigest(bytes) {
32404
- return bytes === undefined ? null : createHash23("sha256").update(bytes).digest("hex");
33588
+ return bytes === undefined ? null : createHash24("sha256").update(bytes).digest("hex");
32405
33589
  }
32406
33590
  function expectedAuth(input, snapshot) {
32407
33591
  const entry2 = inspectNativeHostAuthEntry(input.host, snapshot.data);
@@ -35263,11 +36447,8 @@ var PLACEHOLDER_LIFETIME_MS = 365 * 24 * 60 * 60 * 1000;
35263
36447
  function placeholderSecret(integrationID) {
35264
36448
  return `${PLACEHOLDER_PREFIX}.${integrationID}`;
35265
36449
  }
35266
-
35267
- // ../../node_modules/@cortexkit/common-auth/dist/opencode2/install.js
35268
- var MAX_RETRY_HOLD_MS = 20 * 60 * 1000;
35269
36450
  // ../../node_modules/@cortexkit/common-auth/dist/pi-slot/slot.js
35270
- import { createHash as createHash24 } from "node:crypto";
36451
+ import { createHash as createHash25 } from "node:crypto";
35271
36452
  import { constants as constants4 } from "node:fs";
35272
36453
  import { lstat as lstat16, mkdir as mkdir14, open as open12, unlink as unlink9 } from "node:fs/promises";
35273
36454
  import { dirname as dirname20, resolve as resolve15 } from "node:path";
@@ -35546,7 +36727,7 @@ function canonical(value) {
35546
36727
  return JSON.stringify(value);
35547
36728
  }
35548
36729
  function digest2(value) {
35549
- return createHash24("sha256").update(canonical(value)).digest("hex");
36730
+ return createHash25("sha256").update(canonical(value)).digest("hex");
35550
36731
  }
35551
36732
  function code(error) {
35552
36733
  return object2(error) ? error.code : undefined;
@@ -35943,7 +37124,7 @@ function createAnthropicOAuthFetch(options = {}) {
35943
37124
  });
35944
37125
  }
35945
37126
  // src/prime.ts
35946
- import { createHash as createHash25 } from "node:crypto";
37127
+ import { createHash as createHash26 } from "node:crypto";
35947
37128
  import { realpathSync as realpathSync3 } from "node:fs";
35948
37129
  import { mkdir as mkdir15, readdir as readdir4, rm as rm8, stat as stat11, writeFile as writeFile5 } from "node:fs/promises";
35949
37130
  import { tmpdir as tmpdir7 } from "node:os";
@@ -36147,7 +37328,7 @@ function primeStorageFingerprint(storagePath) {
36147
37328
  throw error;
36148
37329
  canonicalPath2 = absolutePath;
36149
37330
  }
36150
- return createHash25("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
37331
+ return createHash26("sha256").update(canonicalPath2).digest("hex").slice(0, 12);
36151
37332
  }
36152
37333
  function primeMarkerNamespaceDir(markerDir, storagePath) {
36153
37334
  return join24(markerDir, primeStorageFingerprint(storagePath));
@@ -39771,6 +40952,7 @@ export {
39771
40952
  primeEligibilityReasonLabel,
39772
40953
  primeAccountMarkerDir,
39773
40954
  prepareNativeMigration,
40955
+ prepareMessageThreadRequest,
39774
40956
  pinsEffortOnEveryRequest,
39775
40957
  parseSseFrame,
39776
40958
  parseRoutingCommandAction,
@@ -39791,12 +40973,14 @@ export {
39791
40973
  orderClaudeCodeBody,
39792
40974
  openNativePiAuthSlot,
39793
40975
  openCodeHolderKind,
40976
+ observeMessageThreadResponse,
39794
40977
  oauthProfileMatchesIdentity,
39795
40978
  oauthProfileIsFresh,
39796
40979
  normalizeQuotaHeaders,
39797
40980
  normalizeKillswitchThresholds,
39798
40981
  normalizeAnthropicModelId,
39799
40982
  normalizeAdaptiveEffort,
40983
+ nativeVaultRuntimeKey,
39800
40984
  nativeSettingsRecord,
39801
40985
  nativeRuntimeOptionIdentity,
39802
40986
  nativeRelocationRuntimePaths,
@@ -39816,6 +41000,8 @@ export {
39816
41000
  nativeAccountPolicy,
39817
41001
  nativeAccountCanServe,
39818
41002
  migrateStickyRoutingState,
41003
+ messageThreadSnapshot,
41004
+ messageThreadBetas,
39819
41005
  mergeNativeSettingsSection,
39820
41006
  mergeMainRefreshErrorClearedAt,
39821
41007
  mergeMainQuotaErrorClearedAt,
@@ -39845,6 +41031,7 @@ export {
39845
41031
  isOAuthAccount,
39846
41032
  isNativeTransientAccountError,
39847
41033
  isNativeLocalCredentialValidation,
41034
+ isMessageThreadRejection,
39848
41035
  isKillswitchEnabled,
39849
41036
  isFastModeSupportedModel,
39850
41037
  isFastModePersistentlyEnabled,
@@ -39976,6 +41163,7 @@ export {
39976
41163
  decidePiStateLayout,
39977
41164
  decideOpenCodeStateLayoutOnce,
39978
41165
  decideOpenCodeStateLayout,
41166
+ decideMessageThread,
39979
41167
  custodyTombstoneOAuth,
39980
41168
  custodyTombstoneKey,
39981
41169
  custodyStatusLabel,
@@ -39984,6 +41172,7 @@ export {
39984
41172
  createStickyNoRouteResponse,
39985
41173
  createSseFramer,
39986
41174
  createRelocationGuard,
41175
+ createRelayPatch,
39987
41176
  createQuotaRefusalResponse,
39988
41177
  createProviderErrorResponseScope,
39989
41178
  createProviderErrorRedactor,
@@ -40064,6 +41253,7 @@ export {
40064
41253
  THINKING_BINDING_CONTROLS_BETA,
40065
41254
  TEXT_REPLACEMENTS,
40066
41255
  StickySessionRouter,
41256
+ StickyQuotaRetryCounter,
40067
41257
  StateLayoutRefusalError,
40068
41258
  StateLayoutFileError,
40069
41259
  SseFrameTooLargeError,
@@ -40121,6 +41311,9 @@ export {
40121
41311
  NativeCustodyActivationError,
40122
41312
  NativeAccountRefusal,
40123
41313
  NATIVE_VAULT_NO_ACCOUNT_MESSAGE,
41314
+ MessageThreadTracker,
41315
+ MESSAGE_THREADS_BETA,
41316
+ MAX_UNCONFIRMED_SAME_ACCOUNT_RETRIES,
40124
41317
  MAX_SAME_ACCOUNT_WAITS,
40125
41318
  LOGGING_LEVELS,
40126
41319
  LEGACY_STATE_LAYOUT,