@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/server.js CHANGED
@@ -1619,6 +1619,12 @@ var init_provider = __esm(() => {
1619
1619
  hasRateLimitSignal(headerName) {
1620
1620
  return super.hasRateLimitSignal(headerName) || headerName.toLowerCase().startsWith("anthropic-ratelimit-unified-");
1621
1621
  }
1622
+ spendsExtraUsage(response) {
1623
+ if (!response.ok)
1624
+ return false;
1625
+ const overageStatus = response.headers.get("anthropic-ratelimit-unified-overage-status");
1626
+ return response.headers.get("anthropic-ratelimit-unified-overage-in-use") === "true" || response.headers.get("anthropic-ratelimit-unified-status") === "rejected" && (overageStatus === "allowed" || overageStatus === "allowed_warning");
1627
+ }
1622
1628
  quotaBucketsFor(model) {
1623
1629
  const familyBucket = familyQuotaBucket(model);
1624
1630
  return familyBucket ? [...SHARED_QUOTA_BUCKETS, familyBucket] : SHARED_QUOTA_BUCKETS;
@@ -3885,6 +3891,12 @@ function sanitizeConfigData(value) {
3885
3891
  sanitized.provider_pools = providerPools;
3886
3892
  continue;
3887
3893
  }
3894
+ if (key === "alerts") {
3895
+ const alerts = sanitizeAlerts(entry);
3896
+ if (alerts)
3897
+ sanitized.alerts = alerts;
3898
+ continue;
3899
+ }
3888
3900
  if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
3889
3901
  sanitized[key] = entry;
3890
3902
  }
@@ -3915,6 +3927,46 @@ function sanitizeConfigData(value) {
3915
3927
  }
3916
3928
  return sanitized;
3917
3929
  }
3930
+ function filledText(value) {
3931
+ if (typeof value !== "string")
3932
+ return;
3933
+ const text = value.trim();
3934
+ return text.length > 0 && text.length <= MAX_ALERT_VALUE_LENGTH ? text : undefined;
3935
+ }
3936
+ function sanitizeHttpsUrl(value) {
3937
+ const text = filledText(value);
3938
+ if (!text)
3939
+ return;
3940
+ try {
3941
+ return new URL(text).protocol === "https:" ? text : undefined;
3942
+ } catch {
3943
+ return;
3944
+ }
3945
+ }
3946
+ function sanitizeAlerts(value) {
3947
+ if (!isRecord(value))
3948
+ return;
3949
+ const alerts = {};
3950
+ const slackWebhookUrl = sanitizeHttpsUrl(value.slack_webhook_url);
3951
+ if (slackWebhookUrl)
3952
+ alerts.slack_webhook_url = slackWebhookUrl;
3953
+ const slackBotToken = filledText(value.slack_bot_token);
3954
+ if (slackBotToken)
3955
+ alerts.slack_bot_token = slackBotToken;
3956
+ const slackChannel = filledText(value.slack_channel);
3957
+ if (slackChannel)
3958
+ alerts.slack_channel = slackChannel;
3959
+ const email = normalizeEnrollmentEmail(value.email);
3960
+ if (email)
3961
+ alerts.email = email;
3962
+ const emailFrom = filledText(value.email_from);
3963
+ if (emailFrom)
3964
+ alerts.email_from = emailFrom;
3965
+ const resendApiKey = filledText(value.resend_api_key);
3966
+ if (resendApiKey)
3967
+ alerts.resend_api_key = resendApiKey;
3968
+ return alerts;
3969
+ }
3918
3970
  function isProviderStrategy(value) {
3919
3971
  return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
3920
3972
  }
@@ -4016,7 +4068,7 @@ function sanitizeTeamRouting(value) {
4016
4068
  }
4017
4069
  return result;
4018
4070
  }
