@certalis/agent-smith 0.1.19 → 0.2.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,17 @@ 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
+
1286
1305
  // ../../packages/config/src/paths-common.ts
1287
1306
  import { homedir } from "os";
1288
1307
  import { join as join3 } from "path";
@@ -1313,6 +1332,242 @@ var init_paths = __esm(() => {
1313
1332
  init_paths_common();
1314
1333
  });
1315
1334
 
1335
+ // ../../packages/config/src/rewrite-config.ts
1336
+ function rewriteLegacyConfig(value) {
1337
+ if (!isRecord2(value))
1338
+ throw new Error("Configuration must be a JSON object");
1339
+ const output = structuredClone(value);
1340
+ const hasTeam = Object.hasOwn(output, "team_routing");
1341
+ const hasRoutes = Object.hasOwn(output, "provider_pools");
1342
+ const hasBlockPolicy = Object.hasOwn(output, "block_when_all_full");
1343
+ if (!hasTeam && !hasRoutes && !hasBlockPolicy)
1344
+ return output;
1345
+ if (Object.hasOwn(output, "routing"))
1346
+ throw new Error("Cannot rewrite a config containing both legacy keys and routing");
1347
+ const team = hasTeam ? output.team_routing : {};
1348
+ const routes = hasRoutes ? output.provider_pools : {};
1349
+ if (!isRecord2(team) || !isRecord2(routes))
1350
+ throw new Error("Legacy team_routing and provider_pools must be objects");
1351
+ if (output.providers !== undefined && !isRecord2(output.providers))
1352
+ throw new Error("Legacy providers must be an object");
1353
+ const providers = structuredClone(output.providers ?? {});
1354
+ if (Object.values(providers).some((provider) => !isRecord2(provider) || Object.hasOwn(provider, "pool")))
1355
+ throw new Error("Cannot rewrite invalid providers or existing provider pools");
1356
+ const knownTeamFields = new Set([
1357
+ "enabled",
1358
+ "allowlisted_account_uuids",
1359
+ "distribution_enabled",
1360
+ "prefer_expiring_quota",
1361
+ "max_usage",
1362
+ "weekly_max_usage",
1363
+ "weekly_max_usage_by_email",
1364
+ "caller_weekly_max_usage",
1365
+ "caller_provider_fallback",
1366
+ "admission_cap",
1367
+ "admission_queue_limit",
1368
+ "admission_wait_ms",
1369
+ "hold_seconds",
1370
+ "quota_probe_seconds",
1371
+ "window_warmup"
1372
+ ]);
1373
+ if (Object.keys(team).some((field) => !knownTeamFields.has(field)))
1374
+ throw new Error("Cannot safely rewrite unknown team_routing fields");
1375
+ if (team.enabled !== undefined && typeof team.enabled !== "boolean")
1376
+ throw new Error("Invalid team_routing.enabled");
1377
+ if (hasBlockPolicy && typeof output.block_when_all_full !== "boolean")
1378
+ throw new Error("Invalid block_when_all_full");
1379
+ if (team.caller_provider_fallback !== undefined && (!isRecord2(team.caller_provider_fallback) || Object.values(team.caller_provider_fallback).some((policy) => policy !== "ordered")))
1380
+ throw new Error("Invalid caller_provider_fallback");
1381
+ const enabled = team.enabled === true;
1382
+ const dormantFields = [
1383
+ "allowlisted_account_uuids",
1384
+ "distribution_enabled",
1385
+ "prefer_expiring_quota",
1386
+ "max_usage",
1387
+ "weekly_max_usage",
1388
+ "weekly_max_usage_by_email",
1389
+ "caller_weekly_max_usage",
1390
+ "admission_cap",
1391
+ "admission_queue_limit",
1392
+ "admission_wait_ms",
1393
+ "quota_probe_seconds",
1394
+ "window_warmup"
1395
+ ];
1396
+ const keepPool = enabled || hasBlockPolicy || dormantFields.some((field) => Object.hasOwn(team, field));
1397
+ const callers = {};
1398
+ if (enabled && isRecord2(team.caller_provider_fallback)) {
1399
+ for (const [caller, policy] of Object.entries(team.caller_provider_fallback))
1400
+ if (policy === "ordered")
1401
+ callers[caller] = { allow_fallbacks: true };
1402
+ }
1403
+ const routing = {
1404
+ routes: structuredClone(routes),
1405
+ api_key_accounts: enabled ? "chooser_or_fallback" : "everyone",
1406
+ callers,
1407
+ hold_seconds: typeof team.hold_seconds === "number" ? team.hold_seconds : 0
1408
+ };
1409
+ if (keepPool) {
1410
+ const pool = {
1411
+ ...!enabled && { enabled: false },
1412
+ members: structuredClone(team.allowlisted_account_uuids ?? [])
1413
+ };
1414
+ for (const field of [
1415
+ "distribution_enabled",
1416
+ "prefer_expiring_quota",
1417
+ "max_usage",
1418
+ "weekly_max_usage",
1419
+ "weekly_max_usage_by_email",
1420
+ "caller_weekly_max_usage",
1421
+ "quota_probe_seconds",
1422
+ "window_warmup"
1423
+ ])
1424
+ if (Object.hasOwn(team, field))
1425
+ pool[field] = structuredClone(team[field]);
1426
+ const admission = {};
1427
+ for (const [oldKey, newKey] of [
1428
+ ["admission_cap", "cap"],
1429
+ ["admission_queue_limit", "queue_limit"],
1430
+ ["admission_wait_ms", "wait_ms"]
1431
+ ])
1432
+ if (Object.hasOwn(team, oldKey))
1433
+ admission[newKey] = team[oldKey];
1434
+ if (Object.keys(admission).length)
1435
+ pool.admission = admission;
1436
+ if (hasBlockPolicy)
1437
+ pool.block_when_all_full = output.block_when_all_full;
1438
+ for (const { name } of BUILTIN_PROVIDER_CONFIGS)
1439
+ if (!Object.hasOwn(providers, name))
1440
+ providers[name] = {};
1441
+ for (const [name, entry] of Object.entries(providers)) {
1442
+ if (!isRecord2(entry))
1443
+ throw new Error(`Invalid provider: ${name}`);
1444
+ providers[name] = { ...entry, pool: structuredClone(pool) };
1445
+ }
1446
+ }
1447
+ delete output.team_routing;
1448
+ delete output.provider_pools;
1449
+ delete output.block_when_all_full;
1450
+ output.providers = providers;
1451
+ output.routing = routing;
1452
+ return output;
1453
+ }
1454
+ function isRecord2(value) {
1455
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1456
+ }
1457
+ var init_rewrite_config = __esm(() => {
1458
+ init_builtin_providers();
1459
+ });
1460
+
1461
+ // ../../packages/config/src/rewrite-file.ts
1462
+ import { randomUUID } from "crypto";
1463
+ import {
1464
+ accessSync,
1465
+ constants,
1466
+ linkSync,
1467
+ lstatSync,
1468
+ readFileSync,
1469
+ realpathSync,
1470
+ renameSync,
1471
+ statSync as statSync2,
1472
+ unlinkSync as unlinkSync2,
1473
+ writeFileSync
1474
+ } from "fs";
1475
+ import { basename, dirname, join as join5, resolve } from "path";
1476
+ function hasLegacyConfig(value) {
1477
+ return typeof value === "object" && value !== null && !Array.isArray(value) && ["team_routing", "provider_pools", "block_when_all_full"].some((key) => Object.hasOwn(value, key));
1478
+ }
1479
+ function isFileError(error, code) {
1480
+ return error instanceof Error && "code" in error && error.code === code;
1481
+ }
1482
+ function matchesPrivateBackup(path, expected) {
1483
+ try {
1484
+ const file = lstatSync(path);
1485
+ return file.isFile() && (file.mode & 63) === 0 && (typeof process.getuid !== "function" || file.uid === process.getuid()) && readFileSync(path, "utf8") === expected;
1486
+ } catch {
1487
+ return false;
1488
+ }
1489
+ }
1490
+ function rewriteConfigFile(input, output) {
1491
+ if (output !== undefined && resolve(input) === resolve(output))
1492
+ throw new Error("Input and output must be different files");
1493
+ const destination = realpathSync(input);
1494
+ const initial = statSync2(destination);
1495
+ const original = readFileSync(input, "utf8");
1496
+ const data = JSON.parse(original);
1497
+ const rewritten = rewriteLegacyConfig(data);
1498
+ const result = `${JSON.stringify(rewritten, null, 2)}
1499
+ `;
1500
+ if (output !== undefined) {
1501
+ writeFileSync(output, result, {
1502
+ encoding: "utf8",
1503
+ mode: 384,
1504
+ flag: "wx"
1505
+ });
1506
+ return { changed: true };
1507
+ }
1508
+ if (!hasLegacyConfig(data))
1509
+ return { changed: false };
1510
+ if ((initial.mode & 146) === 0)
1511
+ throw new Error("Config file is read-only");
1512
+ accessSync(destination, constants.W_OK);
1513
+ const token = randomUUID();
1514
+ const backupTemp = join5(dirname(destination), `.${basename(destination)}.${token}.backup.tmp`);
1515
+ const temporary = join5(dirname(destination), `.${basename(destination)}.${token}.tmp`);
1516
+ const state = () => {
1517
+ if (realpathSync(input) !== destination)
1518
+ throw new Error("Config path changed while rewriting");
1519
+ const current = readFileSync(destination, "utf8");
1520
+ if (current === original)
1521
+ return "original";
1522
+ const parsed = JSON.parse(current);
1523
+ if (!hasLegacyConfig(parsed))
1524
+ return "new";
1525
+ throw new Error("Config changed while it was being rewritten");
1526
+ };
1527
+ try {
1528
+ if (state() === "new")
1529
+ return { changed: false };
1530
+ writeFileSync(backupTemp, original, {
1531
+ encoding: "utf8",
1532
+ mode: 384,
1533
+ flag: "wx"
1534
+ });
1535
+ const base = `${destination}.backup`;
1536
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1537
+ let backup = base;
1538
+ for (let attempt = 0;; attempt++) {
1539
+ try {
1540
+ linkSync(backupTemp, backup);
1541
+ break;
1542
+ } catch (error) {
1543
+ if (!isFileError(error, "EEXIST"))
1544
+ throw error;
1545
+ if (matchesPrivateBackup(backup, original))
1546
+ break;
1547
+ backup = `${base}-${stamp}${attempt === 0 ? "" : `-${attempt}`}`;
1548
+ }
1549
+ }
1550
+ writeFileSync(temporary, result, {
1551
+ encoding: "utf8",
1552
+ mode: 384,
1553
+ flag: "wx"
1554
+ });
1555
+ if (state() === "new")
1556
+ return { changed: false };
1557
+ renameSync(temporary, destination);
1558
+ return { changed: true, backup };
1559
+ } finally {
1560
+ for (const path of [backupTemp, temporary]) {
1561
+ try {
1562
+ unlinkSync2(path);
1563
+ } catch {}
1564
+ }
1565
+ }
1566
+ }
1567
+ var init_rewrite_file = __esm(() => {
1568
+ init_rewrite_config();
1569
+ });
1570
+
1316
1571
  // ../../packages/config/src/window-warmup.ts
