@certalis/agent-smith 0.1.4 → 0.1.6

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.
package/dist/bin.js CHANGED
@@ -1263,11 +1263,13 @@ var init_paths = __esm(() => {
1263
1263
  // ../../packages/config/src/index.ts
1264
1264
  import { EventEmitter as EventEmitter3 } from "events";
1265
1265
  import {
1266
+ chmodSync,
1266
1267
  existsSync as existsSync2,
1267
1268
  mkdirSync as mkdirSync2,
1268
1269
  readFileSync,
1269
1270
  renameSync,
1270
1271
  rmSync,
1272
+ statSync as statSync2,
1271
1273
  writeFileSync
1272
1274
  } from "fs";
1273
1275
  import { dirname } from "path";
@@ -1320,6 +1322,18 @@ function sanitizeConfigData(value) {
1320
1322
  sanitized.provider_pools = providerPools;
1321
1323
  continue;
1322
1324
  }
1325
+ if (key === "client") {
1326
+ const client = sanitizeClientRouting(entry);
1327
+ if (client)
1328
+ sanitized.client = client;
1329
+ continue;
1330
+ }
1331
+ if (key === "alerts") {
1332
+ const alerts = sanitizeAlerts(entry);
1333
+ if (alerts)
1334
+ sanitized.alerts = alerts;
1335
+ continue;
1336
+ }
1323
1337
  if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
1324
1338
  sanitized[key] = entry;
1325
1339
  }
@@ -1350,6 +1364,46 @@ function sanitizeConfigData(value) {
1350
1364
  }
1351
1365
  return sanitized;
1352
1366
  }
1367
+ function filledText(value) {
1368
+ if (typeof value !== "string")
1369
+ return;
1370
+ const text = value.trim();
1371
+ return text.length > 0 && text.length <= MAX_ALERT_VALUE_LENGTH ? text : undefined;
1372
+ }
1373
+ function sanitizeHttpsUrl(value) {
1374
+ const text = filledText(value);
1375
+ if (!text)
1376
+ return;
1377
+ try {
1378
+ return new URL(text).protocol === "https:" ? text : undefined;
1379
+ } catch {
1380
+ return;
1381
+ }
1382
+ }
1383
+ function sanitizeAlerts(value) {
1384
+ if (!isRecord(value))
1385
+ return;
1386
+ const alerts = {};
1387
+ const slackWebhookUrl = sanitizeHttpsUrl(value.slack_webhook_url);
1388
+ if (slackWebhookUrl)
1389
+ alerts.slack_webhook_url = slackWebhookUrl;
1390
+ const slackBotToken = filledText(value.slack_bot_token);
1391
+ if (slackBotToken)
1392
+ alerts.slack_bot_token = slackBotToken;
1393
+ const slackChannel = filledText(value.slack_channel);
1394
+ if (slackChannel)
1395
+ alerts.slack_channel = slackChannel;
1396
+ const email = normalizeEnrollmentEmail(value.email);
1397
+ if (email)
1398
+ alerts.email = email;
1399
+ const emailFrom = filledText(value.email_from);
1400
+ if (emailFrom)
1401
+ alerts.email_from = emailFrom;
1402
+ const resendApiKey = filledText(value.resend_api_key);
1403
+ if (resendApiKey)
1404
+ alerts.resend_api_key = resendApiKey;
1405
+ return alerts;
1406
+ }
1353
1407
  function isProviderStrategy(value) {
1354
1408
  return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
1355
1409
  }
@@ -1363,6 +1417,23 @@ function sanitizeProviderBaseUrl(value) {
1363
1417
  return;
1364
1418
  }
1365
1419
  }
1420
+ function sanitizeClientRouting(value) {
1421
+ if (!isRecord(value))
1422
+ return;
1423
+ const client = {};
1424
+ if (typeof value.base_url === "string") {
1425
+ try {
1426
+ const url = new URL(value.base_url);
1427
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
1428
+ client.base_url = url.origin;
1429
+ }
1430
+ } catch {}
1431
+ }
1432
+ if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1433
+ client.proxy_key_file = value.proxy_key_file;
1434
+ }
1435
+ return Object.keys(client).length > 0 ? client : undefined;
1436
+ }
1366
1437
  function sanitizeProviderModels(value) {
1367
1438
  if (!isRecord(value))
1368
1439
  return;
@@ -1451,7 +1522,7 @@ function sanitizeTeamRouting(value) {
1451
1522
  }
1452
1523
  return result;
1453
1524
  }
