@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.
package/dist/bin.js CHANGED
@@ -1250,6 +1250,198 @@ var init_builtin_providers = __esm(() => {
1250
1250
  ];
1251
1251
  });
1252
1252
 
1253
+ // ../../packages/config/src/zoned-time.ts
1254
+ function isTimeZone(value) {
1255
+ if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1256
+ return false;
1257
+ }
1258
+ try {
1259
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
1260
+ return true;
1261
+ } catch {
1262
+ return false;
1263
+ }
1264
+ }
1265
+ function localTimeOfDayMs(time) {
1266
+ const [hour = 0, minute = 0] = time.split(":").map(Number);
1267
+ return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
1268
+ }
1269
+ function wallClockFormat(timeZone) {
1270
+ let format = wallClockFormats.get(timeZone);
1271
+ if (!format) {
1272
+ format = new Intl.DateTimeFormat("en-US", {
1273
+ timeZone,
1274
+ hourCycle: "h23",
1275
+ year: "numeric",
1276
+ month: "numeric",
1277
+ day: "numeric",
1278
+ hour: "numeric",
1279
+ minute: "numeric",
1280
+ second: "numeric"
1281
+ });
1282
+ wallClockFormats.set(timeZone, format);
1283
+ }
1284
+ return format;
1285
+ }
1286
+ function wallClock(at, timeZone) {
1287
+ const parts = wallClockFormat(timeZone).formatToParts(at);
1288
+ const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1289
+ return {
1290
+ year: part("year"),
1291
+ month: part("month"),
1292
+ day: part("day"),
1293
+ hour: part("hour") % 24,
1294
+ minute: part("minute"),
1295
+ second: part("second")
1296
+ };
1297
+ }
1298
+ function zoneOffsetMs(at, timeZone) {
1299
+ const wall = wallClock(at, timeZone);
1300
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1301
+ }
1302
+ function zonedInstant(wall, timeZone) {
1303
+ return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1304
+ }
1305
+ var LOCAL_TIME, wallClockFormats;
1306
+ var init_zoned_time = __esm(() => {
1307
+ init_src2();
1308
+ LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1309
+ wallClockFormats = new Map;
1310
+ });
1311
+
1312
+ // ../../packages/config/src/night-pacing.ts
1313
+ function localHours(value) {
1314
+ 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) {
1315
+ return;
1316
+ }
1317
+ return { start: value.start, end: value.end };
1318
+ }
1319
+ function isWorkingDays(value) {
1320
+ return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
1321
+ }
1322
+ function sanitizeNightPacing(value) {
1323
+ if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
1324
+ return;
1325
+ }
1326
+ const result = {};
1327
+ if (value.time_zone !== undefined) {
1328
+ if (!isTimeZone(value.time_zone))
1329
+ return;
1330
+ result.time_zone = value.time_zone;
1331
+ }
1332
+ if (value.working_days !== undefined) {
1333
+ if (!isWorkingDays(value.working_days))
1334
+ return;
1335
+ result.working_days = [...value.working_days];
1336
+ }
1337
+ if (value.working_hours !== undefined) {
1338
+ const hours = localHours(value.working_hours);
1339
+ if (!hours || hours.start > hours.end)
1340
+ return;
1341
+ result.working_hours = hours;
1342
+ }
1343
+ if (value.night_hours !== undefined) {
1344
+ const hours = localHours(value.night_hours);
1345
+ if (!hours)
1346
+ return;
1347
+ result.night_hours = hours;
1348
+ }
1349
+ if (value.margin_working_days !== undefined) {
1350
+ if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
1351
+ return;
1352
+ }
1353
+ result.margin_working_days = value.margin_working_days;
1354
+ }
1355
+ if (value.use_up_before !== undefined) {
1356
+ if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
1357
+ return;
1358
+ }
1359
+ result.use_up_before = value.use_up_before;
1360
+ }
1361
+ return result;
1362
+ }
1363
+ function nightPacingSettings(file) {
1364
+ return {
1365
+ timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
1366
+ workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
1367
+ workingHours: {
1368
+ ...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
1369
+ },
1370
+ nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
1371
+ marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
1372
+ useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
1373
+ };
1374
+ }
1375
+ function localDay(at, timeZone) {
1376
+ const wall = wallClock(at, timeZone);
1377
+ return {
1378
+ day: Date.UTC(wall.year, wall.month - 1, wall.day),
1379
+ timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
1380
+ };
1381
+ }
1382
+ function nightEndAt(pacing, now) {
1383
+ const { day, timeOfDay } = localDay(now, pacing.timeZone);
1384
+ const start = localTimeOfDayMs(pacing.nightHours.start);
1385
+ const end = localTimeOfDayMs(pacing.nightHours.end);
1386
+ const wraps = start > end;
1387
+ const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
1388
+ if (!night)
1389
+ return null;
1390
+ const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
1391
+ return zonedInstant(endDay + end, pacing.timeZone);
1392
+ }
1393
+ function workingMsBetween(pacing, from, to) {
1394
+ const start = localTimeOfDayMs(pacing.workingHours.start);
1395
+ const end = localTimeOfDayMs(pacing.workingHours.end);
1396
+ let total = 0;
1397
+ for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
1398
+ if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
1399
+ continue;
1400
+ const opens = zonedInstant(day + start, pacing.timeZone);
1401
+ const closes = zonedInstant(day + end, pacing.timeZone);
1402
+ total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
1403
+ }
1404
+ return total;
1405
+ }
1406
+ function expiresBeforeUseUpTime(pacing, resetAt, now) {
1407
+ const endAt = nightEndAt(pacing, now);
1408
+ if (endAt === null || resetAt <= now)
1409
+ return false;
1410
+ return resetAt <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
1411
+ }
1412
+ function nightWeeklyTarget(pacing, resetAt, now) {
1413
+ if (expiresBeforeUseUpTime(pacing, resetAt, now))
1414
+ return 1;
1415
+ const windowStart = resetAt - WEEKLY_WINDOW_MS;
1416
+ const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
1417
+ const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt));
1418
+ return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt);
1419
+ }
1420
+ var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
1421
+ var init_night_pacing = __esm(() => {
1422
+ init_src2();
1423
+ init_src();
1424
+ init_zoned_time();
1425
+ WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
1426
+ WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
1427
+ NIGHT_PACING_DEFAULTS = {
1428
+ timeZone: "Europe/Paris",
1429
+ workingDays: ["mon", "tue", "wed", "thu", "fri"],
1430
+ workingHours: { start: "07:00", end: "21:00" },
1431
+ nightHours: { start: "21:00", end: "07:00" },
1432
+ marginWorkingDays: 1,
1433
+ useUpBefore: "10:00"
1434
+ };
1435
+ NIGHT_PACING_FIELDS = new Set([
1436
+ "time_zone",
1437
+ "working_days",
1438
+ "working_hours",
1439
+ "night_hours",
1440
+ "margin_working_days",
1441
+ "use_up_before"
1442
+ ]);
1443
+ });
1444
+
1253
1445
  // ../../packages/config/src/paths-common.ts
