@certalis/agent-smith 0.2.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.
@@ -1302,6 +1302,198 @@ var init_builtin_providers = __esm(() => {
1302
1302
  ];
1303
1303
  });
1304
1304
 
1305
+ // ../../packages/config/src/zoned-time.ts
1306
+ function isTimeZone(value) {
1307
+ if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1308
+ return false;
1309
+ }
1310
+ try {
1311
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
1312
+ return true;
1313
+ } catch {
1314
+ return false;
1315
+ }
1316
+ }
1317
+ function localTimeOfDayMs(time) {
1318
+ const [hour = 0, minute = 0] = time.split(":").map(Number);
1319
+ return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
1320
+ }
1321
+ function wallClockFormat(timeZone) {
1322
+ let format = wallClockFormats.get(timeZone);
1323
+ if (!format) {
1324
+ format = new Intl.DateTimeFormat("en-US", {
1325
+ timeZone,
1326
+ hourCycle: "h23",
1327
+ year: "numeric",
1328
+ month: "numeric",
1329
+ day: "numeric",
1330
+ hour: "numeric",
1331
+ minute: "numeric",
1332
+ second: "numeric"
1333
+ });
1334
+ wallClockFormats.set(timeZone, format);
1335
+ }
1336
+ return format;
1337
+ }
1338
+ function wallClock(at, timeZone) {
1339
+ const parts = wallClockFormat(timeZone).formatToParts(at);
1340
+ const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1341
+ return {
1342
+ year: part("year"),
1343
+ month: part("month"),
1344
+ day: part("day"),
1345
+ hour: part("hour") % 24,
1346
+ minute: part("minute"),
1347
+ second: part("second")
1348
+ };
1349
+ }
1350
+ function zoneOffsetMs(at, timeZone) {
1351
+ const wall = wallClock(at, timeZone);
1352
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1353
+ }
1354
+ function zonedInstant(wall, timeZone) {
1355
+ return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1356
+ }
1357
+ var LOCAL_TIME, wallClockFormats;
1358
+ var init_zoned_time = __esm(() => {
1359
+ init_src2();
1360
+ LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1361
+ wallClockFormats = new Map;
1362
+ });
1363
+
1364
+ // ../../packages/config/src/night-pacing.ts
1365
+ function localHours(value) {
1366
+ if (!isRecord(value) || Object.keys(value).length !== 2 || typeof value.start !== "string" || typeof value.end !== "string" || !LOCAL_TIME.test(value.start) || !LOCAL_TIME.test(value.end) || value.start === value.end) {
1367
+ return;
1368
+ }
1369
+ return { start: value.start, end: value.end };
1370
+ }
1371
+ function isWorkingDays(value) {
1372
+ return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
1373
+ }
1374
+ function sanitizeNightPacing(value) {
1375
+ if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
1376
+ return;
1377
+ }
1378
+ const result = {};
1379
+ if (value.time_zone !== undefined) {
1380
+ if (!isTimeZone(value.time_zone))
1381
+ return;
1382
+ result.time_zone = value.time_zone;
1383
+ }
1384
+ if (value.working_days !== undefined) {
1385
+ if (!isWorkingDays(value.working_days))
1386
+ return;
1387
+ result.working_days = [...value.working_days];
1388
+ }
1389
+ if (value.working_hours !== undefined) {
1390
+ const hours = localHours(value.working_hours);
1391
+ if (!hours || hours.start > hours.end)
1392
+ return;
1393
+ result.working_hours = hours;
1394
+ }
1395
+ if (value.night_hours !== undefined) {
1396
+ const hours = localHours(value.night_hours);
1397
+ if (!hours)
1398
+ return;
1399
+ result.night_hours = hours;
1400
+ }
1401
+ if (value.margin_working_days !== undefined) {
1402
+ if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
1403
+ return;
1404
+ }
1405
+ result.margin_working_days = value.margin_working_days;
1406
+ }
1407
+ if (value.use_up_before !== undefined) {
1408
+ if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
1409
+ return;
1410
+ }
1411
+ result.use_up_before = value.use_up_before;
1412
+ }
1413
+ return result;
1414
+ }
1415
+ function nightPacingSettings(file) {
1416
+ return {
1417
+ timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
1418
+ workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
1419
+ workingHours: {
1420
+ ...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
1421
+ },
1422
+ nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
1423
+ marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
1424
+ useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
1425
+ };
1426
+ }
1427
+ function localDay(at, timeZone) {
1428
+ const wall = wallClock(at, timeZone);
1429
+ return {
1430
+ day: Date.UTC(wall.year, wall.month - 1, wall.day),
1431
+ timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
1432
+ };
1433
+ }
1434
+ function nightEndAt(pacing, now) {
1435
+ const { day, timeOfDay } = localDay(now, pacing.timeZone);
1436
+ const start = localTimeOfDayMs(pacing.nightHours.start);
1437
+ const end = localTimeOfDayMs(pacing.nightHours.end);
1438
+ const wraps = start > end;
1439
+ const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
1440
+ if (!night)
1441
+ return null;
1442
+ const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
1443
+ return zonedInstant(endDay + end, pacing.timeZone);
1444
+ }
1445
+ function workingMsBetween(pacing, from, to) {
1446
+ const start = localTimeOfDayMs(pacing.workingHours.start);
1447
+ const end = localTimeOfDayMs(pacing.workingHours.end);
1448
+ let total = 0;
1449
+ for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
1450
+ if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
1451
+ continue;
1452
+ const opens = zonedInstant(day + start, pacing.timeZone);
1453
+ const closes = zonedInstant(day + end, pacing.timeZone);
1454
+ total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
1455
+ }
1456
+ return total;
1457
+ }
1458
+ function expiresBeforeUseUpTime(pacing, resetAt, now) {
1459
+ const endAt = nightEndAt(pacing, now);
1460
+ if (endAt === null || resetAt <= now)
1461
+ return false;
1462
+ return resetAt <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
1463
+ }
1464
+ function nightWeeklyTarget(pacing, resetAt, now) {
1465
+ if (expiresBeforeUseUpTime(pacing, resetAt, now))
1466
+ return 1;
1467
+ const windowStart = resetAt - WEEKLY_WINDOW_MS;
1468
+ const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
1469
+ const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt));
1470
+ return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt);
1471
+ }
1472
+ var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
1473
+ var init_night_pacing = __esm(() => {
1474
+ init_src2();
1475
+ init_src();
1476
+ init_zoned_time();
1477
+ WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1478
+ WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
1479
+ NIGHT_PACING_DEFAULTS = {
1480
+ timeZone: "Europe/Paris",
1481
+ workingDays: ["mon", "tue", "wed", "thu", "fri"],
1482
+ workingHours: { start: "07:00", end: "21:00" },
1483
+ nightHours: { start: "21:00", end: "07:00" },
1484
+ marginWorkingDays: 1,
1485
+ useUpBefore: "10:00"
1486
+ };
1487
+ NIGHT_PACING_FIELDS = new Set([
1488
+ "time_zone",
1489
+ "working_days",
1490
+ "working_hours",
1491
+ "night_hours",
1492
+ "margin_working_days",
1493
+ "use_up_before"
1494
+ ]);
1495
+ });
1496
+
1305
1497
  // ../../packages/config/src/paths-common.ts
