@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",
@@ -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 === "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
  }
@@ -1665,6 +1935,12 @@ function sanitizeTeamRouting(value) {
1665
1935
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1666
1936
  }
1667
1937
  }
1938
+ if (isRecord(value.caller_provider_fallback)) {
1939
+ const entries = Object.entries(value.caller_provider_fallback);
1940
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
1941
+ result.caller_provider_fallback = Object.fromEntries(entries);
1942
+ }
1943
+ }
1668
1944
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1669
1945
  result.admission_cap = Math.floor(value.admission_cap);
1670
1946
  }
@@ -1685,13 +1961,105 @@ function sanitizeTeamRouting(value) {
1685
1961
  result.window_warmup = windowWarmup;
1686
1962
  return result;
1687
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
+ }
1688
2055
  function readClientRouting(configPath = resolveConfigPath()) {
1689
2056
  let data;
1690
2057
  try {
1691
- data = JSON.parse(readFileSync(configPath, "utf8"));
2058
+ data = JSON.parse(readFileSync2(configPath, "utf8"));
1692
2059
  } catch {
1693
2060
  throw new Error("Agent Smith client config could not be read");
1694
2061
  }
2062
+ data = migrateLegacyConfig(configPath, data);
1695
2063
  if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1696
2064
  throw new Error("Agent Smith client config is invalid");
1697
2065
  }
@@ -1706,34 +2074,35 @@ function clientRouting(client) {
1706
2074
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1707
2075
  };
1708
2076
  }