1254
1446
  import { homedir } from "os";
1255
1447
  import { join as join4 } from "path";
@@ -1520,17 +1712,6 @@ var init_rewrite_file = __esm(() => {
1520
1712
  function isLocalTimes(value) {
1521
1713
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1522
1714
  }
1523
- function isTimeZone(value) {
1524
- if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1525
- return false;
1526
- }
1527
- try {
1528
- new Intl.DateTimeFormat("en-US", { timeZone: value });
1529
- return true;
1530
- } catch {
1531
- return false;
1532
- }
1533
- }
1534
1715
  function sanitizeWindowWarmup(value) {
1535
1716
  if (!isRecord(value))
1536
1717
  return;
@@ -1567,42 +1748,6 @@ function windowWarmupFileConfig(config) {
1567
1748
  ...config.model && { model: config.model }
1568
1749
  };
1569
1750
  }
1570
- function wallClockFormat(timeZone) {
1571
- let format = wallClockFormats.get(timeZone);
1572
- if (!format) {
1573
- format = new Intl.DateTimeFormat("en-US", {
1574
- timeZone,
1575
- hourCycle: "h23",
1576
- year: "numeric",
1577
- month: "numeric",
1578
- day: "numeric",
1579
- hour: "numeric",
1580
- minute: "numeric",
1581
- second: "numeric"
1582
- });
1583
- wallClockFormats.set(timeZone, format);
1584
- }
1585
- return format;
1586
- }
1587
- function wallClock(at, timeZone) {
1588
- const parts = wallClockFormat(timeZone).formatToParts(at);
1589
- const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1590
- return {
1591
- year: part("year"),
1592
- month: part("month"),
1593
- day: part("day"),
1594
- hour: part("hour") % 24,
1595
- minute: part("minute"),
1596
- second: part("second")
1597
- };
1598
- }
1599
- function zoneOffsetMs(at, timeZone) {
1600
- const wall = wallClock(at, timeZone);
1601
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1602
- }
1603
- function zonedInstant(wall, timeZone) {
1604
- return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1605
- }
1606
1751
  function nextWindowWarmupAt(routing, after) {
1607
1752
  const warmup = routing.windowWarmup;
1608
1753
  if (!routing.enabled || !warmup.enabled)
@@ -1614,19 +1759,16 @@ function nextWindowWarmupAt(routing, after) {
1614
1759
  if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
1615
1760
  continue;
1616
1761
  }
1617
- const instants = warmup.times.map((time) => {
1618
- const [hour = 0, minute = 0] = time.split(":").map(Number);
1619
- return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
1620
- }).filter((at) => at > after);
1762
+ const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
1621
1763
  if (instants.length > 0)
1622
1764
  return Math.min(...instants);
1623
1765
  }
1624
1766
  return null;
1625
1767
  }