1454
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
1525
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1455
1526
  var init_src4 = __esm(() => {
1456
1527
  init_src2();
1457
1528
  init_src3();
@@ -1498,17 +1569,30 @@ var init_src4 = __esm(() => {
1498
1569
  try {
1499
1570
  const content = readFileSync(this.configPath, "utf8");
1500
1571
  this.data = sanitizeConfigData(JSON.parse(content));
1501
- if ("default_agent_model" in this.data) {
1502
- delete this.data.default_agent_model;
1503
- this.saveConfig();
1504
- }
1505
1572
  } catch (error) {
1506
1573
  log2.error(`Failed to parse config file: ${error}`);
1507
1574
  this.data = {};
1575
+ return;
1576
+ }
1577
+ try {
1578
+ chmodSync(this.configPath, 384);
1579
+ } catch {
1580
+ let ownerOnly = false;
1581
+ try {
1582
+ ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
1583
+ } catch {}
1584
+ if (!ownerOnly) {
1585
+ throw new Error("Config file must be owner-only");
1586
+ }
1587
+ }
1588
+ if ("default_agent_model" in this.data) {
1589
+ delete this.data.default_agent_model;
1590
+ this.saveConfig();
1508
1591
  }
1509
1592
  } else {
1510
1593
  const dir = dirname(this.configPath);
1511
- mkdirSync2(dir, { recursive: true });
1594
+ mkdirSync2(dir, { recursive: true, mode: 448 });
1595
+ chmodSync(dir, 448);
1512
1596
  this.data = {
1513
1597
  lb_strategy: DEFAULT_STRATEGY
1514
1598
  };
@@ -1517,12 +1601,23 @@ var init_src4 = __esm(() => {
1517
1601
  }
1518
1602
  saveConfig() {
1519
1603
  try {
1520
- const content = JSON.stringify(this.data, null, 2);
1521
- writeFileSync(this.configPath, content, "utf8");
1604
+ this.writePrivately(this.data);
1522
1605
  } catch (error) {
1523
1606
  log2.error(`Failed to save config file: ${error}`);
1524
1607
  }
1525
1608
  }
1609
+ writePrivately(data) {
1610
+ const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1611
+ try {
1612
+ writeFileSync(temporary, JSON.stringify(data, null, 2), {
1613
+ mode: 384,
1614
+ flag: "wx"
1615
+ });
1616
+ renameSync(temporary, this.configPath);
1617
+ } finally {
1618
+ rmSync(temporary, { force: true });
1619
+ }
1620
+ }
1526
1621
  get(key, defaultValue) {
1527
1622
  const value = this.data[key];
1528
1623
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
@@ -1617,6 +1712,29 @@ var init_src4 = __esm(() => {
1617
1712
  quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
1618
1713
  };
1619
1714
  }
1715
+ getAlerts() {
1716
+ const file = this.data.alerts;
1717
+ return {
1718
+ slackWebhookUrl: file?.slack_webhook_url ?? null,
1719
+ slackBotToken: file?.slack_bot_token ?? null,
1720
+ slackChannel: file?.slack_channel ?? null,
1721
+ email: file?.email ?? null,
1722
+ emailFrom: file?.email_from ?? null,
1723
+ resendApiKey: file?.resend_api_key ?? null
1724
+ };
1725
+ }
1726
+ getClientRouting() {
1727
+ const client = this.data.client;
1728
+ return {
1729
+ ...client?.base_url && { baseUrl: client.base_url },
1730
+ ...client?.proxy_key_file && {
1731
+ proxyKeyFile: client.proxy_key_file
1732
+ }
1733
+ };
1734
+ }
1735
+ getBlockWhenAllFull() {
1736
+ return this.data.block_when_all_full !== false;
1737
+ }
1620
1738
  getProviderConfig(name) {
1621
1739
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1622
1740
  const configured = this.data.providers?.[name];
@@ -1717,22 +1835,14 @@ var init_src4 = __esm(() => {
1717
1835
  }
1718
1836
  persistStrictly(key, value) {
1719
1837
  const next = { ...this.data, [key]: value };
1720
- const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1721
- try {
1722
- writeFileSync(temporary, JSON.stringify(next, null, 2), {
1723
- mode: 384,
1724
- flag: "wx"
1725
- });
1726
- renameSync(temporary, this.configPath);
1727
- } finally {
1728
- rmSync(temporary, { force: true });
1729
- }
1838
+ this.writePrivately(next);
1730
1839
  const oldValue = this.data[key];
1731
1840
  this.data = next;
1732
1841
  this.emit("change", { key, oldValue, newValue: value });
1733
1842
  }
1734
1843
  getRuntime() {
1735
1844
  const defaults = {
1845
+ blockWhenAllFull: this.getBlockWhenAllFull(),
1736
1846
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
1737
1847
  maxBodyBytes: 64 * 1024 * 1024,
1738
1848
  quotaThreshold: 0.98,
@@ -4686,6 +4796,12 @@ var init_provider = __esm(() => {
4686
4796
  hasRateLimitSignal(headerName) {
4687
4797
  return super.hasRateLimitSignal(headerName) || headerName.toLowerCase().startsWith("anthropic-ratelimit-unified-");
4688
4798
  }
4799
+ spendsExtraUsage(response) {
4800
+ if (!response.ok)
4801
+ return false;
4802
+ const overageStatus = response.headers.get("anthropic-ratelimit-unified-overage-status");
4803
+ return response.headers.get("anthropic-ratelimit-unified-overage-in-use") === "true" || response.headers.get("anthropic-ratelimit-unified-status") === "rejected" && (overageStatus === "allowed" || overageStatus === "allowed_warning");
4804
+ }
4689
4805
  quotaBucketsFor(model) {
4690
4806
  const familyBucket = familyQuotaBucket(model);
4691
4807
  return familyBucket ? [...SHARED_QUOTA_BUCKETS, familyBucket] : SHARED_QUOTA_BUCKETS;
@@ -8367,28 +8483,58 @@ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
8367
8483
  }
8368
8484
  return true;
8369
8485
  }
8486
+ function fleetAccounts(provider, ctx) {
8487
+ const teamRouting = ctx.runtime.teamRouting;
8488
+ return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
8489
+ }
8490
+ function cooldownEnd(account2, now) {
8491
+ return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8492
+ }
8493
+ function blockingResets(provider, account2, model, ctx, now) {
8494
+ return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
8495
+ }
8496
+ function servableAt(provider, account2, model, ctx, now) {
8497
+ const cooldown = cooldownEnd(account2, now);
8498
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
8499
+ return cooldown;
8500
+ }
8501
+ const resets = blockingResets(provider, account2, model, ctx, now);
8502
+ return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
8503
+ }
8504
+ function soonestServableAt(provider, fleet, seats, model, ctx, now) {
8505
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
8506
+ return null;
8507
+ }
8508
+ const times = seats.flatMap((account2) => {
8509
+ const at = servableAt(provider, account2, model, ctx, now);
8510
+ return at === null ? [] : [at];
8511
+ });
8512
+ return times.length > 0 ? Math.min(...times) : null;
8513
+ }
8370
8514
  function getPoolStatus(provider, model, ctx) {
8371
8515
  const providerStrategy = ctx.providerRegistry.getProvider(provider);
8372
8516
  if (!providerStrategy)
8373
8517
  throw new Error(`Unknown provider '${provider}'`);
8374
8518
  const config = ctx.runtime.teamRouting;
8375
8519
  const now = Date.now();
8376
- const accounts = config?.enabled ? ctx.dbOps.getAvailableAccountsByProvider(provider).filter((account2) => isAllowlisted(account2, config)) : [];
8377
- const eligibleAccounts = accounts.filter((account2) => isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8378
- const resets = accounts.flatMap((account2) => Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(providerStrategy, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt));
8520
+ const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
8521
+ const eligibleAccounts = accounts.filter((account2) => cooldownEnd(account2, now) === null && isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8379
8522
  return {
8380
8523
  version: 1,
8381
8524
  provider,
8382
8525
  routingEnabled: config?.enabled === true,
8383
8526
  eligibleAccounts,
8384
- retryAtMs: eligibleAccounts === 0 && resets.length > 0 ? Math.min(...resets) : null,
8527
+ retryAtMs: eligibleAccounts === 0 ? soonestServableAt(providerStrategy, accounts, accounts, model, ctx, now) : null,
8385
8528
  holdSeconds: config?.holdSeconds ?? 0,
8386
8529
  admissionWaitMs: config?.admissionWaitMs ?? 0
8387
8530
  };
8388
8531
  }
8389
- function getSoonestQuotaReset(meta, ctx, now = Date.now()) {
8390
- const resets = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).flatMap((account2) => Object.entries(account2.quota_state?.windows ?? {}).map(([bucket, window2]) => ({ account: account2, bucket, window: window2 }))).filter(({ account: account2, bucket, window: window2 }) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(ctx.provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, meta.model, pooledMaxUsage(account2, ctx))).map(({ window: window2 }) => window2.resetAt);
8391
- return resets.length > 0 ? Math.min(...resets) : null;
8532
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
8533
+ const fleet = fleetAccounts(ctx.providerName, ctx);
8534
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
8535
+ }
8536
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
8537
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8392
8538
  }
8393
8539
  function selectRevalidationProbe(accounts, ctx, now) {
8394
8540
  const probes = ctx.quotaProbeAt;
@@ -8408,7 +8554,7 @@ function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8408
8554
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8409
8555
  const now = Date.now();
8410
8556
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8411
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8557
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8412
8558
  const prioritized = [...candidates].sort((left, right) => {
8413
8559
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
8414
8560
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9745,9 +9891,15 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9745
9891
  try {
9746
9892
  const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
9747
9893
  if (attempt.kind === "response") {
9894
+ const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
9748
9895
  return {
9749
9896
  ...attempt,
9750
- response: releaseAfterResponse(attempt.response, release)
9897
+ response: releaseAfterResponse(attempt.response, () => {
9898
+ release();
9899
+ if (spentExtraUsage) {
9900
+ request2.ctx.seatAlerts?.extraUsageSpent(account2, request2.ctx.providerName);
9901
+ }
9902
+ })
9751
9903
  };
9752
9904
  }
9753
9905
  release();
@@ -9923,23 +10075,32 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
9923
10075
  provider: ctx.providerName,
9924
10076
  sessionId
9925
10077
  };
9926
- const selectedAccounts = selectAccountsForRequest(meta, ctx, teamRequest, selectionOptions);
9927
- const threadAccountId = getThreadBoundAccountId(ctx.messageThreads, thread);
9928
- const accounts = threadAccountId ? selectedAccounts.filter((account2) => account2.id === threadAccountId) : selectedAccounts;
10078
+ const request2 = {
10079
+ body,
10080
+ ctx,
10081
+ mappedModel,
10082
+ meta,
10083
+ req,
10084
+ teamRequest,
10085
+ thread,
10086
+ url
10087
+ };
9929
10088
  return {
9930
- accounts,
9931
- request: {
9932
- body,
9933
- ctx,
9934
- mappedModel,
9935
- meta,
9936
- req,
9937
- teamRequest,
9938
- thread,
9939
- url
9940
- }
10089
+ accounts: selectRequestAccounts(request2, selectionOptions),
10090
+ request: request2
9941
10091
  };
9942
10092
  }
10093
+ function onThreadSeat(request2, accounts) {
10094
+ const threadAccountId = getThreadBoundAccountId(request2.ctx.messageThreads, request2.thread);
10095
+ return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
10096
+ }
10097
+ function selectRequestAccounts(request2, selectionOptions) {
10098
+ return onThreadSeat(request2, selectAccountsForRequest(request2.meta, request2.ctx, request2.teamRequest, selectionOptions));
10099
+ }
10100
+ function getRequestRetryAt(request2) {
10101
+ const { ctx, teamRequest } = request2;
10102
+ return getSoonestQuotaReset(request2.meta, ctx, (fleet) => onThreadSeat(request2, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10103
+ }
9943
10104
  var init_proxy_request = __esm(() => {
9944
10105
  init_account_selector();
9945
10106
  init_message_thread();
@@ -10061,8 +10222,16 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10061
10222
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10062
10223
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10063
10224
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
10064
- let soonestReset = null;
10225
+ let soonestRetry = null;
10226
+ let soonestFleetReset = null;
10227
+ let everyCandidateFull = true;
10065
10228
  let emittedIngress = false;
10229
+ const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
10230
+ const recordUnserved = (request2) => {
10231
+ everyCandidateFull &&= isEveryAccountQuotaBlocked(request2.meta, request2.ctx);
10232
+ soonestRetry = earliest(soonestRetry, getRequestRetryAt(request2));
10233
+ soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request2.meta, request2.ctx));
10234
+ };
10066
10235
  const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10067
10236
  for (const [candidateIndex, candidate] of candidates.entries()) {
10068
10237
  const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
@@ -10074,8 +10243,7 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10074
10243
  }
10075
10244
  accounts = preferPinnedAccount(accounts, pinnedId);
10076
10245
  if (accounts.length === 0) {
10077
- const resetAt3 = getSoonestQuotaReset(candidateMeta, candidateContext);
10078
- soonestReset = resetAt3 !== null && (soonestReset === null || resetAt3 < soonestReset) ? resetAt3 : soonestReset;
10246
+ recordUnserved(prepared.request);
10079
10247
  continue;
10080
10248
  }
10081
10249
  if (!emittedIngress) {
@@ -10096,11 +10264,13 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10096
10264
  }
10097
10265
  return result.response;
10098
10266
  }
10099
- const resetAt2 = getSoonestQuotaReset(candidateMeta, candidateContext);
10100
- soonestReset = resetAt2 !== null && (soonestReset === null || resetAt2 < soonestReset) ? resetAt2 : soonestReset;
10267
+ recordUnserved(prepared.request);
10101
10268
  }
10102
- if (soonestReset !== null)
10103
- return quotaExhaustionResponse(soonestReset);
10269
+ if (everyCandidateFull && soonestFleetReset !== null) {
10270
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
10271
+ }
10272
+ if (soonestRetry !== null)
10273
+ return quotaExhaustionResponse(soonestRetry);
10104
10274
  log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10105
10275
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
10106
10276
  }
@@ -10114,6 +10284,133 @@ var init_provider_pool = __esm(() => {
10114
10284
  log22 = new Logger("Proxy");
10115
10285
  });
10116
10286
 
10287
+ // ../../packages/proxy/src/seat-alerts.ts
10288
+ function alertWhenFleetFull(meta, ctx, holdSeconds) {
10289
+ const resetAt2 = getSoonestQuotaReset(meta, ctx);
10290
+ if (resetAt2 === null || !isEveryAccountQuotaBlocked(meta, ctx))
10291
+ return;
10292
+ ctx.seatAlerts?.allAccountsFull(ctx.providerName, resetAt2, {
10293
+ blocked: ctx.runtime.blockWhenAllFull,
10294
+ holdSeconds
10295
+ });
10296
+ }
10297
+ function utc(at) {
10298
+ return `${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
10299
+ }
10300
+
10301
+ class SeatAlerts {
10302
+ config;
10303
+ send;
10304
+ fullUntil = new Map;
10305
+ constructor(config, send = (url, init) => fetch(url, init)) {
10306
+ this.config = config;
10307
+ this.send = send;
10308
+ if (config.email && !(config.emailFrom && config.resendApiKey)) {
10309
+ log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
10310
+ }
10311
+ if (!config.slackBotToken !== !config.slackChannel) {
10312
+ log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
10313
+ }
10314
+ }
10315
+ extraUsageSpent(account2, provider) {
10316
+ const claim = account2.quota_state?.representativeClaim;
10317
+ const resetAt2 = account2.quota_state?.windows.unified?.resetAt;
10318
+ this.notify({
10319
+ subject: `agent-smith: ${account2.name} spent extra usage`,
10320
+ text: `${account2.name} (${provider}) is past its plan limit${claim ? ` (${claim})` : ""} and a response it just served was billed to extra usage.${resetAt2 ? ` The limit resets at ${utc(resetAt2)}.` : ""}`
10321
+ });
10322
+ }
10323
+ allAccountsFull(scope, resetAt2, policy) {
10324
+ if ((this.fullUntil.get(scope) ?? 0) > Date.now())
10325
+ return;
10326
+ this.fullUntil.set(scope, resetAt2);
10327
+ const probe = policy.blocked ? "" : ", except one a minute that revalidates and may spend extra usage";
10328
+ const hold = policy.holdSeconds > 0 ? `; one within ${policy.holdSeconds}s of the reset waits for it instead` : "";
10329
+ this.notify({
10330
+ subject: `agent-smith: every ${scope} account is full`,
10331
+ text: `Every ${scope} account is out of quota until ${utc(resetAt2)}. Requests are refused until then${probe}${hold}.`
10332
+ });
10333
+ }
10334
+ notify(alert) {
10335
+ log23.warn(alert.text);
10336
+ for (const delivery of this.deliveries(alert)) {
10337
+ trackProxyBackgroundTask(this.deliver(delivery));
10338
+ }
10339
+ }
10340
+ deliveries(alert) {
10341
+ const {
10342
+ email,
10343
+ emailFrom,
10344
+ resendApiKey,
10345
+ slackBotToken,
10346
+ slackChannel,
10347
+ slackWebhookUrl
10348
+ } = this.config;
10349
+ const deliveries = [];
10350
+ if (slackWebhookUrl) {
10351
+ deliveries.push({
10352
+ channel: "Slack",
10353
+ url: slackWebhookUrl,
10354
+ body: { text: alert.text }
10355
+ });
10356
+ }
10357
+ if (slackBotToken && slackChannel) {
10358
+ deliveries.push({
10359
+ channel: "Slack",
10360
+ url: SLACK_POST_MESSAGE_URL,
10361
+ headers: { authorization: `Bearer ${slackBotToken}` },
10362
+ body: { channel: slackChannel, text: alert.text },
10363
+ repliesOk: true
10364
+ });
10365
+ }
10366
+ if (email && emailFrom && resendApiKey) {
10367
+ deliveries.push({
10368
+ channel: "email",
10369
+ url: RESEND_EMAILS_URL,
10370
+ headers: { authorization: `Bearer ${resendApiKey}` },
10371
+ body: {
10372
+ from: emailFrom,
10373
+ to: [email],
10374
+ subject: alert.subject,
10375
+ text: alert.text
10376
+ }
10377
+ });
10378
+ }
10379
+ return deliveries;
10380
+ }
10381
+ async deliver(delivery) {
10382
+ try {
10383
+ const response = await this.send(delivery.url, {
10384
+ method: "POST",
10385
+ headers: { "content-type": "application/json", ...delivery.headers },
10386
+ body: JSON.stringify(delivery.body),
10387
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
10388
+ });
10389
+ if (!response.ok) {
10390
+ log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
10391
+ return;
10392
+ }
10393
+ if (!delivery.repliesOk)
10394
+ return;
10395
+ const reply = await response.json();
10396
+ if (reply.ok !== true) {
10397
+ const code = typeof reply.error === "string" && SLACK_ERROR_CODE.test(reply.error) ? reply.error : "no reason given";
10398
+ log23.warn(`${delivery.channel} alert was refused (${code})`);
10399
+ }
10400
+ } catch (error) {
10401
+ log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
10402
+ }
10403
+ }
10404
+ }
10405
+ var log23, RESEND_EMAILS_URL = "https://api.resend.com/emails", SLACK_POST_MESSAGE_URL = "https://slack.com/api/chat.postMessage", SEND_TIMEOUT_MS = 1e4, SLACK_ERROR_CODE;
10406
+ var init_seat_alerts = __esm(() => {
10407
+ init_src3();
10408
+ init_background_tasks();
10409
+ init_account_selector();
10410
+ log23 = new Logger("SeatAlerts");
10411
+ SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
10412
+ });
10413
+
10117
10414
  // ../../packages/proxy/src/usage-worker.ts
10118
10415
  import { isAbsolute, resolve } from "path";
10119
10416
  import { pathToFileURL } from "url";
@@ -10495,7 +10792,7 @@ function getUsageWorker() {
10495
10792
  }
10496
10793
  if (!usageWorkerInstance) {
10497
10794
  usageWorkerInstance = new UsageWorkerController({
10498
- logger: log23,
10795
+ logger: log24,
10499
10796
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
10500
10797
  onWorkerMessage: (data) => {
10501
10798
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -10566,21 +10863,23 @@ async function handleProxy(req, url, ctx) {
10566
10863
  const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
10567
10864
  let accounts = initiallySelectedAccounts;
10568
10865
  if (accounts.length === 0) {
10569
- const resetAt2 = getSoonestQuotaReset(requestMeta, requestContext);
10570
- if (resetAt2 !== null) {
10571
- const holdMs = requestContext.runtime.teamRouting.holdSeconds * 1000;
10572
- if (requestContext.runtime.teamRouting.enabled && holdMs > 0 && resetAt2 - Date.now() <= holdMs && requestContext.quotaHold) {
10573
- await requestContext.quotaHold.waitUntil(resetAt2, req.signal);
10574
- const resumedAccounts = selectAccountsForRequest(request2.meta, requestContext, request2.teamRequest);
10866
+ const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
10867
+ alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
10868
+ const retryAt = getRequestRetryAt(request2);
10869
+ if (retryAt !== null) {
10870
+ const holdMs = holdSeconds * 1000;
10871
+ if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
10872
+ await requestContext.quotaHold.waitUntil(retryAt, req.signal);
10873
+ const resumedAccounts = selectRequestAccounts(request2);
10575
10874
  if (resumedAccounts.length > 0) {
10576
10875
  accounts = resumedAccounts;
10577
10876
  }
10578
10877
  }
10579
10878
  if (accounts.length === 0)
10580
- return quotaExhaustionResponse(resetAt2);
10879
+ return quotaExhaustionResponse(retryAt);
10581
10880
  }
10582
10881
  if (accounts.length === 0) {
10583
- log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10882
+ log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10584
10883
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
10585
10884
  }
10586
10885
  }
@@ -10591,19 +10890,20 @@ async function handleProxy(req, url, ctx) {
10591
10890
  method: requestMeta.method,
10592
10891
  path: requestMeta.path
10593
10892
  });
10594
- log23.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10595
- log23.info(`Request: ${req.method} ${url.pathname}`);
10893
+ log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10894
+ log24.info(`Request: ${req.method} ${url.pathname}`);
10596
10895
  return await proxySelectedAccounts(request2, accounts);
10597
10896
  }
10598
- var log23, usageWorkerInstance = null;
10897
+ var log24, usageWorkerInstance = null;
10599
10898
  var init_proxy = __esm(() => {
10600
10899
  init_src2();
10601
10900
  init_src3();
10602
10901
  init_src();
10603
10902
  init_handlers();
10604
10903
  init_provider_pool();
10904
+ init_seat_alerts();
10605
10905
  init_usage_worker();
10606
- log23 = new Logger("Proxy");
10906
+ log24 = new Logger("Proxy");
10607
10907
  });
10608
10908
 
10609
10909
  // ../../packages/proxy/src/quota-hold.ts
@@ -10951,7 +11251,7 @@ function endActiveTurn(session, success, error) {
10951
11251
  if (!activeTurn) {
10952
11252
  return;
10953
11253
  }
10954
- log24.debug("Ending tracked websocket turn", {
11254
+ log25.debug("Ending tracked websocket turn", {
10955
11255
  requestId: activeTurn.requestId,
10956
11256
  provider: session.providerName,
10957
11257
  path: session.path,
@@ -11004,7 +11304,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
11004
11304
  timestamp,
11005
11305
  model: getEventModel(parsed)
11006
11306
  };
11007
- log24.debug("Starting tracked websocket turn", {
11307
+ log25.debug("Starting tracked websocket turn", {
11008
11308
  requestId,
11009
11309
  provider: session.providerName,
11010
11310
  path: session.path,
@@ -11034,7 +11334,7 @@ function handleTrackedUpstreamText(session, data) {
11034
11334
  if (!messageType) {
11035
11335
  return;
11036
11336
  }
11037
- log24.debug("Processing tracked websocket message", {
11337
+ log25.debug("Processing tracked websocket message", {
11038
11338
  provider: session.providerName,
11039
11339
  path: session.path,
11040
11340
  messageType,
@@ -11075,7 +11375,7 @@ function capturePendingRequestBody(session, message) {
11075
11375
  }
11076
11376
  session.pendingRequestBody = Buffer.from(message).toString("base64");
11077
11377
  session.pendingRequestTimestamp = Date.now();
11078
- log24.debug("Captured websocket request body for next tracked turn", {
11378
+ log25.debug("Captured websocket request body for next tracked turn", {
11079
11379
  provider: session.providerName,
11080
11380
  path: session.path,
11081
11381
  size: message.length
@@ -11148,7 +11448,7 @@ async function connectToNextUpstream(ws) {
11148
11448
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
11149
11449
  } catch (error) {
11150
11450
  session.connecting = false;
11151
- log24.warn("Skipping websocket account during upstream connection", {
11451
+ log25.warn("Skipping websocket account during upstream connection", {
11152
11452
  account: account2.name,
11153
11453
  error: error instanceof Error ? error.message : String(error)
11154
11454
  });
@@ -11207,7 +11507,7 @@ async function connectToNextUpstream(ws) {
11207
11507
  }
11208
11508
  });
11209
11509
  upstream.addEventListener("error", () => {
11210
- log24.warn("Upstream websocket error", {
11510
+ log25.warn("Upstream websocket error", {
11211
11511
  account: plan.account.name,
11212
11512
  provider: session.providerName,
11213
11513
  path: session.path
@@ -11216,7 +11516,7 @@ async function connectToNextUpstream(ws) {
11216
11516
  } catch (error) {
11217
11517
  session.connecting = false;
11218
11518
  clearConnectTimeout(session);
11219
- log24.warn("Failed to create upstream websocket", {
11519
+ log25.warn("Failed to create upstream websocket", {
11220
11520
  account: plan.account.name,
11221
11521
  error: error instanceof Error ? error.message : String(error)
11222
11522
  });
@@ -11259,7 +11559,8 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11259
11559
  };
11260
11560
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
11261
11561
  if (accounts.length === 0) {
11262
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11562
+ alertWhenFleetFull(requestMeta, requestContext, 0);
11563
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11263
11564
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
11264
11565
  }
11265
11566
  const protocols = getProtocols(req.headers);
@@ -11297,7 +11598,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11297
11598
  }
11298
11599
  return;
11299
11600
  }
11300
- var log24, CONNECT_TIMEOUT_MS = 5000, PENDING_MESSAGE_LIMIT = 128, CLOSE_CODE_NORMAL = 1000, CLOSE_CODE_INTERNAL_ERROR = 1011, CLOSE_CODE_TRY_AGAIN_LATER = 1013, websocketSessions, textEncoder, websocketProxyHandler;
11601
+ var log25, CONNECT_TIMEOUT_MS = 5000, PENDING_MESSAGE_LIMIT = 128, CLOSE_CODE_NORMAL = 1000, CLOSE_CODE_INTERNAL_ERROR = 1011, CLOSE_CODE_TRY_AGAIN_LATER = 1013, websocketSessions, textEncoder, websocketProxyHandler;
11301
11602
  var init_websocket_proxy = __esm(() => {
11302
11603
  init_src2();
11303
11604
  init_src6();
@@ -11307,7 +11608,8 @@ var init_websocket_proxy = __esm(() => {
11307
11608
  init_request_handler();
11308
11609
  init_token_manager();
11309
11610
  init_openai_usage();
11310
- log24 = new Logger("WebSocketProxy");
11611
+ init_seat_alerts();
11612
+ log25 = new Logger("WebSocketProxy");
11311
11613
  websocketSessions = new Map;
11312
11614
  textEncoder = new TextEncoder;
11313
11615
  websocketProxyHandler = {
@@ -11361,6 +11663,7 @@ var init_src10 = __esm(() => {
11361
11663
  init_proxy();
11362
11664
  init_quota_probe();
11363
11665
  init_response_handler();
11666
+ init_seat_alerts();
11364
11667
  init_strategies();
11365
11668
  init_team_admission();
11366
11669
  init_team_router();
@@ -11406,12 +11709,23 @@ function safeKeyEqual(candidate, expected) {
11406
11709
  }
11407
11710
  return timingSafeEqual(Buffer.from(candidate), Buffer.from(expected));
11408
11711
  }
11409
- function keyRole(req, config) {
11410
- const key = req.headers.get("x-api-key");
11411
- if (safeKeyEqual(key, config.adminKey)) {
11712
+ function bearerToken(req) {
11713
+ const authorization = req.headers.get("authorization");
11714
+ const match = authorization?.match(/^Bearer ([^\s]+)$/);
11715
+ return match?.[1] ?? null;
11716
+ }
11717
+ function isResponsesInferenceRoute(pathname) {
11718
+ return pathname === "/v1/codex/responses" || pathname === "/v1/pool/openai-responses/responses";
11719
+ }
11720
+ function keyRole(req, url, config) {
11721
+ const apiKey = req.headers.get("x-api-key");
11722
+ if (safeKeyEqual(apiKey, config.adminKey)) {
11412
11723
  return "admin";
11413
11724
  }
11414
- if (safeKeyEqual(key, config.proxyKey)) {
11725
+ if (safeKeyEqual(apiKey, config.proxyKey)) {
11726
+ return "proxy";
11727
+ }
11728
+ if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
11415
11729
  return "proxy";
11416
11730
  }
11417
11731
  return null;
@@ -11451,7 +11765,7 @@ function jsonError(status, message) {
11451
11765
  function exposureFailure(req, url, server, config) {
11452
11766
  const remote = requestAddress(server, req);
11453
11767
  const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
11454
- const role = keyRole(req, config);
11768
+ const role = keyRole(req, url, config);
11455
11769
  if (!role && !loopbackExempt) {
11456
11770
  return jsonError(401, "A proxy key is required for this request");
11457
11771
  }
@@ -11484,6 +11798,7 @@ var init_exposure = __esm(() => {
11484
11798
  // ../../packages/runtime-server/src/bootstrap-runtime.ts
11485
11799
  function createRuntimeConfig(config, port) {
11486
11800
  return {
11801
+ blockWhenAllFull: config.getBlockWhenAllFull(),
11487
11802
  clientId: config.get("client_id", "9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
11488
11803
  maxBodyBytes: config.get("max_body_bytes", 64 * 1024 * 1024),
11489
11804
  requestScopedRetryDelayMs: config.get("request_scoped_429_retry_delay_ms", 2000),
@@ -11498,10 +11813,10 @@ function createRuntimeConfig(config, port) {
11498
11813
  teamRouting: config.getTeamRouting()
11499
11814
  };
11500
11815
  }
11501
- function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11816
+ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11502
11817
  config.on("change", (change) => {
11503
11818
  if (change.key === "lb_strategy") {
11504
- log25.info("Strategy configuration changed");
11819
+ log26.info("Strategy configuration changed");
11505
11820
  const newStrategyName = config.getStrategy();
11506
11821
  if (newStrategyName === "session") {
11507
11822
  const strategy3 = new SessionStrategy;
@@ -11512,7 +11827,7 @@ function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig
11512
11827
  if (change.key === "team_routing") {
11513
11828
  runtimeConfig2.teamRouting = config.getTeamRouting();
11514
11829
  quotaProbe.reschedule();
11515
- log25.info("Team routing configuration changed");
11830
+ log26.info("Team routing configuration changed");
11516
11831
  }
11517
11832
  });
11518
11833
  }
@@ -11526,7 +11841,7 @@ function bootstrapRuntime(port, serverLog) {
11526
11841
  sessionDurationMs: runtimeConfig2.sessionDurationMs
11527
11842
  });
11528
11843
  const dbOps = DatabaseFactory.getInstance();
11529
- const log25 = container.resolve(SERVICE_KEYS.Logger);
11844
+ const log26 = container.resolve(SERVICE_KEYS.Logger);
11530
11845
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
11531
11846
  const asyncWriter = new AsyncDbWriter;
11532
11847
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -11574,6 +11889,7 @@ function bootstrapRuntime(port, serverLog) {
11574
11889
  teamAdmission,
11575
11890
  quotaHold,
11576
11891
  outsideSpendTracker,
11892
+ seatAlerts: new SeatAlerts(config.getAlerts()),
11577
11893
  asyncWriter,
11578
11894
  usageWorker: getUsageWorker()
11579
11895
  };
@@ -11590,11 +11906,11 @@ function bootstrapRuntime(port, serverLog) {
11590
11906
  });
11591
11907
  quotaProbe.start();
11592
11908
  registerDisposable(quotaProbe);
11593
- wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11909
+ wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11594
11910
  return {
11595
11911
  config,
11596
11912
  dbOps,
11597
- log: log25,
11913
+ log: log26,
11598
11914
  asyncWriter,
11599
11915
  apiRouter,
11600
11916
  exposureConfig,
@@ -11603,12 +11919,12 @@ function bootstrapRuntime(port, serverLog) {
11603
11919
  runtimeConfig: runtimeConfig2
11604
11920
  };
11605
11921
  }
11606
- function logInitialAccountStatus(log25, dbOps) {
11922
+ function logInitialAccountStatus(log26, dbOps) {
11607
11923
  const accounts = dbOps.getAllAccounts();
11608
11924
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
11609
- log25.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11925
+ log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11610
11926
  if (activeAccounts.length === 0) {
11611
- log25.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11927
+ log26.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11612
11928
  }
11613
11929
  }
11614
11930
  var init_bootstrap_runtime = __esm(() => {
@@ -11835,20 +12151,20 @@ var init_startup_banner = __esm(() => {
11835
12151
 
11836
12152
  // ../../packages/runtime-server/src/startup-maintenance.ts
11837
12153
  function runStartupMaintenance(config, dbOps) {
11838
- const log25 = new Logger("StartupMaintenance");
12154
+ const log26 = new Logger("StartupMaintenance");
11839
12155
  try {
11840
12156
  const payloadDays = config.getDataRetentionDays();
11841
12157
  const requestDays = config.getRequestRetentionDays();
11842
12158
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
11843
- log25.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
12159
+ log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
11844
12160
  } catch (err) {
11845
- log25.error(`Startup cleanup error: ${err}`);
12161
+ log26.error(`Startup cleanup error: ${err}`);
11846
12162
  }
11847
12163
  try {
11848
12164
  dbOps.compact();
11849
- log25.info("Database compacted at startup");
12165
+ log26.info("Database compacted at startup");
11850
12166
  } catch (err) {
11851
- log25.error(`Database compaction error: ${err}`);
12167
+ log26.error(`Database compaction error: ${err}`);
11852
12168
  }
11853
12169
  return () => {};
11854
12170
  }
@@ -11945,7 +12261,7 @@ function startServer(options) {
11945
12261
  const {
11946
12262
  config,
11947
12263
  dbOps,
11948
- log: log25,
12264
+ log: log26,
11949
12265
  apiRouter,
11950
12266
  exposureConfig,
11951
12267
  proxyContext,
@@ -11988,7 +12304,7 @@ function startServer(options) {
11988
12304
  strategy: config.getStrategy(),
11989
12305
  providers: providerRegistry.listProviders()
11990
12306
  }));
11991
- logInitialAccountStatus(log25, dbOps);
12307
+ logInitialAccountStatus(log26, dbOps);
11992
12308
  return {
11993
12309
  port: activePort,
11994
12310
  stop: () => stopServerRuntime(),
@@ -13562,6 +13878,9 @@ var init_analytics2 = __esm(() => {
13562
13878
  // src/core/args.ts
13563
13879
  import { parseArgs as nodeParseArgs } from "util";
13564
13880
  function parseArgs(args) {
13881
+ if (args.length === 1 && args[0] === "install-client") {
13882
+ return { installClient: true };
13883
+ }
13565
13884
  if (args[0] === "run") {
13566
13885
  const separator = args.indexOf("--");
13567
13886
  if (separator === -1) {
@@ -13637,11 +13956,12 @@ var init_args = () => {};
13637
13956
  // src/core/local-routing.ts
13638
13957
  import {
13639
13958
  accessSync,
13640
- chmodSync,
13959
+ chmodSync as chmodSync2,
13641
13960
  constants as constants2,
13642
13961
  existsSync as existsSync3,
13643
13962
  mkdirSync as mkdirSync4,
13644
13963
  readFileSync as readFileSync3,
13964
+ statSync as statSync3,
13645
13965
  unlinkSync as unlinkSync2,
13646
13966
  writeFileSync as writeFileSync2
13647
13967
  } from "fs";
@@ -13653,25 +13973,56 @@ function shellQuote(value) {
13653
13973
  function shellDoubleQuote(value) {
13654
13974
  return `"${value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
13655
13975
  }
13656
- function proxyBaseUrl(port, directProvider, wire, providerPoolWires) {
13976
+ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoolWires) {
13657
13977
  const route = providerPoolWires?.includes(wire) ? `/v1/pool/${wire}` : `/v1/${directProvider}`;
13658
- return `http://127.0.0.1:${port}${route}`;
13978
+ return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
13979
+ }
13980
+ function validateProxyKeyFile(proxyKeyFile) {
13981
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join8(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
13982
+ let metadata;
13983
+ try {
13984
+ metadata = statSync3(resolvedPath);
13985
+ } catch {
13986
+ throw new Error("Agent-smith forwarding-key file is not readable");
13987
+ }
13988
+ if (!metadata.isFile()) {
13989
+ throw new Error("Agent-smith forwarding-key path must be a file");
13990
+ }
13991
+ if ((metadata.mode & 63) !== 0) {
13992
+ throw new Error("Agent-smith forwarding-key file must be owner-only");
13993
+ }
13994
+ const key = readFileSync3(resolvedPath, "utf8").trim();
13995
+ if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
13996
+ throw new Error("Agent-smith forwarding-key file is invalid");
13997
+ }
13998
+ return resolvedPath;
13659
13999
  }
13660
- function claudeWrapper(claudePath, baseUrl) {
14000
+ function proxyKeySetup(proxyKeyFile) {
14001
+ if (!proxyKeyFile) {
14002
+ return `export AGENT_SMITH_PROXY_KEY=${shellQuote(LOCAL_CLIENT_KEY)}`;
14003
+ }
14004
+ return `if [ ! -r ${shellQuote(proxyKeyFile)} ]; then
14005
+ echo "Agent-smith forwarding-key file is not readable" >&2
14006
+ exit 1
14007
+ fi
14008
+ export AGENT_SMITH_PROXY_KEY=$(cat ${shellQuote(proxyKeyFile)})`;
14009
+ }
14010
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile) {
13661
14011
  return `#!/bin/sh
13662
14012
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
13663
14013
  unset CF_ADMIN_KEY
13664
14014
  unset CF_PROXY_KEY
13665
- export ANTHROPIC_API_KEY=${shellQuote(LOCAL_CLIENT_KEY)}
13666
- export ANTHROPIC_AUTH_TOKEN=${shellQuote(LOCAL_CLIENT_KEY)}
14015
+ ${proxyKeySetup(proxyKeyFile)}
14016
+ export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"
14017
+ export ANTHROPIC_AUTH_TOKEN="$AGENT_SMITH_PROXY_KEY"
13667
14018
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
13668
14019
  exec ${shellQuote(claudePath)} "$@"
13669
14020
  `;
13670
14021
  }
13671
- function codexWrapper(codexPath, baseUrl) {
14022
+ function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
13672
14023
  const config = [
13673
14024
  'model_provider="agent_smith"',
13674
- 'model_providers.agent_smith.name="Agent-smith local pool"',
14025
+ 'model_providers.agent_smith.name="Agent-smith"',
13675
14026
  `model_providers.agent_smith.base_url="${baseUrl}"`,
13676
14027
  'model_providers.agent_smith.env_key="AGENT_SMITH_PROXY_KEY"',
13677
14028
  'model_providers.agent_smith.wire_api="responses"',
@@ -13683,29 +14034,33 @@ function codexWrapper(codexPath, baseUrl) {
13683
14034
  # Generated by agent-smith. This file delegates to the real Codex binary.
13684
14035
  unset CF_ADMIN_KEY
13685
14036
  unset CF_PROXY_KEY
13686
- export AGENT_SMITH_PROXY_KEY=${shellQuote(LOCAL_CLIENT_KEY)}
14037
+ ${proxyKeySetup(proxyKeyFile)}
13687
14038
  exec ${shellQuote(codexPath)} \\
13688
14039
  ${overrides} \\
13689
14040
  "$@"
13690
14041
  `;
13691
14042
  }
13692
14043
  async function installClientWrappers(options) {
14044
+ if (options.baseUrl && !options.proxyKeyFile) {
14045
+ throw new Error("A configured Agent-smith server requires a forwarding key file");
14046
+ }
13693
14047
  mkdirSync4(options.binDir, { recursive: true, mode: 448 });
14048
+ const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
13694
14049
  if (options.claudePath) {
13695
14050
  const claude = join8(options.binDir, "claude");
13696
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, "claude-code", "anthropic-messages", options.providerPoolWires)), {
14051
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile), {
13697
14052
  encoding: "utf8",
13698
14053
  mode: 448
13699
14054
  });
13700
- chmodSync(claude, 448);
14055
+ chmodSync2(claude, 448);
13701
14056
  }
13702
14057
  if (options.codexPath) {
13703
14058
  const codex = join8(options.binDir, "codex");
13704
- writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, "codex", "openai-responses", options.providerPoolWires)), {
14059
+ writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
13705
14060
  encoding: "utf8",
13706
14061
  mode: 448
13707
14062
  });
13708
- chmodSync(codex, 448);
14063
+ chmodSync2(codex, 448);
13709
14064
  }
13710
14065
  }
13711
14066
  function defaultShellProfile() {
@@ -13792,6 +14147,8 @@ async function enableLocalClientRouting(options) {
13792
14147
  claudePath,
13793
14148
  codexPath,
13794
14149
  port: options.port,
14150
+ baseUrl: options.baseUrl,
14151
+ proxyKeyFile: options.proxyKeyFile,
13795
14152
  providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
13796
14153
  });
13797
14154
  const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
@@ -13801,7 +14158,7 @@ async function enableLocalClientRouting(options) {
13801
14158
  encoding: "utf8",
13802
14159
  mode: 384
13803
14160
  });
13804
- chmodSync(statePath, 384);
14161
+ chmodSync2(statePath, 384);
13805
14162
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
13806
14163
  }
13807
14164
  function disableLocalClientRouting(paths2 = {}) {
@@ -15851,13 +16208,13 @@ function reducer(state, action) {
15851
16208
  function LogsScreen({ refreshKey }) {
15852
16209
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
15853
16210
  const logKeyCounts = new Map;
15854
- const keyedLogs = state.logs.map((log25) => {
15855
- const baseKey = `${log25.ts}-${log25.level ?? ""}-${log25.msg}`;
16211
+ const keyedLogs = state.logs.map((log26) => {
16212
+ const baseKey = `${log26.ts}-${log26.level ?? ""}-${log26.msg}`;
15856
16213
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
15857
16214
  logKeyCounts.set(baseKey, count);
15858
16215
  return {
15859
16216
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
15860
- log: log25
16217
+ log: log26
15861
16218
  };
15862
16219
  });
15863
16220
  useKeyboard3((key) => {
@@ -15881,8 +16238,8 @@ function LogsScreen({ refreshKey }) {
15881
16238
  }, [refreshKey]);
15882
16239
  useEffect3(() => {
15883
16240
  if (!state.paused && !state.loading) {
15884
- const unsubscribe = streamLogs((log25) => {
15885
- dispatch({ type: "new_entry", log: log25 });
16241
+ const unsubscribe = streamLogs((log26) => {
16242
+ dispatch({ type: "new_entry", log: log26 });
15886
16243
  });
15887
16244
  return () => {
15888
16245
  unsubscribe();
@@ -15935,15 +16292,15 @@ function LogsScreen({ refreshKey }) {
15935
16292
  children: "No logs yet..."
15936
16293
  }) : /* @__PURE__ */ jsx7("box", {
15937
16294
  flexDirection: "column",
15938
- children: keyedLogs.map(({ key, log: log25 }) => {
15939
- const sev = getLogSeverityMeta(log25.level);
16295
+ children: keyedLogs.map(({ key, log: log26 }) => {
16296
+ const sev = getLogSeverityMeta(log26.level);
15940
16297
  return /* @__PURE__ */ jsxs7("text", {
15941
16298
  fg: sev.termColor,
15942
16299
  children: [
15943
16300
  "[",
15944
16301
  sev.label,
15945
16302
  "] ",
15946
- log25.msg
16303
+ log26.msg
15947
16304
  ]
15948
16305
  }, key);
15949
16306
  })
@@ -17530,6 +17887,7 @@ ${POC_NOTICE}
17530
17887
 
17531
17888
  Usage: agent-smith [options]
17532
17889
  agent-smith run [--port <number>] -- [claude arguments]
17890
+ agent-smith install-client
17533
17891
 
17534
17892
  Options:
17535
17893
  --serve Start API server with dashboard
@@ -17559,6 +17917,7 @@ Examples:
17559
17917
  agent-smith --pause work # Pause account
17560
17918
  agent-smith --analyze # Run performance analysis
17561
17919
  agent-smith --stats # View stats
17920
+ agent-smith install-client # Configure Claude Code and Codex for this Agent-smith server
17562
17921
  `);
17563
17922
  process.exit(0);
17564
17923
  }
@@ -17570,6 +17929,21 @@ Examples:
17570
17929
  await new Promise(() => {});
17571
17930
  return;
17572
17931
  }
17932
+ if (parsed.installClient) {
17933
+ const config2 = new Config;
17934
+ const client2 = config2.getClientRouting();
17935
+ if (!client2.baseUrl || !client2.proxyKeyFile) {
17936
+ throw new Error("client.base_url and client.proxy_key_file are required before installing client wrappers");
17937
+ }
17938
+ const port2 = config2.getRuntime().port || NETWORK.DEFAULT_PORT;
17939
+ await enableLocalClientRouting({
17940
+ port: port2,
17941
+ baseUrl: client2.baseUrl,
17942
+ proxyKeyFile: client2.proxyKeyFile
17943
+ });
17944
+ console.log(`Claude Code and Codex now route through ${client2.baseUrl}`);
17945
+ return;
17946
+ }
17573
17947
  if (parsed.run) {
17574
17948
  printPocNotice();
17575
17949
  const config2 = new Config;
@@ -17588,13 +17962,13 @@ Examples:
17588
17962
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
17589
17963
  if (typeof parsed.logs === "number") {
17590
17964
  const history = await getLogHistory(limit);
17591
- for (const log25 of history) {
17592
- console.log(`[${log25.level}] ${log25.msg}`);
17965
+ for (const log26 of history) {
17966
+ console.log(`[${log26.level}] ${log26.msg}`);
17593
17967
  }
17594
17968
  console.log("--- Live logs ---");
17595
17969
  }
17596
- await streamLogs((log25) => {
17597
- console.log(`[${log25.level}] ${log25.msg}`);
17970
+ await streamLogs((log26) => {
17971
+ console.log(`[${log26.level}] ${log26.msg}`);
17598
17972
  });
17599
17973
  return;
17600
17974
  }