@certalis/agent-smith 0.3.0 → 0.3.2

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/bin.js CHANGED
@@ -1792,6 +1792,13 @@ import {
1792
1792
  writeFileSync as writeFileSync2
1793
1793
  } from "fs";
1794
1794
  import { dirname as dirname2 } from "path";
1795
+ function callerWeeklyCap(caps, callerId) {
1796
+ if (!Object.hasOwn(caps, callerId))
1797
+ return;
1798
+ const cap = caps[callerId];
1799
+ const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
1800
+ return typeof shared === "number" ? shared : undefined;
1801
+ }
1795
1802
  function runtimeForProvider(runtime, provider) {
1796
1803
  return {
1797
1804
  ...runtime,
@@ -2093,8 +2100,9 @@ function sanitizeTeamRouting(value) {
2093
2100
  if (weeklyMaxUsageByEmail)
2094
2101
  result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
2095
2102
  if (isRecord(value.caller_weekly_max_usage)) {
2096
- const entries = Object.entries(value.caller_weekly_max_usage);
2097
- if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
2103
+ const caps = value.caller_weekly_max_usage;
2104
+ const entries = Object.entries(caps);
2105
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
2098
2106
  result.caller_weekly_max_usage = Object.fromEntries(entries);
2099
2107
  }
2100
2108
  }
@@ -2251,7 +2259,7 @@ function clientRouting(client) {
2251
2259
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2252
2260
  };
2253
2261
  }
2254
- var log2, 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;
2262
+ var log2, 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;
2255
2263
  var init_src4 = __esm(() => {
2256
2264
  init_src2();
2257
2265
  init_src3();
@@ -2828,10 +2836,11 @@ function addPerformanceIndexes(db) {
2828
2836
  `);
2829
2837
  log3.info("Added index: idx_accounts_paused");
2830
2838
  db.run(`
2831
- CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp
2832
- ON requests(account_used, timestamp DESC)
2839
+ CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
2840
+ ON requests(account_used, timestamp DESC, cost_usd)
2833
2841
  `);
2834
- log3.info("Added index: idx_requests_account_timestamp");
2842
+ db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
2843
+ log3.info("Added index: idx_requests_account_timestamp_cost");
2835
2844
  db.run(`
2836
2845
  CREATE INDEX IF NOT EXISTS idx_requests_cost_model
2837
2846
  ON requests(cost_usd, model, timestamp DESC)
@@ -3222,6 +3231,13 @@ function ensureAccountExtensionColumns(db) {
3222
3231
  }
3223
3232
  }
3224
3233
  }
3234
+ function backfillRequestLinkageColumnsOnce(db) {
3235
+ const { user_version } = db.query("PRAGMA user_version").get();
3236
+ if (user_version >= LINKAGE_BACKFILLED_VERSION)
3237
+ return;
3238
+ backfillRequestLinkageColumns(db);
3239
+ db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
3240
+ }
3225
3241
  function backfillRequestLinkageColumns(db) {
3226
3242
  const missingCount = db.query(`
3227
3243
  SELECT COUNT(*) AS count
@@ -3645,7 +3661,7 @@ function runMigrations(db) {
3645
3661
  migrateRequestsTable(db, requestsInfo);
3646
3662
  }
3647
3663
  ensureRequestLinkageColumns(db);
3648
- backfillRequestLinkageColumns(db);
3664
+ backfillRequestLinkageColumnsOnce(db);
3649
3665
  db.run("DROP TABLE IF EXISTS agent_preferences");
3650
3666
  db.run("DROP TABLE IF EXISTS oauth_sessions");
3651
3667
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
@@ -3661,7 +3677,7 @@ function runMigrations(db) {
3661
3677
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
3662
3678
  addPerformanceIndexes(db);
3663
3679
  }
3664
- var log5;
3680
+ var log5, LINKAGE_BACKFILLED_VERSION = 1;
3665
3681
  var init_migrations = __esm(() => {
3666
3682
  init_src3();
3667
3683
  init_src();
@@ -4508,7 +4524,7 @@ function requestLinkageFromPayload(payload) {
4508
4524
  clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
4509
4525
  };
4510
4526
  }
4511
- var log6, RequestRepository;
4527
+ var log6, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
4512
4528
  var init_request_repository = __esm(() => {
4513
4529
  init_src3();
4514
4530
  init_src();
@@ -4883,11 +4899,10 @@ var init_request_repository = __esm(() => {
4883
4899
  return errors.map((e) => e.error_message);
4884
4900
  }
4885
4901
  sumAccountCostSince(accountId, since) {
4886
- return this.get(`
4887
- SELECT SUM(cost_usd) AS cost
4888
- FROM requests
4889
- WHERE account_used = ? AND timestamp >= ?
4890
- `, [accountId, since])?.cost ?? 0;
4902
+ return this.get(ACCOUNT_COST_SINCE_SQL, [
4903
+ accountId,
4904
+ since
4905
+ ])?.cost ?? 0;
4891
4906
  }
4892
4907
  getRequestsByAccount(since) {
4893
4908
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
@@ -4911,23 +4926,26 @@ var init_request_repository = __esm(() => {
4911
4926
  successRate: row.success_rate
4912
4927
  }));
4913
4928
  }
4914
- deleteOlderThan(cutoffTs) {
4915
- return this.runWithChanges(`DELETE FROM requests WHERE timestamp < ?`, [
4916
- cutoffTs
4917
- ]);
4929
+ deleteOlderThan(cutoffTs, limit) {
4930
+ return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
4931
+ SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
4932
+ )`, [cutoffTs, limit]);
4918
4933
  }
4919
4934
  clear() {
4920
4935
  return this.runWithChanges(`DELETE FROM requests`);
4921
4936
  }
4922
- deleteOrphanedPayloads() {
4923
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
4924
- }
4925
- deletePayloadsOlderThan(cutoffTs) {
4926
- return this.runWithChanges(`DELETE FROM request_payloads
4927
- WHERE EXISTS (
4928
- SELECT 1 FROM requests r
4929
- WHERE r.id = request_payloads.id AND r.timestamp < ?
4930
- )`, [cutoffTs]);
4937
+ deleteOldestExpiredPayloads(cutoffTs, limit) {
4938
+ const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
4939
+ FROM request_payloads rp
4940
+ LEFT JOIN requests r ON r.id = rp.id
4941
+ ORDER BY rp.rowid
4942
+ LIMIT ?`, [limit]);
4943
+ const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
4944
+ const expiredCount = firstLive === -1 ? oldest.length : firstLive;
4945
+ const lastExpired = oldest[expiredCount - 1];
4946
+ if (!lastExpired)
4947
+ return 0;
4948
+ return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
4931
4949
  }
4932
4950
  };
4933
4951
  });
@@ -5056,6 +5074,7 @@ var init_strategy_repository = __esm(() => {
5056
5074
  import { Database } from "bun:sqlite";
5057
5075
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
5058
5076
  import { dirname as dirname3 } from "path";
5077
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
5059
5078
  function freeDiskBytes(directory) {
5060
5079
  const { bavail, bsize } = statfsSync(directory);
5061
5080
  return bavail * bsize;
@@ -5075,7 +5094,7 @@ class DatabaseOperations {
5075
5094
  conversationProviderPreferences;
5076
5095
  strategy;
5077
5096
  stats;
5078
- constructor(dbPath) {
5097
+ constructor(dbPath, { migrate = true } = {}) {
5079
5098
  const resolvedPath = dbPath ?? resolveDbPath();
5080
5099
  this.dbPath = resolvedPath;
5081
5100
  const dir = dirname3(resolvedPath);
@@ -5085,8 +5104,11 @@ class DatabaseOperations {
5085
5104
  this.db.exec("PRAGMA journal_mode = WAL");
5086
5105
  this.db.exec("PRAGMA busy_timeout = 5000");
5087
5106
  this.db.exec("PRAGMA synchronous = NORMAL");
5088
- ensureSchema(this.db);
5089
- runMigrations(this.db);
5107
+ this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
5108
+ if (migrate) {
5109
+ ensureSchema(this.db);
5110
+ runMigrations(this.db);
5111
+ }
5090
5112
  this.accounts = new AccountRepository(this.db);
5091
5113
  this.analytics = new AnalyticsRepository(this.db);
5092
5114
  this.requests = new RequestRepository(this.db);
@@ -5302,18 +5324,40 @@ class DatabaseOperations {
5302
5324
  getAnalytics(options) {
5303
5325
  return this.analytics.getAnalytics(options);
5304
5326
  }
5305
- cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
5306
- const now = Date.now();
5307
- const payloadCutoff = now - payloadRetentionMs;
5308
- let removedRequests = 0;
5309
- if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5310
- const requestCutoff = now - requestRetentionMs;
5311
- removedRequests = this.requests.deleteOlderThan(requestCutoff);
5327
+ cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
5328
+ const total = { removedRequests: 0, removedPayloads: 0 };
5329
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5330
+ total.removedRequests += batch.removedRequests;
5331
+ total.removedPayloads += batch.removedPayloads;
5332
+ }
5333
+ return total;
5334
+ }
5335
+ async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
5336
+ batchRows = CLEANUP_BATCH_ROWS,
5337
+ signal
5338
+ } = {}) {
5339
+ const total = { removedRequests: 0, removedPayloads: 0 };
5340
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5341
+ total.removedRequests += batch.removedRequests;
5342
+ total.removedPayloads += batch.removedPayloads;
5343
+ await yieldToEventLoop();
5344
+ if (signal?.aborted)
5345
+ break;
5346
+ }
5347
+ return total;
5348
+ }
5349
+ *cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
5350
+ for (;; ) {
5351
+ const now = Date.now();
5352
+ let removedRequests = 0;
5353
+ if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5354
+ removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
5355
+ }
5356
+ const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
5357
+ yield { removedRequests, removedPayloads };
5358
+ if (removedRequests < batchRows && removedPayloads < batchRows)
5359
+ return;
5312
5360
  }
5313
- const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
5314
- const removedOrphans = this.requests.deleteOrphanedPayloads();
5315
- const removedPayloads = removedPayloadsByAge + removedOrphans;
5316
- return { removedRequests, removedPayloads };
5317
5361
  }
5318
5362
  close() {
5319
5363
  if (this.closed) {
@@ -5352,6 +5396,7 @@ class DatabaseOperations {
5352
5396
  return this.stats;
5353
5397
  }
5354
5398
  }
5399
+ var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
5355
5400
  var init_database_operations = __esm(() => {
5356
5401
  init_migrations();
5357
5402
  init_paths2();
@@ -5364,6 +5409,7 @@ var init_database_operations = __esm(() => {
5364
5409
  init_request_repository();
5365
5410
  init_stats_repository();
5366
5411
  init_strategy_repository();
5412
+ WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
5367
5413
  });
5368
5414
 
5369
5415
  // ../../packages/database/src/factory.ts
@@ -9890,13 +9936,13 @@ var init_logs_history = __esm(() => {
9890
9936
 
9891
9937
  // ../../packages/api/src/handlers/maintenance.ts
9892
9938
  function createCleanupHandler(dbOps, config) {
9893
- return () => {
9939
+ return async () => {
9894
9940
  try {
9895
9941
  const payloadDays = config.getDataRetentionDays();
9896
9942
  const requestDays = config.getRequestRetentionDays();
9897
9943
  const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
9898
9944
  const requestMs = requestDays * 24 * 60 * 60 * 1000;
9899
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadMs, requestMs);
9945
+ const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
9900
9946
  const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
9901
9947
  const cleanupData = {
9902
9948
  removedRequests,
@@ -10415,7 +10461,7 @@ class APIRouter {
10415
10461
  error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
10416
10462
  }, { status: 401 });
10417
10463
  }
10418
- const status = await getCallerPoolStatus(pool, model, callerId);
10464
+ const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
10419
10465
  if (!status) {
10420
10466
  return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
10421
10467
  }
@@ -11445,7 +11491,7 @@ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
11445
11491
  };
11446
11492
  }
11447
11493
  const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
11448
- const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) && !pacedNight(teamRouting, account2, now, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11494
+ const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
11449
11495
  return {
11450
11496
  limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
11451
11497
  overridesFleetThreshold: accountOverride !== undefined
@@ -11548,7 +11594,7 @@ function getPoolStatus(provider, model, ctx) {
11548
11594
  admissionWaitMs: config?.admissionWaitMs ?? 0
11549
11595
  };
11550
11596
  }
11551
- function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
11597
+ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
11552
11598
  const strategy3 = ctx.providerRegistry.getProvider(provider);
11553
11599
  if (!strategy3)
11554
11600
  throw new Error(`Unknown provider '${provider}'`);
@@ -11556,7 +11602,7 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
11556
11602
  const now = Date.now();
11557
11603
  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));
11558
11604
  const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
11559
- const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
11605
+ const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
11560
11606
  return {
11561
11607
  poolEnabled: config.enabled,
11562
11608
  servableSeats,
@@ -11988,7 +12034,7 @@ class ProviderSupply {
11988
12034
  admissionWaitMs: context2.runtime.pool.admissionWaitMs
11989
12035
  };
11990
12036
  if (route.scope.kind === "pool-route" && route.callerId) {
11991
- return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
12037
+ return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
11992
12038
  }
11993
12039
  return getPoolStatus(this.name, mapped, context2);
11994
12040
  }
@@ -12890,7 +12936,9 @@ async function getCallerPoolStatus(input) {
12890
12936
  retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
12891
12937
  holdSeconds: input.holdSeconds,
12892
12938
  admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
12893
- nightBudget: callerNightBudget2(statuses, Date.now())
12939
+ ...input.route.readNightBudget && {
12940
+ nightBudget: callerNightBudget2(statuses, Date.now())
12941
+ }
12894
12942
  };
12895
12943
  }
12896
12944
  function toCents(value) {
@@ -14719,6 +14767,18 @@ var init_router_bridge = __esm(() => {
14719
14767
  // ../../packages/proxy/src/usage-worker.ts
14720
14768
  import { isAbsolute, resolve as resolve2 } from "path";
14721
14769
  import { pathToFileURL } from "url";
14770
+ function heldBytesOf(message) {
14771
+ switch (message.type) {
14772
+ case "start":
14773
+ return MESSAGE_OVERHEAD_BYTES + (message.requestBody?.length ?? 0);
14774
+ case "chunk":
14775
+ return MESSAGE_OVERHEAD_BYTES + message.data.byteLength;
14776
+ case "end":
14777
+ return MESSAGE_OVERHEAD_BYTES + (message.responseBody?.length ?? 0);
14778
+ default:
14779
+ return MESSAGE_OVERHEAD_BYTES;
14780
+ }
14781
+ }
14722
14782
  function noop() {}
14723
14783
  function createDefaultLogger() {
14724
14784
  return {
@@ -14772,6 +14832,7 @@ class UsageWorkerController {
14772
14832
  readyTimeoutMs;
14773
14833
  ackTimeoutMs;
14774
14834
  shutdownDelayMs;
14835
+ maxHeldBytes;
14775
14836
  logger;
14776
14837
  worker = null;
14777
14838
  ready = false;
@@ -14781,6 +14842,9 @@ class UsageWorkerController {
14781
14842
  shutdownTimer = null;
14782
14843
  queuedMessages = [];
14783
14844
  pendingAcks = new Map;
14845
+ heldBytes = 0;
14846
+ droppedRequestIds = new Set;
14847
+ droppedRequests = 0;
14784
14848
  shutdownPromise = null;
14785
14849
  resolveShutdown = null;
14786
14850
  rejectShutdown = null;
@@ -14791,6 +14855,7 @@ class UsageWorkerController {
14791
14855
  this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
14792
14856
  this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
14793
14857
  this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
14858
+ this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
14794
14859
  this.logger = options.logger ?? createDefaultLogger();
14795
14860
  this.startWorker();
14796
14861
  }
@@ -14799,16 +14864,65 @@ class UsageWorkerController {
14799
14864
  this.logger.warn("Dropping usage worker message because the worker is shutting down");
14800
14865
  return;
14801
14866
  }
14867
+ if (!this.admit(message)) {
14868
+ return;
14869
+ }
14802
14870
  const decoratedMessage = {
14803
14871
  ...message,
14804
14872
  messageId: crypto.randomUUID()
14805
14873
  };
14806
14874
  if (!this.ready || !this.worker) {
14807
- this.queuedMessages.push(decoratedMessage);
14875
+ this.queue(decoratedMessage);
14808
14876
  return;
14809
14877
  }
14810
14878
  this.sendMessage(decoratedMessage);
14811
14879
  }
14880
+ admit(message) {
14881
+ if (message.type === "shutdown") {
14882
+ return true;
14883
+ }
14884
+ if (this.droppedRequestIds.has(message.requestId)) {
14885
+ if (message.type === "end") {
14886
+ this.droppedRequestIds.delete(message.requestId);
14887
+ }
14888
+ return false;
14889
+ }
14890
+ if (message.type !== "start") {
14891
+ return true;
14892
+ }
14893
+ if (this.heldBytes + heldBytesOf(message) > this.maxHeldBytes) {
14894
+ if (this.droppedRequests === 0) {
14895
+ 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`);
14896
+ }
14897
+ this.droppedRequests += 1;
14898
+ this.droppedRequestIds.add(message.requestId);
14899
+ return false;
14900
+ }
14901
+ if (this.droppedRequests > 0) {
14902
+ this.logger.warn(`Dropped the usage of ${this.droppedRequests} requests while usage worker messages were over their byte cap`);
14903
+ this.droppedRequests = 0;
14904
+ }
14905
+ return true;
14906
+ }
14907
+ queue(message) {
14908
+ this.queuedMessages.push(message);
14909
+ this.heldBytes += heldBytesOf(message);
14910
+ }
14911
+ forgetQueuedMessages() {
14912
+ for (const message of this.queuedMessages) {
14913
+ this.heldBytes -= heldBytesOf(message);
14914
+ }
14915
+ this.queuedMessages.length = 0;
14916
+ }
14917
+ forgetPendingAck(messageId) {
14918
+ const pending = this.pendingAcks.get(messageId);
14919
+ if (!pending) {
14920
+ return;
14921
+ }
14922
+ clearTimeout(pending.timer);
14923
+ this.heldBytes -= heldBytesOf(pending.message);
14924
+ this.pendingAcks.delete(messageId);
14925
+ }
14812
14926
  isShuttingDown() {
14813
14927
  return this.shuttingDown;
14814
14928
  }