1626
- var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
1768
+ var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
1627
1769
  var init_window_warmup = __esm(() => {
1628
- init_src2();
1629
1770
  init_src();
1771
+ init_zoned_time();
1630
1772
  WINDOW_WARMUP_DEFAULTS = {
1631
1773
  enabled: false,
1632
1774
  times: ["06:00"],
@@ -1634,9 +1776,7 @@ var init_window_warmup = __esm(() => {
1634
1776
  weekdaysOnly: true,
1635
1777
  model: null
1636
1778
  };
1637
- LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1638
1779
  MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
1639
- wallClockFormats = new Map;
1640
1780
  });
1641
1781
 
1642
1782
  // ../../packages/config/src/index.ts
@@ -1902,6 +2042,29 @@ function wireForStrategy(strategy3) {
1902
2042
  function isNonNegativeFiniteNumber(value) {
1903
2043
  return isFiniteNumber(value) && value >= 0;
1904
2044
  }
2045
+ function sanitizeCapsByEmail(value, maximum) {
2046
+ if (!isRecord(value))
2047
+ return;
2048
+ const entries = Object.entries(value);
2049
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
2050
+ const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
2051
+ if (!isValid)
2052
+ return;
2053
+ return Object.fromEntries(normalized);
2054
+ }
2055
+ function isDeviceList(value) {
2056
+ 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;
2057
+ }
2058
+ function sanitizeOwnerDevicesByEmail(value) {
2059
+ if (!isRecord(value))
2060
+ return;
2061
+ const entries = Object.entries(value);
2062
+ const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
2063
+ const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
2064
+ if (!isValid)
2065
+ return;
2066
+ return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
2067
+ }
1905
2068
  function sanitizeTeamRouting(value) {
1906
2069
  if (!isRecord(value))
1907
2070
  return;
@@ -1923,19 +2086,21 @@ function sanitizeTeamRouting(value) {
1923
2086
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1924
2087
  result.weekly_max_usage = value.weekly_max_usage;
1925
2088
  }
1926
- if (isRecord(value.weekly_max_usage_by_email)) {
1927
- const entries = Object.entries(value.weekly_max_usage_by_email);
1928
- const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1929
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1930
- result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1931
- }
1932
- }
2089
+ const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
2090
+ if (maxUsageByEmail)
2091
+ result.max_usage_by_email = maxUsageByEmail;
2092
+ const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
2093
+ if (weeklyMaxUsageByEmail)
2094
+ result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
1933
2095
  if (isRecord(value.caller_weekly_max_usage)) {
1934
2096
  const entries = Object.entries(value.caller_weekly_max_usage);
1935
2097
  if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1936
2098
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1937
2099
  }
1938
2100
  }
2101
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
2102
+ if (ownerDevicesByEmail)
2103
+ result.owner_devices_by_email = ownerDevicesByEmail;
1939
2104
  if (isRecord(value.caller_provider_fallback)) {
1940
2105
  const entries = Object.entries(value.caller_provider_fallback);
1941
2106
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -1986,9 +2151,11 @@ function sanitizeProviderPool(value) {
1986
2151
  "distribution_enabled",
1987
2152
  "prefer_expiring_quota",
1988
2153
  "max_usage",
2154
+ "max_usage_by_email",
1989
2155
  "weekly_max_usage",
1990
2156
  "weekly_max_usage_by_email",
1991
2157
  "caller_weekly_max_usage",
2158
+ "owner_devices_by_email",
1992
2159
  "quota_probe_seconds",
1993
2160
  "window_warmup"
1994
2161
  ]) {
@@ -2010,8 +2177,17 @@ function sanitizeProviderPool(value) {
2010
2177
  }
2011
2178
  if (typeof value.block_when_all_full === "boolean")
2012
2179
  pool.block_when_all_full = value.block_when_all_full;
2180
+ const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
2181
+ if (nightPacing)
2182
+ pool.caller_night_pacing = nightPacing;
2013
2183
  return pool;
2014
2184
  }
2185
+ function sanitizeCallerNightPacing(value) {
2186
+ if (!isRecord(value))
2187
+ return;
2188
+ const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
2189
+ return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
2190
+ }
2015
2191
  function sanitizeRouting(value) {
2016
2192
  if (!isRecord(value))
2017
2193
  return;
@@ -2081,9 +2257,11 @@ var init_src4 = __esm(() => {
2081
2257
  init_src3();
2082
2258
  init_src();
2083
2259
  init_builtin_providers();
2260
+ init_night_pacing();
2084
2261
  init_paths();
2085
2262
  init_rewrite_file();
2086
2263
  init_window_warmup();
2264
+ init_night_pacing();
2087
2265
  init_paths();
2088
2266
  init_paths_common();
2089
2267
  init_rewrite_config();
@@ -2109,9 +2287,12 @@ var init_src4 = __esm(() => {
2109
2287
  preferExpiringQuota: false,
2110
2288
  allowlistedAccountUuids: [],
2111
2289
  maxUsage: 0.9,
2290
+ maxUsageByEmail: {},
2112
2291
  weeklyMaxUsage: 0.95,
2113
2292
  weeklyMaxUsageByEmail: {},
2114
2293
  callerWeeklyMaxUsage: {},
2294
+ callerNightPacing: {},
2295
+ ownerDevicesByEmail: {},
2115
2296
  admissionCap: 5,
2116
2297
  admissionQueueLimit: 25,
2117
2298
  admissionWaitMs: 30000,
@@ -2285,9 +2466,12 @@ var init_src4 = __esm(() => {
2285
2466
  preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2286
2467
  allowlistedAccountUuids: [...pool?.members ?? []],
2287
2468
  maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2469
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
2288
2470
  weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2289
2471
  weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2290
2472
  callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2473
+ callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
2474
+ ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
2291
2475
  admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2292
2476
  admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2293
2477
  admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
@@ -2364,9 +2548,12 @@ var init_src4 = __esm(() => {
2364
2548
  "distribution_enabled",
2365
2549
  "prefer_expiring_quota",
2366
2550
  "max_usage",
2551
+ "max_usage_by_email",
2367
2552
  "weekly_max_usage",
2368
2553
  "weekly_max_usage_by_email",
2369
2554
  "caller_weekly_max_usage",
2555
+ "caller_night_pacing",
2556
+ "owner_devices_by_email",
2370
2557
  "admission",
2371
2558
  "quota_probe_seconds",
2372
2559
  "window_warmup",
@@ -3010,7 +3197,8 @@ function ensureRequestLinkageColumns(db) {
3010
3197
  ["ttft_ms", "INTEGER"],
3011
3198
  ["proxy_overhead_ms", "INTEGER"],
3012
3199
  ["upstream_ttfb_ms", "INTEGER"],
3013
- ["streaming_duration_ms", "INTEGER"]
3200
+ ["streaming_duration_ms", "INTEGER"],
3201
+ ["caller", "TEXT"]
3014
3202
  ];
3015
3203
  for (const [columnName, columnType] of requestColumns) {
3016
3204
  if (!hasColumn(columns, columnName)) {
@@ -3428,7 +3616,8 @@ function ensureSchema(db) {
3428
3616
  ttft_ms INTEGER,
3429
3617
  proxy_overhead_ms INTEGER,
3430
3618
  upstream_ttfb_ms INTEGER,
3431
- streaming_duration_ms INTEGER
3619
+ streaming_duration_ms INTEGER,
3620
+ caller TEXT
3432
3621
  )
3433
3622
  `);
3434
3623
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
@@ -3882,6 +4071,30 @@ var init_analytics_repository = __esm(() => {
3882
4071
  totalTokens: row.total_tokens ?? 0,
3883
4072
  totalCostUsd: row.total_cost_usd ?? 0
3884
4073
  }));
4074
+ const callerBreakdown = this.query(`
4075
+ SELECT
4076
+ r.caller as caller,
4077
+ COUNT(*) as requests,
4078
+ SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
4079
+ SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
4080
+ SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
4081
+ SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
4082
+ SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
4083
+ FROM requests r
4084
+ WHERE ${whereClause}
4085
+ GROUP BY r.caller
4086
+ ORDER BY total_cost_usd DESC, requests DESC
4087
+ `, queryParams).map((row) => ({
4088
+ caller: row.caller,
4089
+ requests: row.requests,
4090
+ tokenBreakdown: {
4091
+ inputTokens: row.input_tokens ?? 0,
4092
+ cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
4093
+ cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
4094
+ outputTokens: row.output_tokens ?? 0
4095
+ },
4096
+ totalCostUsd: row.total_cost_usd ?? 0
4097
+ }));
3885
4098
  const modelPerformance = this.query(`
3886
4099
  WITH model_stats AS (
3887
4100
  SELECT
@@ -3978,6 +4191,7 @@ var init_analytics_repository = __esm(() => {
3978
4191
  successRate: account2.success_rate ?? 0
3979
4192
  })),
3980
4193
  providerBreakdown,
4194
+ callerBreakdown,
3981
4195
  costByModel,
3982
4196
  modelPerformance
3983
4197
  };
@@ -4372,7 +4586,8 @@ var init_request_repository = __esm(() => {
4372
4586
  response_id = ?,
4373
4587
  previous_response_id = ?,
4374
4588
  response_chain_id = ?,
4375
- client_session_id = ?
4589
+ client_session_id = ?,
4590
+ caller = ?
4376
4591
  WHERE id = ?
4377
4592
  `, [
4378
4593
  data.method,
@@ -4404,6 +4619,7 @@ var init_request_repository = __esm(() => {
4404
4619
  linkage.previousResponseId,
4405
4620
  responseChainId,
4406
4621
  linkage.clientSessionId,
4622
+ data.caller ?? null,
4407
4623
  data.id
4408
4624
  ]);
4409
4625
  if (payloadJson !== undefined) {
@@ -4666,6 +4882,13 @@ var init_request_repository = __esm(() => {
4666
4882
  `, [limit]);
4667
4883
  return errors.map((e) => e.error_message);
4668
4884
  }
4885
+ 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;
4891
+ }
4669
4892
  getRequestsByAccount(since) {
4670
4893
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
4671
4894
  const params = since ? [since] : [];
@@ -5009,9 +5232,13 @@ class DatabaseOperations {
5009
5232
  timestamp: options?.timestamp,
5010
5233
  payload: options?.payload,
5011
5234
  storePayload: options?.storePayload,
5012
- timings: options?.timings
5235
+ timings: options?.timings,
5236
+ caller: options?.callerId ?? null
5013
5237
  });
5014
5238
  }
5239
+ getAccountCostSince(accountId, since) {
5240
+ return this.requests.sumAccountCostSince(accountId, since);
5241
+ }
5015
5242
  updateRequestUsage(requestId, usage) {
5016
5243
  this.requests.updateUsage(requestId, usage);
5017
5244
  }
@@ -8692,8 +8919,11 @@ var init_analytics = __esm(() => {
8692
8919
  // ../../packages/api/src/handlers/config.ts
8693
8920
  function publicProviderPool(config, name) {
8694
8921
  const {
8922
+ maxUsageByEmail: _fiveHour,
8695
8923
  weeklyMaxUsageByEmail: _weekly,
8696
8924
  callerWeeklyMaxUsage: _caller,
8925
+ callerNightPacing: _nightPacing,
8926
+ ownerDevicesByEmail: _owners,
8697
8927
  ...pool
8698
8928
  } = config.getTeamRouting(name);
8699
8929
  return pool;
@@ -10555,9 +10785,12 @@ class TeamAdmission {
10555
10785
  preferExpiringQuota: false,
10556
10786
  allowlistedAccountUuids: [],
10557
10787
  maxUsage: 0.9,
10788
+ maxUsageByEmail: {},
10558
10789
  weeklyMaxUsage: 0.95,
10559
10790
  weeklyMaxUsageByEmail: {},
10560
10791
  callerWeeklyMaxUsage: {},
10792
+ callerNightPacing: {},
10793
+ ownerDevicesByEmail: {},
10561
10794
  admissionCap: 1,
10562
10795
  admissionQueueLimit: 0,
10563
10796
  admissionWaitMs: 0,
@@ -10979,13 +11212,17 @@ function pinKey(request3, provider) {
10979
11212
  function isAllowlisted(account2, config) {
10980
11213
  return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
10981
11214
  }
11215
+ function soonestToUseUp(accounts, useUpResetAt) {
11216
+ const soonest = Math.min(...accounts.map(useUpResetAt));
11217
+ return soonest === Number.POSITIVE_INFINITY ? accounts : accounts.filter((account2) => useUpResetAt(account2) === soonest);
11218
+ }
10982
11219
 
10983
11220
  class TeamRouter {
10984
11221
  inFlight = new Map;
10985
11222
  pins = new Map;
10986
11223
  pinLookups = new WeakMap;
10987
11224
  cleanedLookups = new WeakSet;
10988
- order(accounts, request3, config, provider, store, now = Date.now()) {
11225
+ order(accounts, request3, config, provider, store, now = Date.now(), useUpResetAt = () => Number.POSITIVE_INFINITY) {
10989
11226
  if (!config.enabled || !request3)
10990
11227
  return accounts;
10991
11228
  this.removeExpiredPinsOnce(request3, now, store);
@@ -11004,7 +11241,7 @@ class TeamRouter {
11004
11241
  }
11005
11242
  if (!config.distributionEnabled || !key)
11006
11243
  return eligible;
11007
- const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
11244
+ const selected = this.leastUsedPriorityAccount(soonestToUseUp(eligible, useUpResetAt), compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
11008
11245
  this.touchPin(key, selected.id, now, store);
11009
11246
  return [
11010
11247
  selected,
@@ -11092,37 +11329,144 @@ var init_seat_router = __esm(() => {
11092
11329
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
11093
11330
  });
11094
11331
 
11332
+ // ../../packages/pool/src/night-pacing.ts
11333
+ function callerNightPacing(pool, callerId) {
11334
+ return callerId && pool.enabled && Object.hasOwn(pool.callerNightPacing, callerId) ? pool.callerNightPacing[callerId] ?? null : null;
11335
+ }
11336
+ function pacedNight(pool, account2, now, callerId) {
11337
+ const pacing = callerNightPacing(pool, callerId);
11338
+ if (!pacing || !isAllowlisted(account2, pool))
11339
+ return null;
11340
+ const endAt = nightEndAt(pacing, now);
11341
+ return endAt === null ? null : { pacing, endAt };
11342
+ }
11343
+ function startsWindowIntoMorning(provider, account2, night, now) {
11344
+ return now >= night.endAt - FIVE_HOUR_WINDOW_MS && !Object.entries(account2.quota_state?.windows ?? {}).some(([bucket, window2]) => provider.isFiveHourBucket(bucket) && window2.resetAt !== null && window2.resetAt > now && window2.resetAt <= night.endAt);
11345
+ }
11346
+ function weeklyWindows(provider, account2, model, now) {
11347
+ return Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
11348
+ if (window2.resetAt === null || !provider.isWeeklyBucket(bucket) || !(provider.quotaBucketsFor(model)?.includes(bucket) ?? true)) {
11349
+ return [];
11350
+ }
11351
+ const rolled = window2.resetAt <= now;
11352
+ const resetAt2 = rolled ? window2.resetAt + (Math.floor((now - window2.resetAt) / WEEKLY_WINDOW_MS) + 1) * WEEKLY_WINDOW_MS : window2.resetAt;
11353
+ return [
11354
+ {
11355
+ bucket,
11356
+ resetAt: resetAt2,
11357
+ used: rolled ? 0 : window2.status === "rejected" ? 1 : window2.utilization ?? 0
11358
+ }
11359
+ ];
11360
+ });
11361
+ }
11362
+ function nightWeeklyWindows(provider, account2, model, pacing, now) {
11363
+ return weeklyWindows(provider, account2, model, now).map((window2) => ({
11364
+ ...window2,
11365
+ target: nightWeeklyTarget(pacing, window2.resetAt, now)
11366
+ }));
11367
+ }
11368
+ function useUpResetAt(provider, account2, model, pool, now, callerId) {
11369
+ const night = pacedNight(pool, account2, now, callerId);
11370
+ if (!night)
11371
+ return Number.POSITIVE_INFINITY;
11372
+ return Math.min(...weeklyWindows(provider, account2, model, now).flatMap(({ resetAt: resetAt2 }) => expiresBeforeUseUpTime(night.pacing, resetAt2, now) ? [resetAt2] : []), Number.POSITIVE_INFINITY);
11373
+ }
11374
+ function nightPacingBlock(provider, account2, model, pool, now, callerId) {
11375
+ const night = pacedNight(pool, account2, now, callerId);
11376
+ if (!night)
11377
+ return null;
11378
+ if (startsWindowIntoMorning(provider, account2, night, now)) {
11379
+ return { category: "five-hour-limit", retryAt: night.endAt };
11380
+ }
11381
+ return nightWeeklyWindows(provider, account2, model, night.pacing, now).some((window2) => window2.used >= Math.max(0, window2.target)) ? { category: "weekly-limit", retryAt: night.endAt } : null;
11382
+ }
11383
+ function median(values) {
11384
+ if (values.length === 0)
11385
+ return 0;
11386
+ const sorted = [...values].sort((left, right) => left - right);
11387
+ const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
11388
+ const lower = sorted[Math.ceil(sorted.length / 2) - 1] ?? 0;
11389
+ return (lower + upper) / 2;
11390
+ }
11391
+ function seatsNightCostEq(provider, seats, model, pacing, now, costSince, weeklyCap) {
11392
+ const endAt = nightEndAt(pacing, now);
11393
+ const headrooms = seats.flatMap((account2) => {
11394
+ if (endAt !== null && startsWindowIntoMorning(provider, account2, { pacing, endAt }, now)) {
11395
+ return [];
11396
+ }
11397
+ const [binding] = nightWeeklyWindows(provider, account2, model, pacing, now).map((window2) => ({
11398
+ ...window2,
11399
+ ceiling: Math.min(window2.target, weeklyCap(account2, window2.bucket))
11400
+ })).sort((left, right) => left.ceiling - left.used - (right.ceiling - right.used));
11401
+ if (!binding)
11402
+ return [];
11403
+ const usedPoints = binding.used * 100;
11404
+ return [
11405
+ {
11406
+ points: Math.max(0, binding.ceiling - binding.used) * 100,
11407
+ costPerPoint: usedPoints >= MIN_OWN_RATE_POINTS ? costSince(account2.id, binding.resetAt - WEEKLY_WINDOW_MS) / usedPoints : null
11408
+ }
11409
+ ];
11410
+ });
11411
+ const fallbackRate = median(headrooms.flatMap(({ costPerPoint }) => costPerPoint === null ? [] : [costPerPoint]));
11412
+ return headrooms.reduce((sum, { points, costPerPoint }) => sum + points * (costPerPoint ?? fallbackRate), 0);
11413
+ }
11414
+ var FIVE_HOUR_WINDOW_MS, MIN_OWN_RATE_POINTS = 5;
11415
+ var init_night_pacing2 = __esm(() => {
11416
+ init_src4();
11417
+ init_seat_router();
11418
+ FIVE_HOUR_WINDOW_MS = 5 * 60 * 60000;
11419
+ });
11420
+
11095
11421
  // ../../packages/pool/src/handlers/account-selector.ts
11096
- function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
11422
+ function quotaCeiling(account2, bucket, fleetThreshold, maxUsage) {
11097
11423
  const accountThreshold = account2.switch_threshold === null || account2.switch_threshold === undefined ? undefined : quotaThresholdFor(account2, bucket, fleetThreshold);
11098
- const threshold = maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
11424
+ return maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
11425
+ }
11426
+ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
11427
+ const threshold = quotaCeiling(account2, bucket, fleetThreshold, maxUsage);
11099
11428
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
11100
11429
  }
11101
- function pooledMaxUsage(provider, account2, bucket, ctx, callerId) {
11430
+ function capForAccountEmail(capsByEmail, account2, ctx) {
11431
+ if (Object.keys(capsByEmail).length === 0)
11432
+ return;
11433
+ const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11434
+ return email ? capsByEmail[email] : undefined;
11435
+ }
11436
+ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
11102
11437
  const teamRouting = ctx.runtime.pool;
11103
11438
  if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
11104
11439
  return;
11105
11440
  if (!provider.isWeeklyBucket(bucket)) {
11106
- return { limit: teamRouting.maxUsage, overridesFleetThreshold: false };
11441
+ const accountCap = capForAccountEmail(teamRouting.maxUsageByEmail, account2, ctx);
11442
+ return {
11443
+ limit: Math.min(teamRouting.maxUsage, accountCap ?? Number.POSITIVE_INFINITY),
11444
+ overridesFleetThreshold: false
11445
+ };
11107
11446
  }
11108
- const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11109
- const accountOverride = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
11110
- const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11447
+ 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;
11111
11449
  return {
11112
11450
  limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
11113
11451
  overridesFleetThreshold: accountOverride !== undefined
11114
11452
  };
11115
11453
  }
11116
- function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
11117
- const quota2 = account2.quota_state;
11118
- if (!quota2)
11454
+ function servesCaller(account2, ctx, callerId) {
11455
+ const ownerDevices = ctx.runtime.pool?.ownerDevicesByEmail;
11456
+ if (!ownerDevices || Object.keys(ownerDevices).length === 0)
11457
+ return true;
11458
+ const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
11459
+ if (!email || !Object.hasOwn(ownerDevices, email))
11119
11460
  return true;
11120
- for (const [name, window2] of Object.entries(quota2.windows)) {
11121
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, callerId))) {
11461
+ return callerId !== undefined && !!ownerDevices[email]?.includes(callerId);
11462
+ }
11463
+ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
11464
+ for (const [name, window2] of Object.entries(account2.quota_state?.windows ?? {})) {
11465
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, now, callerId))) {
11122
11466
  return false;
11123
11467
  }
11124
11468
  }
11125
- return true;
11469
+ return nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId) === null;
11126
11470
  }
11127
11471
  function fleetAccounts(provider, ctx) {
11128
11472
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
@@ -11146,19 +11490,23 @@ function callerPoolAccounts(provider, ctx, orderedFallback) {
11146
11490
  return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx) || orderedFallback && !account2.paused && account2.auth_method === "api_key");
11147
11491
  }
11148
11492
  function blockingResets(provider, account2, model, ctx, now, callerId) {
11149
- return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx, callerId))).map(([, window2]) => window2.resetAt);
11493
+ const nightEnd = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId)?.retryAt;
11494
+ return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket, ctx, now, callerId))).map(([, window2]) => window2.resetAt).concat(nightEnd === undefined ? [] : [nightEnd]);
11150
11495
  }
11151
11496
  function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
11152
- const blocking = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket2, window3]) => isQuotaBlocking(provider, account2, bucket2, window3, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket2, ctx, callerId)));
11497
+ const night = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId);
11498
+ const blocking = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket2, window3]) => isQuotaBlocking(provider, account2, bucket2, window3, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket2, ctx, now, callerId)));
11153
11499
  if (blocking.length === 0)
