@certalis/agent-smith 0.3.0 → 0.3.3

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/pool.js CHANGED
@@ -5221,6 +5221,13 @@ import {
5221
5221
  writeFileSync as writeFileSync2
5222
5222
  } from "fs";
5223
5223
  import { dirname as dirname2 } from "path";
5224
+ function callerWeeklyCap(caps, callerId) {
5225
+ if (!Object.hasOwn(caps, callerId))
5226
+ return;
5227
+ const cap = caps[callerId];
5228
+ const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
5229
+ return typeof shared === "number" ? shared : undefined;
5230
+ }
5224
5231
  function runtimeForProvider(runtime, provider) {
5225
5232
  return {
5226
5233
  ...runtime,
@@ -5407,6 +5414,9 @@ function sanitizeClientRouting(value) {
5407
5414
  if (typeof value.keep_claude_login === "boolean") {
5408
5415
  client2.keep_claude_login = value.keep_claude_login;
5409
5416
  }
5417
+ if (typeof value.remote_control === "boolean") {
5418
+ client2.remote_control = value.remote_control;
5419
+ }
5410
5420
  if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
5411
5421
  client2.pool_ssh_host = value.pool_ssh_host;
5412
5422
  }
@@ -5522,8 +5532,9 @@ function sanitizeTeamRouting(value) {
5522
5532
  if (weeklyMaxUsageByEmail)
5523
5533
  result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
5524
5534
  if (isRecord(value.caller_weekly_max_usage)) {
5525
- const entries = Object.entries(value.caller_weekly_max_usage);
5526
- if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
5535
+ const caps = value.caller_weekly_max_usage;
5536
+ const entries = Object.entries(caps);
5537
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
5527
5538
  result.caller_weekly_max_usage = Object.fromEntries(entries);
5528
5539
  }
5529
5540
  }
@@ -5677,10 +5688,11 @@ function clientRouting(client2) {
5677
5688
  ...client2?.base_url && { baseUrl: client2.base_url },
5678
5689
  ...client2?.proxy_key_file && { proxyKeyFile: client2.proxy_key_file },
5679
5690
  ...client2?.keep_claude_login === true && { keepClaudeLogin: true },
5691
+ ...client2?.remote_control === false && { remoteControl: false },
5680
5692
  ...client2?.pool_ssh_host && { poolSshHost: client2.pool_ssh_host }
5681
5693
  };
5682
5694
  }
5683
- var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
5695
+ var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, isCallerWeeklyCap = (cap) => isFiniteNumber(cap) && cap > 0 && cap <= 0.95, sharesACallerCap = (caps, cap) => typeof cap === "string" && Object.hasOwn(caps, cap) && isCallerWeeklyCap(caps[cap]), POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
5684
5696
  var init_src8 = __esm(() => {
5685
5697
  init_src2();
5686
5698
  init_src4();
@@ -6204,10 +6216,11 @@ function addPerformanceIndexes(db) {
6204
6216
  `);
6205
6217
  log7.info("Added index: idx_accounts_paused");
6206
6218
  db.run(`
6207
- CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp
6208
- ON requests(account_used, timestamp DESC)
6219
+ CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
6220
+ ON requests(account_used, timestamp DESC, cost_usd)
6209
6221
  `);
6210
- log7.info("Added index: idx_requests_account_timestamp");
6222
+ db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
6223
+ log7.info("Added index: idx_requests_account_timestamp_cost");
6211
6224
  db.run(`
6212
6225
  CREATE INDEX IF NOT EXISTS idx_requests_cost_model
6213
6226
  ON requests(cost_usd, model, timestamp DESC)
@@ -6598,6 +6611,13 @@ function ensureAccountExtensionColumns(db) {
6598
6611
  }
6599
6612
  }
6600
6613
  }
6614
+ function backfillRequestLinkageColumnsOnce(db) {
6615
+ const { user_version } = db.query("PRAGMA user_version").get();
6616
+ if (user_version >= LINKAGE_BACKFILLED_VERSION)
6617
+ return;
6618
+ backfillRequestLinkageColumns(db);
6619
+ db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
6620
+ }
6601
6621
  function backfillRequestLinkageColumns(db) {
6602
6622
  const missingCount = db.query(`
6603
6623
  SELECT COUNT(*) AS count
@@ -7021,7 +7041,7 @@ function runMigrations(db) {
7021
7041
  migrateRequestsTable(db, requestsInfo);
7022
7042
  }
7023
7043
  ensureRequestLinkageColumns(db);
7024
- backfillRequestLinkageColumns(db);
7044
+ backfillRequestLinkageColumnsOnce(db);
7025
7045
  db.run("DROP TABLE IF EXISTS agent_preferences");
7026
7046
  db.run("DROP TABLE IF EXISTS oauth_sessions");
7027
7047
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
@@ -7037,7 +7057,7 @@ function runMigrations(db) {
7037
7057
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
7038
7058
  addPerformanceIndexes(db);
7039
7059
  }
7040
- var log9;
7060
+ var log9, LINKAGE_BACKFILLED_VERSION = 1;
7041
7061
  var init_migrations = __esm(() => {
7042
7062
  init_src4();
7043
7063
  init_src();
@@ -7884,7 +7904,7 @@ function requestLinkageFromPayload(payload) {
7884
7904
  clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
7885
7905
  };
7886
7906
  }
7887
- var log10, RequestRepository;
7907
+ var log10, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
7888
7908
  var init_request_repository = __esm(() => {
7889
7909
  init_src4();
7890
7910
  init_src();
@@ -8259,11 +8279,10 @@ var init_request_repository = __esm(() => {
8259
8279
  return errors2.map((e) => e.error_message);
8260
8280
  }
8261
8281
  sumAccountCostSince(accountId, since) {
8262
- return this.get(`
8263
- SELECT SUM(cost_usd) AS cost
8264
- FROM requests
8265
- WHERE account_used = ? AND timestamp >= ?
8266
- `, [accountId, since])?.cost ?? 0;
8282
+ return this.get(ACCOUNT_COST_SINCE_SQL, [
8283
+ accountId,
8284
+ since
8285
+ ])?.cost ?? 0;
8267
8286
  }
8268
8287
  getRequestsByAccount(since) {
8269
8288
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
@@ -8287,23 +8306,26 @@ var init_request_repository = __esm(() => {
8287
8306
  successRate: row.success_rate
8288
8307
  }));
8289
8308
  }
8290
- deleteOlderThan(cutoffTs) {
8291
- return this.runWithChanges(`DELETE FROM requests WHERE timestamp < ?`, [
8292
- cutoffTs
8293
- ]);
8309
+ deleteOlderThan(cutoffTs, limit) {
8310
+ return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
8311
+ SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
8312
+ )`, [cutoffTs, limit]);
8294
8313
  }
8295
8314
  clear() {
8296
8315
  return this.runWithChanges(`DELETE FROM requests`);
8297
8316
  }
8298
- deleteOrphanedPayloads() {
8299
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
8300
- }
8301
- deletePayloadsOlderThan(cutoffTs) {
8302
- return this.runWithChanges(`DELETE FROM request_payloads
8303
- WHERE EXISTS (
8304
- SELECT 1 FROM requests r
8305
- WHERE r.id = request_payloads.id AND r.timestamp < ?
8306
- )`, [cutoffTs]);
8317
+ deleteOldestExpiredPayloads(cutoffTs, limit) {
8318
+ const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
8319
+ FROM request_payloads rp
8320
+ LEFT JOIN requests r ON r.id = rp.id
8321
+ ORDER BY rp.rowid
8322
+ LIMIT ?`, [limit]);
8323
+ const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
8324
+ const expiredCount = firstLive === -1 ? oldest.length : firstLive;
8325
+ const lastExpired = oldest[expiredCount - 1];
8326
+ if (!lastExpired)
8327
+ return 0;
8328
+ return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
8307
8329
  }
8308
8330
  };
8309
8331
  });
@@ -8432,6 +8454,7 @@ var init_strategy_repository = __esm(() => {
8432
8454
  import { Database } from "bun:sqlite";
8433
8455
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
8434
8456
  import { dirname as dirname3 } from "path";
8457
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
8435
8458
  function freeDiskBytes(directory) {
8436
8459
  const { bavail, bsize } = statfsSync(directory);
8437
8460
  return bavail * bsize;
@@ -8451,7 +8474,7 @@ class DatabaseOperations {
8451
8474
  conversationProviderPreferences;
8452
8475
  strategy;
8453
8476
  stats;
8454
- constructor(dbPath) {
8477
+ constructor(dbPath, { migrate = true } = {}) {
8455
8478
  const resolvedPath = dbPath ?? resolveDbPath();
8456
8479
  this.dbPath = resolvedPath;
8457
8480
  const dir = dirname3(resolvedPath);
@@ -8461,8 +8484,11 @@ class DatabaseOperations {
8461
8484
  this.db.exec("PRAGMA journal_mode = WAL");
8462
8485
  this.db.exec("PRAGMA busy_timeout = 5000");
8463
8486
  this.db.exec("PRAGMA synchronous = NORMAL");
8464
- ensureSchema(this.db);
8465
- runMigrations(this.db);
8487
+ this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
8488
+ if (migrate) {
8489
+ ensureSchema(this.db);
8490
+ runMigrations(this.db);
8491
+ }
8466
8492
  this.accounts = new AccountRepository(this.db);
8467
8493
  this.analytics = new AnalyticsRepository(this.db);
8468
8494
  this.requests = new RequestRepository(this.db);
@@ -8678,18 +8704,40 @@ class DatabaseOperations {
8678
8704
  getAnalytics(options) {
8679
8705
  return this.analytics.getAnalytics(options);
8680
8706
  }
8681
- cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
8682
- const now = Date.now();
8683
- const payloadCutoff = now - payloadRetentionMs;
8684
- let removedRequests = 0;
8685
- if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
8686
- const requestCutoff = now - requestRetentionMs;
8687
- removedRequests = this.requests.deleteOlderThan(requestCutoff);
8707
+ cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
8708
+ const total = { removedRequests: 0, removedPayloads: 0 };
8709
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
8710
+ total.removedRequests += batch.removedRequests;
8711
+ total.removedPayloads += batch.removedPayloads;
8712
+ }
8713
+ return total;
8714
+ }
8715
+ async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
8716
+ batchRows = CLEANUP_BATCH_ROWS,
8717
+ signal
8718
+ } = {}) {
8719
+ const total = { removedRequests: 0, removedPayloads: 0 };
8720
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
8721
+ total.removedRequests += batch.removedRequests;
8722
+ total.removedPayloads += batch.removedPayloads;
8723
+ await yieldToEventLoop();
8724
+ if (signal?.aborted)
8725
+ break;
8726
+ }
8727
+ return total;
8728
+ }
8729
+ *cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
8730
+ for (;; ) {
8731
+ const now = Date.now();
8732
+ let removedRequests = 0;
8733
+ if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
8734
+ removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
8735
+ }
8736
+ const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
8737
+ yield { removedRequests, removedPayloads };
8738
+ if (removedRequests < batchRows && removedPayloads < batchRows)
8739
+ return;
8688
8740
  }
8689
- const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
8690
- const removedOrphans = this.requests.deleteOrphanedPayloads();
8691
- const removedPayloads = removedPayloadsByAge + removedOrphans;
8692
- return { removedRequests, removedPayloads };
8693
8741
  }
8694
8742
  close() {
8695
8743
  if (this.closed) {
@@ -8728,6 +8776,7 @@ class DatabaseOperations {
8728
8776
  return this.stats;
8729
8777
  }
8730
8778
  }
8779
+ var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
8731
8780
  var init_database_operations = __esm(() => {
8732
8781
  init_migrations();
8733
8782
  init_paths2();
@@ -8740,6 +8789,7 @@ var init_database_operations = __esm(() => {
8740
8789
  init_request_repository();
8741
8790
  init_stats_repository();
8742
8791
  init_strategy_repository();
8792
+ WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
8743
8793
  });
8744
8794
 
8745
8795
  // ../../packages/database/src/factory.ts
@@ -9889,13 +9939,13 @@ var init_logs_history = __esm(() => {
9889
9939
 
9890
9940
  // ../../packages/api/src/handlers/maintenance.ts
9891
9941
  function createCleanupHandler(dbOps, config) {
9892
- return () => {
9942
+ return async () => {
9893
9943
  try {
9894
9944
  const payloadDays = config.getDataRetentionDays();
9895
9945
  const requestDays = config.getRequestRetentionDays();
9896
9946
  const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
9897
9947
  const requestMs = requestDays * 24 * 60 * 60 * 1000;
9898
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadMs, requestMs);
9948
+ const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
9899
9949
  const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
9900
9950
  const cleanupData = {
9901
9951
  removedRequests,
@@ -10414,7 +10464,7 @@ class APIRouter {
10414
10464
  error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
10415
10465
  }, { status: 401 });
10416
10466
  }
10417
- const status = await getCallerPoolStatus(pool, model, callerId);
10467
+ const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
10418
10468
  if (!status) {
10419
10469
  return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
10420
10470
  }
@@ -11444,7 +11494,7 @@ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
11444
11494
  };
11445
11495
  }
11446
11496
  const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
11447
- const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) && !pacedNight(teamRouting, account2, now, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11497
+ const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
11448
11498
  return {
11449
11499
  limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
11450
11500
  overridesFleetThreshold: accountOverride !== undefined
@@ -11547,7 +11597,7 @@ function getPoolStatus(provider, model, ctx) {
11547
11597
  admissionWaitMs: config?.admissionWaitMs ?? 0
11548
11598
  };
11549
11599
  }
11550
- function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
11600
+ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
11551
11601
  const strategy3 = ctx.providerRegistry.getProvider(provider);
11552
11602
  if (!strategy3)
11553
11603
  throw new Error(`Unknown provider '${provider}'`);
@@ -11555,7 +11605,7 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
11555
11605
  const now = Date.now();
11556
11606
  const accounts = (config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"))).filter((account2) => servesCaller(account2, ctx, callerId));
11557
11607
  const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
11558
- const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
11608
+ const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
11559
11609
  return {
11560
11610
  poolEnabled: config.enabled,
11561
11611
  servableSeats,
@@ -11987,7 +12037,7 @@ class ProviderSupply {
11987
12037
  admissionWaitMs: context2.runtime.pool.admissionWaitMs
11988
12038
  };
11989
12039
  if (route.scope.kind === "pool-route" && route.callerId) {
11990
- return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
12040
+ return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
11991
12041
  }
11992
12042
  return getPoolStatus(this.name, mapped, context2);
11993
12043
  }
@@ -12889,7 +12939,9 @@ async function getCallerPoolStatus(input) {
12889
12939
  retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
12890
12940
  holdSeconds: input.holdSeconds,
12891
12941
  admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
12892
- nightBudget: callerNightBudget2(statuses, Date.now())
12942
+ ...input.route.readNightBudget && {
12943
+ nightBudget: callerNightBudget2(statuses, Date.now())
12944
+ }
12893
12945
  };
12894
12946
  }
12895
12947
  function toCents(value) {
@@ -14718,6 +14770,18 @@ var init_router_bridge = __esm(() => {
14718
14770
  // ../../packages/proxy/src/usage-worker.ts
14719
14771
  import { isAbsolute, resolve as resolve2 } from "path";
14720
14772
  import { pathToFileURL } from "url";
14773
+ function heldBytesOf(message) {
14774
+ switch (message.type) {
14775
+ case "start":
14776
+ return MESSAGE_OVERHEAD_BYTES + (message.requestBody?.length ?? 0);
14777
+ case "chunk":
14778
+ return MESSAGE_OVERHEAD_BYTES + message.data.byteLength;
14779
+ case "end":
14780
+ return MESSAGE_OVERHEAD_BYTES + (message.responseBody?.length ?? 0);
14781
+ default:
14782
+ return MESSAGE_OVERHEAD_BYTES;
14783
+ }
14784
+ }
14721
14785
  function noop() {}
14722
14786
  function createDefaultLogger() {
14723
14787
  return {
@@ -14771,6 +14835,7 @@ class UsageWorkerController {
14771
14835
  readyTimeoutMs;
14772
14836
  ackTimeoutMs;
14773
14837
  shutdownDelayMs;
14838
+ maxHeldBytes;
14774
14839
  logger;
14775
14840
  worker = null;
14776
14841
  ready = false;
@@ -14780,6 +14845,9 @@ class UsageWorkerController {
14780
14845
  shutdownTimer = null;
14781
14846
  queuedMessages = [];
14782
14847
  pendingAcks = new Map;
14848
+ heldBytes = 0;
14849
+ droppedRequestIds = new Set;
14850
+ droppedRequests = 0;
14783
14851
  shutdownPromise = null;
14784
14852
  resolveShutdown = null;
14785
14853
  rejectShutdown = null;
@@ -14790,6 +14858,7 @@ class UsageWorkerController {
14790
14858
  this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
14791
14859
  this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
14792
14860
  this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
14861
+ this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
14793
14862
  this.logger = options.logger ?? createDefaultLogger();
14794
14863
  this.startWorker();
14795
14864
  }
@@ -14798,16 +14867,65 @@ class UsageWorkerController {
14798
14867
  this.logger.warn("Dropping usage worker message because the worker is shutting down");
14799
14868
  return;
14800
14869
  }
14870
+ if (!this.admit(message)) {
14871
+ return;
14872
+ }
14801
14873
  const decoratedMessage = {
14802
14874
  ...message,
14803
14875
  messageId: crypto.randomUUID()
14804
14876
  };
14805
14877
  if (!this.ready || !this.worker) {
14806
- this.queuedMessages.push(decoratedMessage);
14878
+ this.queue(decoratedMessage);
14807
14879
  return;
14808
14880
  }
14809
14881
  this.sendMessage(decoratedMessage);
14810
14882
  }
14883
+ admit(message) {
14884
+ if (message.type === "shutdown") {
14885
+ return true;
14886
+ }
14887
+ if (this.droppedRequestIds.has(message.requestId)) {
14888
+ if (message.type === "end") {
14889
+ this.droppedRequestIds.delete(message.requestId);
14890
+ }
14891
+ return false;
14892
+ }
14893
+ if (message.type !== "start") {
14894
+ return true;
14895
+ }
14896
+ if (this.heldBytes + heldBytesOf(message) > this.maxHeldBytes) {
14897
+ if (this.droppedRequests === 0) {
14898
+ this.logger.warn(`Usage worker messages hold ${this.heldBytes} bytes, over the ${this.maxHeldBytes}-byte cap; dropping new requests' usage until the worker catches up`);
14899
+ }
14900
+ this.droppedRequests += 1;
14901
+ this.droppedRequestIds.add(message.requestId);
14902
+ return false;
14903
+ }
14904
+ if (this.droppedRequests > 0) {
14905
+ this.logger.warn(`Dropped the usage of ${this.droppedRequests} requests while usage worker messages were over their byte cap`);
14906
+ this.droppedRequests = 0;
14907
+ }
14908
+ return true;
14909
+ }
14910
+ queue(message) {
14911
+ this.queuedMessages.push(message);
14912
+ this.heldBytes += heldBytesOf(message);
14913
+ }
14914
+ forgetQueuedMessages() {
14915
+ for (const message of this.queuedMessages) {
14916
+ this.heldBytes -= heldBytesOf(message);
14917
+ }
14918
+ this.queuedMessages.length = 0;
14919
+ }
14920
+ forgetPendingAck(messageId) {
14921
+ const pending = this.pendingAcks.get(messageId);
14922
+ if (!pending) {
14923
+ return;
14924
+ }
14925
+ clearTimeout(pending.timer);
14926
+ this.heldBytes -= heldBytesOf(pending.message);
14927
+ this.pendingAcks.delete(messageId);
14928
+ }
14811
14929
  isShuttingDown() {
14812
14930
  return this.shuttingDown;
14813
14931
  }
@@ -14828,7 +14946,7 @@ class UsageWorkerController {
14828
14946
  this.ready = false;
14829
14947
  this.clearReadyTimer();
14830
14948
  this.clearPendingAcks();
14831
- this.queuedMessages.length = 0;
14949
+ this.forgetQueuedMessages();
14832
14950
  const worker = this.worker;
14833
14951
  if (!worker) {
14834
14952
  this.shuttingDown = false;
@@ -14864,7 +14982,7 @@ class UsageWorkerController {
14864
14982
  this.ready = false;
14865
14983
  this.clearReadyTimer();
14866
14984
  this.clearPendingAcks();
14867
- this.queuedMessages.length = 0;
14985
+ this.forgetQueuedMessages();
14868
14986
  if (this.shutdownTimer) {
14869
14987
  clearTimeout(this.shutdownTimer);
14870
14988
  this.shutdownTimer = null;
@@ -14935,10 +15053,9 @@ class UsageWorkerController {
14935
15053
  this.readyTimer = null;
14936
15054
  }
14937
15055
  clearPendingAcks() {
14938
- for (const pending of this.pendingAcks.values()) {
14939
- clearTimeout(pending.timer);
15056
+ for (const messageId of Array.from(this.pendingAcks.keys())) {
15057
+ this.forgetPendingAck(messageId);
14940
15058
  }
14941
- this.pendingAcks.clear();
14942
15059
  }
14943
15060
  handleWorkerMessage(message) {
14944
15061
  if (isShutdownCompleteMessage(message)) {
@@ -14961,12 +15078,7 @@ class UsageWorkerController {
14961
15078
  return;
14962
15079
  }
14963
15080
  if (isAckMessage(message)) {
14964
- const pendingAck = this.pendingAcks.get(message.messageId);
14965
- if (!pendingAck) {
14966
- return;
14967
- }
14968
- clearTimeout(pendingAck.timer);
14969
- this.pendingAcks.delete(message.messageId);
15081
+ this.forgetPendingAck(message.messageId);
14970
15082
  return;
14971
15083
  }
14972
15084
  this.onWorkerMessage?.(message);
@@ -14975,14 +15087,15 @@ class UsageWorkerController {
14975
15087
  if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
14976
15088
  return;
14977
15089
  }
14978
- const queuedMessages = this.queuedMessages.splice(0, this.queuedMessages.length);
15090
+ const queuedMessages = this.queuedMessages.slice();
15091
+ this.forgetQueuedMessages();
14979
15092
  for (const message of queuedMessages) {
14980
15093
  this.sendMessage(message);
14981
15094
  }
14982
15095
  }
14983
15096
  sendMessage(message) {
14984
15097
  if (!this.worker) {
14985
- this.queuedMessages.push(message);
15098
+ this.queue(message);
14986
15099
  return;
14987
15100
  }
14988
15101
  try {
@@ -14996,11 +15109,10 @@ class UsageWorkerController {
14996
15109
  return;
14997
15110
  }
14998
15111
  const timer = setTimeout(() => {
14999
- const pendingAck = this.pendingAcks.get(message.messageId);
15000
- if (!pendingAck) {
15112
+ if (!this.pendingAcks.has(message.messageId)) {
15001
15113
  return;
15002
15114
  }
15003
- this.pendingAcks.delete(message.messageId);
15115
+ this.forgetPendingAck(message.messageId);
15004
15116
  this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
15005
15117
  this.restartWorker();
15006
15118
  }, this.ackTimeoutMs);
@@ -15009,6 +15121,7 @@ class UsageWorkerController {
15009
15121
  message,
15010
15122
  timer
15011
15123
  });
15124
+ this.heldBytes += heldBytesOf(message);
15012
15125
  }
15013
15126
  restartWorker() {
15014
15127
  if (this.shuttingDown) {
@@ -15062,12 +15175,13 @@ class UsageWorkerController {
15062
15175
  resolveShutdown?.();
15063
15176
  }
15064
15177
  }
15065
- var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100;
15178
+ var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100, DEFAULT_MAX_HELD_BYTES, MESSAGE_OVERHEAD_BYTES = 1024;
15066
15179
  var init_usage_worker = __esm(() => {
15067
15180
  init_src2();
15068
15181
  init_src();
15069
15182
  DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15070
15183
  DEFAULT_ACK_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_ACK_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15184
+ DEFAULT_MAX_HELD_BYTES = Number(process.env.AGENT_SMITH_USAGE_WORKER_MAX_HELD_MB || 256) * 1024 * 1024;
15071
15185
  });
15072
15186
 
15073
15187
  // ../../packages/proxy/src/proxy.ts
@@ -15581,7 +15695,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15581
15695
  admissionWaitMs: status.admissionWaitMs
15582
15696
  };
15583
15697
  },
15584
- getCallerPoolStatus: async (pool, model, callerId) => {
15698
+ getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
15585
15699
  const members = providerRegistry.poolCapacityMembers(pool, model);
15586
15700
  const url = new URL(`http://localhost/v1/pool/${pool}/`);
15587
15701
  const providers2 = members.map(({ provider }) => {
@@ -15591,7 +15705,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15591
15705
  return supply;
15592
15706
  });
15593
15707
  return getCallerPoolStatus({
15594
- route: createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15708
+ route: {
15709
+ ...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15710
+ readNightBudget
15711
+ },
15595
15712
  providers: providers2,
15596
15713
  orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
15597
15714
  apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
@@ -15909,35 +16026,49 @@ var init_fetch_handler = __esm(() => {
15909
16026
  });
15910
16027
 
15911
16028
  // ../../packages/runtime-server/src/retention-maintenance.ts
15912
- function removeExpiredRequests(config, dbOps, log27, label) {
15913
- try {
15914
- const payloadDays = config.getDataRetentionDays();
15915
- const requestDays = config.getRequestRetentionDays();
15916
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
15917
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
15918
- } catch (err) {
15919
- log27.error(`${label} cleanup error: ${err}`);
15920
- }
16029
+ function retentionWindows(config) {
16030
+ const payloadDays = config.getDataRetentionDays();
16031
+ const requestDays = config.getRequestRetentionDays();
16032
+ return {
16033
+ payloadMs: payloadDays * DAY_MS2,
16034
+ requestMs: requestDays * DAY_MS2,
16035
+ description: `payload=${payloadDays}d, requests=${requestDays}d`
16036
+ };
16037
+ }
16038
+ function logRemoved(log27, label, { removedRequests, removedPayloads }, description) {
16039
+ log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (${description})`);
15921
16040
  }
15922
16041
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
15923
16042
  const log27 = new Logger("RetentionMaintenance");
15924
- removeExpiredRequests(config, dbOps, log27, "Startup");
16043
+ try {
16044
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16045
+ logRemoved(log27, "Startup", dbOps.cleanupOldRequests(payloadMs, requestMs), description);
16046
+ } catch (err) {
16047
+ log27.error(`Startup cleanup error: ${err}`);
16048
+ }
15925
16049
  try {
15926
16050
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
15927
16051
  log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
15928
16052
  } catch (err) {
15929
16053
  log27.error(`Database compaction error: ${err}`);
15930
16054
  }
16055
+ const stopped = new AbortController;
16056
+ let running;
15931
16057
  const timer = setInterval(() => {
15932
- removeExpiredRequests(config, dbOps, log27, "Periodic");
15933
- try {
15934
- dbOps.checkpointWal();
15935
- } catch (err) {
15936
- log27.error(`WAL checkpoint error: ${err}`);
15937
- }
16058
+ if (running)
16059
+ return;
16060
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16061
+ running = dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs, {
16062
+ signal: stopped.signal
16063
+ }).then((removed) => logRemoved(log27, "Periodic", removed, description), (err) => log27.error(`Periodic cleanup error: ${err}`)).finally(() => {
16064
+ running = undefined;
16065
+ });
15938
16066
  }, intervalMs);
15939
16067
  timer.unref?.();
15940
- return () => clearInterval(timer);
16068
+ return () => {
16069
+ clearInterval(timer);
16070
+ stopped.abort();
16071
+ };
15941
16072
  }
15942
16073
  var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
15943
16074
  var init_retention_maintenance = __esm(() => {