@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.
@@ -1844,6 +1844,13 @@ import {
1844
1844
  writeFileSync as writeFileSync2
1845
1845
  } from "fs";
1846
1846
  import { dirname as dirname2 } from "path";
1847
+ function callerWeeklyCap(caps, callerId) {
1848
+ if (!Object.hasOwn(caps, callerId))
1849
+ return;
1850
+ const cap = caps[callerId];
1851
+ const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
1852
+ return typeof shared === "number" ? shared : undefined;
1853
+ }
1847
1854
  function runtimeForProvider(runtime, provider) {
1848
1855
  return {
1849
1856
  ...runtime,
@@ -2145,8 +2152,9 @@ function sanitizeTeamRouting(value) {
2145
2152
  if (weeklyMaxUsageByEmail)
2146
2153
  result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
2147
2154
  if (isRecord(value.caller_weekly_max_usage)) {
2148
- const entries = Object.entries(value.caller_weekly_max_usage);
2149
- if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
2155
+ const caps = value.caller_weekly_max_usage;
2156
+ const entries = Object.entries(caps);
2157
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
2150
2158
  result.caller_weekly_max_usage = Object.fromEntries(entries);
2151
2159
  }
2152
2160
  }
@@ -2303,7 +2311,7 @@ function clientRouting(client) {
2303
2311
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2304
2312
  };
2305
2313
  }
2306
- 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;
2314
+ 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;
2307
2315
  var init_src4 = __esm(() => {
2308
2316
  init_src2();
2309
2317
  init_src3();
@@ -2827,10 +2835,11 @@ function addPerformanceIndexes(db) {
2827
2835
  `);
2828
2836
  log3.info("Added index: idx_accounts_paused");
2829
2837
  db.run(`
2830
- CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp
2831
- ON requests(account_used, timestamp DESC)
2838
+ CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
2839
+ ON requests(account_used, timestamp DESC, cost_usd)
2832
2840
  `);
2833
- log3.info("Added index: idx_requests_account_timestamp");
2841
+ db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
2842
+ log3.info("Added index: idx_requests_account_timestamp_cost");
2834
2843
  db.run(`
2835
2844
  CREATE INDEX IF NOT EXISTS idx_requests_cost_model
2836
2845
  ON requests(cost_usd, model, timestamp DESC)
@@ -3221,6 +3230,13 @@ function ensureAccountExtensionColumns(db) {
3221
3230
  }
3222
3231
  }
3223
3232
  }
3233
+ function backfillRequestLinkageColumnsOnce(db) {
3234
+ const { user_version } = db.query("PRAGMA user_version").get();
3235
+ if (user_version >= LINKAGE_BACKFILLED_VERSION)
3236
+ return;
3237
+ backfillRequestLinkageColumns(db);
3238
+ db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
3239
+ }
3224
3240
  function backfillRequestLinkageColumns(db) {
3225
3241
  const missingCount = db.query(`
3226
3242
  SELECT COUNT(*) AS count
@@ -3644,7 +3660,7 @@ function runMigrations(db) {
3644
3660
  migrateRequestsTable(db, requestsInfo);
3645
3661
  }
3646
3662
  ensureRequestLinkageColumns(db);
3647
- backfillRequestLinkageColumns(db);
3663
+ backfillRequestLinkageColumnsOnce(db);
3648
3664
  db.run("DROP TABLE IF EXISTS agent_preferences");
3649
3665
  db.run("DROP TABLE IF EXISTS oauth_sessions");
3650
3666
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
@@ -3660,7 +3676,7 @@ function runMigrations(db) {
3660
3676
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
3661
3677
  addPerformanceIndexes(db);
3662
3678
  }
3663
- var log5;
3679
+ var log5, LINKAGE_BACKFILLED_VERSION = 1;
3664
3680
  var init_migrations = __esm(() => {
3665
3681
  init_src3();
3666
3682
  init_src();
@@ -4507,7 +4523,7 @@ function requestLinkageFromPayload(payload) {
4507
4523
  clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
4508
4524
  };
4509
4525
  }
4510
- var log6, RequestRepository;
4526
+ var log6, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
4511
4527
  var init_request_repository = __esm(() => {
4512
4528
  init_src3();
4513
4529
  init_src();
@@ -4882,11 +4898,10 @@ var init_request_repository = __esm(() => {
4882
4898
  return errors.map((e) => e.error_message);
4883
4899
  }
4884
4900
  sumAccountCostSince(accountId, since) {
4885
- return this.get(`
4886
- SELECT SUM(cost_usd) AS cost
4887
- FROM requests
4888
- WHERE account_used = ? AND timestamp >= ?
4889
- `, [accountId, since])?.cost ?? 0;
4901
+ return this.get(ACCOUNT_COST_SINCE_SQL, [
4902
+ accountId,
4903
+ since
4904
+ ])?.cost ?? 0;
4890
4905
  }
4891
4906
  getRequestsByAccount(since) {
4892
4907
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
@@ -4910,23 +4925,26 @@ var init_request_repository = __esm(() => {
4910
4925
  successRate: row.success_rate
4911
4926
  }));
4912
4927
  }
4913
- deleteOlderThan(cutoffTs) {
4914
- return this.runWithChanges(`DELETE FROM requests WHERE timestamp < ?`, [
4915
- cutoffTs
4916
- ]);
4928
+ deleteOlderThan(cutoffTs, limit) {
4929
+ return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
4930
+ SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
4931
+ )`, [cutoffTs, limit]);
4917
4932
  }
4918
4933
  clear() {
4919
4934
  return this.runWithChanges(`DELETE FROM requests`);
4920
4935
  }
4921
- deleteOrphanedPayloads() {
4922
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
4923
- }
4924
- deletePayloadsOlderThan(cutoffTs) {
4925
- return this.runWithChanges(`DELETE FROM request_payloads
4926
- WHERE EXISTS (
4927
- SELECT 1 FROM requests r
4928
- WHERE r.id = request_payloads.id AND r.timestamp < ?
4929
- )`, [cutoffTs]);
4936
+ deleteOldestExpiredPayloads(cutoffTs, limit) {
4937
+ const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
4938
+ FROM request_payloads rp
4939
+ LEFT JOIN requests r ON r.id = rp.id
4940
+ ORDER BY rp.rowid
4941
+ LIMIT ?`, [limit]);
4942
+ const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
4943
+ const expiredCount = firstLive === -1 ? oldest.length : firstLive;
4944
+ const lastExpired = oldest[expiredCount - 1];
4945
+ if (!lastExpired)
4946
+ return 0;
4947
+ return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
4930
4948
  }
4931
4949
  };
4932
4950
  });
@@ -5055,6 +5073,7 @@ var init_strategy_repository = __esm(() => {
5055
5073
  import { Database } from "bun:sqlite";
5056
5074
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
5057
5075
  import { dirname as dirname3 } from "path";
5076
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
5058
5077
  function freeDiskBytes(directory) {
5059
5078
  const { bavail, bsize } = statfsSync(directory);
5060
5079
  return bavail * bsize;
@@ -5074,7 +5093,7 @@ class DatabaseOperations {
5074
5093
  conversationProviderPreferences;
5075
5094
  strategy;
5076
5095
  stats;
5077
- constructor(dbPath) {
5096
+ constructor(dbPath, { migrate = true } = {}) {
5078
5097
  const resolvedPath = dbPath ?? resolveDbPath();
5079
5098
  this.dbPath = resolvedPath;
5080
5099
  const dir = dirname3(resolvedPath);
@@ -5084,8 +5103,11 @@ class DatabaseOperations {
5084
5103
  this.db.exec("PRAGMA journal_mode = WAL");
5085
5104
  this.db.exec("PRAGMA busy_timeout = 5000");
5086
5105
  this.db.exec("PRAGMA synchronous = NORMAL");
5087
- ensureSchema(this.db);
5088
- runMigrations(this.db);
5106
+ this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
5107
+ if (migrate) {
5108
+ ensureSchema(this.db);
5109
+ runMigrations(this.db);
5110
+ }
5089
5111
  this.accounts = new AccountRepository(this.db);
5090
5112
  this.analytics = new AnalyticsRepository(this.db);
5091
5113
  this.requests = new RequestRepository(this.db);
@@ -5301,18 +5323,40 @@ class DatabaseOperations {
5301
5323
  getAnalytics(options) {
5302
5324
  return this.analytics.getAnalytics(options);
5303
5325
  }
5304
- cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
5305
- const now = Date.now();
5306
- const payloadCutoff = now - payloadRetentionMs;
5307
- let removedRequests = 0;
5308
- if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5309
- const requestCutoff = now - requestRetentionMs;
5310
- removedRequests = this.requests.deleteOlderThan(requestCutoff);
5326
+ cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
5327
+ const total = { removedRequests: 0, removedPayloads: 0 };
5328
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5329
+ total.removedRequests += batch.removedRequests;
5330
+ total.removedPayloads += batch.removedPayloads;
5331
+ }
5332
+ return total;
5333
+ }
5334
+ async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
5335
+ batchRows = CLEANUP_BATCH_ROWS,
5336
+ signal
5337
+ } = {}) {
5338
+ const total = { removedRequests: 0, removedPayloads: 0 };
5339
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5340
+ total.removedRequests += batch.removedRequests;
5341
+ total.removedPayloads += batch.removedPayloads;
5342
+ await yieldToEventLoop();
5343
+ if (signal?.aborted)
5344
+ break;
5345
+ }
5346
+ return total;
5347
+ }
5348
+ *cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
5349
+ for (;; ) {
5350
+ const now = Date.now();
5351
+ let removedRequests = 0;
5352
+ if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5353
+ removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
5354
+ }
5355
+ const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
5356
+ yield { removedRequests, removedPayloads };
5357
+ if (removedRequests < batchRows && removedPayloads < batchRows)
5358
+ return;
5311
5359
  }
5312
- const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
5313
- const removedOrphans = this.requests.deleteOrphanedPayloads();
5314
- const removedPayloads = removedPayloadsByAge + removedOrphans;
5315
- return { removedRequests, removedPayloads };
5316
5360
  }
5317
5361
  close() {
5318
5362
  if (this.closed) {
@@ -5351,6 +5395,7 @@ class DatabaseOperations {
5351
5395
  return this.stats;
5352
5396
  }
5353
5397
  }
5398
+ var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
5354
5399
  var init_database_operations = __esm(() => {
5355
5400
  init_migrations();
5356
5401
  init_paths2();
@@ -5363,6 +5408,7 @@ var init_database_operations = __esm(() => {
5363
5408
  init_request_repository();
5364
5409
  init_stats_repository();
5365
5410
  init_strategy_repository();
5411
+ WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
5366
5412
  });
5367
5413
 
5368
5414
  // ../../packages/database/src/factory.ts
@@ -5563,7 +5609,7 @@ var log7 = new Logger("PostProcessor");
5563
5609
  var requests = new Map;
5564
5610
  var tokenEncoder = get_encoding("cl100k_base");
5565
5611
  var streamDecoder = new TextDecoder("utf-8", { fatal: false });
5566
- var dbOps = new DatabaseOperations;
5612
+ var dbOps = new DatabaseOperations(undefined, { migrate: false });
5567
5613
  var asyncWriter = new AsyncDbWriter;
5568
5614
  var MAX_BUFFER_SIZE = Number(process.env.AGENT_SMITH_STREAM_USAGE_BUFFER_KB || BUFFER_SIZES.STREAM_USAGE_BUFFER_KB) * 1024;
5569
5615
  var TIMEOUT_MS = Number(process.env.AGENT_SMITH_STREAM_TIMEOUT_MS || TIME_CONSTANTS.STREAM_TIMEOUT_DEFAULT);