11154
- return null;
11500
+ return night;
11155
11501
  const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
11156
11502
  const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
11157
11503
  const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
11158
11504
  return rightReset - leftReset;
11159
11505
  })[0];
11160
11506
  const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
11161
- return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
11507
+ if (window2.resetAt === null)
11508
+ return { category };
11509
+ return night?.retryAt !== undefined && night.retryAt > window2.resetAt ? night : { category, retryAt: window2.resetAt };
11162
11510
  }
11163
11511
  function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
11164
11512
  const now = Date.now();
@@ -11206,13 +11554,24 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
11206
11554
  throw new Error(`Unknown provider '${provider}'`);
11207
11555
  const config = ctx.runtime.pool;
11208
11556
  const now = Date.now();
11209
- const accounts = config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"));
11557
+ 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));
11210
11558
  const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
11559
+ const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
11211
11560
  return {
11212
11561
  poolEnabled: config.enabled,
11213
11562
  servableSeats,
11214
11563
  retryAt: servableSeats === 0 ? soonestServableAt(strategy3, accounts, accounts, model, ctx, now, callerId) : null,
11215
- admissionWaitMs: config.admissionWaitMs
11564
+ admissionWaitMs: config.admissionWaitMs,
11565
+ ...nightBudget && { nightBudget }
11566
+ };
11567
+ }
11568
+ function callerNightBudget(provider, accounts, model, callerId, ctx, now) {
11569
+ const pacing = callerNightPacing(ctx.runtime.pool, callerId);
11570
+ if (!pacing)
11571
+ return null;
11572
+ return {
11573
+ night: nightEndAt(pacing, now) !== null,
11574
+ seatsCostEq: seatsNightCostEq(provider, accounts.filter((account2) => isFleetSeat(account2, ctx)), model, pacing, now, (accountId, since) => ctx.dbOps.getAccountCostSince(accountId, since), (account2, bucket) => quotaCeiling(account2, bucket, ctx.runtime.quotaThreshold, pooledMaxUsage(provider, account2, bucket, ctx, now)))
11216
11575
  };
11217
11576
  }
