@certalis/agent-smith 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
@@ -1954,6 +2094,29 @@ function wireForStrategy(strategy3) {
1954
2094
  function isNonNegativeFiniteNumber(value) {
1955
2095
  return isFiniteNumber(value) && value >= 0;
1956
2096
  }
2097
+ function sanitizeCapsByEmail(value, maximum) {
2098
+ if (!isRecord(value))
2099
+ return;
2100
+ const entries = Object.entries(value);
2101
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
2102
+ const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
2103
+ if (!isValid)
2104
+ return;
2105
+ return Object.fromEntries(normalized);
2106
+ }
2107
+ function isDeviceList(value) {
2108
+ 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;
2109
+ }
2110
+ function sanitizeOwnerDevicesByEmail(value) {
2111
+ if (!isRecord(value))
2112
+ return;
2113
+ const entries = Object.entries(value);
2114
+ const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
2115
+ const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
2116
+ if (!isValid)
2117
+ return;
2118
+ return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
2119
+ }
1957
2120
  function sanitizeTeamRouting(value) {
1958
2121
  if (!isRecord(value))
1959
2122
  return;
@@ -1975,19 +2138,21 @@ function sanitizeTeamRouting(value) {
1975
2138
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1976
2139
  result.weekly_max_usage = value.weekly_max_usage;
1977
2140
  }
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
- }
2141
+ const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
2142
+ if (maxUsageByEmail)
2143
+ result.max_usage_by_email = maxUsageByEmail;
2144
+ const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
2145
+ if (weeklyMaxUsageByEmail)
2146
+ result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
1985
2147
  if (isRecord(value.caller_weekly_max_usage)) {
1986
2148
  const entries = Object.entries(value.caller_weekly_max_usage);
1987
2149
  if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1988
2150
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1989
2151
  }
1990
2152
  }
2153
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
2154
+ if (ownerDevicesByEmail)
2155
+ result.owner_devices_by_email = ownerDevicesByEmail;
1991
2156
  if (isRecord(value.caller_provider_fallback)) {
1992
2157
  const entries = Object.entries(value.caller_provider_fallback);
1993
2158
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -2038,9 +2203,11 @@ function sanitizeProviderPool(value) {
2038
2203
  "distribution_enabled",
2039
2204
  "prefer_expiring_quota",
2040
2205
  "max_usage",
2206
+ "max_usage_by_email",
2041
2207
  "weekly_max_usage",
2042
2208
  "weekly_max_usage_by_email",
2043
2209
  "caller_weekly_max_usage",
2210
+ "owner_devices_by_email",
2044
2211
  "quota_probe_seconds",
2045
2212
  "window_warmup"
2046
2213
  ]) {
@@ -2062,8 +2229,17 @@ function sanitizeProviderPool(value) {
2062
2229
  }
2063
2230
  if (typeof value.block_when_all_full === "boolean")
2064
2231
  pool.block_when_all_full = value.block_when_all_full;
2232
+ const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
2233
+ if (nightPacing)
2234
+ pool.caller_night_pacing = nightPacing;
2065
2235
  return pool;
2066
2236
  }
