@certalis/agent-smith 0.1.4 → 0.1.5

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
@@ -1320,6 +1320,12 @@ function sanitizeConfigData(value) {
1320
1320
  sanitized.provider_pools = providerPools;
1321
1321
  continue;
1322
1322
  }
1323
+ if (key === "alerts") {
1324
+ const alerts = sanitizeAlerts(entry);
1325
+ if (alerts)
1326
+ sanitized.alerts = alerts;
1327
+ continue;
1328
+ }
1323
1329
  if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
1324
1330
  sanitized[key] = entry;
1325
1331
  }
@@ -1350,6 +1356,46 @@ function sanitizeConfigData(value) {
1350
1356
  }
1351
1357
  return sanitized;
1352
1358
  }
1359
+ function filledText(value) {
1360
+ if (typeof value !== "string")
1361
+ return;
1362
+ const text = value.trim();
1363
+ return text.length > 0 && text.length <= MAX_ALERT_VALUE_LENGTH ? text : undefined;
1364
+ }
1365
+ function sanitizeHttpsUrl(value) {
1366
+ const text = filledText(value);
1367
+ if (!text)
1368
+ return;
1369
+ try {
1370
+ return new URL(text).protocol === "https:" ? text : undefined;
1371
+ } catch {
1372
+ return;
1373
+ }
1374
+ }
1375
+ function sanitizeAlerts(value) {
1376
+ if (!isRecord(value))
1377
+ return;
1378
+ const alerts = {};
1379
+ const slackWebhookUrl = sanitizeHttpsUrl(value.slack_webhook_url);
1380
+ if (slackWebhookUrl)
1381
+ alerts.slack_webhook_url = slackWebhookUrl;
1382
+ const slackBotToken = filledText(value.slack_bot_token);
1383
+ if (slackBotToken)
1384
+ alerts.slack_bot_token = slackBotToken;
1385
+ const slackChannel = filledText(value.slack_channel);
1386
+ if (slackChannel)
1387
+ alerts.slack_channel = slackChannel;
1388
+ const email = normalizeEnrollmentEmail(value.email);
1389
+ if (email)
1390
+ alerts.email = email;
1391
+ const emailFrom = filledText(value.email_from);
1392
+ if (emailFrom)
1393
+ alerts.email_from = emailFrom;
1394
+ const resendApiKey = filledText(value.resend_api_key);
1395
+ if (resendApiKey)
1396
+ alerts.resend_api_key = resendApiKey;
1397
+ return alerts;
1398
+ }
1353
1399
  function isProviderStrategy(value) {
1354
1400
  return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
1355
1401
  }
@@ -1451,7 +1497,7 @@ function sanitizeTeamRouting(value) {
1451
1497
  }
1452
1498
  return result;
1453
1499
  }