11218
11577
  function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
@@ -11240,19 +11599,23 @@ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
11240
11599
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
11241
11600
  const now = Date.now();
11242
11601
  const callerId = teamRequest?.callerId;
11243
- const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
11602
+ const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null && servesCaller(account2, ctx, callerId));
11244
11603
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
11245
11604
  const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.pool.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
11246
- const prioritized = [...candidates].sort((left, right) => {
11247
- const priority = (left.priority ?? 0) - (right.priority ?? 0);
11248
- return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
11249
- });
11605
+ const useUpResets = new Map(candidates.map((account2) => [
11606
+ account2.id,
11607
+ useUpResetAt(ctx.provider, account2, meta.model, ctx.runtime.pool, now, callerId)
11608
+ ]));
11609
+ const useUpAt = (account2) => useUpResets.get(account2.id) ?? Number.POSITIVE_INFINITY;
11610
+ const prioritized = [...candidates].sort((left, right) => useUpAt(left) - useUpAt(right) || (left.priority ?? 0) - (right.priority ?? 0) || soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
11250
11611
  const ordered = ctx.strategy.select(prioritized, meta);
11251
- return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps)) ?? ordered;
11612
+ return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps, now, useUpAt)) ?? ordered;
11252
11613
  }
11253
11614
  var QUOTA_PROBE_INTERVAL_MS = 60000;