1306
1498
  import { homedir } from "os";
1307
1499
  import { join as join3 } from "path";
@@ -1572,17 +1764,6 @@ var init_rewrite_file = __esm(() => {
1572
1764
  function isLocalTimes(value) {
1573
1765
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1574
1766
  }
1575
- function isTimeZone(value) {
1576
- if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1577
- return false;
1578
- }
1579
- try {
1580
- new Intl.DateTimeFormat("en-US", { timeZone: value });
1581
- return true;
1582
- } catch {
1583
- return false;
1584
- }
1585
- }
1586
1767
  function sanitizeWindowWarmup(value) {
1587
1768
  if (!isRecord(value))
1588
1769
  return;
@@ -1619,42 +1800,6 @@ function windowWarmupFileConfig(config) {
1619
1800
  ...config.model && { model: config.model }
1620
1801
  };
1621
1802
  }
1622
- function wallClockFormat(timeZone) {
1623
- let format = wallClockFormats.get(timeZone);
1624
- if (!format) {
1625
- format = new Intl.DateTimeFormat("en-US", {
1626
- timeZone,
1627
- hourCycle: "h23",
1628
- year: "numeric",
1629
- month: "numeric",
1630
- day: "numeric",
1631
- hour: "numeric",
1632
- minute: "numeric",
1633
- second: "numeric"
1634
- });
1635
- wallClockFormats.set(timeZone, format);
1636
- }
1637
- return format;
1638
- }
1639
- function wallClock(at, timeZone) {
1640
- const parts = wallClockFormat(timeZone).formatToParts(at);
1641
- const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1642
- return {
1643
- year: part("year"),
1644
- month: part("month"),
1645
- day: part("day"),
1646
- hour: part("hour") % 24,
1647
- minute: part("minute"),
1648
- second: part("second")
1649
- };
1650
- }
1651
- function zoneOffsetMs(at, timeZone) {
1652
- const wall = wallClock(at, timeZone);
1653
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1654
- }
1655
- function zonedInstant(wall, timeZone) {
1656
- return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1657
- }
1658
1803
  function nextWindowWarmupAt(routing, after) {
1659
1804
  const warmup = routing.windowWarmup;
1660
1805
  if (!routing.enabled || !warmup.enabled)
@@ -1666,19 +1811,16 @@ function nextWindowWarmupAt(routing, after) {
1666
1811
  if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
1667
1812
  continue;
1668
1813
  }
1669
- const instants = warmup.times.map((time) => {
1670
- const [hour = 0, minute = 0] = time.split(":").map(Number);
1671
- return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
1672
- }).filter((at) => at > after);
1814
+ const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
1673
1815
  if (instants.length > 0)
1674
1816
  return Math.min(...instants);
1675
1817
  }
1676
1818
  return null;
1677
1819
  }
