@certalis/agent-smith 0.1.18 → 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 === "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
  }
@@ -1718,6 +1988,12 @@ function sanitizeTeamRouting(value) {
1718
1988
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1719
1989
  }
1720
1990
  }
1991
+ if (isRecord(value.caller_provider_fallback)) {
1992
+ const entries = Object.entries(value.caller_provider_fallback);
1993
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
1994
+ result.caller_provider_fallback = Object.fromEntries(entries);
1995
+ }
1996
+ }
1721
1997
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1722
1998
  result.admission_cap = Math.floor(value.admission_cap);
1723
1999
  }
@@ -1738,13 +2014,105 @@ function sanitizeTeamRouting(value) {
1738
2014
  result.window_warmup = windowWarmup;
1739
2015
  return result;
1740
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
+ }
1741
2108
  function readClientRouting(configPath = resolveConfigPath()) {
1742
2109
  let data;
1743
2110
  try {
1744
- data = JSON.parse(readFileSync(configPath, "utf8"));
2111
+ data = JSON.parse(readFileSync2(configPath, "utf8"));
1745
2112
  } catch {
1746
2113
  throw new Error("Agent Smith client config could not be read");
1747
2114
  }
2115
+ data = migrateLegacyConfig(configPath, data);
1748
2116
  if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1749
2117
  throw new Error("Agent Smith client config is invalid");
1750
2118
  }
@@ -1759,34 +2127,35 @@ function clientRouting(client) {
1759
2127
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1760
2128
  };
1761
2129
  }