11254
11615
  var init_account_selector = __esm(() => {
11616
+ init_src4();
11255
11617
  init_src();
11618
+ init_night_pacing2();
11256
11619
  init_seat_router();
11257
11620
  init_seat_usage();
11258
11621
  init_token_manager();
@@ -11502,7 +11865,7 @@ class ProviderSupply {
11502
11865
  return threadAccount;
11503
11866
  };
11504
11867
  const seatsFor = (fleet) => {
11505
- const eligible = ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet;
11868
+ const eligible = (ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet).filter((account2) => servesCaller(account2, ctx, route.callerId));
11506
11869
  const id = getThreadAccount();
11507
11870
  return id ? eligible.filter((account2) => account2.id === id) : eligible;
11508
11871
  };
@@ -11589,7 +11952,7 @@ class ProviderSupply {
11589
11952
  const teamEnabled = ctx.runtime.pool.enabled;
11590
11953
  const pooled = account2.auth_method !== "api_key" && (!teamEnabled || isAllowlisted(account2, ctx.runtime.pool) && (!route.seatHint || account2.name === route.seatHint));
11591
11954
  const keyReached = route.apiKeyAccounts && account2.auth_method === "api_key";
11592
- return (pooled || keyReached) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
11955
+ return (pooled || keyReached) && servesCaller(account2, ctx, route.callerId) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
11593
11956
  });
11594
11957
  if (hasAvailableAccount)
11595
11958
  return {
@@ -12526,7 +12889,24 @@ async function getCallerPoolStatus(input) {
12526
12889
  eligibleAccounts,
12527
12890
  retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
12528
12891
  holdSeconds: input.holdSeconds,
12529
- admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0
12892
+ admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
12893
+ nightBudget: callerNightBudget2(statuses, Date.now())
12894
+ };
12895
+ }
12896
+ function toCents(value) {
12897
+ return Math.round(value * 100) / 100;
12898
+ }
12899
+ function callerNightBudget2(statuses, now) {
12900
+ const budgets = statuses.flatMap((status) => status.nightBudget ? [status.nightBudget] : []);
12901
+ if (budgets.length === 0)
12902
+ return null;
12903
+ const seatsCostEq = toCents(budgets.reduce((sum, budget) => sum + budget.seatsCostEq, 0));
12904
+ return {
12905
+ costEq: seatsCostEq,
12906
+ creditsCostEq: 0,
12907
+ seatsCostEq,
12908
+ night: budgets.some((budget) => budget.night),
12909
+ computedAtMs: now
12530
12910
  };
12531
12911
  }
12532
12912
  var init_router2 = () => {};
@@ -12597,12 +12977,13 @@ function normalizeMaxBodyBytes(maxBodyBytes) {
12597
12977
  function bodyTooLargeError(maxBodyBytes) {
12598
12978
  return new HttpError(413, `Request body too large (maximum ${maxBodyBytes} bytes)`);
12599
12979
  }
12600
- function createRequestMetadata(req, url) {
12980
+ function createRequestMetadata(req, url, callerId) {
12601
12981
  return {
12602
12982
  id: crypto2.randomUUID(),
12603
12983
  method: isHttpMethod(req.method) ? req.method : "GET",
12604
12984
  path: url.pathname,
12605
- timestamp: Date.now()
12985
+ timestamp: Date.now(),
12986
+ ...callerId !== undefined && { callerId }
12606
12987
  };
12607
12988
  }
12608
12989
  function readRequestModel(body) {
@@ -12697,7 +13078,8 @@ async function forwardToClient(options, ctx) {
12697
13078
  responseHeadersReceivedAt,
12698
13079
  retryAttempt,
12699
13080
  failoverAttempts,
12700
- preExtractedModel
13081
+ preExtractedModel,
13082
+ callerId
12701
13083
  } = options;
12702
13084
  const responseProcessed = ctx.provider.processResponse ? await ctx.provider.processResponse(responseRaw, account2, {
12703
13085
  messageId: `msg_${requestId.replaceAll("-", "")}`,
@@ -12726,7 +13108,8 @@ async function forwardToClient(options, ctx) {
12726
13108
  providerName: ctx.providerName,
12727
13109
  retryAttempt,
12728
13110
  failoverAttempts,
12729
- storePayload: ctx.runtime.storeRequestPayloads
13111
+ storePayload: ctx.runtime.storeRequestPayloads,
13112
+ callerId
12730
13113
  };
12731
13114
  ctx.usageWorker.postMessage(startMessage);
12732
13115
  requestEvents.emit("event", {
@@ -13303,7 +13686,8 @@ function createForwarder(input, upstream, state) {
13303
13686
  responseHeadersReceivedAt: upstream.responseHeadersReceivedAt,
13304
13687
  retryAttempt: 0,
13305
13688
  failoverAttempts: input.failoverAttempts,
13306
- preExtractedModel: input.mappedModel ?? input.requestMeta.model
13689
+ preExtractedModel: input.mappedModel ?? input.requestMeta.model,
13690
+ callerId: input.requestMeta.callerId
13307
13691
  }, input.ctx);
13308
13692
  }
13309
13693
  function discardUpstreamResponse(state) {
@@ -13786,7 +14170,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
13786
14170
  providerName: session.providerName,
13787
14171
  retryAttempt: 0,
13788
14172
  failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
13789
- storePayload: session.requestContext.runtime.storeRequestPayloads
14173
+ storePayload: session.requestContext.runtime.storeRequestPayloads,
14174
+ callerId: session.callerId
13790
14175
  };
13791
14176
  session.activeTurn = {
13792
14177
  requestId,
@@ -14052,7 +14437,7 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
14052
14437
  status: 400
14053
14438
  });
14054
14439
  }
14055
- const requestMeta = createRequestMetadata(req, url);
14440
+ const requestMeta = createRequestMetadata(req, url, callerId);
14056
14441
  const teamRequest = {
14057
14442
  body: null,
14058
14443
  contentType: null,
@@ -14106,7 +14491,8 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
14106
14491
  activeTurn: null,
14107
14492
  connectedAccount: null,
14108
14493
  pendingRequestBody: null,
14109
- pendingRequestTimestamp: null
14494
+ pendingRequestTimestamp: null,
14495
+ callerId
14110
14496
  };
14111
14497
  websocketSessions.set(sessionId, session);
14112
14498
  const upgraded = server.upgrade(req, {
@@ -14763,7 +15149,7 @@ async function handleProxy(req, url, ctx, callerId) {
14763
15149
  if (!upstreamUrl.pathname.startsWith("/v1/pool/")) {
14764
15150
  return new Response("Not Found", { status: 404 });
14765
15151
  }
14766
- const requestMeta2 = createRequestMetadata(req, upstreamUrl);
15152
+ const requestMeta2 = createRequestMetadata(req, upstreamUrl, callerId);
14767
15153
  const { buffer: buffer2 } = await prepareRequestBody(req, ctx.runtime.maxBodyBytes);
14768
15154
  const body2 = buffer2 ?? null;
14769
15155
  requestMeta2.model = readRequestModel(body2);
@@ -14775,7 +15161,7 @@ async function handleProxy(req, url, ctx, callerId) {
14775
15161
  }
14776
15162
  return await routePoolRequest(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
14777
15163
  }
14778
- const requestMeta = createRequestMetadata(req, upstreamUrl);
15164
+ const requestMeta = createRequestMetadata(req, upstreamUrl, callerId);
14779
15165
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
14780
15166
  const body = buffer ?? null;
14781
15167
  requestMeta.model = readRequestModel(body);
@@ -17094,9 +17480,11 @@ function providerPoolFileConfig(routing) {
17094
17480
  prefer_expiring_quota: routing.preferExpiringQuota,
17095
17481
  members: routing.allowlistedAccountUuids,
17096
17482
  max_usage: routing.maxUsage,
17483
+ max_usage_by_email: routing.maxUsageByEmail,
17097
17484
  weekly_max_usage: routing.weeklyMaxUsage,
17098
17485
  weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
17099
17486
  caller_weekly_max_usage: routing.callerWeeklyMaxUsage,
17487
+ owner_devices_by_email: routing.ownerDevicesByEmail,
17100
17488
  admission: {
17101
17489
  cap: routing.admissionCap,
17102
17490
  queue_limit: routing.admissionQueueLimit,
@@ -18222,7 +18610,6 @@ import {
18222
18610
  existsSync as existsSync5,
18223
18611
  mkdirSync as mkdirSync5,
18224
18612
  readFileSync as readFileSync6,
18225
- realpathSync as realpathSync2,
18226
18613
  rmSync as rmSync3,
18227
18614
  writeFileSync as writeFileSync4
18228
18615
  } from "fs";
@@ -18270,12 +18657,22 @@ async function fetchPoolStatus(host) {
18270
18657
  `)[0]) || "ssh failed");
18271
18658
  return JSON.parse(result.stdout.toString());
18272
18659
  }
18660
+ function cliBinDirectories() {
18661
+ const found = [Bun.which("agent-smith"), Bun.which("bun")].flatMap((path) => path ? [dirname6(path)] : []);
18662
+ return [
18663
+ ...new Set([
18664
+ ...found,
18665
+ join10(homedir3(), ".bun", "bin"),
18666
+ "/opt/homebrew/bin",
18667
+ "/usr/local/bin"
18668
+ ])
18669
+ ];
18670
+ }
18273
18671
  function defaultDeps() {
18274
18672
  return {
18275
18673
  configPath: resolveConfigPath(),
18276
18674
  cachePath: join10(homedir3(), "Library", "Caches", "agent-smith", "menubar-status.json"),
18277
- runtime: Bun.which("bun") ?? process.execPath,
18278
- entry: () => realpathSync2(process.argv[1] ?? ""),
18675
+ binDirectories: cliBinDirectories,
18279
18676
  pluginDirectory: swiftBarPluginDirectory,
18280
18677
  fetchStatus: fetchPoolStatus,
18281
18678
  now: Date.now,
@@ -18309,14 +18706,15 @@ async function loadSnapshot(deps) {
18309
18706
  };
18310
18707
  }
18311
18708
  }
18312
- function pluginScript(runtime, entry) {
18709
+ function pluginScript(binDirectories) {
18313
18710
  return `#!/bin/sh
18314
18711
  # <swiftbar.title>Agent Smith pool</swiftbar.title>
18315
18712
  # <swiftbar.hideAbout>true</swiftbar.hideAbout>
18316
18713
  # <swiftbar.hideRunInTerminal>true</swiftbar.hideRunInTerminal>
18317
18714
  # <swiftbar.hideLastUpdated>true</swiftbar.hideLastUpdated>
18318
18715
  export SSH_AUTH_SOCK="\${SSH_AUTH_SOCK:-$(/bin/launchctl getenv SSH_AUTH_SOCK)}"
18319
- exec ${shellQuote(runtime)} ${shellQuote(entry)} ${PLUGIN_MARKER}
18716
+ export PATH=${shellQuote(binDirectories.join(":"))}:"$PATH"
18717
+ exec agent-smith ${PLUGIN_MARKER}
18320
18718
  `;
18321
18719
  }
18322
18720
  function install(deps) {
@@ -18326,7 +18724,7 @@ function install(deps) {
18326
18724
  if (!readClientRouting(deps.configPath).poolSshHost)
18327
18725
  throw new Error(`Set client.pool_ssh_host in ${deps.configPath} first`);
18328
18726
  const path = join10(directory, PLUGIN_FILE);
18329
- writeFileSync4(path, pluginScript(deps.runtime, deps.entry()));
18727
+ writeFileSync4(path, pluginScript(deps.binDirectories()));
18330
18728
  chmodSync3(path, 493);
18331
18729
  deps.log(`Installed ${path}. SwiftBar shows the pool shortly and refreshes it every 5 minutes.`);
18332
18730
  }