1678
- var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
1820
+ var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
1679
1821
  var init_window_warmup = __esm(() => {
1680
- init_src2();
1681
1822
  init_src();
1823
+ init_zoned_time();
1682
1824
  WINDOW_WARMUP_DEFAULTS = {
1683
1825
  enabled: false,
1684
1826
  times: ["06:00"],
@@ -1686,9 +1828,7 @@ var init_window_warmup = __esm(() => {
1686
1828
  weekdaysOnly: true,
1687
1829
  model: null
1688
1830
  };
1689
- LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1690
1831
  MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
1691
- wallClockFormats = new Map;
1692
1832
  });
1693
1833
 
1694
1834
  // ../../packages/config/src/index.ts
@@ -1704,6 +1844,13 @@ import {
1704
1844
  writeFileSync as writeFileSync2
1705
1845
  } from "fs";
1706
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
+ }
1707
1854
  function runtimeForProvider(runtime, provider) {
1708
1855
  return {
1709
1856
  ...runtime,
@@ -1954,6 +2101,29 @@ function wireForStrategy(strategy3) {
1954
2101
  function isNonNegativeFiniteNumber(value) {
1955
2102
  return isFiniteNumber(value) && value >= 0;
1956
2103
  }
2104
+ function sanitizeCapsByEmail(value, maximum) {
2105
+ if (!isRecord(value))
2106
+ return;
2107
+ const entries = Object.entries(value);
2108
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
2109
+ const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
2110
+ if (!isValid)
2111
+ return;
2112
+ return Object.fromEntries(normalized);
2113
+ }
2114
+ function isDeviceList(value) {
2115
+ return Array.isArray(value) && value.length > 0 && value.length <= MAX_CALLERS && value.every((device) => typeof device === "string" && CALLER_ID_PATTERN.test(device)) && new Set(value).size === value.length;
2116
+ }
2117
+ function sanitizeOwnerDevicesByEmail(value) {
2118
+ if (!isRecord(value))
2119
+ return;
2120
+ const entries = Object.entries(value);
2121
+ const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
2122
+ const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
2123
+ if (!isValid)
2124
+ return;
2125
+ return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
2126
+ }
1957
2127
  function sanitizeTeamRouting(value) {
1958
2128
  if (!isRecord(value))
1959
2129
  return;
@@ -1975,19 +2145,22 @@ function sanitizeTeamRouting(value) {
1975
2145
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1976
2146
  result.weekly_max_usage = value.weekly_max_usage;
1977
2147
  }
1978
- if (isRecord(value.weekly_max_usage_by_email)) {
1979
- const entries = Object.entries(value.weekly_max_usage_by_email);
1980
- const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1981
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1982
- result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1983
- }
1984
- }
2148
+ const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
2149
+ if (maxUsageByEmail)
2150
+ result.max_usage_by_email = maxUsageByEmail;
2151
+ const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
2152
+ if (weeklyMaxUsageByEmail)
2153
+ result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
1985
2154
  if (isRecord(value.caller_weekly_max_usage)) {
1986
- const entries = Object.entries(value.caller_weekly_max_usage);
1987
- 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)))) {
1988
2158
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1989
2159
  }
1990
2160
  }