1317
1572
  function isLocalTimes(value) {
1318
1573
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
@@ -1442,13 +1697,19 @@ import {
1442
1697
  chmodSync,
1443
1698
  existsSync as existsSync2,
1444
1699
  mkdirSync as mkdirSync2,
1445
- readFileSync,
1446
- renameSync,
1700
+ readFileSync as readFileSync2,
1701
+ renameSync as renameSync2,
1447
1702
  rmSync,
1448
- statSync as statSync2,
1449
- writeFileSync
1703
+ statSync as statSync3,
1704
+ writeFileSync as writeFileSync2
1450
1705
  } from "fs";
1451
- import { dirname } from "path";
1706
+ import { dirname as dirname2 } from "path";
1707
+ function runtimeForProvider(runtime, provider) {
1708
+ return {
1709
+ ...runtime,
1710
+ pool: runtime.providerPools[provider] ?? { ...POOL_DEFAULTS }
1711
+ };
1712
+ }
1452
1713
  function parseNumber(value) {
1453
1714
  if (value === undefined) {
1454
1715
  return;
@@ -1508,6 +1769,12 @@ function sanitizeConfigData(value) {
1508
1769
  sanitized.provider_pools = providerPools;
1509
1770
  continue;
1510
1771
  }
1772
+ if (key === "routing") {
1773
+ const routing = sanitizeRouting(entry);
1774
+ if (routing)
1775
+ sanitized.routing = routing;
1776
+ continue;
1777
+ }
1511
1778
  if (key === "client") {
1512
1779
  const client = sanitizeClientRouting(entry);
1513
1780
  if (client)
@@ -1661,6 +1928,9 @@ function sanitizeProviderConfigs(value) {
1661
1928
  const models = sanitizeProviderModels(entry.models);
1662
1929
  if (models)
1663
1930
  provider.models = models;
1931
+ const pool = sanitizeProviderPool(entry.pool);
1932
+ if (pool)
1933
+ provider.pool = pool;
1664
1934
  providers[name] = provider;
1665
1935
  }
1666
1936
  return providers;
@@ -1679,7 +1949,7 @@ function sanitizeProviderPools(value) {
1679
1949
  return pools;
1680
1950
  }
1681
1951
  function wireForStrategy(strategy3) {
1682
- return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1952
+ 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
1953
  }
1684
1954
  function isNonNegativeFiniteNumber(value) {
1685
1955
  return isFiniteNumber(value) && value >= 0;
@@ -1708,7 +1978,7 @@ function sanitizeTeamRouting(value) {
1708
1978
  if (isRecord(value.weekly_max_usage_by_email)) {
1709
1979
  const entries = Object.entries(value.weekly_max_usage_by_email);
1710
1980
  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) {
1981
+ if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1712
1982
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1713
1983
  }
1714
1984
  }
@@ -1744,13 +2014,105 @@ function sanitizeTeamRouting(value) {
1744
2014
  result.window_warmup = windowWarmup;
1745
2015
  return result;
1746
2016
  }
2017
+ function sanitizeProviderPool(value) {
2018
+ if (!isRecord(value))
2019
+ return;
2020
+ const legacy = {
2021
+ ...value,
2022
+ allowlisted_account_uuids: value.members
2023
+ };
2024
+ if (isRecord(value.admission)) {
2025
+ legacy.admission_cap = value.admission.cap;
2026
+ legacy.admission_queue_limit = value.admission.queue_limit;
2027
+ legacy.admission_wait_ms = value.admission.wait_ms;
2028
+ }
2029
+ const sanitized = sanitizeTeamRouting(legacy);
2030
+ if (!sanitized)
2031
+ return;
2032
+ const pool = {};
2033
+ if (typeof value.enabled === "boolean")
2034
+ pool.enabled = value.enabled;
2035
+ if (sanitized.allowlisted_account_uuids)
2036
+ pool.members = sanitized.allowlisted_account_uuids;
2037
+ for (const field of [
2038
+ "distribution_enabled",
2039
+ "prefer_expiring_quota",
2040
+ "max_usage",
2041
+ "weekly_max_usage",
2042
+ "weekly_max_usage_by_email",
2043
+ "caller_weekly_max_usage",
2044
+ "quota_probe_seconds",
2045
+ "window_warmup"
2046
+ ]) {
2047
+ if (sanitized[field] !== undefined)
2048
+ Object.assign(pool, { [field]: sanitized[field] });
2049
+ }
2050
+ if (isRecord(value.admission)) {
2051
+ pool.admission = {
2052
+ ...sanitized.admission_cap !== undefined && {
2053
+ cap: sanitized.admission_cap
2054
+ },
2055
+ ...sanitized.admission_queue_limit !== undefined && {
2056
+ queue_limit: sanitized.admission_queue_limit
2057
+ },
2058
+ ...sanitized.admission_wait_ms !== undefined && {
2059
+ wait_ms: sanitized.admission_wait_ms
2060
+ }
2061
+ };
2062
+ }
2063
+ if (typeof value.block_when_all_full === "boolean")
2064
+ pool.block_when_all_full = value.block_when_all_full;
2065
+ return pool;
2066
+ }
2067
+ function sanitizeRouting(value) {
2068
+ if (!isRecord(value))
2069
+ return;
2070
+ const routing = {};
2071
+ const routes = sanitizeProviderPools(value.routes);
2072
+ if (routes)
2073
+ routing.routes = routes;
2074
+ if (value.api_key_accounts === "everyone" || value.api_key_accounts === "chooser_or_fallback")
2075
+ routing.api_key_accounts = value.api_key_accounts;
2076
+ if (isNonNegativeFiniteNumber(value.hold_seconds))
2077
+ routing.hold_seconds = Math.floor(value.hold_seconds);
2078
+ if (isRecord(value.callers)) {
2079
+ const entries = Object.entries(value.callers);
2080
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, policy]) => CALLER_ID_PATTERN.test(caller) && isRecord(policy) && typeof policy.allow_fallbacks === "boolean")) {
2081
+ routing.callers = Object.fromEntries(entries.map(([caller, policy]) => [
2082
+ caller,
2083
+ {
2084
+ allow_fallbacks: policy.allow_fallbacks
2085
+ }
2086
+ ]));
2087
+ }
2088
+ }
2089
+ return routing;
2090
+ }
2091
+ function migrateLegacyConfig(path, parsed) {
2092
+ let current = parsed;
2093
+ for (let attempt = 0;attempt < 3 && hasLegacyConfig(current); attempt++) {
2094
+ try {
2095
+ const result = rewriteConfigFile(path);
2096
+ if (result.changed)
2097
+ log2.info(`Rewrote config ${path}; backup: ${result.backup}`);
2098
+ current = JSON.parse(readFileSync2(path, "utf8"));
2099
+ } catch (error) {
2100
+ const reason = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : String(error);
2101
+ throw new Error(`Could not rewrite legacy config ${path}: ${reason}. Run: agent-smith config rewrite`);
2102
+ }
2103
+ }
2104
+ if (hasLegacyConfig(current))
2105
+ throw new Error(`Config ${path} kept changing while rewriting. Run: agent-smith config rewrite`);
2106
+ return current;
2107
+ }
1747
2108
  function readClientRouting(configPath = resolveConfigPath()) {
1748
2109
  let data;
1749
2110
  try {
1750
- data = JSON.parse(readFileSync(configPath, "utf8"));
2111
+ data = JSON.parse(readFileSync2(configPath, "utf8"));
1751
2112
  } catch {
1752
2113
  throw new Error("Agent Smith client config could not be read");
1753
2114
  }
2115
+ data = migrateLegacyConfig(configPath, data);
1754
2116
  if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1755
2117
  throw new Error("Agent Smith client config is invalid");
1756
2118
  }
@@ -1765,35 +2127,35 @@ function clientRouting(client) {
1765
2127
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1766
2128
  };
1767
2129
  }
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;
2130
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1769
2131
  var init_src4 = __esm(() => {
1770
2132
  init_src2();
1771
2133
  init_src3();
1772
2134
  init_src();
2135
+ init_builtin_providers();
1773
2136
  init_paths();
2137
+ init_rewrite_file();
1774
2138
  init_window_warmup();
1775
2139
  init_paths();
1776
2140
  init_paths_common();
2141
+ init_rewrite_config();
2142
+ init_rewrite_file();
1777
2143
  init_window_warmup();
1778
2144
  log2 = new Logger("Config");
1779
2145
  PROVIDER_STRATEGIES = [
1780
2146
  "anthropic-api",
1781
2147
  "model-studio-anthropic-api",
2148
+ "kimi-code-anthropic-api",
2149
+ "google-gemini-api",
1782
2150
  "openai-api",
1783
2151
  "claude-code",
1784
2152
  "codex"
1785
2153
  ];
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
2154
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1793
2155
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1794
2156
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1795
2157
  CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1796
- TEAM_ROUTING_DEFAULTS = {
2158
+ POOL_DEFAULTS = {
1797
2159
  enabled: false,
1798
2160
  distributionEnabled: true,
1799
2161
  preferExpiringQuota: false,
@@ -1802,13 +2164,12 @@ var init_src4 = __esm(() => {
1802
2164
  weeklyMaxUsage: 0.95,
1803
2165
  weeklyMaxUsageByEmail: {},
1804
2166
  callerWeeklyMaxUsage: {},
1805
- callerProviderFallback: {},
1806
2167
  admissionCap: 5,
1807
2168
  admissionQueueLimit: 25,
1808
2169
  admissionWaitMs: 30000,
1809
- holdSeconds: 0,
1810
2170
  quotaProbeSeconds: 0,
1811
- windowWarmup: WINDOW_WARMUP_DEFAULTS
2171
+ windowWarmup: WINDOW_WARMUP_DEFAULTS,
2172
+ blockWhenAllFull: true
1812
2173
  };
1813
2174
  Config = class Config extends EventEmitter3 {
1814
2175
  configPath;
@@ -1820,20 +2181,23 @@ var init_src4 = __esm(() => {
1820
2181
  }
1821
2182
  loadConfig() {
1822
2183
  if (existsSync2(this.configPath)) {
2184
+ let parsed;
1823
2185
  try {
1824
- const content = readFileSync(this.configPath, "utf8");
1825
- this.data = sanitizeConfigData(JSON.parse(content));
2186
+ const content = readFileSync2(this.configPath, "utf8");
2187
+ parsed = JSON.parse(content);
1826
2188
  } catch (error) {
1827
2189
  log2.error(`Failed to parse config file: ${error}`);
1828
2190
  this.data = {};
1829
2191
  return;
1830
2192
  }
2193
+ parsed = migrateLegacyConfig(this.configPath, parsed);
2194
+ this.data = sanitizeConfigData(parsed);
1831
2195
  try {
1832
2196
  chmodSync(this.configPath, 384);
1833
2197
  } catch {
1834
2198
  let ownerOnly = false;
1835
2199
  try {
1836
- ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
2200
+ ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
1837
2201
  } catch {}
1838
2202
  if (!ownerOnly) {
1839
2203
  throw new Error("Config file must be owner-only");
@@ -1844,7 +2208,7 @@ var init_src4 = __esm(() => {
1844
2208
  this.saveConfig();
1845
2209
  }
1846
2210
  } else {
1847
- const dir = dirname(this.configPath);
2211
+ const dir = dirname2(this.configPath);
1848
2212
  mkdirSync2(dir, { recursive: true, mode: 448 });
1849
2213
  chmodSync(dir, 448);
1850
2214
  this.data = {
@@ -1863,11 +2227,11 @@ var init_src4 = __esm(() => {
1863
2227
  writePrivately(data) {
1864
2228
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1865
2229
  try {
1866
- writeFileSync(temporary, JSON.stringify(data, null, 2), {
2230
+ writeFileSync2(temporary, JSON.stringify(data, null, 2), {
1867
2231
  mode: 384,
1868
2232
  flag: "wx"
1869
2233
  });
1870
- renameSync(temporary, this.configPath);
2234
+ renameSync2(temporary, this.configPath);
1871
2235
  } finally {
1872
2236
  rmSync(temporary, { force: true });
1873
2237
  }
@@ -1953,26 +2317,35 @@ var init_src4 = __esm(() => {
1953
2317
  request_retention_days: this.getRequestRetentionDays()
1954
2318
  };
1955
2319
  }
1956
- getTeamRouting() {
1957
- const file = this.data.team_routing;
2320
+ getRouting() {
2321
+ const routing = this.data.routing;
2322
+ return {
2323
+ routes: structuredClone(routing?.routes ?? {}),
2324
+ apiKeyAccounts: routing?.api_key_accounts ?? "everyone",
2325
+ callers: Object.fromEntries(Object.entries(routing?.callers ?? {}).map(([name, policy]) => [
2326
+ name,
2327
+ { allowFallbacks: policy.allow_fallbacks }
2328
+ ])),
2329
+ holdSeconds: routing?.hold_seconds ?? 0
2330
+ };
2331
+ }
2332
+ getTeamRouting(providerName) {
2333
+ const pool = this.data.providers?.[providerName]?.pool;
1958
2334
  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)
2335
+ enabled: pool !== undefined && pool.enabled !== false,
2336
+ distributionEnabled: pool?.distribution_enabled ?? POOL_DEFAULTS.distributionEnabled,
2337
+ preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2338
+ allowlistedAccountUuids: [...pool?.members ?? []],
2339
+ maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2340
+ weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2341
+ weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2342
+ callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2343
+ admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2344
+ admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2345
+ admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
2346
+ quotaProbeSeconds: pool?.quota_probe_seconds ?? POOL_DEFAULTS.quotaProbeSeconds,
2347
+ windowWarmup: windowWarmupConfig(pool?.window_warmup),
2348
+ blockWhenAllFull: pool?.block_when_all_full !== false
1976
2349
  };
1977
2350
  }
1978
2351
  getAlerts() {
@@ -1992,9 +2365,6 @@ var init_src4 = __esm(() => {
1992
2365
  setClientRoutingEnabled(enabled) {
1993
2366
  this.persistStrictly("client", { ...this.data.client, enabled });
1994
2367
  }
1995
- getBlockWhenAllFull() {
1996
- return this.data.block_when_all_full !== false;
1997
- }
1998
2368
  getProviderConfig(name) {
1999
2369
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
2000
2370
  const configured = this.data.providers?.[name];
@@ -2005,11 +2375,12 @@ var init_src4 = __esm(() => {
2005
2375
  enabled: configured?.enabled ?? builtin?.enabled ?? true,
2006
2376
  strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
2007
2377
  ...configured?.base_url && { baseUrl: configured.base_url },
2008
- ...configured?.models && { models: { ...configured.models } }
2378
+ ...configured?.models && { models: { ...configured.models } },
2379
+ ...configured?.pool && { pool: structuredClone(configured.pool) }
2009
2380
  };
2010
2381
  }
2011
2382
  getProviderPool(wire) {
2012
- return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
2383
+ return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
2013
2384
  const provider = this.getProviderConfig(name);
2014
2385
  return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
2015
2386
  });
@@ -2024,74 +2395,96 @@ var init_src4 = __esm(() => {
2024
2395
  }
2025
2396
  return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
2026
2397
  }
2027
- setTeamRouting(value) {
2028
- if (!isRecord(value)) {
2029
- throw new Error("team routing configuration must be an object");
2030
- }
2398
+ getProviderPoolSettings() {
2399
+ return Object.fromEntries(this.getProviderConfigs().map((provider) => [
2400
+ provider.name,
2401
+ this.getTeamRouting(provider.name)
2402
+ ]));
2403
+ }
2404
+ getProviderPoolConfig(name) {
2405
+ const pool = this.data.providers?.[name]?.pool;
2406
+ return pool ? structuredClone(pool) : undefined;
2407
+ }
2408
+ setProviderPool(name, value) {
2409
+ if (!this.getProviderConfig(name))
2410
+ throw new Error("Unknown provider");
2411
+ if (!isRecord(value))
2412
+ throw new Error("Provider pool configuration must be an object");
2031
2413
  const allowed = new Set([
2032
2414
  "enabled",
2415
+ "members",
2033
2416
  "distribution_enabled",
2034
2417
  "prefer_expiring_quota",
2035
- "allowlisted_account_uuids",
2036
2418
  "max_usage",
2037
2419
  "weekly_max_usage",
2038
2420
  "weekly_max_usage_by_email",
2039
2421
  "caller_weekly_max_usage",
2040
- "caller_provider_fallback",
2041
- "admission_cap",
2042
- "admission_queue_limit",
2043
- "admission_wait_ms",
2044
- "hold_seconds",
2422
+ "admission",
2045
2423
  "quota_probe_seconds",
2046
- "window_warmup"
2424
+ "window_warmup",
2425
+ "block_when_all_full"
2047
2426
  ]);
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}`);
2427
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2428
+ throw new Error("Provider pool contains an unknown field");
2429
+ const sanitized = sanitizeProviderPool(value);
2430
+ if (!sanitized)
2431
+ throw new Error("Invalid provider pool");
2432
+ for (const key of Object.keys(value))
2433
+ if (!(key in sanitized))
2434
+ throw new Error(`Invalid provider pool field: ${key}`);
2435
+ if (isRecord(value.admission) && Object.keys(value.admission).some((key) => !["cap", "queue_limit", "wait_ms"].includes(key) || !(key in (sanitized.admission ?? {}))))
2436
+ throw new Error("Invalid admission field");
2437
+ const old = this.getProviderPoolConfig(name) ?? { enabled: false };
2438
+ this.persistStrictly("providers", {
2439
+ ...this.data.providers,
2440
+ [name]: {
2441
+ ...this.data.providers?.[name],
2442
+ pool: { ...old, ...sanitized }
2058
2443
  }
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);
2444
+ });
2077
2445
  }
2078
- allowAccountUuid(accountUuid) {
2079
- const current = this.getTeamRouting().allowlistedAccountUuids;
2446
+ removeProviderPool(name) {
2447
+ const provider = this.data.providers?.[name];
2448
+ if (!provider?.pool)
2449
+ return;
2450
+ const { pool: _pool, ...rest } = provider;
2451
+ this.persistStrictly("providers", { ...this.data.providers, [name]: rest });
2452
+ }
2453
+ setRouting(value) {
2454
+ if (!isRecord(value))
2455
+ throw new Error("Routing configuration must be an object");
2456
+ const allowed = new Set([
2457
+ "routes",
2458
+ "api_key_accounts",
2459
+ "callers",
2460
+ "hold_seconds"
2461
+ ]);
2462
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2463
+ throw new Error("Routing contains an unknown field");
2464
+ const sanitized = sanitizeRouting(value);
2465
+ if (!sanitized)
2466
+ throw new Error("Invalid routing configuration");
2467
+ for (const key of Object.keys(value))
2468
+ if (!(key in sanitized))
2469
+ throw new Error(`Invalid routing field: ${key}`);
2470
+ 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)))))
2471
+ throw new Error("Invalid routing field: routes");
2472
+ this.persistStrictly("routing", { ...this.data.routing, ...sanitized });
2473
+ }
2474
+ allowAccountUuid(provider, accountUuid) {
2475
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2080
2476
  if (current.includes(accountUuid))
2081
2477
  return;
2082
- this.persistAccountAllowlist([...current, accountUuid]);
2478
+ this.persistAccountAllowlist(provider, [...current, accountUuid]);
2083
2479
  }
2084
- removeAccountUuid(accountUuid) {
2085
- const current = this.getTeamRouting().allowlistedAccountUuids;
2480
+ removeAccountUuid(provider, accountUuid) {
2481
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2086
2482
  if (!current.includes(accountUuid))
2087
2483
  return;
2088
- this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
2484
+ this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
2089
2485
  }
2090
- persistAccountAllowlist(accountUuids) {
2091
- this.persistStrictly("team_routing", {
2092
- ...this.data.team_routing,
2093
- allowlisted_account_uuids: accountUuids
2094
- });
2486
+ persistAccountAllowlist(provider, accountUuids) {
2487
+ this.setProviderPool(provider, { members: accountUuids });
2095
2488
  }
2096
2489
  getEnrollmentEmails() {
2097
2490
  return [...this.data.enrollment_emails ?? []];
@@ -2125,7 +2518,6 @@ var init_src4 = __esm(() => {
2125
2518
  }
2126
2519
  getRuntime() {
2127
2520
  const defaults = {
2128
- blockWhenAllFull: this.getBlockWhenAllFull(),
2129
2521
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
2130
2522
  maxBodyBytes: 64 * 1024 * 1024,
2131
2523
  quotaThreshold: 0.98,
@@ -2138,7 +2530,8 @@ var init_src4 = __esm(() => {
2138
2530
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
2139
2531
  port: NETWORK.DEFAULT_PORT,
2140
2532
  storeRequestPayloads: this.storesRequestPayloads(),
2141
- teamRouting: this.getTeamRouting()
2533
+ routing: this.getRouting(),
2534
+ providerPools: this.getProviderPoolSettings()
2142
2535
  };
2143
2536
  if (process.env.AGENT_SMITH_CLIENT_ID) {
2144
2537
  defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
@@ -2208,14 +2601,14 @@ var init_src4 = __esm(() => {
2208
2601
  });
2209
2602
 
2210
2603
  // ../../packages/database/src/paths.ts
2211
- import { join as join5 } from "path";
2604
+ import { join as join6 } from "path";
2212
2605
  function resolveDbPath() {
2213
2606
  const explicitPath = process.env.AGENT_SMITH_DB_PATH;
2214
2607
  if (explicitPath) {
2215
2608
  return explicitPath;
2216
2609
  }
2217
2610
  const configDir = getPlatformConfigDir();
2218
- return join5(configDir, "agent-smith.db");
2611
+ return join6(configDir, "agent-smith.db");
2219
2612
  }
2220
2613
  var init_paths2 = __esm(() => {
2221
2614
  init_src4();
@@ -4438,7 +4831,7 @@ var init_strategy_repository = __esm(() => {
4438
4831
  // ../../packages/database/src/database-operations.ts
4439
4832
  import { Database } from "bun:sqlite";
4440
4833
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
4441
- import { dirname as dirname2 } from "path";
4834
+ import { dirname as dirname3 } from "path";
4442
4835
  function freeDiskBytes(directory) {
4443
4836
  const { bavail, bsize } = statfsSync(directory);
4444
4837
  return bavail * bsize;
@@ -4461,7 +4854,7 @@ class DatabaseOperations {
4461
4854
  constructor(dbPath) {
4462
4855
  const resolvedPath = dbPath ?? resolveDbPath();
4463
4856
  this.dbPath = resolvedPath;
4464
- const dir = dirname2(resolvedPath);
4857
+ const dir = dirname3(resolvedPath);
4465
4858
  mkdirSync3(dir, { recursive: true });
4466
4859
  this.db = new Database(resolvedPath, { create: true });
4467
4860
  this.db.exec("PRAGMA foreign_keys = ON");
@@ -4712,7 +5105,7 @@ class DatabaseOperations {
4712
5105
  checkpointWal() {
4713
5106
  this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
4714
5107
  }
4715
- compact(freeBytes = freeDiskBytes(dirname2(this.dbPath))) {
5108
+ compact(freeBytes = freeDiskBytes(dirname3(this.dbPath))) {
4716
5109
  this.checkpointWal();
4717
5110
  const requiredBytes = 2 * this.liveDataBytes();
4718
5111
  if (freeBytes < requiredBytes) {