@@ -14829,7 +14943,7 @@ class UsageWorkerController {
14829
14943
  this.ready = false;
14830
14944
  this.clearReadyTimer();
14831
14945
  this.clearPendingAcks();
14832
- this.queuedMessages.length = 0;
14946
+ this.forgetQueuedMessages();
14833
14947
  const worker = this.worker;
14834
14948
  if (!worker) {
14835
14949
  this.shuttingDown = false;
@@ -14865,7 +14979,7 @@ class UsageWorkerController {
14865
14979
  this.ready = false;
14866
14980
  this.clearReadyTimer();
14867
14981
  this.clearPendingAcks();
14868
- this.queuedMessages.length = 0;
14982
+ this.forgetQueuedMessages();
14869
14983
  if (this.shutdownTimer) {
14870
14984
  clearTimeout(this.shutdownTimer);
14871
14985
  this.shutdownTimer = null;
@@ -14936,10 +15050,9 @@ class UsageWorkerController {
14936
15050
  this.readyTimer = null;
14937
15051
  }
14938
15052
  clearPendingAcks() {
14939
- for (const pending of this.pendingAcks.values()) {
14940
- clearTimeout(pending.timer);
15053
+ for (const messageId of Array.from(this.pendingAcks.keys())) {
15054
+ this.forgetPendingAck(messageId);
14941
15055
  }
14942
- this.pendingAcks.clear();
14943
15056
  }
14944
15057
  handleWorkerMessage(message) {
14945
15058
  if (isShutdownCompleteMessage(message)) {
@@ -14962,12 +15075,7 @@ class UsageWorkerController {
14962
15075
  return;
14963
15076
  }
14964
15077
  if (isAckMessage(message)) {
14965
- const pendingAck = this.pendingAcks.get(message.messageId);
14966
- if (!pendingAck) {
14967
- return;
14968
- }
14969
- clearTimeout(pendingAck.timer);
14970
- this.pendingAcks.delete(message.messageId);
15078
+ this.forgetPendingAck(message.messageId);
14971
15079
  return;
14972
15080
  }
14973
15081
  this.onWorkerMessage?.(message);
@@ -14976,14 +15084,15 @@ class UsageWorkerController {
14976
15084
  if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
14977
15085
  return;
14978
15086
  }
14979
- const queuedMessages = this.queuedMessages.splice(0, this.queuedMessages.length);
15087
+ const queuedMessages = this.queuedMessages.slice();
15088
+ this.forgetQueuedMessages();
14980
15089
  for (const message of queuedMessages) {
14981
15090
  this.sendMessage(message);
14982
15091
  }
14983
15092
  }
14984
15093
  sendMessage(message) {
14985
15094
  if (!this.worker) {
14986
- this.queuedMessages.push(message);
15095
+ this.queue(message);
14987
15096
  return;
14988
15097
  }
14989
15098
  try {
@@ -14997,11 +15106,10 @@ class UsageWorkerController {
14997
15106
  return;
14998
15107
  }
14999
15108
  const timer = setTimeout(() => {
15000
- const pendingAck = this.pendingAcks.get(message.messageId);
15001
- if (!pendingAck) {
15109
+ if (!this.pendingAcks.has(message.messageId)) {
15002
15110
  return;
15003
15111
  }
15004
- this.pendingAcks.delete(message.messageId);
15112
+ this.forgetPendingAck(message.messageId);
15005
15113
  this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
15006
15114
  this.restartWorker();
15007
15115
  }, this.ackTimeoutMs);
@@ -15010,6 +15118,7 @@ class UsageWorkerController {
15010
15118
  message,
15011
15119
  timer
15012
15120
  });
15121
+ this.heldBytes += heldBytesOf(message);
15013
15122
  }
15014
15123
  restartWorker() {
15015
15124
  if (this.shuttingDown) {
@@ -15063,12 +15172,13 @@ class UsageWorkerController {
15063
15172
  resolveShutdown?.();
15064
15173
  }
15065
15174
  }
15066
- var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100;
15175
+ var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100, DEFAULT_MAX_HELD_BYTES, MESSAGE_OVERHEAD_BYTES = 1024;
15067
15176
  var init_usage_worker = __esm(() => {
15068
15177
  init_src2();
15069
15178
  init_src();
15070
15179
  DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15071
15180
  DEFAULT_ACK_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_ACK_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15181
+ DEFAULT_MAX_HELD_BYTES = Number(process.env.AGENT_SMITH_USAGE_WORKER_MAX_HELD_MB || 256) * 1024 * 1024;
15072
15182
  });
15073
15183
 
15074
15184
  // ../../packages/proxy/src/proxy.ts
@@ -15582,7 +15692,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15582
15692
  admissionWaitMs: status.admissionWaitMs
15583
15693
  };
15584
15694
  },
15585
- getCallerPoolStatus: async (pool, model, callerId) => {
15695
+ getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
15586
15696
  const members = providerRegistry.poolCapacityMembers(pool, model);
15587
15697
  const url = new URL(`http://localhost/v1/pool/${pool}/`);
15588
15698
  const providers2 = members.map(({ provider }) => {
@@ -15592,7 +15702,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15592
15702
  return supply;
15593
15703
  });
15594
15704
  return getCallerPoolStatus({
15595
- route: createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15705
+ route: {
15706
+ ...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15707
+ readNightBudget
15708
+ },
15596
15709
  providers: providers2,
15597
15710
  orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
15598
15711
  apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
@@ -15910,35 +16023,49 @@ var init_fetch_handler = __esm(() => {
15910
16023
  });
15911
16024
 
15912
16025
  // ../../packages/runtime-server/src/retention-maintenance.ts
15913
- function removeExpiredRequests(config, dbOps, log27, label) {
15914
- try {
15915
- const payloadDays = config.getDataRetentionDays();
15916
- const requestDays = config.getRequestRetentionDays();
15917
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
15918
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
15919
- } catch (err) {
15920
- log27.error(`${label} cleanup error: ${err}`);
15921
- }
16026
+ function retentionWindows(config) {
16027
+ const payloadDays = config.getDataRetentionDays();
16028
+ const requestDays = config.getRequestRetentionDays();
16029
+ return {
16030
+ payloadMs: payloadDays * DAY_MS2,
16031
+ requestMs: requestDays * DAY_MS2,
16032
+ description: `payload=${payloadDays}d, requests=${requestDays}d`
16033
+ };
16034
+ }
16035
+ function logRemoved(log27, label, { removedRequests, removedPayloads }, description) {
16036
+ log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (${description})`);
15922
16037
  }
15923
16038
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
15924
16039
  const log27 = new Logger("RetentionMaintenance");
15925
- removeExpiredRequests(config, dbOps, log27, "Startup");
16040
+ try {
16041
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16042
+ logRemoved(log27, "Startup", dbOps.cleanupOldRequests(payloadMs, requestMs), description);
16043
+ } catch (err) {
16044
+ log27.error(`Startup cleanup error: ${err}`);
16045
+ }
15926
16046
  try {
15927
16047
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
15928
16048
  log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
15929
16049
  } catch (err) {
15930
16050
  log27.error(`Database compaction error: ${err}`);
15931
16051
  }
16052
+ const stopped = new AbortController;
16053
+ let running;
15932
16054
  const timer = setInterval(() => {
15933
- removeExpiredRequests(config, dbOps, log27, "Periodic");
15934
- try {
15935
- dbOps.checkpointWal();
15936
- } catch (err) {
15937
- log27.error(`WAL checkpoint error: ${err}`);
15938
- }
16055
+ if (running)
16056
+ return;
16057
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16058
+ running = dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs, {
16059
+ signal: stopped.signal
16060
+ }).then((removed) => logRemoved(log27, "Periodic", removed, description), (err) => log27.error(`Periodic cleanup error: ${err}`)).finally(() => {
16061
+ running = undefined;
16062
+ });
15939
16063
  }, intervalMs);
15940
16064
  timer.unref?.();
15941
- return () => clearInterval(timer);
16065
+ return () => {
16066
+ clearInterval(timer);
16067
+ stopped.abort();
16068
+ };
15942
16069
  }
15943
16070
  var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
15944
16071
  var init_retention_maintenance = __esm(() => {
@@ -17802,6 +17929,71 @@ function parseArgs(args) {
17802
17929
  }
17803
17930
  var init_args = () => {};
17804
17931
 
17932
+ // src/core/client-relay.ts
17933
+ function forwardedHeaders(original) {
17934
+ const headers3 = new Headers(original);
17935
+ for (const name of UNFORWARDED_REQUEST_HEADERS)
17936
+ headers3.delete(name);
17937
+ return headers3;
17938
+ }
17939
+ async function compressedBody(req, headers3) {
17940
+ const body = new Uint8Array(await req.arrayBuffer());
17941
+ if (body.length === 0)
17942
+ return;
17943
+ if (headers3.has("content-encoding"))
17944
+ return body;
17945
+ headers3.set("content-encoding", "gzip");
17946
+ return Bun.gzipSync(body);
17947
+ }
17948
+ function startClientRelay(remoteBaseUrl) {
17949
+ const remote = remoteBaseUrl.replace(/\/+$/, "");
17950
+ const server = Bun.serve({
17951
+ hostname: "127.0.0.1",
17952
+ port: 0,
17953
+ idleTimeout: 0,
17954
+ async fetch(req) {
17955
+ const url = new URL(req.url);
17956
+ const headers3 = forwardedHeaders(req.headers);
17957
+ const body = await compressedBody(req, headers3);
17958
+ try {
17959
+ const upstream = await fetch(`${remote}${url.pathname}${url.search}`, {
17960
+ method: req.method,
17961
+ headers: headers3,
17962
+ body,
17963
+ signal: req.signal,
17964
+ redirect: "manual"
17965
+ });
17966
+ return withSanitizedProxyHeaders(upstream);
17967
+ } catch (error) {
17968
+ const reason = error instanceof Error ? error.message : String(error);
17969
+ return Response.json({
17970
+ type: "error",
17971
+ error: {
17972
+ type: "api_error",
17973
+ message: `Agent Smith relay could not reach the pool: ${reason}`
17974
+ }
17975
+ }, { status: 502 });
17976
+ }
17977
+ }
17978
+ });
17979
+ return {
17980
+ url: `http://127.0.0.1:${server.port}`,
17981
+ stop: () => server.stop(true)
17982
+ };
17983
+ }
17984
+ var UNFORWARDED_REQUEST_HEADERS;
17985
+ var init_client_relay = __esm(() => {
17986
+ init_src6();
17987
+ UNFORWARDED_REQUEST_HEADERS = [
17988
+ "accept-encoding",
17989
+ "connection",
17990
+ "content-length",
17991
+ "host",
17992
+ "keep-alive",
17993
+ "transfer-encoding"
17994
+ ];
17995
+ });
17996
+
17805
17997
  // src/core/local-routing.ts
17806
17998
  import {
17807
17999
  accessSync as accessSync2,
@@ -18059,12 +18251,15 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
18059
18251
  delete env.AGENT_SMITH_ADMIN_KEY;
18060
18252
  delete env.AGENT_SMITH_PROXY_KEY;
18061
18253
  let command = [target, ...args];
18254
+ let relay;
18062
18255
  if (client2.enabled) {
18063
18256
  if (!client2.baseUrl || !client2.proxyKeyFile)
18064
18257
  throw new Error("client.base_url and client.proxy_key_file are required");
18065
18258
  const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
18066
18259
  const wires = Object.keys(new Config(configPath).getProviderPools());
18067
- const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
18260
+ if (client2.baseUrl.startsWith("https://"))
18261
+ relay = startClientRelay(client2.baseUrl);
18262
+ const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
18068
18263
  const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
18069
18264
  command = ["/bin/sh", "-c", script, "--", ...args];
18070
18265
  }
@@ -18086,6 +18281,7 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
18086
18281
  } finally {
18087
18282
  for (const [signal, listener] of Object.entries(forward))
18088
18283
  process.off(signal, listener);
18284
+ relay?.stop();
18089
18285
  }
18090
18286
  }
18091
18287
  async function enableLocalClientRouting(options) {
@@ -18174,6 +18370,7 @@ ${ROUTING_END}
18174
18370
  var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
18175
18371
  var init_local_routing = __esm(() => {
18176
18372
  init_src4();
18373
+ init_client_relay();
18177
18374
  CLAUDE_COMPANION_FILES = [
18178
18375
  ".claude-plugin/plugin.json",
18179
18376
  "hooks/hooks.json",