2237
+ function sanitizeCallerNightPacing(value) {
2238
+ if (!isRecord(value))
2239
+ return;
2240
+ const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
2241
+ return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
2242
+ }
2067
2243
  function sanitizeRouting(value) {
2068
2244
  if (!isRecord(value))
2069
2245
  return;
@@ -2133,9 +2309,11 @@ var init_src4 = __esm(() => {
2133
2309
  init_src3();
2134
2310
  init_src();
2135
2311
  init_builtin_providers();
2312
+ init_night_pacing();
2136
2313
  init_paths();
2137
2314
  init_rewrite_file();
2138
2315
  init_window_warmup();
2316
+ init_night_pacing();
2139
2317
  init_paths();
2140
2318
  init_paths_common();
2141
2319
  init_rewrite_config();
@@ -2161,9 +2339,12 @@ var init_src4 = __esm(() => {
2161
2339
  preferExpiringQuota: false,
2162
2340
  allowlistedAccountUuids: [],
2163
2341
  maxUsage: 0.9,
2342
+ maxUsageByEmail: {},
2164
2343
  weeklyMaxUsage: 0.95,
2165
2344
  weeklyMaxUsageByEmail: {},
2166
2345
  callerWeeklyMaxUsage: {},
2346
+ callerNightPacing: {},
2347
+ ownerDevicesByEmail: {},
2167
2348
  admissionCap: 5,
2168
2349
  admissionQueueLimit: 25,
2169
2350
  admissionWaitMs: 30000,
@@ -2337,9 +2518,12 @@ var init_src4 = __esm(() => {
2337
2518
  preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2338
2519
  allowlistedAccountUuids: [...pool?.members ?? []],
2339
2520
  maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2521
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
2340
2522
  weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2341
2523
  weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2342
2524
  callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2525
+ callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
2526
+ ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
2343
2527
  admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2344
2528
  admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2345
2529
  admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
@@ -2416,9 +2600,12 @@ var init_src4 = __esm(() => {
2416
2600
  "distribution_enabled",
2417
2601
  "prefer_expiring_quota",
2418
2602
  "max_usage",
2603
+ "max_usage_by_email",
2419
2604
  "weekly_max_usage",
2420
2605
  "weekly_max_usage_by_email",
2421
2606
  "caller_weekly_max_usage",
2607
+ "caller_night_pacing",
2608
+ "owner_devices_by_email",
2422
2609
  "admission",
2423
2610
  "quota_probe_seconds",
2424
2611
  "window_warmup",
@@ -3009,7 +3196,8 @@ function ensureRequestLinkageColumns(db) {
3009
3196
  ["ttft_ms", "INTEGER"],
3010
3197
  ["proxy_overhead_ms", "INTEGER"],
3011
3198
  ["upstream_ttfb_ms", "INTEGER"],
3012
- ["streaming_duration_ms", "INTEGER"]
3199
+ ["streaming_duration_ms", "INTEGER"],
3200
+ ["caller", "TEXT"]
3013
3201
  ];
3014
3202
  for (const [columnName, columnType] of requestColumns) {
3015
3203
  if (!hasColumn(columns, columnName)) {
@@ -3427,7 +3615,8 @@ function ensureSchema(db) {
3427
3615
  ttft_ms INTEGER,
3428
3616
  proxy_overhead_ms INTEGER,
3429
3617
  upstream_ttfb_ms INTEGER,
3430
- streaming_duration_ms INTEGER
3618
+ streaming_duration_ms INTEGER,
3619
+ caller TEXT
3431
3620
  )
3432
3621
  `);
3433
3622
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
@@ -3881,6 +4070,30 @@ var init_analytics_repository = __esm(() => {
3881
4070
  totalTokens: row.total_tokens ?? 0,
3882
4071
  totalCostUsd: row.total_cost_usd ?? 0
3883
4072
  }));
4073
+ const callerBreakdown = this.query(`
4074
+ SELECT
4075
+ r.caller as caller,
4076
+ COUNT(*) as requests,
4077
+ SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
4078
+ SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
4079
+ SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
4080
+ SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
4081
+ SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
4082
+ FROM requests r
4083
+ WHERE ${whereClause}
4084
+ GROUP BY r.caller
4085
+ ORDER BY total_cost_usd DESC, requests DESC
4086
+ `, queryParams).map((row) => ({
4087
+ caller: row.caller,
4088
+ requests: row.requests,
4089
+ tokenBreakdown: {
4090
+ inputTokens: row.input_tokens ?? 0,
4091
+ cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
4092
+ cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
4093
+ outputTokens: row.output_tokens ?? 0
4094
+ },
4095
+ totalCostUsd: row.total_cost_usd ?? 0
4096
+ }));
3884
4097
  const modelPerformance = this.query(`
3885
4098
  WITH model_stats AS (
3886
4099
  SELECT
@@ -3977,6 +4190,7 @@ var init_analytics_repository = __esm(() => {
3977
4190
  successRate: account2.success_rate ?? 0
3978
4191
  })),
3979
4192
  providerBreakdown,
4193
+ callerBreakdown,
3980
4194
  costByModel,
3981
4195
  modelPerformance
3982
4196
  };
@@ -4371,7 +4585,8 @@ var init_request_repository = __esm(() => {
4371
4585
  response_id = ?,
4372
4586
  previous_response_id = ?,
4373
4587
  response_chain_id = ?,
4374
- client_session_id = ?
4588
+ client_session_id = ?,
4589
+ caller = ?
4375
4590
  WHERE id = ?
4376
4591
  `, [
4377
4592
  data.method,
@@ -4403,6 +4618,7 @@ var init_request_repository = __esm(() => {
4403
4618
  linkage.previousResponseId,
4404
4619
  responseChainId,
4405
4620
  linkage.clientSessionId,
4621
+ data.caller ?? null,
4406
4622
  data.id
4407
4623
  ]);
4408
4624
  if (payloadJson !== undefined) {
@@ -4665,6 +4881,13 @@ var init_request_repository = __esm(() => {
4665
4881
  `, [limit]);
4666
4882
  return errors.map((e) => e.error_message);
4667
4883
  }
4884
+ 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;
4890
+ }
4668
4891
  getRequestsByAccount(since) {
4669
4892
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
4670
4893
  const params = since ? [since] : [];
@@ -5008,9 +5231,13 @@ class DatabaseOperations {
5008
5231
  timestamp: options?.timestamp,
5009
5232
  payload: options?.payload,
5010
5233
  storePayload: options?.storePayload,
5011
- timings: options?.timings
5234
+ timings: options?.timings,
5235
+ caller: options?.callerId ?? null
5012
5236
  });
5013
5237
  }
5238
+ getAccountCostSince(accountId, since) {
5239
+ return this.requests.sumAccountCostSince(accountId, since);
5240
+ }
5014
5241
  updateRequestUsage(requestId, usage) {
5015
5242
  this.requests.updateUsage(requestId, usage);
5016
5243
  }
@@ -5738,7 +5965,8 @@ async function handleEnd(msg) {
5738
5965
  timestamp: startMessage.timestamp,
5739
5966
  payload,
5740
5967
  storePayload: startMessage.storePayload,
5741
- timings
5968
+ timings,
5969
+ callerId: startMessage.callerId
5742
5970
  }));
5743
5971
  if (state.usage.model && startMessage.accountId !== null) {
5744
5972
  log7.info(`Usage for request ${startMessage.requestId}: Model: ${state.usage.model}, ` + `Tokens: ${state.usage.totalTokens || 0}, Cost: ${formatCost(state.usage.costUsd)}`);