1709
- 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;
1710
2078
  var init_src4 = __esm(() => {
1711
2079
  init_src2();
1712
2080
  init_src3();
1713
2081
  init_src();
2082
+ init_builtin_providers();
1714
2083
  init_paths();
2084
+ init_rewrite_file();
1715
2085
  init_window_warmup();
1716
2086
  init_paths();
1717
2087
  init_paths_common();
2088
+ init_rewrite_config();
2089
+ init_rewrite_file();
1718
2090
  init_window_warmup();
1719
2091
  log2 = new Logger("Config");
1720
2092
  PROVIDER_STRATEGIES = [
1721
2093
  "anthropic-api",
2094
+ "model-studio-anthropic-api",
2095
+ "kimi-code-anthropic-api",
2096
+ "google-gemini-api",
1722
2097
  "openai-api",
1723
2098
  "claude-code",
1724
2099
  "codex"
1725
2100
  ];
1726
- BUILTIN_PROVIDER_CONFIGS = [
1727
- { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1728
- { name: "openai", enabled: true, strategy: "openai-api" },
1729
- { name: "claude-code", enabled: false, strategy: "claude-code" },
1730
- { name: "codex", enabled: false, strategy: "codex" }
1731
- ];
1732
2101
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1733
2102
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1734
2103
  POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1735
2104
  CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
1736
- TEAM_ROUTING_DEFAULTS = {
2105
+ POOL_DEFAULTS = {
1737
2106
  enabled: false,
1738
2107
  distributionEnabled: true,
1739
2108
  preferExpiringQuota: false,
@@ -1745,9 +2114,9 @@ var init_src4 = __esm(() => {
1745
2114
  admissionCap: 5,
1746
2115
  admissionQueueLimit: 25,
1747
2116
  admissionWaitMs: 30000,
1748
- holdSeconds: 0,
1749
2117
  quotaProbeSeconds: 0,
1750
- windowWarmup: WINDOW_WARMUP_DEFAULTS
2118
+ windowWarmup: WINDOW_WARMUP_DEFAULTS,
2119
+ blockWhenAllFull: true
1751
2120
  };
1752
2121
  Config = class Config extends EventEmitter3 {
1753
2122
  configPath;
@@ -1759,20 +2128,23 @@ var init_src4 = __esm(() => {
1759
2128
  }
1760
2129
  loadConfig() {
1761
2130
  if (existsSync2(this.configPath)) {
2131
+ let parsed;
1762
2132
  try {
1763
- const content = readFileSync(this.configPath, "utf8");
1764
- this.data = sanitizeConfigData(JSON.parse(content));
2133
+ const content = readFileSync2(this.configPath, "utf8");
2134
+ parsed = JSON.parse(content);
1765
2135
  } catch (error) {
1766
2136
  log2.error(`Failed to parse config file: ${error}`);
1767
2137
  this.data = {};
1768
2138
  return;
1769
2139
  }
2140
+ parsed = migrateLegacyConfig(this.configPath, parsed);
2141
+ this.data = sanitizeConfigData(parsed);
1770
2142
  try {
1771
2143
  chmodSync(this.configPath, 384);
1772
2144
  } catch {
1773
2145
  let ownerOnly = false;
1774
2146
  try {
1775
- ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
2147
+ ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
1776
2148
  } catch {}
1777
2149
  if (!ownerOnly) {
1778
2150
  throw new Error("Config file must be owner-only");
@@ -1783,7 +2155,7 @@ var init_src4 = __esm(() => {
1783
2155
  this.saveConfig();
1784
2156
  }
1785
2157
  } else {
1786
- const dir = dirname(this.configPath);
2158
+ const dir = dirname2(this.configPath);
1787
2159
  mkdirSync2(dir, { recursive: true, mode: 448 });
1788
2160
  chmodSync(dir, 448);
1789
2161
  this.data = {
@@ -1802,11 +2174,11 @@ var init_src4 = __esm(() => {
1802
2174
  writePrivately(data) {
1803
2175
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1804
2176
  try {
1805
- writeFileSync(temporary, JSON.stringify(data, null, 2), {
2177
+ writeFileSync2(temporary, JSON.stringify(data, null, 2), {
1806
2178
  mode: 384,
1807
2179
  flag: "wx"
1808
2180
  });
1809
- renameSync(temporary, this.configPath);
2181
+ renameSync2(temporary, this.configPath);
1810
2182
  } finally {
1811
2183
  rmSync(temporary, { force: true });
1812
2184
  }
@@ -1892,25 +2264,35 @@ var init_src4 = __esm(() => {
1892
2264
  request_retention_days: this.getRequestRetentionDays()
1893
2265
  };
1894
2266
  }
1895
- getTeamRouting() {
1896
- const file = this.data.team_routing;
2267
+ getRouting() {
2268
+ const routing = this.data.routing;
2269
+ return {
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;
1897
2281
  return {
1898
- enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1899
- distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1900
- preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
1901
- allowlistedAccountUuids: [
1902
- ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1903
- ],
1904
- maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1905
- weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1906
- weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1907
- callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1908
- admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1909
- admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1910
- admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1911
- holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1912
- quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
1913
- windowWarmup: windowWarmupConfig(file?.window_warmup)
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
1914
2296
  };
1915
2297
  }
1916
2298
  getAlerts() {
@@ -1930,9 +2312,6 @@ var init_src4 = __esm(() => {
1930
2312
  setClientRoutingEnabled(enabled) {
1931
2313
  this.persistStrictly("client", { ...this.data.client, enabled });
1932
2314
  }
1933
- getBlockWhenAllFull() {
1934
- return this.data.block_when_all_full !== false;
1935
- }
1936
2315
  getProviderConfig(name) {
1937
2316
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1938
2317
  const configured = this.data.providers?.[name];
@@ -1943,11 +2322,12 @@ var init_src4 = __esm(() => {
1943
2322
  enabled: configured?.enabled ?? builtin?.enabled ?? true,
1944
2323
  strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
1945
2324
  ...configured?.base_url && { baseUrl: configured.base_url },
1946
- ...configured?.models && { models: { ...configured.models } }
2325
+ ...configured?.models && { models: { ...configured.models } },
2326
+ ...configured?.pool && { pool: structuredClone(configured.pool) }
1947
2327
  };
1948
2328
  }
1949
2329
  getProviderPool(wire) {
1950
- return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
2330
+ return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
1951
2331
  const provider = this.getProviderConfig(name);
1952
2332
  return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
1953
2333
  });
@@ -1962,68 +2342,96 @@ var init_src4 = __esm(() => {
1962
2342
  }
1963
2343
  return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
1964
2344
  }
1965
- setTeamRouting(value) {
1966
- if (!isRecord(value)) {
1967
- throw new Error("team routing configuration must be an object");
1968
- }
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");
1969
2360
  const allowed = new Set([
1970
2361
  "enabled",
2362
+ "members",
1971
2363
  "distribution_enabled",
1972
2364
  "prefer_expiring_quota",
1973
- "allowlisted_account_uuids",
1974
2365
  "max_usage",
1975
2366
  "weekly_max_usage",
1976
2367
  "weekly_max_usage_by_email",
1977
2368
  "caller_weekly_max_usage",
1978
- "admission_cap",
1979
- "admission_queue_limit",
1980
- "admission_wait_ms",
1981
- "hold_seconds",
2369
+ "admission",
1982
2370
  "quota_probe_seconds",
1983
- "window_warmup"
2371
+ "window_warmup",
2372
+ "block_when_all_full"
1984
2373
  ]);
1985
- if (Object.keys(value).some((key) => !allowed.has(key))) {
1986
- throw new Error("team routing configuration contains an unknown field");
1987
- }
1988
- const sanitized = sanitizeTeamRouting(value);
1989
- if (!sanitized) {
1990
- throw new Error("team routing configuration must be an object");
1991
- }
1992
- for (const key of Object.keys(value)) {
1993
- if (!(key in sanitized)) {
1994
- 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 }
1995
2390
  }
1996
- }
1997
- const oldValue = this.data.team_routing;
1998
- if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
1999
- sanitized.weekly_max_usage_by_email = {
2000
- ...oldValue.weekly_max_usage_by_email
2001
- };
2002
- }
2003
- if (!("caller_weekly_max_usage" in value) && oldValue?.caller_weekly_max_usage) {
2004
- sanitized.caller_weekly_max_usage = {
2005
- ...oldValue.caller_weekly_max_usage
2006
- };
2007
- }
2008
- this.persistStrictly("team_routing", sanitized);
2391
+ });
2392
+ }
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 });
2009
2399
  }
2010
- allowAccountUuid(accountUuid) {
2011
- const current = this.getTeamRouting().allowlistedAccountUuids;
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;
2012
2423
  if (current.includes(accountUuid))
2013
2424
  return;
2014
- this.persistAccountAllowlist([...current, accountUuid]);
2425
+ this.persistAccountAllowlist(provider, [...current, accountUuid]);
2015
2426
  }
2016
- removeAccountUuid(accountUuid) {
2017
- const current = this.getTeamRouting().allowlistedAccountUuids;
2427
+ removeAccountUuid(provider, accountUuid) {
2428
+ const current = this.getTeamRouting(provider).allowlistedAccountUuids;
2018
2429
  if (!current.includes(accountUuid))
2019
2430
  return;
2020
- this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
2431
+ this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
2021
2432
  }
2022
- persistAccountAllowlist(accountUuids) {
2023
- this.persistStrictly("team_routing", {
2024
- ...this.data.team_routing,
2025
- allowlisted_account_uuids: accountUuids
2026
- });
2433
+ persistAccountAllowlist(provider, accountUuids) {
2434
+ this.setProviderPool(provider, { members: accountUuids });
2027
2435
  }
2028
2436
  getEnrollmentEmails() {
2029
2437
  return [...this.data.enrollment_emails ?? []];
@@ -2057,7 +2465,6 @@ var init_src4 = __esm(() => {
2057
2465
  }
2058
2466
  getRuntime() {
2059
2467
  const defaults = {
2060
- blockWhenAllFull: this.getBlockWhenAllFull(),
2061
2468
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
2062
2469
  maxBodyBytes: 64 * 1024 * 1024,
2063
2470
  quotaThreshold: 0.98,
@@ -2070,7 +2477,8 @@ var init_src4 = __esm(() => {
2070
2477
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
2071
2478
  port: NETWORK.DEFAULT_PORT,
2072
2479
  storeRequestPayloads: this.storesRequestPayloads(),
2073
- teamRouting: this.getTeamRouting()
2480
+ routing: this.getRouting(),
2481
+ providerPools: this.getProviderPoolSettings()
2074
2482
  };
2075
2483
  if (process.env.AGENT_SMITH_CLIENT_ID) {
2076
2484
  defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
@@ -2141,18 +2549,20 @@ var init_src4 = __esm(() => {
2141
2549
 
2142
2550
  // src/core/local-routing.ts
2143
2551
  import {
2144
- accessSync,
2552
+ accessSync as accessSync2,
2145
2553
  chmodSync as chmodSync2,
2146
- constants,
2554
+ constants as constants2,
2555
+ copyFileSync,
2147
2556
  existsSync as existsSync3,
2148
2557
  mkdirSync as mkdirSync3,
2149
- readFileSync as readFileSync2,
2150
- statSync as statSync3,
2151
- unlinkSync as unlinkSync2,
2152
- writeFileSync as writeFileSync2
2558
+ readFileSync as readFileSync3,
2559
+ rmSync as rmSync2,
2560
+ statSync as statSync4,
2561
+ unlinkSync as unlinkSync3,
2562
+ writeFileSync as writeFileSync3
2153
2563
  } from "fs";
2154
2564
  import { homedir as homedir2 } from "os";
2155
- import { dirname as dirname2, join as join5 } from "path";
2565
+ import { dirname as dirname3, join as join6 } from "path";
2156
2566
  import { fileURLToPath } from "url";
2157
2567
  function shellQuote(value) {
2158
2568
  return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -2165,10 +2575,10 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
2165
2575
  return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
2166
2576
  }
2167
2577
  function validateProxyKeyFile(proxyKeyFile) {
2168
- const resolvedPath = proxyKeyFile.startsWith("~/") ? join5(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
2578
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join6(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
2169
2579
  let metadata;
2170
2580
  try {
2171
- metadata = statSync3(resolvedPath);
2581
+ metadata = statSync4(resolvedPath);
2172
2582
  } catch {
2173
2583
  throw new Error("Agent Smith forwarding-key file is not readable");
2174
2584
  }
@@ -2178,7 +2588,7 @@ function validateProxyKeyFile(proxyKeyFile) {
2178
2588
  if ((metadata.mode & 63) !== 0) {
2179
2589
  throw new Error("Agent Smith forwarding-key file must be owner-only");
2180
2590
  }
2181
- const key = readFileSync2(resolvedPath, "utf8").trim();
2591
+ const key = readFileSync3(resolvedPath, "utf8").trim();
2182
2592
  if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
2183
2593
  throw new Error("Agent Smith forwarding-key file is invalid");
2184
2594
  }
@@ -2202,7 +2612,37 @@ function claudeProxyCredential(keepClaudeLogin) {
2202
2612
  export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
2203
2613
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
2204
2614
  }
2205
- function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
2615
+ function claudeCompanionSourceDir() {
2616
+ const bundled = join6(import.meta.dir, "claude-companion");
2617
+ if (existsSync3(join6(bundled, ".claude-plugin", "plugin.json"))) {
2618
+ return bundled;
2619
+ }
2620
+ const source = join6(import.meta.dir, "..", "claude-companion");
2621
+ if (existsSync3(join6(source, ".claude-plugin", "plugin.json"))) {
2622
+ return source;
2623
+ }
2624
+ throw new Error("Agent-smith Claude companion files are missing");
2625
+ }
2626
+ function installClaudeCompanion(binDir) {
2627
+ const sourceDir = claudeCompanionSourceDir();
2628
+ const targetDir = join6(binDir, CLAUDE_COMPANION_DIRNAME);
2629
+ rmSync2(targetDir, { force: true, recursive: true });
2630
+ for (const relativePath of CLAUDE_COMPANION_FILES) {
2631
+ const target = join6(targetDir, relativePath);
2632
+ mkdirSync3(dirname3(target), { recursive: true, mode: 448 });
2633
+ copyFileSync(join6(sourceDir, relativePath), target, constants2.COPYFILE_FICLONE);
2634
+ chmodSync2(target, 384);
2635
+ }
2636
+ for (const directory of [
2637
+ targetDir,
2638
+ join6(targetDir, ".claude-plugin"),
2639
+ join6(targetDir, "hooks")
2640
+ ]) {
2641
+ chmodSync2(directory, 448);
2642
+ }
2643
+ return targetDir;
2644
+ }
2645
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin, companionDir) {
2206
2646
  return `#!/bin/sh
2207
2647
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
2208
2648
  unset AGENT_SMITH_ADMIN_KEY
@@ -2212,7 +2652,7 @@ ${proxyKeySetup(proxyKeyFile)}
2212
2652
  ${claudeProxyCredential(keepClaudeLogin)}
2213
2653
  unset AGENT_SMITH_PROXY_KEY
2214
2654
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
2215
- exec ${shellQuote(claudePath)} "$@"
2655
+ exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
2216
2656
  `;
2217
2657
  }
2218
2658
  function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
@@ -2246,12 +2686,13 @@ async function installClientWrappers(options) {
2246
2686
  ]) {
2247
2687
  if (!target)
2248
2688
  continue;
2249
- if (target === join5(options.binDir, tool))
2689
+ if (target === join6(options.binDir, tool))
2250
2690
  throw new Error("A client launcher cannot call itself");
2251
- const wrapper = join5(options.binDir, tool);
2252
- writeFileSync2(wrapper, `#!/bin/sh
2691
+ const wrapper = join6(options.binDir, tool);
2692
+ const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
2693
+ writeFileSync3(wrapper, `#!/bin/sh
2253
2694
  ${CONFIG_CLIENT_MARKER}
2254
- exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
2695
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
2255
2696
  `, { encoding: "utf8", mode: 448 });
2256
2697
  chmodSync2(wrapper, 448);
2257
2698
  }
@@ -2263,16 +2704,17 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(
2263
2704
  mkdirSync3(options.binDir, { recursive: true, mode: 448 });
2264
2705
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
2265
2706
  if (options.claudePath) {
2266
- const claude = join5(options.binDir, "claude");
2267
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
2707
+ const claude = join6(options.binDir, "claude");
2708
+ const companionDir = installClaudeCompanion(options.binDir);
2709
+ writeFileSync3(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
2268
2710
  encoding: "utf8",
2269
2711
  mode: 448
2270
2712
  });
2271
2713
  chmodSync2(claude, 448);
2272
2714
  }
2273
2715
  if (options.codexPath) {
2274
- const codex = join5(options.binDir, "codex");
2275
- 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), {
2276
2718
  encoding: "utf8",
2277
2719
  mode: 448
2278
2720
  });
@@ -2281,19 +2723,19 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(
2281
2723
  }
2282
2724
  function defaultShellProfile() {
2283
2725
  const shell = process.env.SHELL?.split("/").pop();
2284
- return join5(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
2726
+ return join6(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
2285
2727
  }
2286
2728
  function getLocalRoutingPaths() {
2287
- const configDir = dirname2(resolveConfigPath());
2729
+ const configDir = dirname3(resolveConfigPath());
2288
2730
  return {
2289
- binDir: join5(configDir, "client-bin"),
2731
+ binDir: join6(configDir, "client-bin"),
2290
2732
  shellProfile: defaultShellProfile(),
2291
- statePath: join5(configDir, "client-routing.json")
2733
+ statePath: join6(configDir, "client-routing.json")
2292
2734
  };
2293
2735
  }
2294
2736
  function isExecutable(path) {
2295
2737
  try {
2296
- accessSync(path, constants.X_OK);
2738
+ accessSync2(path, constants2.X_OK);
2297
2739
  return true;
2298
2740
  } catch {
2299
2741
  return false;
@@ -2303,7 +2745,7 @@ function findClientExecutable(name, binDir, path) {
2303
2745
  for (const directory of path.split(":")) {
2304
2746
  if (!directory || directory === binDir)
2305
2747
  continue;
2306
- const candidate = join5(directory, name);
2748
+ const candidate = join6(directory, name);
2307
2749
  if (isExecutable(candidate))
2308
2750
  return candidate;
2309
2751
  }
@@ -2313,7 +2755,7 @@ function readSavedClientPaths(statePath) {
2313
2755
  if (!existsSync3(statePath))
2314
2756
  return null;
2315
2757
  try {
2316
- const saved = JSON.parse(readFileSync2(statePath, "utf8"));
2758
+ const saved = JSON.parse(readFileSync3(statePath, "utf8"));
2317
2759
  if (typeof saved === "object" && saved !== null) {
2318
2760
  const { claudePath, codexPath } = saved;
2319
2761
  const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
@@ -2331,10 +2773,10 @@ function installedRoutingStatus(paths = {}) {
2331
2773
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2332
2774
  let shellProfileHasRouting = false;
2333
2775
  try {
2334
- shellProfileHasRouting = existsSync3(shellProfile) && readFileSync2(shellProfile, "utf8").includes(ROUTING_BEGIN);
2776
+ shellProfileHasRouting = existsSync3(shellProfile) && readFileSync3(shellProfile, "utf8").includes(ROUTING_BEGIN);
2335
2777
  } catch {}
2336
2778
  return {
2337
- enabled: shellProfileHasRouting && (existsSync3(join5(binDir, "claude")) || existsSync3(join5(binDir, "codex"))),
2779
+ enabled: shellProfileHasRouting && (existsSync3(join6(binDir, "claude")) || existsSync3(join6(binDir, "codex"))),
2338
2780
  binDir,
2339
2781
  shellProfile
2340
2782
  };
@@ -2351,10 +2793,10 @@ function getLocalRoutingStatus(paths = {}) {
2351
2793
  }
2352
2794
  function configClientWrappersInstalled(paths = {}) {
2353
2795
  const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
2354
- const files = ["claude", "codex"].map((name) => join5(binDir, name)).filter(existsSync3);
2355
- 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));
2356
2798
  }
2357
- async function launchConfiguredClient(configPath, tool, target, args) {
2799
+ async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
2358
2800
  if (tool !== "claude" && tool !== "codex")
2359
2801
  throw new Error("Unknown Agent Smith client");
2360
2802
  const client = readClientRouting(configPath);
@@ -2368,7 +2810,7 @@ async function launchConfiguredClient(configPath, tool, target, args) {
2368
2810
  const keyFile = validateProxyKeyFile(client.proxyKeyFile);
2369
2811
  const wires = Object.keys(new Config(configPath).getProviderPools());
2370
2812
  const base = proxyBaseUrl(8080, client.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
2371
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
2813
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
2372
2814
  command = ["/bin/sh", "-c", script, "--", ...args];
2373
2815
  }
2374
2816
  const child = Bun.spawn(command, {
@@ -2421,10 +2863,10 @@ async function enableLocalClientRouting(options) {
2421
2863
  clientConfigPath: options.clientConfigPath,
2422
2864
  providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
2423
2865
  });
2424
- const existingProfile = existsSync3(shellProfile) ? readFileSync2(shellProfile, "utf8") : "";
2425
- writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
2426
- mkdirSync3(dirname2(statePath), { recursive: true, mode: 448 });
2427
- 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 }), {
2428
2870
  encoding: "utf8",
2429
2871
  mode: 384
2430
2872
  });
@@ -2437,15 +2879,19 @@ function disableLocalClientRouting(paths = {}) {
2437
2879
  const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2438
2880
  const statePath = paths.statePath ?? defaults.statePath;
2439
2881
  if (existsSync3(shellProfile)) {
2440
- writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync2(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
2882
+ writeFileSync3(shellProfile, removeRoutingFromShellProfile(readFileSync3(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
2441
2883
  }
2442
2884
  for (const name of ["claude", "codex"]) {
2443
- const wrapper = join5(binDir, name);
2885
+ const wrapper = join6(binDir, name);
2444
2886
  if (existsSync3(wrapper))
2445
- unlinkSync2(wrapper);
2887
+ unlinkSync3(wrapper);
2446
2888
  }
2889
+ rmSync2(join6(binDir, CLAUDE_COMPANION_DIRNAME), {
2890
+ force: true,
2891
+ recursive: true
2892
+ });
2447
2893
  if (existsSync3(statePath))
2448
- unlinkSync2(statePath);
2894
+ unlinkSync3(statePath);
2449
2895
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
2450
2896
  }
2451
2897
  function removeRoutingFromShellProfile(profile) {
@@ -2470,18 +2916,24 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
2470
2916
  ${ROUTING_END}
2471
2917
  `;
2472
2918
  }
2473
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
2919
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
2474
2920
  var init_local_routing = __esm(() => {
2475
2921
  init_src4();
2922
+ CLAUDE_COMPANION_FILES = [
2923
+ ".claude-plugin/plugin.json",
2924
+ "hooks/hooks.json",
2925
+ "hooks/provider-choice.js",
2926
+ "hooks/register.js"
2927
+ ];
2476
2928
  });
2477
2929
 
2478
2930
  // src/core/client-launcher.ts
2479
2931
  init_local_routing();
2480
2932
  try {
2481
- const [configPath, tool, target, ...args] = process.argv.slice(2);
2482
- if (!configPath || !tool || !target)
2933
+ const [configPath, tool, target, claudeCompanionDir, ...args] = process.argv.slice(2);
2934
+ if (!configPath || !tool || !target || claudeCompanionDir === undefined)
2483
2935
  throw new Error("Invalid Agent Smith client launcher");
2484
- process.exitCode = await launchConfiguredClient(configPath, tool, target, args);
2936
+ process.exitCode = await launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args);
2485
2937
  } catch (error) {
2486
2938
  console.error(error instanceof Error ? error.message : "Agent Smith could not start the client");
2487
2939
  process.exitCode = 1;