4019
- var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
4071
+ var log6, 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;
4020
4072
  var init_src7 = __esm(() => {
4021
4073
  init_src2();
4022
4074
  init_src4();
@@ -4082,12 +4134,23 @@ var init_src7 = __esm(() => {
4082
4134
  }
4083
4135
  saveConfig() {
4084
4136
  try {
4085
- const content = JSON.stringify(this.data, null, 2);
4086
- writeFileSync(this.configPath, content, "utf8");
4137
+ this.writePrivately(this.data);
4087
4138
  } catch (error) {
4088
4139
  log6.error(`Failed to save config file: ${error}`);
4089
4140
  }
4090
4141
  }
4142
+ writePrivately(data) {
4143
+ const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
4144
+ try {
4145
+ writeFileSync(temporary, JSON.stringify(data, null, 2), {
4146
+ mode: 384,
4147
+ flag: "wx"
4148
+ });
4149
+ renameSync(temporary, this.configPath);
4150
+ } finally {
4151
+ rmSync(temporary, { force: true });
4152
+ }
4153
+ }
4091
4154
  get(key, defaultValue) {
4092
4155
  const value = this.data[key];
4093
4156
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
@@ -4182,6 +4245,20 @@ var init_src7 = __esm(() => {
4182
4245
  quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
4183
4246
  };
4184
4247
  }
4248
+ getAlerts() {
4249
+ const file = this.data.alerts;
4250
+ return {
4251
+ slackWebhookUrl: file?.slack_webhook_url ?? null,
4252
+ slackBotToken: file?.slack_bot_token ?? null,
4253
+ slackChannel: file?.slack_channel ?? null,
4254
+ email: file?.email ?? null,
4255
+ emailFrom: file?.email_from ?? null,
4256
+ resendApiKey: file?.resend_api_key ?? null
4257
+ };
4258
+ }
4259
+ getBlockWhenAllFull() {
4260
+ return this.data.block_when_all_full !== false;
4261
+ }
4185
4262
  getProviderConfig(name) {
4186
4263
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
4187
4264
  const configured = this.data.providers?.[name];
@@ -4282,22 +4359,14 @@ var init_src7 = __esm(() => {
4282
4359
  }
4283
4360
  persistStrictly(key, value) {
4284
4361
  const next = { ...this.data, [key]: value };
4285
- const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
4286
- try {
4287
- writeFileSync(temporary, JSON.stringify(next, null, 2), {
4288
- mode: 384,
4289
- flag: "wx"
4290
- });
4291
- renameSync(temporary, this.configPath);
4292
- } finally {
4293
- rmSync(temporary, { force: true });
4294
- }
4362
+ this.writePrivately(next);
4295
4363
  const oldValue = this.data[key];
4296
4364
  this.data = next;
4297
4365
  this.emit("change", { key, oldValue, newValue: value });
4298
4366
  }
4299
4367
  getRuntime() {
4300
4368
  const defaults = {
4369
+ blockWhenAllFull: this.getBlockWhenAllFull(),
4301
4370
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
4302
4371
  maxBodyBytes: 64 * 1024 * 1024,
4303
4372
  quotaThreshold: 0.98,
@@ -8366,28 +8435,58 @@ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
8366
8435
  }
8367
8436
  return true;
8368
8437
  }
8438
+ function fleetAccounts(provider, ctx) {
8439
+ const teamRouting = ctx.runtime.teamRouting;
8440
+ return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
8441
+ }
8442
+ function cooldownEnd(account2, now) {
8443
+ return account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8444
+ }
8445
+ function blockingResets(provider, account2, model, ctx, now) {
8446
+ 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);
8447
+ }
8448
+ function servableAt(provider, account2, model, ctx, now) {
8449
+ const cooldown = cooldownEnd(account2, now);
8450
+ if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx)) {
8451
+ return cooldown;
8452
+ }
8453
+ const resets = blockingResets(provider, account2, model, ctx, now);
8454
+ return resets.length > 0 ? Math.max(...resets, cooldown ?? 0) : null;
8455
+ }
8456
+ function soonestServableAt(provider, fleet, seats, model, ctx, now) {
8457
+ if (!fleet.some((account2) => blockingResets(provider, account2, model, ctx, now).length > 0)) {
8458
+ return null;
8459
+ }
8460
+ const times = seats.flatMap((account2) => {
8461
+ const at = servableAt(provider, account2, model, ctx, now);
8462
+ return at === null ? [] : [at];
8463
+ });
8464
+ return times.length > 0 ? Math.min(...times) : null;
8465
+ }
8369
8466
  function getPoolStatus(provider, model, ctx) {
8370
8467
  const providerStrategy = ctx.providerRegistry.getProvider(provider);
8371
8468
  if (!providerStrategy)
8372
8469
  throw new Error(`Unknown provider '${provider}'`);
8373
8470
  const config = ctx.runtime.teamRouting;
8374
8471
  const now = Date.now();
8375
- const accounts = config?.enabled ? ctx.dbOps.getAvailableAccountsByProvider(provider).filter((account2) => isAllowlisted(account2, config)) : [];
8376
- const eligibleAccounts = accounts.filter((account2) => isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8377
- 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));
8472
+ const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
8473
+ const eligibleAccounts = accounts.filter((account2) => cooldownEnd(account2, now) === null && isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8378
8474
  return {
8379
8475
  version: 1,
8380
8476
  provider,
8381
8477
  routingEnabled: config?.enabled === true,
8382
8478
  eligibleAccounts,
8383
- retryAtMs: eligibleAccounts === 0 && resets.length > 0 ? Math.min(...resets) : null,
8479
+ retryAtMs: eligibleAccounts === 0 ? soonestServableAt(providerStrategy, accounts, accounts, model, ctx, now) : null,
8384
8480
  holdSeconds: config?.holdSeconds ?? 0,
8385
8481
  admissionWaitMs: config?.admissionWaitMs ?? 0
8386
8482
  };
8387
8483
  }
8388
- function getSoonestQuotaReset(meta, ctx, now = Date.now()) {
8389
- 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);
8390
- return resets.length > 0 ? Math.min(...resets) : null;
8484
+ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
8485
+ const fleet = fleetAccounts(ctx.providerName, ctx);
8486
+ return soonestServableAt(ctx.provider, fleet, seatsFor(fleet), meta.model, ctx, Date.now());
8487
+ }
8488
+ function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
8489
+ return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8391
8490
  }
8392
8491
  function selectRevalidationProbe(accounts, ctx, now) {
8393
8492
  const probes = ctx.quotaProbeAt;
@@ -8407,7 +8506,7 @@ function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8407
8506
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8408
8507
  const now = Date.now();
8409
8508
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8410
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8509
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
8411
8510
  const prioritized = [...candidates].sort((left, right) => {
8412
8511
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
8413
8512
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9744,9 +9843,15 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9744
9843
  try {
9745
9844
  const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
9746
9845
  if (attempt.kind === "response") {
9846
+ const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
9747
9847
  return {
9748
9848
  ...attempt,
9749
- response: releaseAfterResponse(attempt.response, release)
9849
+ response: releaseAfterResponse(attempt.response, () => {
9850
+ release();
9851
+ if (spentExtraUsage) {
9852
+ request2.ctx.seatAlerts?.extraUsageSpent(account2, request2.ctx.providerName);
9853
+ }
9854
+ })
9750
9855
  };
9751
9856
  }
9752
9857
  release();
@@ -9922,23 +10027,32 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
9922
10027
  provider: ctx.providerName,
9923
10028
  sessionId
9924
10029
  };
9925
- const selectedAccounts = selectAccountsForRequest(meta, ctx, teamRequest, selectionOptions);
9926
- const threadAccountId = getThreadBoundAccountId(ctx.messageThreads, thread);
9927
- const accounts = threadAccountId ? selectedAccounts.filter((account2) => account2.id === threadAccountId) : selectedAccounts;
10030
+ const request2 = {
10031
+ body,
10032
+ ctx,
10033
+ mappedModel,
10034
+ meta,
10035
+ req,
10036
+ teamRequest,
10037
+ thread,
10038
+ url
10039
+ };
9928
10040
  return {
9929
- accounts,
9930
- request: {
9931
- body,
9932
- ctx,
9933
- mappedModel,
9934
- meta,
9935
- req,
9936
- teamRequest,
9937
- thread,
9938
- url
9939
- }
10041
+ accounts: selectRequestAccounts(request2, selectionOptions),
10042
+ request: request2
9940
10043
  };
9941
10044
  }
10045
+ function onThreadSeat(request2, accounts) {
10046
+ const threadAccountId = getThreadBoundAccountId(request2.ctx.messageThreads, request2.thread);
10047
+ return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
10048
+ }
10049
+ function selectRequestAccounts(request2, selectionOptions) {
10050
+ return onThreadSeat(request2, selectAccountsForRequest(request2.meta, request2.ctx, request2.teamRequest, selectionOptions));
10051
+ }
10052
+ function getRequestRetryAt(request2) {
10053
+ const { ctx, teamRequest } = request2;
10054
+ return getSoonestQuotaReset(request2.meta, ctx, (fleet) => onThreadSeat(request2, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10055
+ }
9942
10056
  var init_proxy_request = __esm(() => {
9943
10057
  init_account_selector();
9944
10058
  init_message_thread();
@@ -10060,8 +10174,16 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10060
10174
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10061
10175
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10062
10176
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
10063
- let soonestReset = null;
10177
+ let soonestRetry = null;
10178
+ let soonestFleetReset = null;
10179
+ let everyCandidateFull = true;
10064
10180
  let emittedIngress = false;
10181
+ const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
10182
+ const recordUnserved = (request2) => {
10183
+ everyCandidateFull &&= isEveryAccountQuotaBlocked(request2.meta, request2.ctx);
10184
+ soonestRetry = earliest(soonestRetry, getRequestRetryAt(request2));
10185
+ soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request2.meta, request2.ctx));
10186
+ };
10065
10187
  const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10066
10188
  for (const [candidateIndex, candidate] of candidates.entries()) {
10067
10189
  const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
@@ -10073,8 +10195,7 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10073
10195
  }
10074
10196
  accounts = preferPinnedAccount(accounts, pinnedId);
10075
10197
  if (accounts.length === 0) {
10076
- const resetAt3 = getSoonestQuotaReset(candidateMeta, candidateContext);
10077
- soonestReset = resetAt3 !== null && (soonestReset === null || resetAt3 < soonestReset) ? resetAt3 : soonestReset;
10198
+ recordUnserved(prepared.request);
10078
10199
  continue;
10079
10200
  }
10080
10201
  if (!emittedIngress) {
@@ -10095,11 +10216,13 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10095
10216
  }
10096
10217
  return result.response;
10097
10218
  }
10098
- const resetAt2 = getSoonestQuotaReset(candidateMeta, candidateContext);
10099
- soonestReset = resetAt2 !== null && (soonestReset === null || resetAt2 < soonestReset) ? resetAt2 : soonestReset;
10219
+ recordUnserved(prepared.request);
10220
+ }
10221
+ if (everyCandidateFull && soonestFleetReset !== null) {
10222
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
10100
10223
  }
10101
- if (soonestReset !== null)
10102
- return quotaExhaustionResponse(soonestReset);
10224
+ if (soonestRetry !== null)
10225
+ return quotaExhaustionResponse(soonestRetry);
10103
10226
  log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10104
10227
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
10105
10228
  }
@@ -10113,6 +10236,133 @@ var init_provider_pool = __esm(() => {
10113
10236
  log22 = new Logger("Proxy");
10114
10237
  });
10115
10238
 
10239
+ // ../../packages/proxy/src/seat-alerts.ts
10240
+ function alertWhenFleetFull(meta, ctx, holdSeconds) {
10241
+ const resetAt2 = getSoonestQuotaReset(meta, ctx);
10242
+ if (resetAt2 === null || !isEveryAccountQuotaBlocked(meta, ctx))
10243
+ return;
10244
+ ctx.seatAlerts?.allAccountsFull(ctx.providerName, resetAt2, {
10245
+ blocked: ctx.runtime.blockWhenAllFull,
10246
+ holdSeconds
10247
+ });
10248
+ }
10249
+ function utc(at) {
10250
+ return `${new Date(at).toISOString().slice(0, 16).replace("T", " ")} UTC`;
10251
+ }
10252
+
10253
+ class SeatAlerts {
10254
+ config;
10255
+ send;
10256
+ fullUntil = new Map;
10257
+ constructor(config, send = (url, init) => fetch(url, init)) {
10258
+ this.config = config;
10259
+ this.send = send;
10260
+ if (config.email && !(config.emailFrom && config.resendApiKey)) {
10261
+ log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
10262
+ }
10263
+ if (!config.slackBotToken !== !config.slackChannel) {
10264
+ log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
10265
+ }
10266
+ }
10267
+ extraUsageSpent(account2, provider) {
10268
+ const claim = account2.quota_state?.representativeClaim;
10269
+ const resetAt2 = account2.quota_state?.windows.unified?.resetAt;
10270
+ this.notify({
10271
+ subject: `agent-smith: ${account2.name} spent extra usage`,
10272
+ 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)}.` : ""}`
10273
+ });
10274
+ }
10275
+ allAccountsFull(scope, resetAt2, policy) {
10276
+ if ((this.fullUntil.get(scope) ?? 0) > Date.now())
10277
+ return;
10278
+ this.fullUntil.set(scope, resetAt2);
10279
+ const probe = policy.blocked ? "" : ", except one a minute that revalidates and may spend extra usage";
10280
+ const hold = policy.holdSeconds > 0 ? `; one within ${policy.holdSeconds}s of the reset waits for it instead` : "";
10281
+ this.notify({
10282
+ subject: `agent-smith: every ${scope} account is full`,
10283
+ text: `Every ${scope} account is out of quota until ${utc(resetAt2)}. Requests are refused until then${probe}${hold}.`
10284
+ });
10285
+ }
10286
+ notify(alert) {
10287
+ log23.warn(alert.text);
10288
+ for (const delivery of this.deliveries(alert)) {
10289
+ trackProxyBackgroundTask(this.deliver(delivery));
10290
+ }
10291
+ }
10292
+ deliveries(alert) {
10293
+ const {
10294
+ email,
10295
+ emailFrom,
10296
+ resendApiKey,
10297
+ slackBotToken,
10298
+ slackChannel,
10299
+ slackWebhookUrl
10300
+ } = this.config;
10301
+ const deliveries = [];
10302
+ if (slackWebhookUrl) {
10303
+ deliveries.push({
10304
+ channel: "Slack",
10305
+ url: slackWebhookUrl,
10306
+ body: { text: alert.text }
10307
+ });
10308
+ }
10309
+ if (slackBotToken && slackChannel) {
10310
+ deliveries.push({
10311
+ channel: "Slack",
10312
+ url: SLACK_POST_MESSAGE_URL,
10313
+ headers: { authorization: `Bearer ${slackBotToken}` },
10314
+ body: { channel: slackChannel, text: alert.text },
10315
+ repliesOk: true
10316
+ });
10317
+ }
10318
+ if (email && emailFrom && resendApiKey) {
10319
+ deliveries.push({
10320
+ channel: "email",
10321
+ url: RESEND_EMAILS_URL,
10322
+ headers: { authorization: `Bearer ${resendApiKey}` },
10323
+ body: {
10324
+ from: emailFrom,
10325
+ to: [email],
10326
+ subject: alert.subject,
10327
+ text: alert.text
10328
+ }
10329
+ });
10330
+ }
10331
+ return deliveries;
10332
+ }
10333
+ async deliver(delivery) {
10334
+ try {
10335
+ const response = await this.send(delivery.url, {
10336
+ method: "POST",
10337
+ headers: { "content-type": "application/json", ...delivery.headers },
10338
+ body: JSON.stringify(delivery.body),
10339
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
10340
+ });
10341
+ if (!response.ok) {
10342
+ log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
10343
+ return;
10344
+ }
10345
+ if (!delivery.repliesOk)
10346
+ return;
10347
+ const reply = await response.json();
10348
+ if (reply.ok !== true) {
10349
+ const code = typeof reply.error === "string" && SLACK_ERROR_CODE.test(reply.error) ? reply.error : "no reason given";
10350
+ log23.warn(`${delivery.channel} alert was refused (${code})`);
10351
+ }
10352
+ } catch (error) {
10353
+ log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
10354
+ }
10355
+ }
10356
+ }
10357
+ 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;
10358
+ var init_seat_alerts = __esm(() => {
10359
+ init_src4();
10360
+ init_background_tasks();
10361
+ init_account_selector();
10362
+ log23 = new Logger("SeatAlerts");
10363
+ SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
10364
+ });
10365
+
10116
10366
  // ../../packages/proxy/src/usage-worker.ts
