@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",
@@ -1230,6 +1238,17 @@ var init_src3 = __esm(() => {
1230
1238
  log = new Logger;
1231
1239
  });
1232
1240
 
1241
+ // ../../packages/config/src/builtin-providers.ts
1242
+ var BUILTIN_PROVIDER_CONFIGS;
1243
+ var init_builtin_providers = __esm(() => {
1244
+ BUILTIN_PROVIDER_CONFIGS = [
1245
+ { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1246
+ { name: "openai", enabled: true, strategy: "openai-api" },
1247
+ { name: "claude-code", enabled: false, strategy: "claude-code" },
1248
+ { name: "codex", enabled: false, strategy: "codex" }
1249
+ ];
1250
+ });
1251
+
1233
1252
  // ../../packages/config/src/paths-common.ts
1234
1253
  import { homedir } from "os";
1235
1254
  import { join as join3 } from "path";
@@ -1260,6 +1279,242 @@ var init_paths = __esm(() => {
1260
1279
  init_paths_common();
1261
1280
  });
1262
1281
 
1282
+ // ../../packages/config/src/rewrite-config.ts
1283
+ function rewriteLegacyConfig(value) {
1284
+ if (!isRecord2(value))
1285
+ throw new Error("Configuration must be a JSON object");
1286
+ const output = structuredClone(value);
1287
+ const hasTeam = Object.hasOwn(output, "team_routing");
1288
+ const hasRoutes = Object.hasOwn(output, "provider_pools");
1289
+ const hasBlockPolicy = Object.hasOwn(output, "block_when_all_full");
1290
+ if (!hasTeam && !hasRoutes && !hasBlockPolicy)
1291
+ return output;
1292
+ if (Object.hasOwn(output, "routing"))
1293
+ throw new Error("Cannot rewrite a config containing both legacy keys and routing");
1294
+ const team = hasTeam ? output.team_routing : {};
1295
+ const routes = hasRoutes ? output.provider_pools : {};
1296
+ if (!isRecord2(team) || !isRecord2(routes))
1297
+ throw new Error("Legacy team_routing and provider_pools must be objects");
1298
+ if (output.providers !== undefined && !isRecord2(output.providers))
1299
+ throw new Error("Legacy providers must be an object");
1300
+ const providers = structuredClone(output.providers ?? {});
1301
+ if (Object.values(providers).some((provider) => !isRecord2(provider) || Object.hasOwn(provider, "pool")))
1302
+ throw new Error("Cannot rewrite invalid providers or existing provider pools");
1303
+ const knownTeamFields = new Set([
1304
+ "enabled",
1305
+ "allowlisted_account_uuids",
1306
+ "distribution_enabled",
1307
+ "prefer_expiring_quota",
1308
+ "max_usage",
1309
+ "weekly_max_usage",
1310
+ "weekly_max_usage_by_email",
1311
+ "caller_weekly_max_usage",
1312
+ "caller_provider_fallback",
1313
+ "admission_cap",
1314
+ "admission_queue_limit",
1315
+ "admission_wait_ms",
1316
+ "hold_seconds",
1317
+ "quota_probe_seconds",
1318
+ "window_warmup"
1319
+ ]);
1320
+ if (Object.keys(team).some((field) => !knownTeamFields.has(field)))
1321
+ throw new Error("Cannot safely rewrite unknown team_routing fields");
1322
+ if (team.enabled !== undefined && typeof team.enabled !== "boolean")
1323
+ throw new Error("Invalid team_routing.enabled");
1324
+ if (hasBlockPolicy && typeof output.block_when_all_full !== "boolean")
1325
+ throw new Error("Invalid block_when_all_full");
1326
+ if (team.caller_provider_fallback !== undefined && (!isRecord2(team.caller_provider_fallback) || Object.values(team.caller_provider_fallback).some((policy) => policy !== "ordered")))
1327
+ throw new Error("Invalid caller_provider_fallback");
1328
+ const enabled = team.enabled === true;
1329
+ const dormantFields = [
1330
+ "allowlisted_account_uuids",
1331
+ "distribution_enabled",
1332
+ "prefer_expiring_quota",
1333
+ "max_usage",
1334
+ "weekly_max_usage",
1335
+ "weekly_max_usage_by_email",
1336
+ "caller_weekly_max_usage",
1337
+ "admission_cap",
1338
+ "admission_queue_limit",
1339
+ "admission_wait_ms",
1340
+ "quota_probe_seconds",
1341
+ "window_warmup"
1342
+ ];
1343
+ const keepPool = enabled || hasBlockPolicy || dormantFields.some((field) => Object.hasOwn(team, field));
1344
+ const callers = {};
1345
+ if (enabled && isRecord2(team.caller_provider_fallback)) {
1346
+ for (const [caller, policy] of Object.entries(team.caller_provider_fallback))
1347
+ if (policy === "ordered")
1348
+ callers[caller] = { allow_fallbacks: true };
1349
+ }
1350
+ const routing = {
1351
+ routes: structuredClone(routes),
1352
+ api_key_accounts: enabled ? "chooser_or_fallback" : "everyone",
1353
+ callers,
1354
+ hold_seconds: typeof team.hold_seconds === "number" ? team.hold_seconds : 0
1355
+ };
1356
+ if (keepPool) {
1357
+ const pool = {
1358
+ ...!enabled && { enabled: false },
1359
+ members: structuredClone(team.allowlisted_account_uuids ?? [])
1360
+ };
1361
+ for (const field of [
1362
+ "distribution_enabled",
1363
+ "prefer_expiring_quota",
1364
+ "max_usage",
1365
+ "weekly_max_usage",
1366
+ "weekly_max_usage_by_email",
1367
+ "caller_weekly_max_usage",
1368
+ "quota_probe_seconds",
1369
+ "window_warmup"
1370
+ ])
1371
+ if (Object.hasOwn(team, field))
1372
+ pool[field] = structuredClone(team[field]);
1373
+ const admission = {};
1374
+ for (const [oldKey, newKey] of [
1375
+ ["admission_cap", "cap"],
1376
+ ["admission_queue_limit", "queue_limit"],
1377
+ ["admission_wait_ms", "wait_ms"]
1378
+ ])
1379
+ if (Object.hasOwn(team, oldKey))
1380
+ admission[newKey] = team[oldKey];
1381
+ if (Object.keys(admission).length)
1382
+ pool.admission = admission;
1383
+ if (hasBlockPolicy)
1384
+ pool.block_when_all_full = output.block_when_all_full;
1385
+ for (const { name } of BUILTIN_PROVIDER_CONFIGS)
1386
+ if (!Object.hasOwn(providers, name))
1387
+ providers[name] = {};
1388
+ for (const [name, entry] of Object.entries(providers)) {
1389
+ if (!isRecord2(entry))
1390
+ throw new Error(`Invalid provider: ${name}`);
1391
+ providers[name] = { ...entry, pool: structuredClone(pool) };
1392
+ }
1393
+ }
1394
+ delete output.team_routing;
1395
+ delete output.provider_pools;
1396
+ delete output.block_when_all_full;
1397
+ output.providers = providers;
1398
+ output.routing = routing;
1399
+ return output;
1400
+ }
1401
+ function isRecord2(value) {
1402
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1403
+ }
1404
+ var init_rewrite_config = __esm(() => {
1405
+ init_builtin_providers();
1406
+ });
1407
+
1408
+ // ../../packages/config/src/rewrite-file.ts
1409
+ import { randomUUID } from "crypto";
1410
+ import {
1411
+ accessSync,
1412
+ constants,
1413
+ linkSync,
1414
+ lstatSync,
1415
+ readFileSync,
1416
+ realpathSync,
1417
+ renameSync,
1418
+ statSync as statSync2,
1419
+ unlinkSync as unlinkSync2,
1420
+ writeFileSync
1421
+ } from "fs";
1422
+ import { basename, dirname, join as join5, resolve } from "path";
1423
+ function hasLegacyConfig(value) {
1424
+ return typeof value === "object" && value !== null && !Array.isArray(value) && ["team_routing", "provider_pools", "block_when_all_full"].some((key) => Object.hasOwn(value, key));
1425
+ }
1426
+ function isFileError(error, code) {
1427
+ return error instanceof Error && "code" in error && error.code === code;
1428
+ }
1429
+ function matchesPrivateBackup(path, expected) {
1430
+ try {
1431
+ const file = lstatSync(path);
1432
+ return file.isFile() && (file.mode & 63) === 0 && (typeof process.getuid !== "function" || file.uid === process.getuid()) && readFileSync(path, "utf8") === expected;
1433
+ } catch {
1434
+ return false;
1435
+ }
1436
+ }
1437
+ function rewriteConfigFile(input, output) {
1438
+ if (output !== undefined && resolve(input) === resolve(output))
1439
+ throw new Error("Input and output must be different files");
1440
+ const destination = realpathSync(input);
1441
+ const initial = statSync2(destination);
1442
+ const original = readFileSync(input, "utf8");
1443
+ const data = JSON.parse(original);
1444
+ const rewritten = rewriteLegacyConfig(data);
1445
+ const result = `${JSON.stringify(rewritten, null, 2)}
1446
+ `;
1447
+ if (output !== undefined) {
1448
+ writeFileSync(output, result, {
1449
+ encoding: "utf8",
1450
+ mode: 384,
1451
+ flag: "wx"
1452
+ });
1453
+ return { changed: true };
1454
+ }
1455
+ if (!hasLegacyConfig(data))
1456
+ return { changed: false };
1457
+ if ((initial.mode & 146) === 0)
1458
+ throw new Error("Config file is read-only");
1459
+ accessSync(destination, constants.W_OK);
1460
+ const token = randomUUID();
1461
+ const backupTemp = join5(dirname(destination), `.${basename(destination)}.${token}.backup.tmp`);
1462
+ const temporary = join5(dirname(destination), `.${basename(destination)}.${token}.tmp`);
1463
+ const state = () => {
1464
+ if (realpathSync(input) !== destination)
1465
+ throw new Error("Config path changed while rewriting");
1466
+ const current = readFileSync(destination, "utf8");
1467
+ if (current === original)
1468
+ return "original";
1469
+ const parsed = JSON.parse(current);
1470
+ if (!hasLegacyConfig(parsed))
1471
+ return "new";
1472
+ throw new Error("Config changed while it was being rewritten");
1473
+ };
1474
+ try {
1475
+ if (state() === "new")
1476
+ return { changed: false };
1477
+ writeFileSync(backupTemp, original, {
1478
+ encoding: "utf8",
1479
+ mode: 384,
1480
+ flag: "wx"
1481
+ });
1482
+ const base = `${destination}.backup`;
1483
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1484
+ let backup = base;
1485
+ for (let attempt = 0;; attempt++) {
1486
+ try {
1487
+ linkSync(backupTemp, backup);
1488
+ break;
1489
+ } catch (error) {
1490
+ if (!isFileError(error, "EEXIST"))
1491
+ throw error;
1492
+ if (matchesPrivateBackup(backup, original))
1493
+ break;
1494
+ backup = `${base}-${stamp}${attempt === 0 ? "" : `-${attempt}`}`;
1495
+ }
1496
+ }
1497
+ writeFileSync(temporary, result, {
1498
+ encoding: "utf8",
1499
+ mode: 384,
1500
+ flag: "wx"
1501
+ });
1502
+ if (state() === "new")
1503
+ return { changed: false };
1504
+ renameSync(temporary, destination);
1505
+ return { changed: true, backup };
1506
+ } finally {
1507
+ for (const path of [backupTemp, temporary]) {
1508
+ try {
1509
+ unlinkSync2(path);
1510
+ } catch {}
1511
+ }
1512
+ }
1513
+ }
1514
+ var init_rewrite_file = __esm(() => {
1515
+ init_rewrite_config();
1516
+ });
1517
+
1263
1518
  // ../../packages/config/src/window-warmup.ts
1264
1519
  function isLocalTimes(value) {
1265
1520
  return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
@@ -1389,13 +1644,19 @@ import {
1389
1644
  chmodSync,
1390
1645
  existsSync as existsSync2,
1391
1646
  mkdirSync as mkdirSync2,
1392
- readFileSync,
1393
- renameSync,
1647
+ readFileSync as readFileSync2,
1648
+ renameSync as renameSync2,
1394
1649
  rmSync,
1395
- statSync as statSync2,
1396
- writeFileSync
1650
+ statSync as statSync3,
1651
+ writeFileSync as writeFileSync2
1397
1652
  } from "fs";
1398
- import { dirname } from "path";
1653
+ import { dirname as dirname2 } from "path";
1654
+ function runtimeForProvider(runtime, provider) {
1655
+ return {
1656
+ ...runtime,
1657
+ pool: runtime.providerPools[provider] ?? { ...POOL_DEFAULTS }
1658
+ };
1659
+ }
1399
1660
  function parseNumber(value) {
1400
1661
  if (value === undefined) {
1401
1662
  return;
@@ -1455,6 +1716,12 @@ function sanitizeConfigData(value) {
1455
1716
  sanitized.provider_pools = providerPools;
1456
1717
  continue;
1457
1718
  }
1719
+ if (key === "routing") {
1720
+ const routing = sanitizeRouting(entry);
1721
+ if (routing)
1722
+ sanitized.routing = routing;
1723
+ continue;
1724
+ }
1458
1725
  if (key === "client") {
1459
1726
  const client = sanitizeClientRouting(entry);
1460
1727
  if (client)
@@ -1608,6 +1875,9 @@ function sanitizeProviderConfigs(value) {
1608
1875
  const models = sanitizeProviderModels(entry.models);
1609
1876
  if (models)
1610
1877
  provider.models = models;
1878
+ const pool = sanitizeProviderPool(entry.pool);
1879
+ if (pool)
1880
+ provider.pool = pool;
1611
1881
  providers[name] = provider;
1612
1882
  }
1613
1883
  return providers;
@@ -1626,7 +1896,7 @@ function sanitizeProviderPools(value) {
1626
1896
  return pools;
1627
1897
  }
1628
1898
  function wireForStrategy(strategy3) {
1629
- return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1899
+ 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";
1630
1900
  }
1631
1901
  function isNonNegativeFiniteNumber(value) {
1632
1902
  return isFiniteNumber(value) && value >= 0;
@@ -1655,7 +1925,7 @@ function sanitizeTeamRouting(value) {
1655
1925
  if (isRecord(value.weekly_max_usage_by_email)) {
1656
1926
  const entries = Object.entries(value.weekly_max_usage_by_email);
1657
1927
  const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1658
- if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 0.95) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1928
+ if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 1) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1659
1929
  result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1660
1930
  }
1661
1931
  }
@@ -1691,13 +1961,105 @@ function sanitizeTeamRouting(value) {
1691
1961
  result.window_warmup = windowWarmup;
1692
1962
  return result;
1693
1963
  }
1964
+ function sanitizeProviderPool(value) {
1965
+ if (!isRecord(value))
1966
+ return;
1967
+ const legacy = {
1968
+ ...value,
1969
+ allowlisted_account_uuids: value.members
1970
+ };
1971
+ if (isRecord(value.admission)) {
1972
+ legacy.admission_cap = value.admission.cap;
1973
+ legacy.admission_queue_limit = value.admission.queue_limit;
1974
+ legacy.admission_wait_ms = value.admission.wait_ms;
1975
+ }
1976
+ const sanitized = sanitizeTeamRouting(legacy);
1977
+ if (!sanitized)
1978
+ return;
1979
+ const pool = {};
1980
+ if (typeof value.enabled === "boolean")
1981
+ pool.enabled = value.enabled;
1982
+ if (sanitized.allowlisted_account_uuids)
1983
+ pool.members = sanitized.allowlisted_account_uuids;
1984
+ for (const field of [
1985
+ "distribution_enabled",
1986
+ "prefer_expiring_quota",
1987
+ "max_usage",
1988
+ "weekly_max_usage",
1989
+ "weekly_max_usage_by_email",
1990
+ "caller_weekly_max_usage",
1991
+ "quota_probe_seconds",
1992
+ "window_warmup"
1993
+ ]) {
1994
+ if (sanitized[field] !== undefined)
1995
+ Object.assign(pool, { [field]: sanitized[field] });
1996
+ }
1997
+ if (isRecord(value.admission)) {
1998
+ pool.admission = {
1999
+ ...sanitized.admission_cap !== undefined && {
2000
+ cap: sanitized.admission_cap
2001
+ },
2002
+ ...sanitized.admission_queue_limit !== undefined && {
2003
+ queue_limit: sanitized.admission_queue_limit
2004
+ },
2005
+ ...sanitized.admission_wait_ms !== undefined && {
2006
+ wait_ms: sanitized.admission_wait_ms
2007
+ }
2008
+ };
2009
+ }
2010
+ if (typeof value.block_when_all_full === "boolean")
2011
+ pool.block_when_all_full = value.block_when_all_full;
2012
+ return pool;
2013
+ }
2014
+ function sanitizeRouting(value) {
2015
+ if (!isRecord(value))
2016
+ return;
2017
+ const routing = {};
2018
+ const routes = sanitizeProviderPools(value.routes);
2019
+ if (routes)
2020
+ routing.routes = routes;
2021
+ if (value.api_key_accounts === "everyone" || value.api_key_accounts === "chooser_or_fallback")
2022
+ routing.api_key_accounts = value.api_key_accounts;
2023
+ if (isNonNegativeFiniteNumber(value.hold_seconds))
2024
+ routing.hold_seconds = Math.floor(value.hold_seconds);
2025
+ if (isRecord(value.callers)) {
2026
+ const entries = Object.entries(value.callers);
2027
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, policy]) => CALLER_ID_PATTERN.test(caller) && isRecord(policy) && typeof policy.allow_fallbacks === "boolean")) {
2028
+ routing.callers = Object.fromEntries(entries.map(([caller, policy]) => [
2029
+ caller,
2030
+ {
2031
+ allow_fallbacks: policy.allow_fallbacks
2032
+ }
2033
+ ]));
2034
+ }
2035
+ }
2036
+ return routing;
2037
+ }
2038
+ function migrateLegacyConfig(path, parsed) {
2039
+ let current = parsed;
2040
+ for (let attempt = 0;attempt < 3 && hasLegacyConfig(current); attempt++) {
2041
+ try {
2042
+ const result = rewriteConfigFile(path);
2043
+ if (result.changed)
2044
+ log2.info(`Rewrote config ${path}; backup: ${result.backup}`);
2045
+ current = JSON.parse(readFileSync2(path, "utf8"));
2046
+ } catch (error) {
2047
+ const reason = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : String(error);
2048
+ throw new Error(`Could not rewrite legacy config ${path}: ${reason}. Run: agent-smith config rewrite`);
2049
+ }
2050
+ }
2051
+ if (hasLegacyConfig(current))
2052
+ throw new Error(`Config ${path} kept changing while rewriting. Run: agent-smith config rewrite`);
2053
+ return current;
2054
+ }
1694
2055
  function readClientRouting(configPath = resolveConfigPath()) {
1695
2056
  let data;
1696
2057
  try {
1697
- data = JSON.parse(readFileSync(configPath, "utf8"));
2058
+ data = JSON.parse(readFileSync2(configPath, "utf8"));
1698
2059
  } catch {
1699
2060
  throw new Error("Agent Smith client config could not be read");
1700
2061
  }
2062
+ data = migrateLegacyConfig(configPath, data);
1701
2063
  if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1702
2064
  throw new Error("Agent Smith client config is invalid");
1703
2065
  }