1454
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
1500
+ 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
1501
  var init_src4 = __esm(() => {
1456
1502
  init_src2();
1457
1503
  init_src3();
@@ -1517,12 +1563,23 @@ var init_src4 = __esm(() => {
1517
1563
  }
1518
1564
  saveConfig() {
1519
1565
  try {
1520
- const content = JSON.stringify(this.data, null, 2);
1521
- writeFileSync(this.configPath, content, "utf8");
1566
+ this.writePrivately(this.data);
1522
1567
  } catch (error) {
1523
1568
  log2.error(`Failed to save config file: ${error}`);
1524
1569
  }
1525
1570
  }
1571
+ writePrivately(data) {
1572
+ const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1573
+ try {
1574
+ writeFileSync(temporary, JSON.stringify(data, null, 2), {
1575
+ mode: 384,
1576
+ flag: "wx"
1577
+ });
1578
+ renameSync(temporary, this.configPath);
1579
+ } finally {
1580
+ rmSync(temporary, { force: true });
1581
+ }
1582
+ }
1526
1583
  get(key, defaultValue) {
1527
1584
  const value = this.data[key];
1528
1585
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
@@ -1617,6 +1674,20 @@ var init_src4 = __esm(() => {
1617
1674
  quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
1618
1675
  };
1619
1676
  }
1677
+ getAlerts() {
1678
+ const file = this.data.alerts;
1679
+ return {
1680
+ slackWebhookUrl: file?.slack_webhook_url ?? null,
1681
+ slackBotToken: file?.slack_bot_token ?? null,
1682
+ slackChannel: file?.slack_channel ?? null,
1683
+ email: file?.email ?? null,
1684
+ emailFrom: file?.email_from ?? null,
1685
+ resendApiKey: file?.resend_api_key ?? null
1686
+ };
1687
+ }
1688
+ getBlockWhenAllFull() {
1689
+ return this.data.block_when_all_full !== false;
1690
+ }
1620
1691
  getProviderConfig(name) {
1621
1692
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1622
1693
  const configured = this.data.providers?.[name];
@@ -1717,22 +1788,14 @@ var init_src4 = __esm(() => {
1717
1788
  }
1718
1789
  persistStrictly(key, value) {
1719
1790
  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
- }
1791
+ this.writePrivately(next);
1730
1792
  const oldValue = this.data[key];
1731
1793
  this.data = next;
1732
1794
  this.emit("change", { key, oldValue, newValue: value });
1733
1795
  }
1734
1796
  getRuntime() {
1735
1797
  const defaults = {
1798
+ blockWhenAllFull: this.getBlockWhenAllFull(),
1736
1799
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
1737
1800
  maxBodyBytes: 64 * 1024 * 1024,
1738
1801
  quotaThreshold: 0.98,
@@ -4686,6 +4749,12 @@ var init_provider = __esm(() => {
4686
4749
  hasRateLimitSignal(headerName) {
4687
4750
  return super.hasRateLimitSignal(headerName) || headerName.toLowerCase().startsWith("anthropic-ratelimit-unified-");
4688
4751
  }
4752
+ spendsExtraUsage(response) {
4753
+ if (!response.ok)
4754
+ return false;
4755
+ const overageStatus = response.headers.get("anthropic-ratelimit-unified-overage-status");
4756
+ return response.headers.get("anthropic-ratelimit-unified-overage-in-use") === "true" || response.headers.get("anthropic-ratelimit-unified-status") === "rejected" && (overageStatus === "allowed" || overageStatus === "allowed_warning");
4757
+ }
4689
4758
  quotaBucketsFor(model) {
4690
4759
  const familyBucket = familyQuotaBucket(model);
4691
4760
  return familyBucket ? [...SHARED_QUOTA_BUCKETS, familyBucket] : SHARED_QUOTA_BUCKETS;
@@ -8367,28 +8436,58 @@ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
8367
8436
  }
8368
8437
  return true;
8369
8438
  }
8439
+ function fleetAccounts(provider, ctx) {
8440
+ const teamRouting = ctx.runtime.teamRouting;
8441
+ return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
8442
+ }
8443
+ function cooldownEnd(account2, now) {
8444
+ return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8445
+ }
8446
+ function blockingResets(provider, account2, model, ctx, now) {
8447
+ 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);
8448
+ }
8449
+ function servableAt(provider, account2, model, ctx, now) {
8450
+ const cooldown = cooldownEnd(account2, now);
8451
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
8452
+ return cooldown;
8453
+ }
8454
+ const resets = blockingResets(provider, account2, model, ctx, now);
8455
+ return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
8456
+ }
8457
+ function soonestServableAt(provider, fleet, seats, model, ctx, now) {
8458
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
8459
+ return null;
8460
+ }
8461
+ const times = seats.flatMap((account2) => {
8462
+ const at = servableAt(provider, account2, model, ctx, now);
8463
+ return at === null ? [] : [at];
8464
+ });
8465
+ return times.length > 0 ? Math.min(...times) : null;
8466
+ }
8370
8467
  function getPoolStatus(provider, model, ctx) {
8371
8468
  const providerStrategy = ctx.providerRegistry.getProvider(provider);
8372
8469
  if (!providerStrategy)
8373
8470
  throw new Error(`Unknown provider '${provider}'`);
8374
8471
  const config = ctx.runtime.teamRouting;
8375
8472
  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));
8473
+ const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
8474
+ const eligibleAccounts = accounts.filter((account2) => cooldownEnd(account2, now) === null && isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8379
8475
  return {
8380
8476
  version: 1,
8381
8477
  provider,
8382
8478
  routingEnabled: config?.enabled === true,
8383
8479
  eligibleAccounts,
8384
- retryAtMs: eligibleAccounts === 0 && resets.length > 0 ? Math.min(...resets) : null,
8480
+ retryAtMs: eligibleAccounts === 0 ? soonestServableAt(providerStrategy, accounts, accounts, model, ctx, now) : null,
8385
8481
  holdSeconds: config?.holdSeconds ?? 0,
8386
8482
  admissionWaitMs: config?.admissionWaitMs ?? 0
8387
8483
  };
8388
8484
  }
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;
8485
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
8486
+ const fleet = fleetAccounts(ctx.providerName, ctx);
8487
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
8488
+ }
8489
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
8490
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8392
8491
  }
8393
8492
  function selectRevalidationProbe(accounts, ctx, now) {
8394
8493
  const probes = ctx.quotaProbeAt;
@@ -8408,7 +8507,7 @@ function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8408
8507
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8409
8508
  const now = Date.now();
8410
8509
  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);
8510
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8412
8511
  const prioritized = [...candidates].sort((left, right) => {
8413
8512
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
8414
8513
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9745,9 +9844,15 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9745
9844
  try {
9746
9845
  const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
9747
9846
  if (attempt.kind === "response") {
9847
+ const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
9748
9848
  return {
9749
9849
  ...attempt,
9750
- response: releaseAfterResponse(attempt.response, release)
9850
+ response: releaseAfterResponse(attempt.response, () => {
9851
+ release();
9852
+ if (spentExtraUsage) {
9853
+ request2.ctx.seatAlerts?.extraUsageSpent(account2, request2.ctx.providerName);
9854
+ }
9855
+ })
9751
9856
  };
9752
9857
  }
9753
9858
  release();
@@ -9923,23 +10028,32 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
9923
10028
  provider: ctx.providerName,
9924
10029
  sessionId
9925
10030
  };
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;
10031
+ const request2 = {
10032
+ body,
10033
+ ctx,
10034
+ mappedModel,
10035
+ meta,
10036
+ req,
10037
+ teamRequest,
10038
+ thread,
10039
+ url
10040
+ };
9929
10041
  return {
9930
- accounts,
9931
- request: {
9932
- body,
9933
- ctx,
9934
- mappedModel,
9935
- meta,
9936
- req,
9937
- teamRequest,
9938
- thread,
9939
- url
9940
- }
10042
+ accounts: selectRequestAccounts(request2, selectionOptions),
10043
+ request: request2
9941
10044
  };
9942
10045
  }
10046
+ function onThreadSeat(request2, accounts) {
10047
+ const threadAccountId = getThreadBoundAccountId(request2.ctx.messageThreads, request2.thread);
10048
+ return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
10049
+ }
10050
+ function selectRequestAccounts(request2, selectionOptions) {
10051
+ return onThreadSeat(request2, selectAccountsForRequest(request2.meta, request2.ctx, request2.teamRequest, selectionOptions));
10052
+ }
10053
+ function getRequestRetryAt(request2) {
10054
+ const { ctx, teamRequest } = request2;
10055
+ return getSoonestQuotaReset(request2.meta, ctx, (fleet) => onThreadSeat(request2, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10056
+ }
9943
10057
  var init_proxy_request = __esm(() => {
9944
10058
  init_account_selector();
9945
10059
  init_message_thread();
@@ -10061,8 +10175,16 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10061
10175
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10062
10176
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10063
10177
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
10064
- let soonestReset = null;
10178
+ let soonestRetry = null;
10179
+ let soonestFleetReset = null;
10180
+ let everyCandidateFull = true;
10065
10181
  let emittedIngress = false;
10182
+ const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
10183
+ const recordUnserved = (request2) => {
10184
+ everyCandidateFull &&= isEveryAccountQuotaBlocked(request2.meta, request2.ctx);
10185
+ soonestRetry = earliest(soonestRetry, getRequestRetryAt(request2));
10186
+ soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request2.meta, request2.ctx));
10187
+ };
10066
10188
  const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10067
10189
  for (const [candidateIndex, candidate] of candidates.entries()) {
10068
10190
  const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
@@ -10074,8 +10196,7 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10074
10196
  }
10075
10197
  accounts = preferPinnedAccount(accounts, pinnedId);
10076
10198
  if (accounts.length === 0) {
10077
- const resetAt3 = getSoonestQuotaReset(candidateMeta, candidateContext);
10078
- soonestReset = resetAt3 !== null && (soonestReset === null || resetAt3 < soonestReset) ? resetAt3 : soonestReset;
10199
+ recordUnserved(prepared.request);
10079
10200
  continue;
10080
10201
  }
10081
10202
  if (!emittedIngress) {
@@ -10096,11 +10217,13 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10096
10217
  }
10097
10218
  return result.response;
10098
10219
  }
10099
- const resetAt2 = getSoonestQuotaReset(candidateMeta, candidateContext);
10100
- soonestReset = resetAt2 !== null && (soonestReset === null || resetAt2 < soonestReset) ? resetAt2 : soonestReset;
10220
+ recordUnserved(prepared.request);
10221
+ }
10222
+ if (everyCandidateFull && soonestFleetReset !== null) {
10223
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
10101
10224
  }
10102
- if (soonestReset !== null)
10103
- return quotaExhaustionResponse(soonestReset);
10225
+ if (soonestRetry !== null)
10226
+ return quotaExhaustionResponse(soonestRetry);
10104
10227
  log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10105
10228
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
10106
10229
  }
@@ -10114,6 +10237,133 @@ var init_provider_pool = __esm(() => {
10114
10237
  log22 = new Logger("Proxy");
10115
10238
  });
10116
10239
 
10240
+ // ../../packages/proxy/src/seat-alerts.ts
10241
+ function alertWhenFleetFull(meta, ctx, holdSeconds) {
10242
+ const resetAt2 = getSoonestQuotaReset(meta, ctx);
10243
+ if (resetAt2 === null || !isEveryAccountQuotaBlocked(meta, ctx))
10244
+ return;
10245
+ ctx.seatAlerts?.allAccountsFull(ctx.providerName, resetAt2, {
10246
+ blocked: ctx.runtime.blockWhenAllFull,
10247
+ holdSeconds
10248
+ });
10249
+ }
10250
+ function utc(at) {
10251
+ return `${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
10252
+ }
10253
+
10254
+ class SeatAlerts {
10255
+ config;
10256
+ send;
10257
+ fullUntil = new Map;
10258
+ constructor(config, send = (url, init) => fetch(url, init)) {
10259
+ this.config = config;
10260
+ this.send = send;
10261
+ if (config.email && !(config.emailFrom && config.resendApiKey)) {
10262
+ log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
10263
+ }
10264
+ if (!config.slackBotToken !== !config.slackChannel) {
10265
+ log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
10266
+ }
10267
+ }
10268
+ extraUsageSpent(account2, provider) {
10269
+ const claim = account2.quota_state?.representativeClaim;
10270
+ const resetAt2 = account2.quota_state?.windows.unified?.resetAt;
10271
+ this.notify({
10272
+ subject: `agent-smith: ${account2.name} spent extra usage`,
10273
+ 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)}.` : ""}`
10274
+ });
10275
+ }
10276
+ allAccountsFull(scope, resetAt2, policy) {
10277
+ if ((this.fullUntil.get(scope) ?? 0) > Date.now())
10278
+ return;
10279
+ this.fullUntil.set(scope, resetAt2);
10280
+ const probe = policy.blocked ? "" : ", except one a minute that revalidates and may spend extra usage";
10281
+ const hold = policy.holdSeconds > 0 ? `; one within ${policy.holdSeconds}s of the reset waits for it instead` : "";
10282
+ this.notify({
10283
+ subject: `agent-smith: every ${scope} account is full`,
10284
+ text: `Every ${scope} account is out of quota until ${utc(resetAt2)}. Requests are refused until then${probe}${hold}.`
10285
+ });
10286
+ }
10287
+ notify(alert) {
10288
+ log23.warn(alert.text);
10289
+ for (const delivery of this.deliveries(alert)) {
10290
+ trackProxyBackgroundTask(this.deliver(delivery));
10291
+ }
10292
+ }
10293
+ deliveries(alert) {
10294
+ const {
10295
+ email,
10296
+ emailFrom,
10297
+ resendApiKey,
10298
+ slackBotToken,
10299
+ slackChannel,
10300
+ slackWebhookUrl
10301
+ } = this.config;
10302
+ const deliveries = [];
10303
+ if (slackWebhookUrl) {
10304
+ deliveries.push({
10305
+ channel: "Slack",
10306
+ url: slackWebhookUrl,
10307
+ body: { text: alert.text }
10308
+ });
10309
+ }
10310
+ if (slackBotToken && slackChannel) {
10311
+ deliveries.push({
10312
+ channel: "Slack",
10313
+ url: SLACK_POST_MESSAGE_URL,
10314
+ headers: { authorization: `Bearer ${slackBotToken}` },
10315
+ body: { channel: slackChannel, text: alert.text },
10316
+ repliesOk: true
10317
+ });
10318
+ }
10319
+ if (email && emailFrom && resendApiKey) {
10320
+ deliveries.push({
10321
+ channel: "email",
10322
+ url: RESEND_EMAILS_URL,
10323
+ headers: { authorization: `Bearer ${resendApiKey}` },
10324
+ body: {
10325
+ from: emailFrom,
10326
+ to: [email],
10327
+ subject: alert.subject,
10328
+ text: alert.text
10329
+ }
10330
+ });
10331
+ }
10332
+ return deliveries;
10333
+ }
10334
+ async deliver(delivery) {
10335
+ try {
10336
+ const response = await this.send(delivery.url, {
10337
+ method: "POST",
10338
+ headers: { "content-type": "application/json", ...delivery.headers },
10339
+ body: JSON.stringify(delivery.body),
10340
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
10341
+ });
10342
+ if (!response.ok) {
10343
+ log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
10344
+ return;
10345
+ }
10346
+ if (!delivery.repliesOk)
10347
+ return;
10348
+ const reply = await response.json();
10349
+ if (reply.ok !== true) {
10350
+ const code = typeof reply.error === "string" && SLACK_ERROR_CODE.test(reply.error) ? reply.error : "no reason given";
10351
+ log23.warn(`${delivery.channel} alert was refused (${code})`);
10352
+ }
10353
+ } catch (error) {
10354
+ log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
10355
+ }
10356
+ }
10357
+ }
10358
+ 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;
10359
+ var init_seat_alerts = __esm(() => {
10360
+ init_src3();
10361
+ init_background_tasks();
10362
+ init_account_selector();
10363
+ log23 = new Logger("SeatAlerts");
10364
+ SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
10365
+ });
10366
+
10117
10367
  // ../../packages/proxy/src/usage-worker.ts
10118
10368
  import { isAbsolute, resolve } from "path";
10119
10369
  import { pathToFileURL } from "url";
@@ -10495,7 +10745,7 @@ function getUsageWorker() {
10495
10745
  }
10496
10746
  if (!usageWorkerInstance) {
10497
10747
  usageWorkerInstance = new UsageWorkerController({
10498
- logger: log23,
10748
+ logger: log24,
10499
10749
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
10500
10750
  onWorkerMessage: (data) => {
10501
10751
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -10566,21 +10816,23 @@ async function handleProxy(req, url, ctx) {
10566
10816
  const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
10567
10817
  let accounts = initiallySelectedAccounts;
10568
10818
  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);
10819
+ const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
10820
+ alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
10821
+ const retryAt = getRequestRetryAt(request2);
10822
+ if (retryAt !== null) {
10823
+ const holdMs = holdSeconds * 1000;
10824
+ if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
10825
+ await requestContext.quotaHold.waitUntil(retryAt, req.signal);
10826
+ const resumedAccounts = selectRequestAccounts(request2);
10575
10827
  if (resumedAccounts.length > 0) {
10576
10828
  accounts = resumedAccounts;
10577
10829
  }
10578
10830
  }
10579
10831
  if (accounts.length === 0)
10580
- return quotaExhaustionResponse(resetAt2);
10832
+ return quotaExhaustionResponse(retryAt);
10581
10833
  }
10582
10834
  if (accounts.length === 0) {
10583
- log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10835
+ log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10584
10836
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
10585
10837
  }
10586
10838
  }
@@ -10591,19 +10843,20 @@ async function handleProxy(req, url, ctx) {
10591
10843
  method: requestMeta.method,
10592
10844
  path: requestMeta.path
10593
10845
  });
10594
- log23.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10595
- log23.info(`Request: ${req.method} ${url.pathname}`);
10846
+ log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10847
+ log24.info(`Request: ${req.method} ${url.pathname}`);
10596
10848
  return await proxySelectedAccounts(request2, accounts);
10597
10849
  }
10598
- var log23, usageWorkerInstance = null;
10850
+ var log24, usageWorkerInstance = null;
10599
10851
  var init_proxy = __esm(() => {
10600
10852
  init_src2();
10601
10853
  init_src3();
10602
10854
  init_src();
10603
10855
  init_handlers();
10604
10856
  init_provider_pool();
10857
+ init_seat_alerts();
10605
10858
  init_usage_worker();
10606
- log23 = new Logger("Proxy");
10859
+ log24 = new Logger("Proxy");
10607
10860
  });
10608
10861
 
10609
10862
  // ../../packages/proxy/src/quota-hold.ts
@@ -10951,7 +11204,7 @@ function endActiveTurn(session, success, error) {
10951
11204
  if (!activeTurn) {
10952
11205
  return;
10953
11206
  }
10954
- log24.debug("Ending tracked websocket turn", {
11207
+ log25.debug("Ending tracked websocket turn", {
10955
11208
  requestId: activeTurn.requestId,
10956
11209
  provider: session.providerName,
10957
11210
  path: session.path,
@@ -11004,7 +11257,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
11004
11257
  timestamp,
11005
11258
  model: getEventModel(parsed)
11006
11259
  };
11007
- log24.debug("Starting tracked websocket turn", {
11260
+ log25.debug("Starting tracked websocket turn", {
11008
11261
  requestId,
11009
11262
  provider: session.providerName,
11010
11263
  path: session.path,
@@ -11034,7 +11287,7 @@ function handleTrackedUpstreamText(session, data) {
11034
11287
  if (!messageType) {
11035
11288
  return;
11036
11289
  }
11037
- log24.debug("Processing tracked websocket message", {
11290
+ log25.debug("Processing tracked websocket message", {
11038
11291
  provider: session.providerName,
11039
11292
  path: session.path,
11040
11293
  messageType,
@@ -11075,7 +11328,7 @@ function capturePendingRequestBody(session, message) {
11075
11328
  }
11076
11329
  session.pendingRequestBody = Buffer.from(message).toString("base64");
11077
11330
  session.pendingRequestTimestamp = Date.now();
11078
- log24.debug("Captured websocket request body for next tracked turn", {
11331
+ log25.debug("Captured websocket request body for next tracked turn", {
11079
11332
  provider: session.providerName,
11080
11333
  path: session.path,
11081
11334
  size: message.length
@@ -11148,7 +11401,7 @@ async function connectToNextUpstream(ws) {
11148
11401
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
11149
11402
  } catch (error) {
11150
11403
  session.connecting = false;
11151
- log24.warn("Skipping websocket account during upstream connection", {
11404
+ log25.warn("Skipping websocket account during upstream connection", {
11152
11405
  account: account2.name,
11153
11406
  error: error instanceof Error ? error.message : String(error)
11154
11407
  });
@@ -11207,7 +11460,7 @@ async function connectToNextUpstream(ws) {
11207
11460
  }
11208
11461
  });
11209
11462
  upstream.addEventListener("error", () => {
11210
- log24.warn("Upstream websocket error", {
11463
+ log25.warn("Upstream websocket error", {
11211
11464
  account: plan.account.name,
11212
11465
  provider: session.providerName,
11213
11466
  path: session.path
@@ -11216,7 +11469,7 @@ async function connectToNextUpstream(ws) {
11216
11469
  } catch (error) {
11217
11470
  session.connecting = false;
11218
11471
  clearConnectTimeout(session);
11219
- log24.warn("Failed to create upstream websocket", {
11472
+ log25.warn("Failed to create upstream websocket", {
11220
11473
  account: plan.account.name,
11221
11474
  error: error instanceof Error ? error.message : String(error)
11222
11475
  });
@@ -11259,7 +11512,8 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11259
11512
  };
11260
11513
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
11261
11514
  if (accounts.length === 0) {
11262
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11515
+ alertWhenFleetFull(requestMeta, requestContext, 0);
11516
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11263
11517
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
11264
11518
  }
11265
11519
  const protocols = getProtocols(req.headers);
@@ -11297,7 +11551,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11297
11551
  }
11298
11552
  return;
11299
11553
  }
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;
11554
+ 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
11555
  var init_websocket_proxy = __esm(() => {
11302
11556
  init_src2();
11303
11557
  init_src6();
@@ -11307,7 +11561,8 @@ var init_websocket_proxy = __esm(() => {
11307
11561
  init_request_handler();
11308
11562
  init_token_manager();
11309
11563
  init_openai_usage();
11310
- log24 = new Logger("WebSocketProxy");
11564
+ init_seat_alerts();
11565
+ log25 = new Logger("WebSocketProxy");
11311
11566
  websocketSessions = new Map;
11312
11567
  textEncoder = new TextEncoder;
11313
11568
  websocketProxyHandler = {
@@ -11361,6 +11616,7 @@ var init_src10 = __esm(() => {
11361
11616
  init_proxy();
11362
11617
  init_quota_probe();
11363
11618
  init_response_handler();
11619
+ init_seat_alerts();
11364
11620
  init_strategies();
11365
11621
  init_team_admission();
11366
11622
  init_team_router();
@@ -11484,6 +11740,7 @@ var init_exposure = __esm(() => {
11484
11740
  // ../../packages/runtime-server/src/bootstrap-runtime.ts
11485
11741
  function createRuntimeConfig(config, port) {
11486
11742
  return {
11743
+ blockWhenAllFull: config.getBlockWhenAllFull(),
11487
11744
  clientId: config.get("client_id", "9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
11488
11745
  maxBodyBytes: config.get("max_body_bytes", 64 * 1024 * 1024),
11489
11746
  requestScopedRetryDelayMs: config.get("request_scoped_429_retry_delay_ms", 2000),
@@ -11498,10 +11755,10 @@ function createRuntimeConfig(config, port) {
11498
11755
  teamRouting: config.getTeamRouting()
11499
11756
  };
11500
11757
  }
11501
- function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11758
+ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11502
11759
  config.on("change", (change) => {
11503
11760
  if (change.key === "lb_strategy") {
11504
- log25.info("Strategy configuration changed");
11761
+ log26.info("Strategy configuration changed");
11505
11762
  const newStrategyName = config.getStrategy();
11506
11763
  if (newStrategyName === "session") {
11507
11764
  const strategy3 = new SessionStrategy;
@@ -11512,7 +11769,7 @@ function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig
11512
11769
  if (change.key === "team_routing") {
11513
11770
  runtimeConfig2.teamRouting = config.getTeamRouting();
11514
11771
  quotaProbe.reschedule();
11515
- log25.info("Team routing configuration changed");
11772
+ log26.info("Team routing configuration changed");
11516
11773
  }
11517
11774
  });
11518
11775
  }
@@ -11526,7 +11783,7 @@ function bootstrapRuntime(port, serverLog) {
11526
11783
  sessionDurationMs: runtimeConfig2.sessionDurationMs
11527
11784
  });
11528
11785
  const dbOps = DatabaseFactory.getInstance();
11529
- const log25 = container.resolve(SERVICE_KEYS.Logger);
11786
+ const log26 = container.resolve(SERVICE_KEYS.Logger);
11530
11787
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
11531
11788
  const asyncWriter = new AsyncDbWriter;
11532
11789
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -11574,6 +11831,7 @@ function bootstrapRuntime(port, serverLog) {
11574
11831
  teamAdmission,
11575
11832
  quotaHold,
11576
11833
  outsideSpendTracker,
11834
+ seatAlerts: new SeatAlerts(config.getAlerts()),
11577
11835
  asyncWriter,
11578
11836
  usageWorker: getUsageWorker()
11579
11837
  };
@@ -11590,11 +11848,11 @@ function bootstrapRuntime(port, serverLog) {
11590
11848
  });
11591
11849
  quotaProbe.start();
11592
11850
  registerDisposable(quotaProbe);
11593
- wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11851
+ wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11594
11852
  return {
11595
11853
  config,
11596
11854
  dbOps,
11597
- log: log25,
11855
+ log: log26,
11598
11856
  asyncWriter,
11599
11857
  apiRouter,
11600
11858
  exposureConfig,
@@ -11603,12 +11861,12 @@ function bootstrapRuntime(port, serverLog) {
11603
11861
  runtimeConfig: runtimeConfig2
11604
11862
  };
11605
11863
  }
11606
- function logInitialAccountStatus(log25, dbOps) {
11864
+ function logInitialAccountStatus(log26, dbOps) {
11607
11865
  const accounts = dbOps.getAllAccounts();
11608
11866
  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)`);
11867
+ log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11610
11868
  if (activeAccounts.length === 0) {
11611
- log25.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11869
+ log26.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11612
11870
  }
11613
11871
  }