10117
10367
  import { isAbsolute, resolve } from "path";
10118
10368
  import { pathToFileURL } from "url";
@@ -10494,7 +10744,7 @@ function getUsageWorker() {
10494
10744
  }
10495
10745
  if (!usageWorkerInstance) {
10496
10746
  usageWorkerInstance = new UsageWorkerController({
10497
- logger: log23,
10747
+ logger: log24,
10498
10748
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
10499
10749
  onWorkerMessage: (data) => {
10500
10750
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -10565,21 +10815,23 @@ async function handleProxy(req, url, ctx) {
10565
10815
  const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
10566
10816
  let accounts = initiallySelectedAccounts;
10567
10817
  if (accounts.length === 0) {
10568
- const resetAt2 = getSoonestQuotaReset(requestMeta, requestContext);
10569
- if (resetAt2 !== null) {
10570
- const holdMs = requestContext.runtime.teamRouting.holdSeconds * 1000;
10571
- if (requestContext.runtime.teamRouting.enabled && holdMs > 0 && resetAt2 - Date.now() <= holdMs && requestContext.quotaHold) {
10572
- await requestContext.quotaHold.waitUntil(resetAt2, req.signal);
10573
- const resumedAccounts = selectAccountsForRequest(request2.meta, requestContext, request2.teamRequest);
10818
+ const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
10819
+ alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
10820
+ const retryAt = getRequestRetryAt(request2);
10821
+ if (retryAt !== null) {
10822
+ const holdMs = holdSeconds * 1000;
10823
+ if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
10824
+ await requestContext.quotaHold.waitUntil(retryAt, req.signal);
10825
+ const resumedAccounts = selectRequestAccounts(request2);
10574
10826
  if (resumedAccounts.length > 0) {
10575
10827
  accounts = resumedAccounts;
10576
10828
  }
10577
10829
  }
10578
10830
  if (accounts.length === 0)
10579
- return quotaExhaustionResponse(resetAt2);
10831
+ return quotaExhaustionResponse(retryAt);
10580
10832
  }
10581
10833
  if (accounts.length === 0) {
10582
- log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10834
+ log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10583
10835
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
10584
10836
  }
10585
10837
  }
@@ -10590,19 +10842,20 @@ async function handleProxy(req, url, ctx) {
10590
10842
  method: requestMeta.method,
10591
10843
  path: requestMeta.path
10592
10844
  });
10593
- log23.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10594
- log23.info(`Request: ${req.method} ${url.pathname}`);
10845
+ log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10846
+ log24.info(`Request: ${req.method} ${url.pathname}`);
10595
10847
  return await proxySelectedAccounts(request2, accounts);
10596
10848
  }
10597
- var log23, usageWorkerInstance = null;
10849
+ var log24, usageWorkerInstance = null;
10598
10850
  var init_proxy = __esm(() => {
10599
10851
  init_src2();
10600
10852
  init_src4();
10601
10853
  init_src();
10602
10854
  init_handlers();
10603
10855
  init_provider_pool();
10856
+ init_seat_alerts();
10604
10857
  init_usage_worker();
10605
- log23 = new Logger("Proxy");
10858
+ log24 = new Logger("Proxy");
10606
10859
  });
10607
10860
 
10608
10861
  // ../../packages/proxy/src/quota-hold.ts
@@ -10950,7 +11203,7 @@ function endActiveTurn(session, success, error) {
10950
11203
  if (!activeTurn) {
10951
11204
  return;
10952
11205
  }
10953
- log24.debug("Ending tracked websocket turn", {
11206
+ log25.debug("Ending tracked websocket turn", {
10954
11207
  requestId: activeTurn.requestId,
10955
11208
  provider: session.providerName,
10956
11209
  path: session.path,
@@ -11003,7 +11256,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
11003
11256
  timestamp,
11004
11257
  model: getEventModel(parsed)
11005
11258
  };
11006
- log24.debug("Starting tracked websocket turn", {
11259
+ log25.debug("Starting tracked websocket turn", {
11007
11260
  requestId,
11008
11261
  provider: session.providerName,
11009
11262
  path: session.path,
@@ -11033,7 +11286,7 @@ function handleTrackedUpstreamText(session, data) {
11033
11286
  if (!messageType) {
11034
11287
  return;
11035
11288
  }
11036
- log24.debug("Processing tracked websocket message", {
11289
+ log25.debug("Processing tracked websocket message", {
11037
11290
  provider: session.providerName,
11038
11291
  path: session.path,
11039
11292
  messageType,
@@ -11074,7 +11327,7 @@ function capturePendingRequestBody(session, message) {
11074
11327
  }
11075
11328
  session.pendingRequestBody = Buffer.from(message).toString("base64");
11076
11329
  session.pendingRequestTimestamp = Date.now();
11077
- log24.debug("Captured websocket request body for next tracked turn", {
11330
+ log25.debug("Captured websocket request body for next tracked turn", {
11078
11331
  provider: session.providerName,
11079
11332
  path: session.path,
11080
11333
  size: message.length
@@ -11147,7 +11400,7 @@ async function connectToNextUpstream(ws) {
11147
11400
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
11148
11401
  } catch (error) {
11149
11402
  session.connecting = false;
11150
- log24.warn("Skipping websocket account during upstream connection", {
11403
+ log25.warn("Skipping websocket account during upstream connection", {
11151
11404
  account: account2.name,
11152
11405
  error: error instanceof Error ? error.message : String(error)
11153
11406
  });
@@ -11206,7 +11459,7 @@ async function connectToNextUpstream(ws) {
11206
11459
  }
11207
11460
  });
11208
11461
  upstream.addEventListener("error", () => {
11209
- log24.warn("Upstream websocket error", {
11462
+ log25.warn("Upstream websocket error", {
11210
11463
  account: plan.account.name,
11211
11464
  provider: session.providerName,
11212
11465
  path: session.path
@@ -11215,7 +11468,7 @@ async function connectToNextUpstream(ws) {
11215
11468
  } catch (error) {
11216
11469
  session.connecting = false;
11217
11470
  clearConnectTimeout(session);
11218
- log24.warn("Failed to create upstream websocket", {
11471
+ log25.warn("Failed to create upstream websocket", {
11219
11472
  account: plan.account.name,
11220
11473
  error: error instanceof Error ? error.message : String(error)
11221
11474
  });
@@ -11258,7 +11511,8 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11258
11511
  };
11259
11512
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
11260
11513
  if (accounts.length === 0) {
11261
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11514
+ alertWhenFleetFull(requestMeta, requestContext, 0);
11515
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11262
11516
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
11263
11517
  }
11264
11518
  const protocols = getProtocols(req.headers);
@@ -11296,7 +11550,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11296
11550
  }
11297
11551
  return;
11298
11552
  }
11299
- 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;
11553
+ 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;
11300
11554
  var init_websocket_proxy = __esm(() => {
11301
11555
  init_src2();
11302
11556
  init_src3();
@@ -11306,7 +11560,8 @@ var init_websocket_proxy = __esm(() => {
11306
11560
  init_request_handler();
11307
11561
  init_token_manager();
11308
11562
  init_openai_usage();
11309
- log24 = new Logger("WebSocketProxy");
11563
+ init_seat_alerts();
11564
+ log25 = new Logger("WebSocketProxy");
11310
11565
  websocketSessions = new Map;
11311
11566
  textEncoder = new TextEncoder;
11312
11567
  websocketProxyHandler = {
@@ -11360,6 +11615,7 @@ var init_src10 = __esm(() => {
11360
11615
  init_proxy();
11361
11616
  init_quota_probe();
11362
11617
  init_response_handler();
11618
+ init_seat_alerts();
11363
11619
  init_strategies();
11364
11620
  init_team_admission();
11365
11621
  init_team_router();
@@ -11483,6 +11739,7 @@ var init_exposure = __esm(() => {
11483
11739
  // ../../packages/runtime-server/src/bootstrap-runtime.ts
11484
11740
  function createRuntimeConfig(config, port) {
11485
11741
  return {
11742
+ blockWhenAllFull: config.getBlockWhenAllFull(),
11486
11743
  clientId: config.get("client_id", "9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
11487
11744
  maxBodyBytes: config.get("max_body_bytes", 64 * 1024 * 1024),
11488
11745
  requestScopedRetryDelayMs: config.get("request_scoped_429_retry_delay_ms", 2000),
@@ -11497,10 +11754,10 @@ function createRuntimeConfig(config, port) {
11497
11754
  teamRouting: config.getTeamRouting()
11498
11755
  };
11499
11756
  }
11500
- function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11757
+ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11501
11758
  config.on("change", (change) => {
11502
11759
  if (change.key === "lb_strategy") {
11503
- log25.info("Strategy configuration changed");
11760
+ log26.info("Strategy configuration changed");
11504
11761
  const newStrategyName = config.getStrategy();
11505
11762
  if (newStrategyName === "session") {
11506
11763
  const strategy3 = new SessionStrategy;
@@ -11511,7 +11768,7 @@ function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig
11511
11768
  if (change.key === "team_routing") {
11512
11769
  runtimeConfig2.teamRouting = config.getTeamRouting();
11513
11770
  quotaProbe.reschedule();
11514
- log25.info("Team routing configuration changed");
11771
+ log26.info("Team routing configuration changed");
11515
11772
  }
11516
11773
  });
11517
11774
  }
@@ -11525,7 +11782,7 @@ function bootstrapRuntime(port, serverLog) {
11525
11782
  sessionDurationMs: runtimeConfig2.sessionDurationMs
11526
11783
  });
11527
11784
  const dbOps = DatabaseFactory.getInstance();
11528
- const log25 = container.resolve(SERVICE_KEYS.Logger);
11785
+ const log26 = container.resolve(SERVICE_KEYS.Logger);
11529
11786
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
11530
11787
  const asyncWriter = new AsyncDbWriter;
11531
11788
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -11573,6 +11830,7 @@ function bootstrapRuntime(port, serverLog) {
11573
11830
  teamAdmission,
11574
11831
  quotaHold,
11575
11832
  outsideSpendTracker,
11833
+ seatAlerts: new SeatAlerts(config.getAlerts()),
11576
11834
  asyncWriter,
11577
11835
  usageWorker: getUsageWorker()
11578
11836
  };
@@ -11589,11 +11847,11 @@ function bootstrapRuntime(port, serverLog) {
11589
11847
  });
11590
11848
  quotaProbe.start();
11591
11849
  registerDisposable(quotaProbe);
11592
- wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11850
+ wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11593
11851
  return {
11594
11852
  config,
11595
11853
  dbOps,
11596
- log: log25,
11854
+ log: log26,
11597
11855
  asyncWriter,
11598
11856
  apiRouter,
11599
11857
  exposureConfig,
@@ -11602,12 +11860,12 @@ function bootstrapRuntime(port, serverLog) {
11602
11860
  runtimeConfig: runtimeConfig2
11603
11861
  };
11604
11862
  }
11605
- function logInitialAccountStatus(log25, dbOps) {
11863
+ function logInitialAccountStatus(log26, dbOps) {
11606
11864
  const accounts = dbOps.getAllAccounts();
11607
11865
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
11608
- log25.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11866
+ log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11609
11867
  if (activeAccounts.length === 0) {
11610
- log25.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11868
+ log26.warn("No active accounts available - requests will be refused with a 503 until an account is added");
11611
11869
  }
11612
11870
  }
11613
11871
  var init_bootstrap_runtime = __esm(() => {
@@ -11834,20 +12092,20 @@ var init_startup_banner = __esm(() => {
11834
12092
 
11835
12093
  // ../../packages/runtime-server/src/startup-maintenance.ts
11836
12094
  function runStartupMaintenance(config, dbOps) {
11837
- const log25 = new Logger("StartupMaintenance");
12095
+ const log26 = new Logger("StartupMaintenance");
11838
12096
  try {
11839
12097
  const payloadDays = config.getDataRetentionDays();
11840
12098
  const requestDays = config.getRequestRetentionDays();
11841
12099
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
11842
- log25.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
12100
+ log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
11843
12101
  } catch (err) {
11844
- log25.error(`Startup cleanup error: ${err}`);
12102
+ log26.error(`Startup cleanup error: ${err}`);
11845
12103
  }
11846
12104
  try {
11847
12105
  dbOps.compact();
11848
- log25.info("Database compacted at startup");
12106
+ log26.info("Database compacted at startup");
11849
12107
  } catch (err) {
11850
- log25.error(`Database compaction error: ${err}`);
12108
+ log26.error(`Database compaction error: ${err}`);
11851
12109
  }
11852
12110
  return () => {};
11853
12111
  }
@@ -11944,7 +12202,7 @@ function startServer(options) {
11944
12202
  const {
11945
12203
  config,
11946
12204
  dbOps,
11947
- log: log25,
12205
+ log: log26,
11948
12206
  apiRouter,
11949
12207
  exposureConfig,
11950
12208
  proxyContext,
@@ -11987,7 +12245,7 @@ function startServer(options) {
11987
12245
  strategy: config.getStrategy(),
11988
12246
  providers: providerRegistry.listProviders()
11989
12247
  }));
11990
- logInitialAccountStatus(log25, dbOps);
12248
+ logInitialAccountStatus(log26, dbOps);
11991
12249
  return {
11992
12250
  port: activePort,
11993
12251
  stop: () => stopServerRuntime(),