2161
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
2162
+ if (ownerDevicesByEmail)
2163
+ result.owner_devices_by_email = ownerDevicesByEmail;
1991
2164
  if (isRecord(value.caller_provider_fallback)) {
1992
2165
  const entries = Object.entries(value.caller_provider_fallback);
1993
2166
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -2038,9 +2211,11 @@ function sanitizeProviderPool(value) {
2038
2211
  "distribution_enabled",
2039
2212
  "prefer_expiring_quota",
2040
2213
  "max_usage",
2214
+ "max_usage_by_email",
2041
2215
  "weekly_max_usage",
2042
2216
  "weekly_max_usage_by_email",
2043
2217
  "caller_weekly_max_usage",
2218
+ "owner_devices_by_email",
2044
2219
  "quota_probe_seconds",
2045
2220
  "window_warmup"
2046
2221
  ]) {
@@ -2062,8 +2237,17 @@ function sanitizeProviderPool(value) {
2062
2237
  }
2063
2238
  if (typeof value.block_when_all_full === "boolean")
2064
2239
  pool.block_when_all_full = value.block_when_all_full;
2240
+ const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
2241
+ if (nightPacing)
2242
+ pool.caller_night_pacing = nightPacing;
2065
2243
  return pool;
2066
2244
  }
2245
+ function sanitizeCallerNightPacing(value) {
2246
+ if (!isRecord(value))
2247
+ return;
2248
+ const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
2249
+ return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
2250
+ }
2067
2251
  function sanitizeRouting(value) {
2068
2252
  if (!isRecord(value))
2069
2253
  return;
@@ -2127,15 +2311,17 @@ function clientRouting(client) {
2127
2311
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2128
2312
  };
2129
2313
  }