11614
11872
  var init_bootstrap_runtime = __esm(() => {
@@ -11835,20 +12093,20 @@ var init_startup_banner = __esm(() => {
11835
12093
 
11836
12094
  // ../../packages/runtime-server/src/startup-maintenance.ts
11837
12095
  function runStartupMaintenance(config, dbOps) {
11838
- const log25 = new Logger("StartupMaintenance");
12096
+ const log26 = new Logger("StartupMaintenance");
11839
12097
  try {
11840
12098
  const payloadDays = config.getDataRetentionDays();
11841
12099
  const requestDays = config.getRequestRetentionDays();
11842
12100
  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)`);
12101
+ log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
11844
12102
  } catch (err) {
11845
- log25.error(`Startup cleanup error: ${err}`);
12103
+ log26.error(`Startup cleanup error: ${err}`);
11846
12104
  }
11847
12105
  try {
11848
12106
  dbOps.compact();
11849
- log25.info("Database compacted at startup");
12107
+ log26.info("Database compacted at startup");
11850
12108
  } catch (err) {
11851
- log25.error(`Database compaction error: ${err}`);
12109
+ log26.error(`Database compaction error: ${err}`);
11852
12110
  }
11853
12111
  return () => {};
11854
12112
  }
@@ -11945,7 +12203,7 @@ function startServer(options) {
11945
12203
  const {
11946
12204
  config,
11947
12205
  dbOps,
11948
- log: log25,
12206
+ log: log26,
11949
12207
  apiRouter,
11950
12208
  exposureConfig,
11951
12209
  proxyContext,
@@ -11988,7 +12246,7 @@ function startServer(options) {
11988
12246
  strategy: config.getStrategy(),
11989
12247
  providers: providerRegistry.listProviders()
11990
12248
  }));
11991
- logInitialAccountStatus(log25, dbOps);
12249
+ logInitialAccountStatus(log26, dbOps);
11992
12250
  return {
11993
12251
  port: activePort,
11994
12252
  stop: () => stopServerRuntime(),
@@ -15851,13 +16109,13 @@ function reducer(state, action) {
15851
16109
  function LogsScreen({ refreshKey }) {
15852
16110
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
15853
16111
  const logKeyCounts = new Map;
15854
- const keyedLogs = state.logs.map((log25) => {
15855
- const baseKey = `${log25.ts}-${log25.level ?? ""}-${log25.msg}`;
16112
+ const keyedLogs = state.logs.map((log26) => {
16113
+ const baseKey = `${log26.ts}-${log26.level ?? ""}-${log26.msg}`;
15856
16114
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
15857
16115
  logKeyCounts.set(baseKey, count);
15858
16116
  return {
15859
16117
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
15860
- log: log25
16118
+ log: log26
15861
16119
  };
15862
16120
  });
15863
16121
  useKeyboard3((key) => {
@@ -15881,8 +16139,8 @@ function LogsScreen({ refreshKey }) {
15881
16139
  }, [refreshKey]);
15882
16140
  useEffect3(() => {
15883
16141
  if (!state.paused && !state.loading) {
15884
- const unsubscribe = streamLogs((log25) => {
15885
- dispatch({ type: "new_entry", log: log25 });
16142
+ const unsubscribe = streamLogs((log26) => {
16143
+ dispatch({ type: "new_entry", log: log26 });
15886
16144
  });
15887
16145
  return () => {
15888
16146
  unsubscribe();
@@ -15935,15 +16193,15 @@ function LogsScreen({ refreshKey }) {
15935
16193
  children: "No logs yet..."
15936
16194
  }) : /* @__PURE__ */ jsx7("box", {
15937
16195
  flexDirection: "column",
15938
- children: keyedLogs.map(({ key, log: log25 }) => {
15939
- const sev = getLogSeverityMeta(log25.level);
16196
+ children: keyedLogs.map(({ key, log: log26 }) => {
16197
+ const sev = getLogSeverityMeta(log26.level);
15940
16198
  return /* @__PURE__ */ jsxs7("text", {
15941
16199
  fg: sev.termColor,
15942
16200
  children: [
15943
16201
  "[",
15944
16202
  sev.label,
15945
16203
  "] ",
15946
- log25.msg
16204
+ log26.msg
15947
16205
  ]
15948
16206
  }, key);
15949
16207
  })
@@ -17588,13 +17846,13 @@ Examples:
17588
17846
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
17589
17847
  if (typeof parsed.logs === "number") {
17590
17848
  const history = await getLogHistory(limit);
17591
- for (const log25 of history) {
17592
- console.log(`[${log25.level}] ${log25.msg}`);
17849
+ for (const log26 of history) {
17850
+ console.log(`[${log26.level}] ${log26.msg}`);
17593
17851
  }
17594
17852
  console.log("--- Live logs ---");
17595
17853
  }
17596
- await streamLogs((log25) => {
17597
- console.log(`[${log25.level}] ${log25.msg}`);
17854
+ await streamLogs((log26) => {
17855
+ console.log(`[${log26.level}] ${log26.msg}`);
17598
17856
  });
17599
17857
  return;
17600
17858
  }