1762
- 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;
1763
2131
  var init_src4 = __esm(() => {
1764
2132
  init_src2();
1765
2133
  init_src3();
1766
2134
  init_src();
2135
+ init_builtin_providers();
1767
2136
  init_paths();
2137
+ init_rewrite_file();
1768
2138
  init_window_warmup();
1769
2139
  init_paths();
1770
2140
  init_paths_common();
2141
+ init_rewrite_config();
2142
+ init_rewrite_file();
1771
2143
  init_window_warmup();
1772
2144
  log2 = new Logger("Config");
1773
2145
  PROVIDER_STRATEGIES = [
1774
2146
  "anthropic-api",
2147
+ "model-studio-anthropic-api",
2148
+ "kimi-code-anthropic-api",
2149
+ "google-gemini-api",
1775
2150
  "openai-api",
1776
2151
  "claude-code",
1777
2152
  "codex"
1778
2153
  ];
1779
- BUILTIN_PROVIDER_CONFIGS = [
1780
- { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1781
- { name: "openai", enabled: true, strategy: "openai-api" },
1782
- { name: "claude-code", enabled: false, strategy: "claude-code" },
1783
- { name: "codex", enabled: false, strategy: "codex" }
1784
- ];
1785
2154
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1786
2155
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1787
2156
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1788
2157
  CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1789
- TEAM_ROUTING_DEFAULTS = {
2158
+ POOL_DEFAULTS = {
1790
2159
  enabled: false,
1791
2160
  distributionEnabled: true,
1792
2161
  preferExpiringQuota: false,
@@ -1798,9 +2167,9 @@ var init_src4 = __esm(() => {
1798
2167
  admissionCap: 5,
1799
2168
  admissionQueueLimit: 25,
1800
2169
  admissionWaitMs: 30000,
1801
- holdSeconds: 0,
1802
2170
  quotaProbeSeconds: 0,
1803
- windowWarmup: WINDOW_WARMUP_DEFAULTS
2171
+ windowWarmup: WINDOW_WARMUP_DEFAULTS,
2172
+ blockWhenAllFull: true
1804
2173
  };
1805
2174
  Config = class Config extends EventEmitter3 {
1806
2175
  configPath;
@@ -1812,20 +2181,23 @@ var init_src4 = __esm(() => {
1812
2181
  }
1813
2182
  loadConfig() {
1814
2183
  if (existsSync2(this.configPath)) {
2184
+ let parsed;
1815
2185
  try {
1816
- const content = readFileSync(this.configPath, "utf8");
1817
- this.data = sanitizeConfigData(JSON.parse(content));
2186
+ const content = readFileSync2(this.configPath, "utf8");
2187
+ parsed = JSON.parse(content);
1818
2188
  } catch (error) {
1819
2189
  log2.error(`Failed to parse config file: ${error}`);
1820
2190
  this.data = {};
1821
2191
  return;
1822
2192
  }
2193
+ parsed = migrateLegacyConfig(this.configPath, parsed);
2194
+ this.data = sanitizeConfigData(parsed);
1823
2195
  try {
1824
2196
  chmodSync(this.configPath, 384);
1825
2197
  } catch {
1826
2198
  let ownerOnly = false;
1827
2199
  try {
1828
- ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
2200
+ ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
1829
2201
  } catch {}
1830
2202
  if (!ownerOnly) {
1831
2203
  throw new Error("Config file must be owner-only");
@@ -1836,7 +2208,7 @@ var init_src4 = __esm(() => {
1836
2208
  this.saveConfig();
1837
2209
  }
1838
2210
  } else {
1839
- const dir = dirname(this.configPath);
2211
+ const dir = dirname2(this.configPath);
1840
2212
  mkdirSync2(dir, { recursive: true, mode: 448 });
1841
2213
  chmodSync(dir, 448);
1842
2214
  this.data = {
@@ -1855,11 +2227,11 @@ var init_src4 = __esm(() => {
1855
2227
  writePrivately(data) {
1856
2228
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1857
2229
  try {
1858
- writeFileSync(temporary, JSON.stringify(data, null, 2), {
2230
+ writeFileSync2(temporary, JSON.stringify(data, null, 2), {
1859
2231
  mode: 384,
1860
2232
  flag: "wx"
1861
2233
  });
1862
- renameSync(temporary, this.configPath);
2234
+ renameSync2(temporary, this.configPath);
1863
2235
  } finally {
1864
2236
  rmSync(temporary, { force: true });
1865
2237
  }
@@ -1945,25 +2317,35 @@ var init_src4 = __esm(() => {
1945
2317
  request_retention_days: this.getRequestRetentionDays()
1946
2318
  };
1947
2319
  }
1948
- getTeamRouting() {
1949
- 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;
1950
2334
  return {
1951
- enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1952
- distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1953
- preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
1954
- allowlistedAccountUuids: [
1955
- ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1956
- ],
1957
- maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1958
- weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1959
- weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1960
- callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1961
- admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1962
- admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1963
- admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1964
- holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1965
- quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
1966
- 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
1967
2349
  };
1968
2350
  }
1969
2351
  getAlerts() {
@@ -1983,9 +2365,6 @@ var init_src4 = __esm(() => {
1983
2365
  setClientRoutingEnabled(enabled) {
1984
2366
  this.persistStrictly("client", { ...this.data.client, enabled });
1985
2367
  }
1986
- getBlockWhenAllFull() {
1987
- return this.data.block_when_all_full !== false;
1988
- }
1989
2368
  getProviderConfig(name) {
1990
2369
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1991
2370
  const configured = this.data.providers?.[name];
@@ -1996,11 +2375,12 @@ var init_src4 = __esm(() => {
1996
2375
  enabled: configured?.enabled ?? builtin?.enabled ?? true,
1997
2376
  strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
1998
2377
  ...configured?.base_url && { baseUrl: configured.base_url },
1999
- ...configured?.models && { models: { ...configured.models } }
2378
+ ...configured?.models && { models: { ...configured.models } },
2379
+ ...configured?.pool && { pool: structuredClone(configured.pool) }
2000
2380
  };
2001
2381
  }
2002
2382
  getProviderPool(wire) {
2003
- return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
2383
+ return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
2004
2384
  const provider = this.getProviderConfig(name);
2005
2385
  return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
2006
2386
  });
@@ -2015,68 +2395,96 @@ var init_src4 = __esm(() => {
2015
2395
  }
2016
2396
  return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
2017
2397
  }
2018
- setTeamRouting(value) {
2019
- if (!isRecord(value)) {
2020
- throw new Error("team routing configuration must be an object");
2021
- }
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");
2022
2413
  const allowed = new Set([
2023
2414
  "enabled",
2415
+ "members",
2024
2416
  "distribution_enabled",
2025
2417
  "prefer_expiring_quota",
2026
- "allowlisted_account_uuids",
2027
2418
  "max_usage",
2028
2419
  "weekly_max_usage",
2029
2420
  "weekly_max_usage_by_email",
2030
2421
  "caller_weekly_max_usage",
2031
- "admission_cap",
2032
- "admission_queue_limit",
2033
- "admission_wait_ms",
2034
- "hold_seconds",
2422
+ "admission",
2035
2423
  "quota_probe_seconds",
2036
- "window_warmup"
2424
+ "window_warmup",
2425
+ "block_when_all_full"
2037
2426
  ]);
2038
- if (Object.keys(value).some((key) => !allowed.has(key))) {
2039
- throw new Error("team routing configuration contains an unknown field");
2040
- }
2041
- const sanitized = sanitizeTeamRouting(value);
2042
- if (!sanitized) {
2043
- throw new Error("team routing configuration must be an object");
2044
- }
2045
- for (const key of Object.keys(value)) {
2046
- if (!(key in sanitized)) {
2047
- 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 }
2048
2443
  }
2049
- }
2050
- const oldValue = this.data.team_routing;
2051
- if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
2052
- sanitized.weekly_max_usage_by_email = {
2053
- ...oldValue.weekly_max_usage_by_email
2054
- };
2055
- }
2056
- if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2057
- sanitized.caller_weekly_max_usage = {
2058
- ...oldValue.caller_weekly_max_usage
2059
- };
2060
- }
2061
- this.persistStrictly("team_routing", sanitized);
2444
+ });
2062
2445
  }
2063
- allowAccountUuid(accountUuid) {
2064
- 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;
2065
2476
  if (current.includes(accountUuid))
2066
2477
  return;
2067
- this.persistAccountAllowlist([...current, accountUuid]);
2478
+ this.persistAccountAllowlist(provider, [...current, accountUuid]);
2068
2479
  }
2069
- removeAccountUuid(accountUuid) {
2070
- const current = this.getTeamRouting().allowlistedAccountUuids;
2480
+ removeAccountUuid(provider, accountUuid) {
2481
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2071
2482
  if (!current.includes(accountUuid))
2072
2483
  return;
2073
- this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
2484
+ this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
2074
2485
  }
2075
- persistAccountAllowlist(accountUuids) {
2076
- this.persistStrictly("team_routing", {
2077
- ...this.data.team_routing,
2078
- allowlisted_account_uuids: accountUuids
2079
- });
2486
+ persistAccountAllowlist(provider, accountUuids) {
2487
+ this.setProviderPool(provider, { members: accountUuids });
2080
2488
  }
2081
2489
  getEnrollmentEmails() {
2082
2490
  return [...this.data.enrollment_emails ?? []];
@@ -2110,7 +2518,6 @@ var init_src4 = __esm(() => {
2110
2518
  }
2111
2519
  getRuntime() {
2112
2520
  const defaults = {
2113
- blockWhenAllFull: this.getBlockWhenAllFull(),
2114
2521
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
2115
2522
  maxBodyBytes: 64 * 1024 * 1024,
2116
2523
  quotaThreshold: 0.98,
@@ -2123,7 +2530,8 @@ var init_src4 = __esm(() => {
2123
2530
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
2124
2531
  port: NETWORK.DEFAULT_PORT,
2125
2532
  storeRequestPayloads: this.storesRequestPayloads(),
2126
- teamRouting: this.getTeamRouting()
2533
+ routing: this.getRouting(),
2534
+ providerPools: this.getProviderPoolSettings()
2127
2535
  };
2128
2536
  if (process.env.AGENT_SMITH_CLIENT_ID) {
2129
2537
  defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
@@ -2193,14 +2601,14 @@ var init_src4 = __esm(() => {
2193
2601
  });
2194
2602
 
2195
2603
  // ../../packages/database/src/paths.ts
2196
- import { join as join5 } from "path";
2604
+ import { join as join6 } from "path";
2197
2605
  function resolveDbPath() {
2198
2606
  const explicitPath = process.env.AGENT_SMITH_DB_PATH;
2199
2607
  if (explicitPath) {
2200
2608
  return explicitPath;
2201
2609
  }
2202
2610
  const configDir = getPlatformConfigDir();
2203
- return join5(configDir, "agent-smith.db");
2611
+ return join6(configDir, "agent-smith.db");
2204
2612
  }
2205
2613
  var init_paths2 = __esm(() => {
2206
2614
  init_src4();
@@ -2883,6 +3291,30 @@ function ensureConversationPinsTable(db) {
2883
3291
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_account ON conversation_pins(account_id)`);
2884
3292
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_last_seen ON conversation_pins(last_seen_at)`);
2885
3293
  }
3294
+ function ensureConversationProviderPreferencesTable(db) {
3295
+ db.run(`
3296
+ CREATE TABLE IF NOT EXISTS conversation_provider_preferences (
3297
+ pin_key TEXT PRIMARY KEY,
3298
+ provider TEXT NOT NULL,
3299
+ promotion_declined INTEGER NOT NULL DEFAULT 0,
3300
+ last_seen_at INTEGER NOT NULL
3301
+ )
3302
+ `);
3303
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_preferences_last_seen ON conversation_provider_preferences(last_seen_at)`);
3304
+ }
3305
+ function ensureConversationProviderBlocksTable(db) {
3306
+ db.run(`
3307
+ CREATE TABLE IF NOT EXISTS conversation_provider_blocks (
3308
+ pin_key TEXT NOT NULL,
3309
+ provider TEXT NOT NULL,
3310
+ category TEXT NOT NULL DEFAULT 'unknown',
3311
+ retry_at INTEGER,
3312
+ last_seen_at INTEGER NOT NULL,
3313
+ PRIMARY KEY (pin_key, provider)
3314
+ )
3315
+ `);
3316
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_blocks_last_seen ON conversation_provider_blocks(last_seen_at)`);
3317
+ }
2886
3318
  function remediateDuplicateAccountNames(db) {
2887
3319
  const accounts = db.query(`
2888
3320
  SELECT id, name, created_at
@@ -3008,6 +3440,8 @@ function ensureSchema(db) {
3008
3440
  `);
3009
3441
  ensureAuthSessionsTable(db);
3010
3442
  ensureConversationPinsTable(db);
3443
+ ensureConversationProviderPreferencesTable(db);
3444
+ ensureConversationProviderBlocksTable(db);
3011
3445
  }
3012
3446
  function runMigrations(db) {
3013
3447
  ensureSchema(db);
@@ -3027,6 +3461,8 @@ function runMigrations(db) {
3027
3461
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
3028
3462
  ensureAuthSessionsTable(db);
3029
3463
  ensureConversationPinsTable(db);
3464
+ ensureConversationProviderPreferencesTable(db);
3465
+ ensureConversationProviderBlocksTable(db);
3030
3466
  ensureAccountsNameUniqueness(db);
3031
3467
  db.run(`CREATE TABLE IF NOT EXISTS enrollment_contacts (
3032
3468
  account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
@@ -3722,6 +4158,85 @@ var init_conversation_pin_repository = __esm(() => {
3722
4158
  };
3723
4159
  });
3724
4160
 
4161
+ // ../../packages/database/src/repositories/conversation-provider-block.repository.ts
4162
+ var ConversationProviderBlockRepository;
4163
+ var init_conversation_provider_block_repository = __esm(() => {
4164
+ ConversationProviderBlockRepository = class ConversationProviderBlockRepository extends BaseRepository {
4165
+ find(pinKey, provider) {
4166
+ const row = this.get(`SELECT category, retry_at, last_seen_at FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
4167
+ return row ? {
4168
+ category: row.category,
4169
+ lastSeenAt: row.last_seen_at,
4170
+ retryAt: row.retry_at ?? undefined
4171
+ } : null;
4172
+ }
4173
+ upsert(pinKey, provider, category, retryAt, lastSeenAt) {
4174
+ this.run(`
4175
+ INSERT INTO conversation_provider_blocks (
4176
+ pin_key, provider, category, retry_at, last_seen_at
4177
+ )
4178
+ VALUES (?, ?, ?, ?, ?)
4179
+ ON CONFLICT(pin_key, provider) DO UPDATE SET
4180
+ category = excluded.category,
4181
+ retry_at = excluded.retry_at,
4182
+ last_seen_at = excluded.last_seen_at
4183
+ `, [pinKey, provider, category, retryAt ?? null, lastSeenAt]);
4184
+ }
4185
+ delete(pinKey, provider) {
4186
+ this.run(`DELETE FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
4187
+ }
4188
+ deleteExpired(before) {
4189
+ this.run(`DELETE FROM conversation_provider_blocks WHERE last_seen_at < ?`, [before]);
4190
+ }
4191
+ deleteForAccount(accountId) {
4192
+ this.run(`
4193
+ DELETE FROM conversation_provider_blocks
4194
+ WHERE pin_key IN (
4195
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
4196
+ )
4197
+ `, [accountId]);
4198
+ }
4199
+ };
4200
+ });
4201
+
4202
+ // ../../packages/database/src/repositories/conversation-provider-preference.repository.ts
4203
+ var ConversationProviderPreferenceRepository;
4204
+ var init_conversation_provider_preference_repository = __esm(() => {
4205
+ ConversationProviderPreferenceRepository = class ConversationProviderPreferenceRepository extends BaseRepository {
4206
+ find(pinKey) {
4207
+ const row = this.get(`SELECT provider, promotion_declined, last_seen_at FROM conversation_provider_preferences WHERE pin_key = ?`, [pinKey]);
4208
+ return row ? {
4209
+ provider: row.provider,
4210
+ promotionDeclined: row.promotion_declined === 1,
4211
+ lastSeenAt: row.last_seen_at
4212
+ } : null;
4213
+ }
4214
+ upsert(pinKey, provider, promotionDeclined, lastSeenAt) {
4215
+ this.run(`
4216
+ INSERT INTO conversation_provider_preferences (
4217
+ pin_key, provider, promotion_declined, last_seen_at
4218
+ )
4219
+ VALUES (?, ?, ?, ?)
4220
+ ON CONFLICT(pin_key) DO UPDATE SET
4221
+ provider = excluded.provider,
4222
+ promotion_declined = excluded.promotion_declined,
4223
+ last_seen_at = excluded.last_seen_at
4224
+ `, [pinKey, provider, promotionDeclined ? 1 : 0, lastSeenAt]);
4225
+ }
4226
+ deleteExpired(before) {
4227
+ this.run(`DELETE FROM conversation_provider_preferences WHERE last_seen_at < ?`, [before]);
4228
+ }
4229
+ deleteForAccount(accountId) {
4230
+ this.run(`
4231
+ DELETE FROM conversation_provider_preferences
4232
+ WHERE pin_key IN (
4233
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
4234
+ )
4235
+ `, [accountId]);
4236
+ }
4237
+ };
4238
+ });
4239
+
3725
4240
  // ../../packages/database/src/models/request-row.ts
3726
4241
  function toRequest(row) {
3727
4242
  return {
@@ -4316,7 +4831,7 @@ var init_strategy_repository = __esm(() => {
4316
4831
  // ../../packages/database/src/database-operations.ts
4317
4832
  import { Database } from "bun:sqlite";
4318
4833
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
4319
- import { dirname as dirname2 } from "path";
4834
+ import { dirname as dirname3 } from "path";
4320
4835
  function freeDiskBytes(directory) {
4321
4836
  const { bavail, bsize } = statfsSync(directory);
4322
4837
  return bavail * bsize;
@@ -4332,12 +4847,14 @@ class DatabaseOperations {
4332
4847
  requests;
4333
4848
  authSessions;
4334
4849
  conversationPins;
4850
+ conversationProviderBlocks;
4851
+ conversationProviderPreferences;
4335
4852
  strategy;
4336
4853
  stats;
4337
4854
  constructor(dbPath) {
4338
4855
  const resolvedPath = dbPath ?? resolveDbPath();
4339
4856
  this.dbPath = resolvedPath;
4340
- const dir = dirname2(resolvedPath);
4857
+ const dir = dirname3(resolvedPath);
4341
4858
  mkdirSync3(dir, { recursive: true });
4342
4859
  this.db = new Database(resolvedPath, { create: true });
4343
4860
  this.db.exec("PRAGMA foreign_keys = ON");
@@ -4351,6 +4868,8 @@ class DatabaseOperations {
4351
4868
  this.requests = new RequestRepository(this.db);
4352
4869
  this.authSessions = new AuthSessionRepository(this.db);
4353
4870
  this.conversationPins = new ConversationPinRepository(this.db);
4871
+ this.conversationProviderBlocks = new ConversationProviderBlockRepository(this.db);
4872
+ this.conversationProviderPreferences = new ConversationProviderPreferenceRepository(this.db);
4354
4873
  this.strategy = new StrategyRepository(this.db);
4355
4874
  this.stats = new StatsRepository(this.db);
4356
4875
  }
@@ -4394,6 +4913,8 @@ class DatabaseOperations {
4394
4913
  return this.accounts.update(accountId, data);
4395
4914
  }
4396
4915
  deleteAccount(accountId) {
4916
+ this.conversationProviderBlocks.deleteForAccount(accountId);
4917
+ this.conversationProviderPreferences.deleteForAccount(accountId);
4397
4918
  this.conversationPins.deleteForAccount(accountId);
4398
4919
  return this.accounts.delete(accountId);
4399
4920
  }
@@ -4408,6 +4929,23 @@ class DatabaseOperations {
4408
4929
  }
4409
4930
  deleteExpiredConversationPins(before) {
4410
4931
  this.conversationPins.deleteExpired(before);
4932
+ this.conversationProviderBlocks.deleteExpired(before);
4933
+ this.conversationProviderPreferences.deleteExpired(before);
4934
+ }
4935
+ getConversationProviderPreference(pinKey) {
4936
+ return this.conversationProviderPreferences.find(pinKey);
4937
+ }
4938
+ upsertConversationProviderPreference(pinKey, provider, promotionDeclined, lastSeenAt) {
4939
+ this.conversationProviderPreferences.upsert(pinKey, provider, promotionDeclined, lastSeenAt);
4940
+ }
4941
+ getConversationProviderBlock(pinKey, provider) {
4942
+ return this.conversationProviderBlocks.find(pinKey, provider);
4943
+ }
4944
+ upsertConversationProviderBlock(pinKey, provider, category, retryAt, lastSeenAt) {
4945
+ this.conversationProviderBlocks.upsert(pinKey, provider, category, retryAt, lastSeenAt);
4946
+ }
4947
+ deleteConversationProviderBlock(pinKey, provider) {
4948
+ this.conversationProviderBlocks.delete(pinKey, provider);
4411
4949
  }
4412
4950
  countAccounts() {
4413
4951
  return this.accounts.count();
@@ -4567,7 +5105,7 @@ class DatabaseOperations {
4567
5105
  checkpointWal() {
4568
5106
  this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
4569
5107
  }
4570
- compact(freeBytes = freeDiskBytes(dirname2(this.dbPath))) {
5108
+ compact(freeBytes = freeDiskBytes(dirname3(this.dbPath))) {
4571
5109
  this.checkpointWal();
4572
5110
  const requiredBytes = 2 * this.liveDataBytes();
4573
5111
  if (freeBytes < requiredBytes) {
@@ -4593,6 +5131,8 @@ var init_database_operations = __esm(() => {
4593
5131
  init_analytics_repository();
4594
5132
  init_auth_session_repository();
4595
5133
  init_conversation_pin_repository();
5134
+ init_conversation_provider_block_repository();
5135
+ init_conversation_provider_preference_repository();
4596
5136
  init_request_repository();
4597
5137
  init_stats_repository();
4598
5138
  init_strategy_repository();