@certalis/agent-smith 0.1.19 → 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.
@@ -667,6 +667,14 @@ var init_provider_metadata = __esm(() => {
667
667
  defaultBaseUrl: "https://api.openai.com/v1",
668
668
  specialRequirements: []
669
669
  },
670
+ gemini: {
671
+ displayLabel: "Google Gemini",
672
+ authMethod: "api_key",
673
+ supportsOAuth: false,
674
+ supportsWebSocket: false,
675
+ defaultBaseUrl: "https://generativelanguage.googleapis.com",
676
+ specialRequirements: []
677
+ },
670
678
  "claude-code": {
671
679
  displayLabel: "Claude Code",
672
680
  authMethod: "oauth",
@@ -1283,6 +1291,209 @@ var init_src3 = __esm(() => {
1283
1291
  log = new Logger;
1284
1292
  });
1285
1293
 
1294
+ // ../../packages/config/src/builtin-providers.ts
1295
+ var BUILTIN_PROVIDER_CONFIGS;
1296
+ var init_builtin_providers = __esm(() => {
1297
+ BUILTIN_PROVIDER_CONFIGS = [
1298
+ { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1299
+ { name: "openai", enabled: true, strategy: "openai-api" },
1300
+ { name: "claude-code", enabled: false, strategy: "claude-code" },
1301
+ { name: "codex", enabled: false, strategy: "codex" }
1302
+ ];
1303
+ });
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
+
1286
1497
  // ../../packages/config/src/paths-common.ts
1287
1498
  import { homedir } from "os";
1288
1499
  import { join as join3 } from "path";
@@ -1313,21 +1524,246 @@ var init_paths = __esm(() => {
1313
1524
  init_paths_common();
1314
1525
  });
1315
1526
 
1316
- // ../../packages/config/src/window-warmup.ts
1317
- function isLocalTimes(value) {
1318
- return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1527
+ // ../../packages/config/src/rewrite-config.ts
1528
+ function rewriteLegacyConfig(value) {
1529
+ if (!isRecord2(value))
1530
+ throw new Error("Configuration must be a JSON object");
1531
+ const output = structuredClone(value);
1532
+ const hasTeam = Object.hasOwn(output, "team_routing");
1533
+ const hasRoutes = Object.hasOwn(output, "provider_pools");
1534
+ const hasBlockPolicy = Object.hasOwn(output, "block_when_all_full");
1535
+ if (!hasTeam && !hasRoutes && !hasBlockPolicy)
1536
+ return output;
1537
+ if (Object.hasOwn(output, "routing"))
1538
+ throw new Error("Cannot rewrite a config containing both legacy keys and routing");
1539
+ const team = hasTeam ? output.team_routing : {};
1540
+ const routes = hasRoutes ? output.provider_pools : {};
1541
+ if (!isRecord2(team) || !isRecord2(routes))
1542
+ throw new Error("Legacy team_routing and provider_pools must be objects");
1543
+ if (output.providers !== undefined && !isRecord2(output.providers))
1544
+ throw new Error("Legacy providers must be an object");
1545
+ const providers = structuredClone(output.providers ?? {});
1546
+ if (Object.values(providers).some((provider) => !isRecord2(provider) || Object.hasOwn(provider, "pool")))
1547
+ throw new Error("Cannot rewrite invalid providers or existing provider pools");
1548
+ const knownTeamFields = new Set([
1549
+ "enabled",
1550
+ "allowlisted_account_uuids",
1551
+ "distribution_enabled",
1552
+ "prefer_expiring_quota",
1553
+ "max_usage",
1554
+ "weekly_max_usage",
1555
+ "weekly_max_usage_by_email",
1556
+ "caller_weekly_max_usage",
1557
+ "caller_provider_fallback",
1558
+ "admission_cap",
1559
+ "admission_queue_limit",
1560
+ "admission_wait_ms",
1561
+ "hold_seconds",
1562
+ "quota_probe_seconds",
1563
+ "window_warmup"
1564
+ ]);
1565
+ if (Object.keys(team).some((field) => !knownTeamFields.has(field)))
1566
+ throw new Error("Cannot safely rewrite unknown team_routing fields");
1567
+ if (team.enabled !== undefined && typeof team.enabled !== "boolean")
1568
+ throw new Error("Invalid team_routing.enabled");
1569
+ if (hasBlockPolicy && typeof output.block_when_all_full !== "boolean")
1570
+ throw new Error("Invalid block_when_all_full");
1571
+ if (team.caller_provider_fallback !== undefined && (!isRecord2(team.caller_provider_fallback) || Object.values(team.caller_provider_fallback).some((policy) => policy !== "ordered")))
1572
+ throw new Error("Invalid caller_provider_fallback");
1573
+ const enabled = team.enabled === true;
1574
+ const dormantFields = [
1575
+ "allowlisted_account_uuids",
1576
+ "distribution_enabled",
1577
+ "prefer_expiring_quota",
1578
+ "max_usage",
1579
+ "weekly_max_usage",
1580
+ "weekly_max_usage_by_email",
1581
+ "caller_weekly_max_usage",
1582
+ "admission_cap",
1583
+ "admission_queue_limit",
1584
+ "admission_wait_ms",
1585
+ "quota_probe_seconds",
1586
+ "window_warmup"
1587
+ ];
1588
+ const keepPool = enabled || hasBlockPolicy || dormantFields.some((field) => Object.hasOwn(team, field));
1589
+ const callers = {};
1590
+ if (enabled && isRecord2(team.caller_provider_fallback)) {
1591
+ for (const [caller, policy] of Object.entries(team.caller_provider_fallback))
1592
+ if (policy === "ordered")
1593
+ callers[caller] = { allow_fallbacks: true };
1594
+ }
1595
+ const routing = {
1596
+ routes: structuredClone(routes),
1597
+ api_key_accounts: enabled ? "chooser_or_fallback" : "everyone",
1598
+ callers,
1599
+ hold_seconds: typeof team.hold_seconds === "number" ? team.hold_seconds : 0
1600
+ };
1601
+ if (keepPool) {
1602
+ const pool = {
1603
+ ...!enabled && { enabled: false },
1604
+ members: structuredClone(team.allowlisted_account_uuids ?? [])
1605
+ };
1606
+ for (const field of [
1607
+ "distribution_enabled",
1608
+ "prefer_expiring_quota",
1609
+ "max_usage",
1610
+ "weekly_max_usage",
1611
+ "weekly_max_usage_by_email",
1612
+ "caller_weekly_max_usage",
1613
+ "quota_probe_seconds",
1614
+ "window_warmup"
1615
+ ])
1616
+ if (Object.hasOwn(team, field))
1617
+ pool[field] = structuredClone(team[field]);
1618
+ const admission = {};
1619
+ for (const [oldKey, newKey] of [
1620
+ ["admission_cap", "cap"],
1621
+ ["admission_queue_limit", "queue_limit"],
1622
+ ["admission_wait_ms", "wait_ms"]
1623
+ ])
1624
+ if (Object.hasOwn(team, oldKey))
1625
+ admission[newKey] = team[oldKey];
1626
+ if (Object.keys(admission).length)
1627
+ pool.admission = admission;
1628
+ if (hasBlockPolicy)
1629
+ pool.block_when_all_full = output.block_when_all_full;
1630
+ for (const { name } of BUILTIN_PROVIDER_CONFIGS)
1631
+ if (!Object.hasOwn(providers, name))
1632
+ providers[name] = {};
1633
+ for (const [name, entry] of Object.entries(providers)) {
1634
+ if (!isRecord2(entry))
1635
+ throw new Error(`Invalid provider: ${name}`);
1636
+ providers[name] = { ...entry, pool: structuredClone(pool) };
1637
+ }
1638
+ }
1639
+ delete output.team_routing;
1640
+ delete output.provider_pools;
1641
+ delete output.block_when_all_full;
1642
+ output.providers = providers;
1643
+ output.routing = routing;
1644
+ return output;
1645
+ }
1646
+ function isRecord2(value) {
1647
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1319
1648
  }
1320
- function isTimeZone(value) {
1321
- if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1322
- return false;
1323
- }
1649
+ var init_rewrite_config = __esm(() => {
1650
+ init_builtin_providers();
1651
+ });
1652
+
1653
+ // ../../packages/config/src/rewrite-file.ts
1654
+ import { randomUUID } from "crypto";
1655
+ import {
1656
+ accessSync,
1657
+ constants,
1658
+ linkSync,
1659
+ lstatSync,
1660
+ readFileSync,
1661
+ realpathSync,
1662
+ renameSync,
1663
+ statSync as statSync2,
1664
+ unlinkSync as unlinkSync2,
1665
+ writeFileSync
1666
+ } from "fs";
1667
+ import { basename, dirname, join as join5, resolve } from "path";
1668
+ function hasLegacyConfig(value) {
1669
+ return typeof value === "object" && value !== null && !Array.isArray(value) && ["team_routing", "provider_pools", "block_when_all_full"].some((key) => Object.hasOwn(value, key));
1670
+ }
1671
+ function isFileError(error, code) {
1672
+ return error instanceof Error && "code" in error && error.code === code;
1673
+ }
1674
+ function matchesPrivateBackup(path, expected) {
1324
1675
  try {
1325
- new Intl.DateTimeFormat("en-US", { timeZone: value });
1326
- return true;
1676
+ const file = lstatSync(path);
1677
+ return file.isFile() && (file.mode & 63) === 0 && (typeof process.getuid !== "function" || file.uid === process.getuid()) && readFileSync(path, "utf8") === expected;
1327
1678
  } catch {
1328
1679
  return false;
1329
1680
  }
1330
1681
  }
1682
+ function rewriteConfigFile(input, output) {
1683
+ if (output !== undefined && resolve(input) === resolve(output))
1684
+ throw new Error("Input and output must be different files");
1685
+ const destination = realpathSync(input);
1686
+ const initial = statSync2(destination);
1687
+ const original = readFileSync(input, "utf8");
1688
+ const data = JSON.parse(original);
1689
+ const rewritten = rewriteLegacyConfig(data);
1690
+ const result = `${JSON.stringify(rewritten, null, 2)}
1691
+ `;
1692
+ if (output !== undefined) {
1693
+ writeFileSync(output, result, {
1694
+ encoding: "utf8",
1695
+ mode: 384,
1696
+ flag: "wx"
1697
+ });
1698
+ return { changed: true };
1699
+ }
1700
+ if (!hasLegacyConfig(data))
1701
+ return { changed: false };
1702
+ if ((initial.mode & 146) === 0)
1703
+ throw new Error("Config file is read-only");
1704
+ accessSync(destination, constants.W_OK);
1705
+ const token = randomUUID();
1706
+ const backupTemp = join5(dirname(destination), `.${basename(destination)}.${token}.backup.tmp`);
1707
+ const temporary = join5(dirname(destination), `.${basename(destination)}.${token}.tmp`);
1708
+ const state = () => {
1709
+ if (realpathSync(input) !== destination)
1710
+ throw new Error("Config path changed while rewriting");
1711
+ const current = readFileSync(destination, "utf8");
1712
+ if (current === original)
1713
+ return "original";
1714
+ const parsed = JSON.parse(current);
1715
+ if (!hasLegacyConfig(parsed))
1716
+ return "new";
1717
+ throw new Error("Config changed while it was being rewritten");
1718
+ };
1719
+ try {
1720
+ if (state() === "new")
1721
+ return { changed: false };
1722
+ writeFileSync(backupTemp, original, {
1723
+ encoding: "utf8",
1724
+ mode: 384,
1725
+ flag: "wx"
1726
+ });
1727
+ const base = `${destination}.backup`;
1728
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1729
+ let backup = base;
1730
+ for (let attempt = 0;; attempt++) {
1731
+ try {
1732
+ linkSync(backupTemp, backup);
1733
+ break;
1734
+ } catch (error) {
1735
+ if (!isFileError(error, "EEXIST"))
1736
+ throw error;
1737
+ if (matchesPrivateBackup(backup, original))
1738
+ break;
1739
+ backup = `${base}-${stamp}${attempt === 0 ? "" : `-${attempt}`}`;
1740
+ }
1741
+ }
1742
+ writeFileSync(temporary, result, {
1743
+ encoding: "utf8",
1744
+ mode: 384,
1745
+ flag: "wx"
1746
+ });
1747
+ if (state() === "new")
1748
+ return { changed: false };
1749
+ renameSync(temporary, destination);
1750
+ return { changed: true, backup };
1751
+ } finally {
1752
+ for (const path of [backupTemp, temporary]) {
1753
+ try {
1754
+ unlinkSync2(path);
1755
+ } catch {}
1756
+ }
1757
+ }
1758
+ }
1759
+ var init_rewrite_file = __esm(() => {
1760
+ init_rewrite_config();
1761
+ });
1762
+
1763
+ // ../../packages/config/src/window-warmup.ts
1764
+ function isLocalTimes(value) {
1765
+ return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1766
+ }
1331
1767
  function sanitizeWindowWarmup(value) {
1332
1768
  if (!isRecord(value))
1333
1769
  return;
@@ -1364,42 +1800,6 @@ function windowWarmupFileConfig(config) {
1364
1800
  ...config.model && { model: config.model }
1365
1801
  };
1366
1802
  }
1367
- function wallClockFormat(timeZone) {
1368
- let format = wallClockFormats.get(timeZone);
1369
- if (!format) {
1370
- format = new Intl.DateTimeFormat("en-US", {
1371
- timeZone,
1372
- hourCycle: "h23",
1373
- year: "numeric",
1374
- month: "numeric",
1375
- day: "numeric",
1376
- hour: "numeric",
1377
- minute: "numeric",
1378
- second: "numeric"
1379
- });
1380
- wallClockFormats.set(timeZone, format);
1381
- }
1382
- return format;
1383
- }
1384
- function wallClock(at, timeZone) {
1385
- const parts = wallClockFormat(timeZone).formatToParts(at);
1386
- const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1387
- return {
1388
- year: part("year"),
1389
- month: part("month"),
1390
- day: part("day"),
1391
- hour: part("hour") % 24,
1392
- minute: part("minute"),
1393
- second: part("second")
1394
- };
1395
- }
1396
- function zoneOffsetMs(at, timeZone) {
1397
- const wall = wallClock(at, timeZone);
1398
- return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1399
- }
1400
- function zonedInstant(wall, timeZone) {
1401
- return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1402
- }
1403
1803
  function nextWindowWarmupAt(routing, after) {
1404
1804
  const warmup = routing.windowWarmup;
1405
1805
  if (!routing.enabled || !warmup.enabled)
@@ -1411,19 +1811,16 @@ function nextWindowWarmupAt(routing, after) {
1411
1811
  if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
1412
1812
  continue;
1413
1813
  }
1414
- const instants = warmup.times.map((time) => {
1415
- const [hour = 0, minute = 0] = time.split(":").map(Number);
1416
- return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
1417
- }).filter((at) => at > after);
1814
+ const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
1418
1815
  if (instants.length > 0)
1419
1816
  return Math.min(...instants);
1420
1817
  }
1421
1818
  return null;
1422
1819
  }
1423
- 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;
1424
1821
  var init_window_warmup = __esm(() => {
1425
- init_src2();
1426
1822
  init_src();
1823
+ init_zoned_time();
1427
1824
  WINDOW_WARMUP_DEFAULTS = {
1428
1825
  enabled: false,
1429
1826
  times: ["06:00"],
@@ -1431,9 +1828,7 @@ var init_window_warmup = __esm(() => {
1431
1828
  weekdaysOnly: true,
1432
1829
  model: null
1433
1830
  };
1434
- LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1435
1831
  MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
1436
- wallClockFormats = new Map;
1437
1832
  });
1438
1833
 
1439
1834
  // ../../packages/config/src/index.ts
@@ -1442,13 +1837,19 @@ import {
1442
1837
  chmodSync,
1443
1838
  existsSync as existsSync2,
1444
1839
  mkdirSync as mkdirSync2,
1445
- readFileSync,
1446
- renameSync,
1840
+ readFileSync as readFileSync2,
1841
+ renameSync as renameSync2,
1447
1842
  rmSync,
1448
- statSync as statSync2,
1449
- writeFileSync
1843
+ statSync as statSync3,
1844
+ writeFileSync as writeFileSync2
1450
1845
  } from "fs";
1451
- import { dirname } from "path";
1846
+ import { dirname as dirname2 } from "path";
1847
+ function runtimeForProvider(runtime, provider) {
1848
+ return {
1849
+ ...runtime,
1850
+ pool: runtime.providerPools[provider] ?? { ...POOL_DEFAULTS }
1851
+ };
1852
+ }
1452
1853
  function parseNumber(value) {
1453
1854
  if (value === undefined) {
1454
1855
  return;
@@ -1508,6 +1909,12 @@ function sanitizeConfigData(value) {
1508
1909
  sanitized.provider_pools = providerPools;
1509
1910
  continue;
1510
1911
  }
1912
+ if (key === "routing") {
1913
+ const routing = sanitizeRouting(entry);
1914
+ if (routing)
1915
+ sanitized.routing = routing;
1916
+ continue;
1917
+ }
1511
1918
  if (key === "client") {
1512
1919
  const client = sanitizeClientRouting(entry);
1513
1920
  if (client)
@@ -1661,6 +2068,9 @@ function sanitizeProviderConfigs(value) {
1661
2068
  const models = sanitizeProviderModels(entry.models);
1662
2069
  if (models)
1663
2070
  provider.models = models;
2071
+ const pool = sanitizeProviderPool(entry.pool);
2072
+ if (pool)
2073
+ provider.pool = pool;
1664
2074
  providers[name] = provider;
1665
2075
  }
1666
2076
  return providers;
@@ -1679,11 +2089,34 @@ function sanitizeProviderPools(value) {
1679
2089
  return pools;
1680
2090
  }
1681
2091
  function wireForStrategy(strategy3) {
1682
- return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
2092
+ return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "kimi-code-anthropic-api" || strategy3 === "google-gemini-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1683
2093
  }
1684
2094
  function isNonNegativeFiniteNumber(value) {
1685
2095
  return isFiniteNumber(value) && value >= 0;
1686
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
+ }
1687
2120
  function sanitizeTeamRouting(value) {
1688
2121
  if (!isRecord(value))
1689
2122
  return;
@@ -1705,19 +2138,21 @@ function sanitizeTeamRouting(value) {
1705
2138
  if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1706
2139
  result.weekly_max_usage = value.weekly_max_usage;
1707
2140
  }
1708
- if (isRecord(value.weekly_max_usage_by_email)) {
1709
- const entries = Object.entries(value.weekly_max_usage_by_email);
1710
- const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1711
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 0.95) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1712
- result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1713
- }
1714
- }
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;
1715
2147
  if (isRecord(value.caller_weekly_max_usage)) {
1716
2148
  const entries = Object.entries(value.caller_weekly_max_usage);
1717
2149
  if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
1718
2150
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1719
2151
  }
1720
2152
  }
2153
+ const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
2154
+ if (ownerDevicesByEmail)
2155
+ result.owner_devices_by_email = ownerDevicesByEmail;
1721
2156
  if (isRecord(value.caller_provider_fallback)) {
1722
2157
  const entries = Object.entries(value.caller_provider_fallback);
1723
2158
  if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
@@ -1744,13 +2179,116 @@ function sanitizeTeamRouting(value) {
1744
2179
  result.window_warmup = windowWarmup;
1745
2180
  return result;
1746
2181
  }
2182
+ function sanitizeProviderPool(value) {
2183
+ if (!isRecord(value))
2184
+ return;
2185
+ const legacy = {
2186
+ ...value,
2187
+ allowlisted_account_uuids: value.members
2188
+ };
2189
+ if (isRecord(value.admission)) {
2190
+ legacy.admission_cap = value.admission.cap;
2191
+ legacy.admission_queue_limit = value.admission.queue_limit;
2192
+ legacy.admission_wait_ms = value.admission.wait_ms;
2193
+ }
2194
+ const sanitized = sanitizeTeamRouting(legacy);
2195
+ if (!sanitized)
2196
+ return;
2197
+ const pool = {};
2198
+ if (typeof value.enabled === "boolean")
2199
+ pool.enabled = value.enabled;
2200
+ if (sanitized.allowlisted_account_uuids)
2201
+ pool.members = sanitized.allowlisted_account_uuids;
2202
+ for (const field of [
2203
+ "distribution_enabled",
2204
+ "prefer_expiring_quota",
2205
+ "max_usage",
2206
+ "max_usage_by_email",
2207
+ "weekly_max_usage",
2208
+ "weekly_max_usage_by_email",
2209
+ "caller_weekly_max_usage",
2210
+ "owner_devices_by_email",
2211
+ "quota_probe_seconds",
2212
+ "window_warmup"
2213
+ ]) {
2214
+ if (sanitized[field] !== undefined)
2215
+ Object.assign(pool, { [field]: sanitized[field] });
2216
+ }
2217
+ if (isRecord(value.admission)) {
2218
+ pool.admission = {
2219
+ ...sanitized.admission_cap !== undefined && {
2220
+ cap: sanitized.admission_cap
2221
+ },
2222
+ ...sanitized.admission_queue_limit !== undefined && {
2223
+ queue_limit: sanitized.admission_queue_limit
2224
+ },
2225
+ ...sanitized.admission_wait_ms !== undefined && {
2226
+ wait_ms: sanitized.admission_wait_ms
2227
+ }
2228
+ };
2229
+ }
2230
+ if (typeof value.block_when_all_full === "boolean")
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;
2235
+ return pool;
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
+ }
2243
+ function sanitizeRouting(value) {
2244
+ if (!isRecord(value))
2245
+ return;
2246
+ const routing = {};
2247
+ const routes = sanitizeProviderPools(value.routes);
2248
+ if (routes)
2249
+ routing.routes = routes;
2250
+ if (value.api_key_accounts === "everyone" || value.api_key_accounts === "chooser_or_fallback")
2251
+ routing.api_key_accounts = value.api_key_accounts;
2252
+ if (isNonNegativeFiniteNumber(value.hold_seconds))
2253
+ routing.hold_seconds = Math.floor(value.hold_seconds);
2254
+ if (isRecord(value.callers)) {
2255
+ const entries = Object.entries(value.callers);
2256
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, policy]) => CALLER_ID_PATTERN.test(caller) && isRecord(policy) && typeof policy.allow_fallbacks === "boolean")) {
2257
+ routing.callers = Object.fromEntries(entries.map(([caller, policy]) => [
2258
+ caller,
2259
+ {
2260
+ allow_fallbacks: policy.allow_fallbacks
2261
+ }
2262
+ ]));
2263
+ }
2264
+ }
2265
+ return routing;
2266
+ }
2267
+ function migrateLegacyConfig(path, parsed) {
2268
+ let current = parsed;
2269
+ for (let attempt = 0;attempt < 3 && hasLegacyConfig(current); attempt++) {
2270
+ try {
2271
+ const result = rewriteConfigFile(path);
2272
+ if (result.changed)
2273
+ log2.info(`Rewrote config ${path}; backup: ${result.backup}`);
2274
+ current = JSON.parse(readFileSync2(path, "utf8"));
2275
+ } catch (error) {
2276
+ const reason = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : String(error);
2277
+ throw new Error(`Could not rewrite legacy config ${path}: ${reason}. Run: agent-smith config rewrite`);
2278
+ }
2279
+ }
2280
+ if (hasLegacyConfig(current))
2281
+ throw new Error(`Config ${path} kept changing while rewriting. Run: agent-smith config rewrite`);
2282
+ return current;
2283
+ }
1747
2284
  function readClientRouting(configPath = resolveConfigPath()) {
1748
2285
  let data;
1749
2286
  try {
1750
- data = JSON.parse(readFileSync(configPath, "utf8"));
2287
+ data = JSON.parse(readFileSync2(configPath, "utf8"));
1751
2288
  } catch {
1752
2289
  throw new Error("Agent Smith client config could not be read");
1753
2290
  }
2291
+ data = migrateLegacyConfig(configPath, data);
1754
2292
  if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1755
2293
  throw new Error("Agent Smith client config is invalid");
1756
2294
  }
@@ -1765,50 +2303,54 @@ function clientRouting(client) {
1765
2303
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1766
2304
  };
1767
2305
  }
1768
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
2306
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1769
2307
  var init_src4 = __esm(() => {
1770
2308
  init_src2();
1771
2309
  init_src3();
1772
2310
  init_src();
2311
+ init_builtin_providers();
2312
+ init_night_pacing();
1773
2313
  init_paths();
2314
+ init_rewrite_file();
1774
2315
  init_window_warmup();
2316
+ init_night_pacing();
1775
2317
  init_paths();
1776
2318
  init_paths_common();
2319
+ init_rewrite_config();
2320
+ init_rewrite_file();
1777
2321
  init_window_warmup();
1778
2322
  log2 = new Logger("Config");
1779
2323
  PROVIDER_STRATEGIES = [
1780
2324
  "anthropic-api",
1781
2325
  "model-studio-anthropic-api",
2326
+ "kimi-code-anthropic-api",
2327
+ "google-gemini-api",
1782
2328
  "openai-api",
1783
2329
  "claude-code",
1784
2330
  "codex"
1785
2331
  ];
1786
- BUILTIN_PROVIDER_CONFIGS = [
1787
- { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1788
- { name: "openai", enabled: true, strategy: "openai-api" },
1789
- { name: "claude-code", enabled: false, strategy: "claude-code" },
1790
- { name: "codex", enabled: false, strategy: "codex" }
1791
- ];
1792
2332
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1793
2333
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1794
2334
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1795
2335
  CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1796
- TEAM_ROUTING_DEFAULTS = {
2336
+ POOL_DEFAULTS = {
1797
2337
  enabled: false,
1798
2338
  distributionEnabled: true,
1799
2339
  preferExpiringQuota: false,
1800
2340
  allowlistedAccountUuids: [],
1801
2341
  maxUsage: 0.9,
2342
+ maxUsageByEmail: {},
1802
2343
  weeklyMaxUsage: 0.95,
1803
2344
  weeklyMaxUsageByEmail: {},
1804
2345
  callerWeeklyMaxUsage: {},
1805
- callerProviderFallback: {},
2346
+ callerNightPacing: {},
2347
+ ownerDevicesByEmail: {},
1806
2348
  admissionCap: 5,
1807
2349
  admissionQueueLimit: 25,
1808
2350
  admissionWaitMs: 30000,
1809
- holdSeconds: 0,
1810
2351
  quotaProbeSeconds: 0,
1811
- windowWarmup: WINDOW_WARMUP_DEFAULTS
2352
+ windowWarmup: WINDOW_WARMUP_DEFAULTS,
2353
+ blockWhenAllFull: true
1812
2354
  };
1813
2355
  Config = class Config extends EventEmitter3 {
1814
2356
  configPath;
@@ -1820,20 +2362,23 @@ var init_src4 = __esm(() => {
1820
2362
  }
1821
2363
  loadConfig() {
1822
2364
  if (existsSync2(this.configPath)) {
2365
+ let parsed;
1823
2366
  try {
1824
- const content = readFileSync(this.configPath, "utf8");
1825
- this.data = sanitizeConfigData(JSON.parse(content));
2367
+ const content = readFileSync2(this.configPath, "utf8");
2368
+ parsed = JSON.parse(content);
1826
2369
  } catch (error) {
1827
2370
  log2.error(`Failed to parse config file: ${error}`);
1828
2371
  this.data = {};
1829
2372
  return;
1830
2373
  }
2374
+ parsed = migrateLegacyConfig(this.configPath, parsed);
2375
+ this.data = sanitizeConfigData(parsed);
1831
2376
  try {
1832
2377
  chmodSync(this.configPath, 384);
1833
2378
  } catch {
1834
2379
  let ownerOnly = false;
1835
2380
  try {
1836
- ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
2381
+ ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
1837
2382
  } catch {}
1838
2383
  if (!ownerOnly) {
1839
2384
  throw new Error("Config file must be owner-only");
@@ -1844,7 +2389,7 @@ var init_src4 = __esm(() => {
1844
2389
  this.saveConfig();
1845
2390
  }
1846
2391
  } else {
1847
- const dir = dirname(this.configPath);
2392
+ const dir = dirname2(this.configPath);
1848
2393
  mkdirSync2(dir, { recursive: true, mode: 448 });
1849
2394
  chmodSync(dir, 448);
1850
2395
  this.data = {
@@ -1863,11 +2408,11 @@ var init_src4 = __esm(() => {
1863
2408
  writePrivately(data) {
1864
2409
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1865
2410
  try {
1866
- writeFileSync(temporary, JSON.stringify(data, null, 2), {
2411
+ writeFileSync2(temporary, JSON.stringify(data, null, 2), {
1867
2412
  mode: 384,
1868
2413
  flag: "wx"
1869
2414
  });
1870
- renameSync(temporary, this.configPath);
2415
+ renameSync2(temporary, this.configPath);
1871
2416
  } finally {
1872
2417
  rmSync(temporary, { force: true });
1873
2418
  }
@@ -1953,26 +2498,38 @@ var init_src4 = __esm(() => {
1953
2498
  request_retention_days: this.getRequestRetentionDays()
1954
2499
  };
1955
2500
  }
1956
- getTeamRouting() {
1957
- const file = this.data.team_routing;
2501
+ getRouting() {
2502
+ const routing = this.data.routing;
2503
+ return {
2504
+ routes: structuredClone(routing?.routes ?? {}),
2505
+ apiKeyAccounts: routing?.api_key_accounts ?? "everyone",
2506
+ callers: Object.fromEntries(Object.entries(routing?.callers ?? {}).map(([name, policy]) => [
2507
+ name,
2508
+ { allowFallbacks: policy.allow_fallbacks }
2509
+ ])),
2510
+ holdSeconds: routing?.hold_seconds ?? 0
2511
+ };
2512
+ }
2513
+ getTeamRouting(providerName) {
2514
+ const pool = this.data.providers?.[providerName]?.pool;
1958
2515
  return {
1959
- enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1960
- distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1961
- preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
1962
- allowlistedAccountUuids: [
1963
- ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1964
- ],
1965
- maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1966
- weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1967
- weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1968
- callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1969
- callerProviderFallback: { ...file?.caller_provider_fallback },
1970
- admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1971
- admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1972
- admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1973
- holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1974
- quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
1975
- windowWarmup: windowWarmupConfig(file?.window_warmup)
2516
+ enabled: pool !== undefined && pool.enabled !== false,
2517
+ distributionEnabled: pool?.distribution_enabled ?? POOL_DEFAULTS.distributionEnabled,
2518
+ preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2519
+ allowlistedAccountUuids: [...pool?.members ?? []],
2520
+ maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2521
+ maxUsageByEmail: { ...pool?.max_usage_by_email },
2522
+ weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2523
+ weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
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 ?? {}),
2527
+ admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2528
+ admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2529
+ admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
2530
+ quotaProbeSeconds: pool?.quota_probe_seconds ?? POOL_DEFAULTS.quotaProbeSeconds,
2531
+ windowWarmup: windowWarmupConfig(pool?.window_warmup),
2532
+ blockWhenAllFull: pool?.block_when_all_full !== false
1976
2533
  };
1977
2534
  }
1978
2535
  getAlerts() {
@@ -1992,9 +2549,6 @@ var init_src4 = __esm(() => {
1992
2549
  setClientRoutingEnabled(enabled) {
1993
2550
  this.persistStrictly("client", { ...this.data.client, enabled });
1994
2551
  }
1995
- getBlockWhenAllFull() {
1996
- return this.data.block_when_all_full !== false;
1997
- }
1998
2552
  getProviderConfig(name) {
1999
2553
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
2000
2554
  const configured = this.data.providers?.[name];
@@ -2005,11 +2559,12 @@ var init_src4 = __esm(() => {
2005
2559
  enabled: configured?.enabled ?? builtin?.enabled ?? true,
2006
2560
  strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
2007
2561
  ...configured?.base_url && { baseUrl: configured.base_url },
2008
- ...configured?.models && { models: { ...configured.models } }
2562
+ ...configured?.models && { models: { ...configured.models } },
2563
+ ...configured?.pool && { pool: structuredClone(configured.pool) }
2009
2564
  };
2010
2565
  }
2011
2566
  getProviderPool(wire) {
2012
- return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
2567
+ return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
2013
2568
  const provider = this.getProviderConfig(name);
2014
2569
  return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
2015
2570
  });
@@ -2024,74 +2579,99 @@ var init_src4 = __esm(() => {
2024
2579
  }
2025
2580
  return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
2026
2581
  }
2027
- setTeamRouting(value) {
2028
- if (!isRecord(value)) {
2029
- throw new Error("team routing configuration must be an object");
2030
- }
2582
+ getProviderPoolSettings() {
2583
+ return Object.fromEntries(this.getProviderConfigs().map((provider) => [
2584
+ provider.name,
2585
+ this.getTeamRouting(provider.name)
2586
+ ]));
2587
+ }
2588
+ getProviderPoolConfig(name) {
2589
+ const pool = this.data.providers?.[name]?.pool;
2590
+ return pool ? structuredClone(pool) : undefined;
2591
+ }
2592
+ setProviderPool(name, value) {
2593
+ if (!this.getProviderConfig(name))
2594
+ throw new Error("Unknown provider");
2595
+ if (!isRecord(value))
2596
+ throw new Error("Provider pool configuration must be an object");
2031
2597
  const allowed = new Set([
2032
2598
  "enabled",
2599
+ "members",
2033
2600
  "distribution_enabled",
2034
2601
  "prefer_expiring_quota",
2035
- "allowlisted_account_uuids",
2036
2602
  "max_usage",
2603
+ "max_usage_by_email",
2037
2604
  "weekly_max_usage",
2038
2605
  "weekly_max_usage_by_email",
2039
2606
  "caller_weekly_max_usage",
2040
- "caller_provider_fallback",
2041
- "admission_cap",
2042
- "admission_queue_limit",
2043
- "admission_wait_ms",
2044
- "hold_seconds",
2607
+ "caller_night_pacing",
2608
+ "owner_devices_by_email",
2609
+ "admission",
2045
2610
  "quota_probe_seconds",
2046
- "window_warmup"
2611
+ "window_warmup",
2612
+ "block_when_all_full"
2047
2613
  ]);
2048
- if (Object.keys(value).some((key) => !allowed.has(key))) {
2049
- throw new Error("team routing configuration contains an unknown field");
2050
- }
2051
- const sanitized = sanitizeTeamRouting(value);
2052
- if (!sanitized) {
2053
- throw new Error("team routing configuration must be an object");
2054
- }
2055
- for (const key of Object.keys(value)) {
2056
- if (!(key in sanitized)) {
2057
- throw new Error(`Invalid team routing field: ${key}`);
2614
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2615
+ throw new Error("Provider pool contains an unknown field");
2616
+ const sanitized = sanitizeProviderPool(value);
2617
+ if (!sanitized)
2618
+ throw new Error("Invalid provider pool");
2619
+ for (const key of Object.keys(value))
2620
+ if (!(key in sanitized))
2621
+ throw new Error(`Invalid provider pool field: ${key}`);
2622
+ if (isRecord(value.admission) && Object.keys(value.admission).some((key) => !["cap", "queue_limit", "wait_ms"].includes(key) || !(key in (sanitized.admission ?? {}))))
2623
+ throw new Error("Invalid admission field");
2624
+ const old = this.getProviderPoolConfig(name) ?? { enabled: false };
2625
+ this.persistStrictly("providers", {
2626
+ ...this.data.providers,
2627
+ [name]: {
2628
+ ...this.data.providers?.[name],
2629
+ pool: { ...old, ...sanitized }
2058
2630
  }
2059
- }
2060
- const oldValue = this.data.team_routing;
2061
- if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
2062
- sanitized.weekly_max_usage_by_email = {
2063
- ...oldValue.weekly_max_usage_by_email
2064
- };
2065
- }
2066
- if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2067
- sanitized.caller_weekly_max_usage = {
2068
- ...oldValue.caller_weekly_max_usage
2069
- };
2070
- }
2071
- if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
2072
- sanitized.caller_provider_fallback = {
2073
- ...oldValue.caller_provider_fallback
2074
- };
2075
- }
2076
- this.persistStrictly("team_routing", sanitized);
2631
+ });
2632
+ }
2633
+ removeProviderPool(name) {
2634
+ const provider = this.data.providers?.[name];
2635
+ if (!provider?.pool)
2636
+ return;
2637
+ const { pool: _pool, ...rest } = provider;
2638
+ this.persistStrictly("providers", { ...this.data.providers, [name]: rest });
2077
2639
  }
2078
- allowAccountUuid(accountUuid) {
2079
- const current = this.getTeamRouting().allowlistedAccountUuids;
2640
+ setRouting(value) {
2641
+ if (!isRecord(value))
2642
+ throw new Error("Routing configuration must be an object");
2643
+ const allowed = new Set([
2644
+ "routes",
2645
+ "api_key_accounts",
2646
+ "callers",
2647
+ "hold_seconds"
2648
+ ]);
2649
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2650
+ throw new Error("Routing contains an unknown field");
2651
+ const sanitized = sanitizeRouting(value);
2652
+ if (!sanitized)
2653
+ throw new Error("Invalid routing configuration");
2654
+ for (const key of Object.keys(value))
2655
+ if (!(key in sanitized))
2656
+ throw new Error(`Invalid routing field: ${key}`);
2657
+ if ("routes" in value && (!isRecord(value.routes) || Object.entries(value.routes).some(([wire, providers]) => !isProviderWire(wire) || !Array.isArray(providers) || providers.some((provider) => typeof provider !== "string" || !PROVIDER_NAME_PATTERN.test(provider)))))
2658
+ throw new Error("Invalid routing field: routes");
2659
+ this.persistStrictly("routing", { ...this.data.routing, ...sanitized });
2660
+ }
2661
+ allowAccountUuid(provider, accountUuid) {
2662
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2080
2663
  if (current.includes(accountUuid))
2081
2664
  return;
2082
- this.persistAccountAllowlist([...current, accountUuid]);
2665
+ this.persistAccountAllowlist(provider, [...current, accountUuid]);
2083
2666
  }
2084
- removeAccountUuid(accountUuid) {
2085
- const current = this.getTeamRouting().allowlistedAccountUuids;
2667
+ removeAccountUuid(provider, accountUuid) {
2668
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2086
2669
  if (!current.includes(accountUuid))
2087
2670
  return;
2088
- this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
2671
+ this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
2089
2672
  }
2090
- persistAccountAllowlist(accountUuids) {
2091
- this.persistStrictly("team_routing", {
2092
- ...this.data.team_routing,
2093
- allowlisted_account_uuids: accountUuids
2094
- });
2673
+ persistAccountAllowlist(provider, accountUuids) {
2674
+ this.setProviderPool(provider, { members: accountUuids });
2095
2675
  }
2096
2676
  getEnrollmentEmails() {
2097
2677
  return [...this.data.enrollment_emails ?? []];
@@ -2125,7 +2705,6 @@ var init_src4 = __esm(() => {
2125
2705
  }
2126
2706
  getRuntime() {
2127
2707
  const defaults = {
2128
- blockWhenAllFull: this.getBlockWhenAllFull(),
2129
2708
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
2130
2709
  maxBodyBytes: 64 * 1024 * 1024,
2131
2710
  quotaThreshold: 0.98,
@@ -2138,7 +2717,8 @@ var init_src4 = __esm(() => {
2138
2717
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
2139
2718
  port: NETWORK.DEFAULT_PORT,
2140
2719
  storeRequestPayloads: this.storesRequestPayloads(),
2141
- teamRouting: this.getTeamRouting()
2720
+ routing: this.getRouting(),
2721
+ providerPools: this.getProviderPoolSettings()
2142
2722
  };
2143
2723
  if (process.env.AGENT_SMITH_CLIENT_ID) {
2144
2724
  defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
@@ -2208,14 +2788,14 @@ var init_src4 = __esm(() => {
2208
2788
  });
2209
2789
 
2210
2790
  // ../../packages/database/src/paths.ts
2211
- import { join as join5 } from "path";
2791
+ import { join as join6 } from "path";
2212
2792
  function resolveDbPath() {
2213
2793
  const explicitPath = process.env.AGENT_SMITH_DB_PATH;
2214
2794
  if (explicitPath) {
2215
2795
  return explicitPath;
2216
2796
  }
2217
2797
  const configDir = getPlatformConfigDir();
2218
- return join5(configDir, "agent-smith.db");
2798
+ return join6(configDir, "agent-smith.db");
2219
2799
  }
2220
2800
  var init_paths2 = __esm(() => {
2221
2801
  init_src4();
@@ -2616,7 +3196,8 @@ function ensureRequestLinkageColumns(db) {
2616
3196
  ["ttft_ms", "INTEGER"],
2617
3197
  ["proxy_overhead_ms", "INTEGER"],
2618
3198
  ["upstream_ttfb_ms", "INTEGER"],
2619
- ["streaming_duration_ms", "INTEGER"]
3199
+ ["streaming_duration_ms", "INTEGER"],
3200
+ ["caller", "TEXT"]
2620
3201
  ];
2621
3202
  for (const [columnName, columnType] of requestColumns) {
2622
3203
  if (!hasColumn(columns, columnName)) {
@@ -3034,7 +3615,8 @@ function ensureSchema(db) {
3034
3615
  ttft_ms INTEGER,
3035
3616
  proxy_overhead_ms INTEGER,
3036
3617
  upstream_ttfb_ms INTEGER,
3037
- streaming_duration_ms INTEGER
3618
+ streaming_duration_ms INTEGER,
3619
+ caller TEXT
3038
3620
  )
3039
3621
  `);
3040
3622
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
@@ -3488,6 +4070,30 @@ var init_analytics_repository = __esm(() => {
3488
4070
  totalTokens: row.total_tokens ?? 0,
3489
4071
  totalCostUsd: row.total_cost_usd ?? 0
3490
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
+ }));
3491
4097
  const modelPerformance = this.query(`
3492
4098
  WITH model_stats AS (
3493
4099
  SELECT
@@ -3584,6 +4190,7 @@ var init_analytics_repository = __esm(() => {
3584
4190
  successRate: account2.success_rate ?? 0
3585
4191
  })),
3586
4192
  providerBreakdown,
4193
+ callerBreakdown,
3587
4194
  costByModel,
3588
4195
  modelPerformance
3589
4196
  };
@@ -3978,7 +4585,8 @@ var init_request_repository = __esm(() => {
3978
4585
  response_id = ?,
3979
4586
  previous_response_id = ?,
3980
4587
  response_chain_id = ?,
3981
- client_session_id = ?
4588
+ client_session_id = ?,
4589
+ caller = ?
3982
4590
  WHERE id = ?
3983
4591
  `, [
3984
4592
  data.method,
@@ -4010,6 +4618,7 @@ var init_request_repository = __esm(() => {
4010
4618
  linkage.previousResponseId,
4011
4619
  responseChainId,
4012
4620
  linkage.clientSessionId,
4621
+ data.caller ?? null,
4013
4622
  data.id
4014
4623
  ]);
4015
4624
  if (payloadJson !== undefined) {
@@ -4272,6 +4881,13 @@ var init_request_repository = __esm(() => {
4272
4881
  `, [limit]);
4273
4882
  return errors.map((e) => e.error_message);
4274
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
+ }
4275
4891
  getRequestsByAccount(since) {
4276
4892
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
4277
4893
  const params = since ? [since] : [];
@@ -4438,7 +5054,7 @@ var init_strategy_repository = __esm(() => {
4438
5054
  // ../../packages/database/src/database-operations.ts
4439
5055
  import { Database } from "bun:sqlite";
4440
5056
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
4441
- import { dirname as dirname2 } from "path";
5057
+ import { dirname as dirname3 } from "path";
4442
5058
  function freeDiskBytes(directory) {
4443
5059
  const { bavail, bsize } = statfsSync(directory);
4444
5060
  return bavail * bsize;
@@ -4461,7 +5077,7 @@ class DatabaseOperations {
4461
5077
  constructor(dbPath) {
4462
5078
  const resolvedPath = dbPath ?? resolveDbPath();
4463
5079
  this.dbPath = resolvedPath;
4464
- const dir = dirname2(resolvedPath);
5080
+ const dir = dirname3(resolvedPath);
4465
5081
  mkdirSync3(dir, { recursive: true });
4466
5082
  this.db = new Database(resolvedPath, { create: true });
4467
5083
  this.db.exec("PRAGMA foreign_keys = ON");
@@ -4615,9 +5231,13 @@ class DatabaseOperations {
4615
5231
  timestamp: options?.timestamp,
4616
5232
  payload: options?.payload,
4617
5233
  storePayload: options?.storePayload,
4618
- timings: options?.timings
5234
+ timings: options?.timings,
5235
+ caller: options?.callerId ?? null
4619
5236
  });
4620
5237
  }
5238
+ getAccountCostSince(accountId, since) {
5239
+ return this.requests.sumAccountCostSince(accountId, since);
5240
+ }
4621
5241
  updateRequestUsage(requestId, usage) {
4622
5242
  this.requests.updateUsage(requestId, usage);
4623
5243
  }
@@ -4712,7 +5332,7 @@ class DatabaseOperations {
4712
5332
  checkpointWal() {
4713
5333
  this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
4714
5334
  }
4715
- compact(freeBytes = freeDiskBytes(dirname2(this.dbPath))) {
5335
+ compact(freeBytes = freeDiskBytes(dirname3(this.dbPath))) {
4716
5336
  this.checkpointWal();
4717
5337
  const requiredBytes = 2 * this.liveDataBytes();
4718
5338
  if (freeBytes < requiredBytes) {
@@ -5345,7 +5965,8 @@ async function handleEnd(msg) {
5345
5965
  timestamp: startMessage.timestamp,
5346
5966
  payload,
5347
5967
  storePayload: startMessage.storePayload,
5348
- timings
5968
+ timings,
5969
+ callerId: startMessage.callerId
5349
5970
  }));
5350
5971
  if (state.usage.model && startMessage.accountId !== null) {
5351
5972
  log7.info(`Usage for request ${startMessage.requestId}: Model: ${state.usage.model}, ` + `Tokens: ${state.usage.totalTokens || 0}, Cost: ${formatCost(state.usage.costUsd)}`);