@@ -1712,35 +2074,35 @@ function clientRouting(client) {
1712
2074
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1713
2075
  };
1714
2076
  }
1715
- 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;
2077
+ 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;
1716
2078
  var init_src4 = __esm(() => {
1717
2079
  init_src2();
1718
2080
  init_src3();
1719
2081
  init_src();
2082
+ init_builtin_providers();
1720
2083
  init_paths();
2084
+ init_rewrite_file();
1721
2085
  init_window_warmup();
1722
2086
  init_paths();
1723
2087
  init_paths_common();
2088
+ init_rewrite_config();
2089
+ init_rewrite_file();
1724
2090
  init_window_warmup();
1725
2091
  log2 = new Logger("Config");
1726
2092
  PROVIDER_STRATEGIES = [
1727
2093
  "anthropic-api",
1728
2094
  "model-studio-anthropic-api",
2095
+ "kimi-code-anthropic-api",
2096
+ "google-gemini-api",
1729
2097
  "openai-api",
1730
2098
  "claude-code",
1731
2099
  "codex"
1732
2100
  ];
1733
- BUILTIN_PROVIDER_CONFIGS = [
1734
- { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1735
- { name: "openai", enabled: true, strategy: "openai-api" },
1736
- { name: "claude-code", enabled: false, strategy: "claude-code" },
1737
- { name: "codex", enabled: false, strategy: "codex" }
1738
- ];
1739
2101
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1740
2102
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1741
2103
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1742
2104
  CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1743
- TEAM_ROUTING_DEFAULTS = {
2105
+ POOL_DEFAULTS = {
1744
2106
  enabled: false,
1745
2107
  distributionEnabled: true,
1746
2108
  preferExpiringQuota: false,
@@ -1749,13 +2111,12 @@ var init_src4 = __esm(() => {
1749
2111
  weeklyMaxUsage: 0.95,
1750
2112
  weeklyMaxUsageByEmail: {},
1751
2113
  callerWeeklyMaxUsage: {},
1752
- callerProviderFallback: {},
1753
2114
  admissionCap: 5,
1754
2115
  admissionQueueLimit: 25,
1755
2116
  admissionWaitMs: 30000,
1756
- holdSeconds: 0,
1757
2117
  quotaProbeSeconds: 0,
1758
- windowWarmup: WINDOW_WARMUP_DEFAULTS
2118
+ windowWarmup: WINDOW_WARMUP_DEFAULTS,
2119
+ blockWhenAllFull: true
1759
2120
  };
1760
2121
  Config = class Config extends EventEmitter3 {
1761
2122
  configPath;
@@ -1767,20 +2128,23 @@ var init_src4 = __esm(() => {
1767
2128
  }
1768
2129
  loadConfig() {
1769
2130
  if (existsSync2(this.configPath)) {
2131
+ let parsed;
1770
2132
  try {
1771
- const content = readFileSync(this.configPath, "utf8");
1772
- this.data = sanitizeConfigData(JSON.parse(content));
2133
+ const content = readFileSync2(this.configPath, "utf8");
2134
+ parsed = JSON.parse(content);
1773
2135
  } catch (error) {
1774
2136
  log2.error(`Failed to parse config file: ${error}`);
1775
2137
  this.data = {};
1776
2138
  return;
1777
2139
  }
2140
+ parsed = migrateLegacyConfig(this.configPath, parsed);
2141
+ this.data = sanitizeConfigData(parsed);
1778
2142
  try {
1779
2143
  chmodSync(this.configPath, 384);
1780
2144
  } catch {
1781
2145
  let ownerOnly = false;
1782
2146
  try {
1783
- ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
2147
+ ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
1784
2148
  } catch {}
1785
2149
  if (!ownerOnly) {
1786
2150
  throw new Error("Config file must be owner-only");
@@ -1791,7 +2155,7 @@ var init_src4 = __esm(() => {
1791
2155
  this.saveConfig();
1792
2156
  }
1793
2157
  } else {
1794
- const dir = dirname(this.configPath);
2158
+ const dir = dirname2(this.configPath);
1795
2159
  mkdirSync2(dir, { recursive: true, mode: 448 });
1796
2160
  chmodSync(dir, 448);
1797
2161
  this.data = {
@@ -1810,11 +2174,11 @@ var init_src4 = __esm(() => {
1810
2174
  writePrivately(data) {
1811
2175
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1812
2176
  try {
1813
- writeFileSync(temporary, JSON.stringify(data, null, 2), {
2177
+ writeFileSync2(temporary, JSON.stringify(data, null, 2), {
1814
2178
  mode: 384,
1815
2179
  flag: "wx"
1816
2180
  });
1817
- renameSync(temporary, this.configPath);
2181
+ renameSync2(temporary, this.configPath);
1818
2182
  } finally {
1819
2183
  rmSync(temporary, { force: true });
1820
2184
  }
@@ -1900,26 +2264,35 @@ var init_src4 = __esm(() => {
1900
2264
  request_retention_days: this.getRequestRetentionDays()
1901
2265
  };
1902
2266
  }
1903
- getTeamRouting() {
1904
- const file = this.data.team_routing;
2267
+ getRouting() {
2268
+ const routing = this.data.routing;
1905
2269
  return {
1906
- enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1907
- distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1908
- preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
1909
- allowlistedAccountUuids: [
1910
- ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1911
- ],
1912
- maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1913
- weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1914
- weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1915
- callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1916
- callerProviderFallback: { ...file?.caller_provider_fallback },
1917
- admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1918
- admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1919
- admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1920
- holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1921
- quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
1922
- windowWarmup: windowWarmupConfig(file?.window_warmup)
2270
+ routes: structuredClone(routing?.routes ?? {}),
2271
+ apiKeyAccounts: routing?.api_key_accounts ?? "everyone",
2272
+ callers: Object.fromEntries(Object.entries(routing?.callers ?? {}).map(([name, policy]) => [
2273
+ name,
2274
+ { allowFallbacks: policy.allow_fallbacks }
2275
+ ])),
2276
+ holdSeconds: routing?.hold_seconds ?? 0
2277
+ };
2278
+ }
2279
+ getTeamRouting(providerName) {
2280
+ const pool = this.data.providers?.[providerName]?.pool;
2281
+ return {
2282
+ enabled: pool !== undefined && pool.enabled !== false,
2283
+ distributionEnabled: pool?.distribution_enabled ?? POOL_DEFAULTS.distributionEnabled,
2284
+ preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
2285
+ allowlistedAccountUuids: [...pool?.members ?? []],
2286
+ maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
2287
+ weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
2288
+ weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
2289
+ callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
2290
+ admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
2291
+ admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
2292
+ admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
2293
+ quotaProbeSeconds: pool?.quota_probe_seconds ?? POOL_DEFAULTS.quotaProbeSeconds,
2294
+ windowWarmup: windowWarmupConfig(pool?.window_warmup),
2295
+ blockWhenAllFull: pool?.block_when_all_full !== false
1923
2296
  };
1924
2297
  }
1925
2298
  getAlerts() {
@@ -1939,9 +2312,6 @@ var init_src4 = __esm(() => {
1939
2312
  setClientRoutingEnabled(enabled) {
1940
2313
  this.persistStrictly("client", { ...this.data.client, enabled });
1941
2314
  }
1942
- getBlockWhenAllFull() {
1943
- return this.data.block_when_all_full !== false;
1944
- }
1945
2315
  getProviderConfig(name) {
1946
2316
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1947
2317
  const configured = this.data.providers?.[name];
@@ -1952,11 +2322,12 @@ var init_src4 = __esm(() => {
1952
2322
  enabled: configured?.enabled ?? builtin?.enabled ?? true,
1953
2323
  strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
1954
2324
  ...configured?.base_url && { baseUrl: configured.base_url },
1955
- ...configured?.models && { models: { ...configured.models } }
2325
+ ...configured?.models && { models: { ...configured.models } },
2326
+ ...configured?.pool && { pool: structuredClone(configured.pool) }
1956
2327
  };
1957
2328
  }
1958
2329
  getProviderPool(wire) {
1959
- return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
2330
+ return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
1960
2331
  const provider = this.getProviderConfig(name);
1961
2332
  return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
1962
2333
  });
@@ -1971,74 +2342,96 @@ var init_src4 = __esm(() => {
1971
2342
  }
1972
2343
  return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
1973
2344
  }
1974
- setTeamRouting(value) {
1975
- if (!isRecord(value)) {
1976
- throw new Error("team routing configuration must be an object");
1977
- }
2345
+ getProviderPoolSettings() {
2346
+ return Object.fromEntries(this.getProviderConfigs().map((provider) => [
2347
+ provider.name,
2348
+ this.getTeamRouting(provider.name)
2349
+ ]));
2350
+ }
2351
+ getProviderPoolConfig(name) {
2352
+ const pool = this.data.providers?.[name]?.pool;
2353
+ return pool ? structuredClone(pool) : undefined;
2354
+ }
2355
+ setProviderPool(name, value) {
2356
+ if (!this.getProviderConfig(name))
2357
+ throw new Error("Unknown provider");
2358
+ if (!isRecord(value))
2359
+ throw new Error("Provider pool configuration must be an object");
1978
2360
  const allowed = new Set([
1979
2361
  "enabled",
2362
+ "members",
1980
2363
  "distribution_enabled",
1981
2364
  "prefer_expiring_quota",
1982
- "allowlisted_account_uuids",
1983
2365
  "max_usage",
1984
2366
  "weekly_max_usage",
1985
2367
  "weekly_max_usage_by_email",
1986
2368
  "caller_weekly_max_usage",
1987
- "caller_provider_fallback",
1988
- "admission_cap",
1989
- "admission_queue_limit",
1990
- "admission_wait_ms",
1991
- "hold_seconds",
2369
+ "admission",
1992
2370
  "quota_probe_seconds",
1993
- "window_warmup"
2371
+ "window_warmup",
2372
+ "block_when_all_full"
1994
2373
  ]);
1995
- if (Object.keys(value).some((key) => !allowed.has(key))) {
1996
- throw new Error("team routing configuration contains an unknown field");
1997
- }
1998
- const sanitized = sanitizeTeamRouting(value);
1999
- if (!sanitized) {
2000
- throw new Error("team routing configuration must be an object");
2001
- }
2002
- for (const key of Object.keys(value)) {
2003
- if (!(key in sanitized)) {
2004
- throw new Error(`Invalid team routing field: ${key}`);
2374
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2375
+ throw new Error("Provider pool contains an unknown field");
2376
+ const sanitized = sanitizeProviderPool(value);
2377
+ if (!sanitized)
2378
+ throw new Error("Invalid provider pool");
2379
+ for (const key of Object.keys(value))
2380
+ if (!(key in sanitized))
2381
+ throw new Error(`Invalid provider pool field: ${key}`);
2382
+ if (isRecord(value.admission) && Object.keys(value.admission).some((key) => !["cap", "queue_limit", "wait_ms"].includes(key) || !(key in (sanitized.admission ?? {}))))
2383
+ throw new Error("Invalid admission field");
2384
+ const old = this.getProviderPoolConfig(name) ?? { enabled: false };
2385
+ this.persistStrictly("providers", {
2386
+ ...this.data.providers,
2387
+ [name]: {
2388
+ ...this.data.providers?.[name],
2389
+ pool: { ...old, ...sanitized }
2005
2390
  }
2006
- }
2007
- const oldValue = this.data.team_routing;
2008
- if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
2009
- sanitized.weekly_max_usage_by_email = {
2010
- ...oldValue.weekly_max_usage_by_email
2011
- };
2012
- }
2013
- if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2014
- sanitized.caller_weekly_max_usage = {
2015
- ...oldValue.caller_weekly_max_usage
2016
- };
2017
- }
2018
- if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
2019
- sanitized.caller_provider_fallback = {
2020
- ...oldValue.caller_provider_fallback
2021
- };
2022
- }
2023
- this.persistStrictly("team_routing", sanitized);
2391
+ });
2024
2392
  }
2025
- allowAccountUuid(accountUuid) {
2026
- const current = this.getTeamRouting().allowlistedAccountUuids;
2393
+ removeProviderPool(name) {
2394
+ const provider = this.data.providers?.[name];
2395
+ if (!provider?.pool)
2396
+ return;
2397
+ const { pool: _pool, ...rest } = provider;
2398
+ this.persistStrictly("providers", { ...this.data.providers, [name]: rest });
2399
+ }
2400
+ setRouting(value) {
2401
+ if (!isRecord(value))
2402
+ throw new Error("Routing configuration must be an object");
2403
+ const allowed = new Set([
2404
+ "routes",
2405
+ "api_key_accounts",
2406
+ "callers",
2407
+ "hold_seconds"
2408
+ ]);
2409
+ if (Object.keys(value).some((key) => !allowed.has(key)))
2410
+ throw new Error("Routing contains an unknown field");
2411
+ const sanitized = sanitizeRouting(value);
2412
+ if (!sanitized)
2413
+ throw new Error("Invalid routing configuration");
2414
+ for (const key of Object.keys(value))
2415
+ if (!(key in sanitized))
2416
+ throw new Error(`Invalid routing field: ${key}`);
2417
+ 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)))))
2418
+ throw new Error("Invalid routing field: routes");
2419
+ this.persistStrictly("routing", { ...this.data.routing, ...sanitized });
2420
+ }
2421
+ allowAccountUuid(provider, accountUuid) {
2422
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2027
2423
  if (current.includes(accountUuid))
2028
2424
  return;
2029
- this.persistAccountAllowlist([...current, accountUuid]);
2425
+ this.persistAccountAllowlist(provider, [...current, accountUuid]);
2030
2426
  }
2031
- removeAccountUuid(accountUuid) {
2032
- const current = this.getTeamRouting().allowlistedAccountUuids;
2427
+ removeAccountUuid(provider, accountUuid) {
2428
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2033
2429
  if (!current.includes(accountUuid))
2034
2430
  return;
2035
- this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
2431
+ this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
2036
2432
  }
2037
- persistAccountAllowlist(accountUuids) {
2038
- this.persistStrictly("team_routing", {
2039
- ...this.data.team_routing,
2040
- allowlisted_account_uuids: accountUuids
2041
- });
2433
+ persistAccountAllowlist(provider, accountUuids) {
2434
+ this.setProviderPool(provider, { members: accountUuids });
2042
2435
  }
2043
2436
  getEnrollmentEmails() {
2044
2437
  return [...this.data.enrollment_emails ?? []];
@@ -2072,7 +2465,6 @@ var init_src4 = __esm(() => {
2072
2465
  }
2073
2466
  getRuntime() {
2074
2467
  const defaults = {
2075
- blockWhenAllFull: this.getBlockWhenAllFull(),
2076
2468
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
2077
2469
  maxBodyBytes: 64 * 1024 * 1024,
2078
2470
  quotaThreshold: 0.98,
@@ -2085,7 +2477,8 @@ var init_src4 = __esm(() => {
2085
2477
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
2086
2478
  port: NETWORK.DEFAULT_PORT,
2087
2479
  storeRequestPayloads: this.storesRequestPayloads(),
2088
- teamRouting: this.getTeamRouting()
2480
+ routing: this.getRouting(),
2481
+ providerPools: this.getProviderPoolSettings()
2089
2482
  };
2090
2483
  if (process.env.AGENT_SMITH_CLIENT_ID) {
2091
2484
  defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
@@ -2156,20 +2549,20 @@ var init_src4 = __esm(() => {
2156
2549
 
2157
2550
  // src/core/local-routing.ts
2158
2551
  import {
2159
- accessSync,
2552
+ accessSync as accessSync2,
2160
2553
  chmodSync as chmodSync2,
2161
- constants,
2554
+ constants as constants2,
2162
2555
  copyFileSync,
2163
2556
  existsSync as existsSync3,
2164
2557
  mkdirSync as mkdirSync3,
2165
- readFileSync as readFileSync2,
2558
+ readFileSync as readFileSync3,
2166
2559
  rmSync as rmSync2,
2167
- statSync as statSync3,
2168
- unlinkSync as unlinkSync2,
2169
- writeFileSync as writeFileSync2
2560
+ statSync as statSync4,
2561
+ unlinkSync as unlinkSync3,
2562
+ writeFileSync as writeFileSync3
2170
2563
  } from "fs";
2171
2564
  import { homedir as homedir2 } from "os";
2172
- import { dirname as dirname2, join as join5 } from "path";
2565
+ import { dirname as dirname3, join as join6 } from "path";
2173
2566
  import { fileURLToPath } from "url";
2174
2567
  function shellQuote(value) {
2175
2568
  return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -2182,10 +2575,10 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
2182
2575
  return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
2183
2576
  }
2184
2577
  function validateProxyKeyFile(proxyKeyFile) {
2185
- const resolvedPath = proxyKeyFile.startsWith("~/") ? join5(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
2578
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join6(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
2186
2579
  let metadata;
2187
2580
  try {
2188
- metadata = statSync3(resolvedPath);
2581
+ metadata = statSync4(resolvedPath);
2189
2582
  } catch {
2190
2583
  throw new Error("Agent Smith forwarding-key file is not readable");
2191
2584
  }
@@ -2195,7 +2588,7 @@ function validateProxyKeyFile(proxyKeyFile) {
2195
2588
  if ((metadata.mode & 63) !== 0) {
2196
2589
  throw new Error("Agent Smith forwarding-key file must be owner-only");
2197
2590
  }
2198
- const key = readFileSync2(resolvedPath, "utf8").trim();
2591
+ const key = readFileSync3(resolvedPath, "utf8").trim();
2199
2592
  if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
2200
2593
  throw new Error("Agent Smith forwarding-key file is invalid");
2201
2594
  }
@@ -2220,30 +2613,30 @@ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_
2220
2613
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
2221
2614
  }
2222
2615
  function claudeCompanionSourceDir() {
2223
- const bundled = join5(import.meta.dir, "claude-companion");
2224
- if (existsSync3(join5(bundled, ".claude-plugin", "plugin.json"))) {
2616
+ const bundled = join6(import.meta.dir, "claude-companion");
2617
+ if (existsSync3(join6(bundled, ".claude-plugin", "plugin.json"))) {
2225
2618
  return bundled;
2226
2619
  }
2227
- const source = join5(import.meta.dir, "..", "claude-companion");
2228
- if (existsSync3(join5(source, ".claude-plugin", "plugin.json"))) {
2620
+ const source = join6(import.meta.dir, "..", "claude-companion");
2621
+ if (existsSync3(join6(source, ".claude-plugin", "plugin.json"))) {
2229
2622
  return source;
2230
2623
  }
2231
2624
  throw new Error("Agent-smith Claude companion files are missing");
2232
2625
  }
2233
2626
  function installClaudeCompanion(binDir) {
2234
2627
  const sourceDir = claudeCompanionSourceDir();
2235
- const targetDir = join5(binDir, CLAUDE_COMPANION_DIRNAME);
2628
+ const targetDir = join6(binDir, CLAUDE_COMPANION_DIRNAME);
2236
2629
  rmSync2(targetDir, { force: true, recursive: true });
2237
2630
  for (const relativePath of CLAUDE_COMPANION_FILES) {
2238
- const target = join5(targetDir, relativePath);
2239
- mkdirSync3(dirname2(target), { recursive: true, mode: 448 });
2240
- copyFileSync(join5(sourceDir, relativePath), target, constants.COPYFILE_FICLONE);
2631
+ const target = join6(targetDir, relativePath);
2632
+ mkdirSync3(dirname3(target), { recursive: true, mode: 448 });
2633
+ copyFileSync(join6(sourceDir, relativePath), target, constants2.COPYFILE_FICLONE);
2241
2634
  chmodSync2(target, 384);
2242
2635
  }
2243
2636
  for (const directory of [
2244
2637
  targetDir,
2245
- join5(targetDir, ".claude-plugin"),
2246
- join5(targetDir, "hooks")
2638
+ join6(targetDir, ".claude-plugin"),
2639
+ join6(targetDir, "hooks")
2247
2640
  ]) {
2248
2641
  chmodSync2(directory, 448);
2249
2642
  }
@@ -2293,11 +2686,11 @@ async function installClientWrappers(options) {
2293
2686
  ]) {
2294
2687
  if (!target)
2295
2688
  continue;
2296
- if (target === join5(options.binDir, tool))
2689
+ if (target === join6(options.binDir, tool))
2297
2690
  throw new Error("A client launcher cannot call itself");
2298
- const wrapper = join5(options.binDir, tool);
2691
+ const wrapper = join6(options.binDir, tool);
2299
2692
  const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
2300
- writeFileSync2(wrapper, `#!/bin/sh
2693
+ writeFileSync3(wrapper, `#!/bin/sh
2301
2694
  ${CONFIG_CLIENT_MARKER}
2302
2695
  exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
2303
2696
  `, { encoding: "utf8", mode: 448 });
@@ -2311,17 +2704,17 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, comp
2311
2704
  mkdirSync3(options.binDir, { recursive: true, mode: 448 });
2312
2705
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
2313
2706
  if (options.claudePath) {
2314
- const claude = join5(options.binDir, "claude");
2707
+ const claude = join6(options.binDir, "claude");
2315
2708
  const companionDir = installClaudeCompanion(options.binDir);
2316
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
2709
+ writeFileSync3(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
2317
2710
  encoding: "utf8",
2318
2711
  mode: 448
2319
2712
  });
2320
2713
  chmodSync2(claude, 448);
2321
2714
  }
2322
2715
  if (options.codexPath) {
2323
- const codex = join5(options.binDir, "codex");
2324
- writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
2716
+ const codex = join6(options.binDir, "codex");
2717
+ writeFileSync3(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
2325
2718
  encoding: "utf8",
2326
2719
  mode: 448
2327
2720
  });
@@ -2330,19 +2723,19 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, comp
2330
2723
  }
2331
2724
  function defaultShellProfile() {
2332
2725
  const shell = process.env.SHELL?.split("/").pop();
2333
- return join5(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
2726
+ return join6(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
2334
2727
  }
2335
2728
  function getLocalRoutingPaths() {
2336
- const configDir = dirname2(resolveConfigPath());
2729
+ const configDir = dirname3(resolveConfigPath());
2337
2730
  return {
2338
- binDir: join5(configDir, "client-bin"),
2731
+ binDir: join6(configDir, "client-bin"),
2339
2732
  shellProfile: defaultShellProfile(),
2340
- statePath: join5(configDir, "client-routing.json")
2733
+ statePath: join6(configDir, "client-routing.json")
2341
2734
  };
2342
2735
  }
2343
2736
  function isExecutable(path) {
2344
2737
  try {
2345
- accessSync(path, constants.X_OK);
2738
+ accessSync2(path, constants2.X_OK);
2346
2739
  return true;
2347
2740
  } catch {
2348
2741
  return false;
@@ -2352,7 +2745,7 @@ function findClientExecutable(name, binDir, path) {
2352
2745
  for (const directory of path.split(":")) {
2353
2746
  if (!directory || directory === binDir)
2354
2747
  continue;
2355
- const candidate = join5(directory, name);
2748
+ const candidate = join6(directory, name);
2356
2749
  if (isExecutable(candidate))
2357
2750
  return candidate;
2358
2751
  }
@@ -2362,7 +2755,7 @@ function readSavedClientPaths(statePath) {
2362
2755
  if (!existsSync3(statePath))
2363
2756
  return null;
2364
2757
  try {
2365
- const saved = JSON.parse(readFileSync2(statePath, "utf8"));
2758
+ const saved = JSON.parse(readFileSync3(statePath, "utf8"));
2366
2759
  if (typeof saved === "object" && saved !== null) {
2367
2760
  const { claudePath, codexPath } = saved;
2368
2761
  const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
@@ -2380,10 +2773,10 @@ function installedRoutingStatus(paths = {}) {
2380
2773
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2381
2774
  let shellProfileHasRouting = false;
2382
2775
  try {
2383
- shellProfileHasRouting = existsSync3(shellProfile) && readFileSync2(shellProfile, "utf8").includes(ROUTING_BEGIN);
2776
+ shellProfileHasRouting = existsSync3(shellProfile) && readFileSync3(shellProfile, "utf8").includes(ROUTING_BEGIN);
2384
2777
  } catch {}
2385
2778
  return {
2386
- enabled: shellProfileHasRouting && (existsSync3(join5(binDir, "claude")) || existsSync3(join5(binDir, "codex"))),
2779
+ enabled: shellProfileHasRouting && (existsSync3(join6(binDir, "claude")) || existsSync3(join6(binDir, "codex"))),
2387
2780
  binDir,
2388
2781
  shellProfile
2389
2782
  };
@@ -2400,8 +2793,8 @@ function getLocalRoutingStatus(paths = {}) {
2400
2793
  }
2401
2794
  function configClientWrappersInstalled(paths = {}) {
2402
2795
  const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
2403
- const files = ["claude", "codex"].map((name) => join5(binDir, name)).filter(existsSync3);
2404
- return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync2(path, "utf8").includes(CONFIG_CLIENT_MARKER));
2796
+ const files = ["claude", "codex"].map((name) => join6(binDir, name)).filter(existsSync3);
2797
+ return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync3(path, "utf8").includes(CONFIG_CLIENT_MARKER));
2405
2798
  }
2406
2799
  async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
2407
2800
  if (tool !== "claude" && tool !== "codex")
@@ -2470,10 +2863,10 @@ async function enableLocalClientRouting(options) {
2470
2863
  clientConfigPath: options.clientConfigPath,
2471
2864
  providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
2472
2865
  });
2473
- const existingProfile = existsSync3(shellProfile) ? readFileSync2(shellProfile, "utf8") : "";
2474
- writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
2475
- mkdirSync3(dirname2(statePath), { recursive: true, mode: 448 });
2476
- writeFileSync2(statePath, JSON.stringify({ claudePath, codexPath }), {
2866
+ const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
2867
+ writeFileSync3(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
2868
+ mkdirSync3(dirname3(statePath), { recursive: true, mode: 448 });
2869
+ writeFileSync3(statePath, JSON.stringify({ claudePath, codexPath }), {
2477
2870
  encoding: "utf8",
2478
2871
  mode: 384
2479
2872
  });
@@ -2486,19 +2879,19 @@ function disableLocalClientRouting(paths = {}) {
2486
2879
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2487
2880
  const statePath = paths.statePath ?? defaults.statePath;
2488
2881
  if (existsSync3(shellProfile)) {
2489
- writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync2(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
2882
+ writeFileSync3(shellProfile, removeRoutingFromShellProfile(readFileSync3(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
2490
2883
  }
2491
2884
  for (const name of ["claude", "codex"]) {
2492
- const wrapper = join5(binDir, name);
2885
+ const wrapper = join6(binDir, name);
2493
2886
  if (existsSync3(wrapper))
2494
- unlinkSync2(wrapper);
2887
+ unlinkSync3(wrapper);
2495
2888
  }
2496
- rmSync2(join5(binDir, CLAUDE_COMPANION_DIRNAME), {
2889
+ rmSync2(join6(binDir, CLAUDE_COMPANION_DIRNAME), {
2497
2890
  force: true,
2498
2891
  recursive: true
2499
2892
  });
2500
2893
  if (existsSync3(statePath))
2501
- unlinkSync2(statePath);
2894
+ unlinkSync3(statePath);
2502
2895
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
2503
2896
  }
2504
2897
  function removeRoutingFromShellProfile(profile) {