2130
- 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;
2131
2315
  var init_src4 = __esm(() => {
2132
2316
  init_src2();
2133
2317
  init_src3();
2134
2318
  init_src();
2135
2319
  init_builtin_providers();
2320
+ init_night_pacing();
2136
2321
  init_paths();
2137
2322
  init_rewrite_file();
2138
2323
  init_window_warmup();
2324
+ init_night_pacing();
2139
2325
  init_paths();
2140
2326
  init_paths_common();
2141
2327
  init_rewrite_config();
@@ -2161,9 +2347,12 @@ var init_src4 = __esm(() => {
2161
2347
  preferExpiringQuota: false,
2162
2348
  allowlistedAccountUuids: [],
2163
2349
  maxUsage: 0.9,
2350
+ maxUsageByEmail: {},
2164
2351
  weeklyMaxUsage: 0.95,
2165
2352
  weeklyMaxUsageByEmail: {},
2166
2353
  callerWeeklyMaxUsage: {},
2354
+ callerNightPacing: {},
2355
+ ownerDevicesByEmail: {},
2167
2356
  admissionCap: 5,
2168
2357
  admissionQueueLimit: 25,
2169
2358
  admissionWaitMs: 30000,
@@ -2337,9 +2526,12 @@ var init_src4 = __esm(() => {
2337
2526
  preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2338
2527
  allowlistedAccountUuids: [...pool?.members ?? []],
2339
2528
  maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2529
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
2340
2530
  weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2341
2531
  weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2342
2532
  callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2533
+ callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
2534
+ ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
2343
2535
  admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2344
2536
  admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2345
2537
  admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
@@ -2416,9 +2608,12 @@ var init_src4 = __esm(() => {
2416
2608
  "distribution_enabled",
2417
2609
  "prefer_expiring_quota",
2418
2610
  "max_usage",
2611
+ "max_usage_by_email",
2419
2612
  "weekly_max_usage",
2420
2613
  "weekly_max_usage_by_email",
2421
2614
  "caller_weekly_max_usage",
2615
+ "caller_night_pacing",
2616
+ "owner_devices_by_email",
2422
2617
  "admission",
2423
2618
  "quota_probe_seconds",
2424
2619
  "window_warmup",
@@ -2640,10 +2835,11 @@ function addPerformanceIndexes(db) {
2640
2835
  `);
2641
2836
  log3.info("Added index: idx_accounts_paused");
2642
2837
  db.run(`
2643
- CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp
2644
- 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)
2645
2840
  `);
2646
- 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");
2647
2843
  db.run(`
2648
2844
  CREATE INDEX IF NOT EXISTS idx_requests_cost_model
2649
2845
  ON requests(cost_usd, model, timestamp DESC)
@@ -3009,7 +3205,8 @@ function ensureRequestLinkageColumns(db) {
3009
3205
  ["ttft_ms", "INTEGER"],
3010
3206
  ["proxy_overhead_ms", "INTEGER"],
3011
3207
  ["upstream_ttfb_ms", "INTEGER"],
3012
- ["streaming_duration_ms", "INTEGER"]
3208
+ ["streaming_duration_ms", "INTEGER"],
3209
+ ["caller", "TEXT"]
3013
3210
  ];
3014
3211
  for (const [columnName, columnType] of requestColumns) {
3015
3212
  if (!hasColumn(columns, columnName)) {
@@ -3033,6 +3230,13 @@ function ensureAccountExtensionColumns(db) {
3033
3230
  }
3034
3231
  }
3035
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
+ }
3036
3240
  function backfillRequestLinkageColumns(db) {
3037
3241
  const missingCount = db.query(`
3038
3242
  SELECT COUNT(*) AS count
@@ -3427,7 +3631,8 @@ function ensureSchema(db) {
3427
3631
  ttft_ms INTEGER,
3428
3632
  proxy_overhead_ms INTEGER,
3429
3633
  upstream_ttfb_ms INTEGER,
3430
- streaming_duration_ms INTEGER
3634
+ streaming_duration_ms INTEGER,
3635
+ caller TEXT
3431
3636
  )
3432
3637
  `);
3433
3638
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
@@ -3455,7 +3660,7 @@ function runMigrations(db) {
3455
3660
  migrateRequestsTable(db, requestsInfo);
3456
3661
  }
3457
3662
  ensureRequestLinkageColumns(db);
3458
- backfillRequestLinkageColumns(db);
3663
+ backfillRequestLinkageColumnsOnce(db);
3459
3664
  db.run("DROP TABLE IF EXISTS agent_preferences");
3460
3665
  db.run("DROP TABLE IF EXISTS oauth_sessions");
3461
3666
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
@@ -3471,7 +3676,7 @@ function runMigrations(db) {
3471
3676
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
3472
3677
  addPerformanceIndexes(db);
3473
3678
  }
3474
- var log5;
3679
+ var log5, LINKAGE_BACKFILLED_VERSION = 1;
3475
3680
  var init_migrations = __esm(() => {
3476
3681
  init_src3();
3477
3682
  init_src();
@@ -3881,6 +4086,30 @@ var init_analytics_repository = __esm(() => {
3881
4086
  totalTokens: row.total_tokens ?? 0,
3882
4087
  totalCostUsd: row.total_cost_usd ?? 0
3883
4088
  }));
4089
+ const callerBreakdown = this.query(`
4090
+ SELECT
4091
+ r.caller as caller,
4092
+ COUNT(*) as requests,
4093
+ SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
4094
+ SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
4095
+ SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
4096
+ SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
4097
+ SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
4098
+ FROM requests r
4099
+ WHERE ${whereClause}
4100
+ GROUP BY r.caller
4101
+ ORDER BY total_cost_usd DESC, requests DESC
4102
+ `, queryParams).map((row) => ({
4103
+ caller: row.caller,
4104
+ requests: row.requests,
4105
+ tokenBreakdown: {
4106
+ inputTokens: row.input_tokens ?? 0,
4107
+ cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
4108
+ cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
4109
+ outputTokens: row.output_tokens ?? 0
4110
+ },
4111
+ totalCostUsd: row.total_cost_usd ?? 0
4112
+ }));
3884
4113
  const modelPerformance = this.query(`
3885
4114
  WITH model_stats AS (
3886
4115
  SELECT
@@ -3977,6 +4206,7 @@ var init_analytics_repository = __esm(() => {
3977
4206
  successRate: account2.success_rate ?? 0
3978
4207
  })),
3979
4208
  providerBreakdown,
4209
+ callerBreakdown,
3980
4210
  costByModel,
3981
4211
  modelPerformance
3982
4212
  };
@@ -4293,7 +4523,7 @@ function requestLinkageFromPayload(payload) {
4293
4523
  clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
4294
4524
  };
4295
4525
  }
4296
- var log6, RequestRepository;
4526
+ var log6, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
4297
4527
  var init_request_repository = __esm(() => {
4298
4528
  init_src3();
4299
4529
  init_src();
@@ -4371,7 +4601,8 @@ var init_request_repository = __esm(() => {
4371
4601
  response_id = ?,
4372
4602
  previous_response_id = ?,
4373
4603
  response_chain_id = ?,
4374
- client_session_id = ?
4604
+ client_session_id = ?,
4605
+ caller = ?
4375
4606
  WHERE id = ?
4376
4607
  `, [
4377
4608
  data.method,
@@ -4403,6 +4634,7 @@ var init_request_repository = __esm(() => {
4403
4634
  linkage.previousResponseId,
4404
4635
  responseChainId,
4405
4636
  linkage.clientSessionId,
4637
+ data.caller ?? null,
4406
4638
  data.id
4407
4639
  ]);
4408
4640
  if (payloadJson !== undefined) {
@@ -4665,6 +4897,12 @@ var init_request_repository = __esm(() => {
4665
4897
  `, [limit]);
4666
4898
  return errors.map((e) => e.error_message);
4667
4899
  }
4900
+ sumAccountCostSince(accountId, since) {
4901
+ return this.get(ACCOUNT_COST_SINCE_SQL, [
4902
+ accountId,
4903
+ since
4904
+ ])?.cost ?? 0;
4905
+ }
4668
4906
  getRequestsByAccount(since) {
4669
4907
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
4670
4908
  const params = since ? [since] : [];
@@ -4687,23 +4925,26 @@ var init_request_repository = __esm(() => {
4687
4925
  successRate: row.success_rate
4688
4926
  }));
4689
4927
  }
4690
- deleteOlderThan(cutoffTs) {
4691
- return this.runWithChanges(`DELETE FROM requests WHERE timestamp < ?`, [
4692
- cutoffTs
4693
- ]);
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]);
4694
4932
  }
4695
4933
  clear() {
4696
4934
  return this.runWithChanges(`DELETE FROM requests`);
4697
4935
  }
4698
- deleteOrphanedPayloads() {
4699
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
4700
- }
4701
- deletePayloadsOlderThan(cutoffTs) {
4702
- return this.runWithChanges(`DELETE FROM request_payloads
4703
- WHERE EXISTS (
4704
- SELECT 1 FROM requests r
4705
- WHERE r.id = request_payloads.id AND r.timestamp < ?
4706
- )`, [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]);
4707
4948
  }
4708
4949
  };
4709
4950
  });
@@ -4832,6 +5073,7 @@ var init_strategy_repository = __esm(() => {
4832
5073
  import { Database } from "bun:sqlite";
4833
5074
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
4834
5075
  import { dirname as dirname3 } from "path";
5076
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
4835
5077
  function freeDiskBytes(directory) {
4836
5078
  const { bavail, bsize } = statfsSync(directory);
4837
5079
  return bavail * bsize;
@@ -4851,7 +5093,7 @@ class DatabaseOperations {
4851
5093
  conversationProviderPreferences;
4852
5094
  strategy;
4853
5095
  stats;
4854
- constructor(dbPath) {
5096
+ constructor(dbPath, { migrate = true } = {}) {
4855
5097
  const resolvedPath = dbPath ?? resolveDbPath();
4856
5098
  this.dbPath = resolvedPath;
4857
5099
  const dir = dirname3(resolvedPath);
@@ -4861,8 +5103,11 @@ class DatabaseOperations {
4861
5103
  this.db.exec("PRAGMA journal_mode = WAL");
4862
5104
  this.db.exec("PRAGMA busy_timeout = 5000");
4863
5105
  this.db.exec("PRAGMA synchronous = NORMAL");
4864
- ensureSchema(this.db);
4865
- 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
+ }
4866
5111
  this.accounts = new AccountRepository(this.db);
4867
5112
  this.analytics = new AnalyticsRepository(this.db);
4868
5113
  this.requests = new RequestRepository(this.db);
@@ -5008,9 +5253,13 @@ class DatabaseOperations {
5008
5253
  timestamp: options?.timestamp,
5009
5254
  payload: options?.payload,
5010
5255
  storePayload: options?.storePayload,
5011
- timings: options?.timings
5256
+ timings: options?.timings,
5257
+ caller: options?.callerId ?? null
5012
5258
  });
5013
5259
  }
5260
+ getAccountCostSince(accountId, since) {
5261
+ return this.requests.sumAccountCostSince(accountId, since);
5262
+ }
5014
5263
  updateRequestUsage(requestId, usage) {
5015
5264
  this.requests.updateUsage(requestId, usage);
5016
5265
  }
@@ -5074,18 +5323,40 @@ class DatabaseOperations {
5074
5323
  getAnalytics(options) {
5075
5324
  return this.analytics.getAnalytics(options);
5076
5325
  }
5077
- cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
5078
- const now = Date.now();
5079
- const payloadCutoff = now - payloadRetentionMs;
5080
- let removedRequests = 0;
5081
- if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5082
- const requestCutoff = now - requestRetentionMs;
5083
- 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;
5084
5359
  }
5085
- const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
5086
- const removedOrphans = this.requests.deleteOrphanedPayloads();
5087
- const removedPayloads = removedPayloadsByAge + removedOrphans;
5088
- return { removedRequests, removedPayloads };
5089
5360
  }
5090
5361
  close() {
5091
5362
  if (this.closed) {
@@ -5124,6 +5395,7 @@ class DatabaseOperations {
5124
5395
  return this.stats;
5125
5396
  }
5126
5397
  }
5398
+ var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
5127
5399
  var init_database_operations = __esm(() => {
5128
5400
  init_migrations();
5129
5401
  init_paths2();
@@ -5136,6 +5408,7 @@ var init_database_operations = __esm(() => {
5136
5408
  init_request_repository();
5137
5409
  init_stats_repository();
5138
5410
  init_strategy_repository();
5411
+ WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
5139
5412
  });
5140
5413
 
5141
5414
  // ../../packages/database/src/factory.ts
@@ -5336,7 +5609,7 @@ var log7 = new Logger("PostProcessor");
5336
5609
  var requests = new Map;
5337
5610
  var tokenEncoder = get_encoding("cl100k_base");
5338
5611
  var streamDecoder = new TextDecoder("utf-8", { fatal: false });
5339
- var dbOps = new DatabaseOperations;
5612
+ var dbOps = new DatabaseOperations(undefined, { migrate: false });
5340
5613
  var asyncWriter = new AsyncDbWriter;
5341
5614
  var MAX_BUFFER_SIZE = Number(process.env.AGENT_SMITH_STREAM_USAGE_BUFFER_KB || BUFFER_SIZES.STREAM_USAGE_BUFFER_KB) * 1024;
5342
5615
  var TIMEOUT_MS = Number(process.env.AGENT_SMITH_STREAM_TIMEOUT_MS || TIME_CONSTANTS.STREAM_TIMEOUT_DEFAULT);
@@ -5738,7 +6011,8 @@ async function handleEnd(msg) {
5738
6011
  timestamp: startMessage.timestamp,
5739
6012
  payload,
5740
6013
  storePayload: startMessage.storePayload,
5741
- timings
6014
+ timings,
6015
+ callerId: startMessage.callerId
5742
6016
  }));
5743
6017
  if (state.usage.model && startMessage.accountId !== null) {
5744
6018
  log7.info(`Usage for request ${startMessage.requestId}: Model: ${state.usage.model}, ` + `Tokens: ${state.usage.totalTokens || 0}, Cost: ${formatCost(state.usage.costUsd)}`);