@certalis/agent-smith 0.1.3 → 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
@@ -705,6 +705,9 @@ function quotaThresholdFor(account, bucket, fleetThreshold) {
705
705
  function isCurrentQuotaWindow(window, now) {
706
706
  return (window.resetAt === null || window.resetAt > now) && now - window.seenAt <= QUOTA_STALE_MS;
707
707
  }
708
+ function isOpenQuotaWindow(window, now) {
709
+ return window.resetAt === null ? isCurrentQuotaWindow(window, now) : window.resetAt > now;
710
+ }
708
711
  var QUOTA_STALE_MS;
709
712
  var init_quota = __esm(() => {
710
713
  QUOTA_STALE_MS = 30 * 60000;
@@ -1317,6 +1320,12 @@ function sanitizeConfigData(value) {
1317
1320
  sanitized.provider_pools = providerPools;
1318
1321
  continue;
1319
1322
  }
1323
+ if (key === "alerts") {
1324
+ const alerts = sanitizeAlerts(entry);
1325
+ if (alerts)
1326
+ sanitized.alerts = alerts;
1327
+ continue;
1328
+ }
1320
1329
  if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
1321
1330
  sanitized[key] = entry;
1322
1331
  }
@@ -1347,6 +1356,46 @@ function sanitizeConfigData(value) {
1347
1356
  }
1348
1357
  return sanitized;
1349
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
+ }
1350
1399
  function isProviderStrategy(value) {
1351
1400
  return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
1352
1401
  }
@@ -1448,7 +1497,7 @@ function sanitizeTeamRouting(value) {
1448
1497
  }
1449
1498
  return result;
1450
1499
  }
1451
- 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;
1452
1501
  var init_src4 = __esm(() => {
1453
1502
  init_src2();
1454
1503
  init_src3();
@@ -1514,12 +1563,23 @@ var init_src4 = __esm(() => {
1514
1563
  }
1515
1564
  saveConfig() {
1516
1565
  try {
1517
- const content = JSON.stringify(this.data, null, 2);
1518
- writeFileSync(this.configPath, content, "utf8");
1566
+ this.writePrivately(this.data);
1519
1567
  } catch (error) {
1520
1568
  log2.error(`Failed to save config file: ${error}`);
1521
1569
  }
1522
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
+ }
1523
1583
  get(key, defaultValue) {
1524
1584
  const value = this.data[key];
1525
1585
  if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
@@ -1614,6 +1674,20 @@ var init_src4 = __esm(() => {
1614
1674
  quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
1615
1675
  };
1616
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
+ }
1617
1691
  getProviderConfig(name) {
1618
1692
  const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1619
1693
  const configured = this.data.providers?.[name];
@@ -1714,22 +1788,14 @@ var init_src4 = __esm(() => {
1714
1788
  }
1715
1789
  persistStrictly(key, value) {
1716
1790
  const next = { ...this.data, [key]: value };
1717
- const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1718
- try {
1719
- writeFileSync(temporary, JSON.stringify(next, null, 2), {
1720
- mode: 384,
1721
- flag: "wx"
1722
- });
1723
- renameSync(temporary, this.configPath);
1724
- } finally {
1725
- rmSync(temporary, { force: true });
1726
- }
1791
+ this.writePrivately(next);
1727
1792
  const oldValue = this.data[key];
1728
1793
  this.data = next;
1729
1794
  this.emit("change", { key, oldValue, newValue: value });
1730
1795
  }
1731
1796
  getRuntime() {
1732
1797
  const defaults = {
1798
+ blockWhenAllFull: this.getBlockWhenAllFull(),
1733
1799
  clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
1734
1800
  maxBodyBytes: 64 * 1024 * 1024,
1735
1801
  quotaThreshold: 0.98,
@@ -4683,6 +4749,12 @@ var init_provider = __esm(() => {
4683
4749
  hasRateLimitSignal(headerName) {
4684
4750
  return super.hasRateLimitSignal(headerName) || headerName.toLowerCase().startsWith("anthropic-ratelimit-unified-");
4685
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
+ }
4686
4758
  quotaBucketsFor(model) {
4687
4759
  const familyBucket = familyQuotaBucket(model);
4688
4760
  return familyBucket ? [...SHARED_QUOTA_BUCKETS, familyBucket] : SHARED_QUOTA_BUCKETS;
@@ -8186,14 +8258,7 @@ var init_background_tasks = __esm(() => {
8186
8258
  function liveUtilization(window2, now) {
8187
8259
  if (window2.utilization === null)
8188
8260
  return 0;
8189
- const windowOpen = window2.resetAt === null ? isCurrentQuotaWindow(window2, now) : window2.resetAt > now;
8190
- return windowOpen ? window2.utilization : 0;
8191
- }
8192
- function isAheadOfWeeklyPace(window2, now) {
8193
- if (window2.resetAt === null || window2.resetAt <= now)
8194
- return false;
8195
- const elapsedShareOfWeek = 1 - (window2.resetAt - now) / WEEK_MS;
8196
- return liveUtilization(window2, now) > elapsedShareOfWeek;
8261
+ return isOpenQuotaWindow(window2, now) ? window2.utilization : 0;
8197
8262
  }
8198
8263
  function highestUtilization(windows, now) {
8199
8264
  return Math.max(0, ...windows.map(([, window2]) => liveUtilization(window2, now)));
@@ -8204,7 +8269,6 @@ function seatUsage(provider, account2, model, now) {
8204
8269
  const weekly = windows.filter(([bucket]) => provider.isWeeklyBucket(bucket));
8205
8270
  const fiveHour = windows.filter(([bucket]) => provider.isFiveHourBucket(bucket));
8206
8271
  return {
8207
- aheadOfWeeklyPace: weekly.some(([, window2]) => isAheadOfWeeklyPace(window2, now)),
8208
8272
  fiveHour: highestUtilization(fiveHour, now),
8209
8273
  weekly: highestUtilization(weekly, now)
8210
8274
  };
@@ -8217,13 +8281,11 @@ function compareSeatUsage(provider, model, now) {
8217
8281
  return (left, right) => {
8218
8282
  const a = seatUsage(provider, left, model, now);
8219
8283
  const b = seatUsage(provider, right, model, now);
8220
- return Number(a.aheadOfWeeklyPace) - Number(b.aheadOfWeeklyPace) || a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
8284
+ return a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
8221
8285
  };
8222
8286
  }
8223
- var WEEK_MS;
8224
8287
  var init_seat_usage = __esm(() => {
8225
8288
  init_src();
8226
- WEEK_MS = 7 * 24 * 60 * 60 * 1000;
8227
8289
  });
8228
8290
 
8229
8291
  // ../../packages/proxy/src/team-router.ts
@@ -8357,7 +8419,7 @@ var init_team_router = __esm(() => {
8357
8419
  // ../../packages/proxy/src/handlers/account-selector.ts
8358
8420
  function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
8359
8421
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
8360
- return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && isCurrentQuotaWindow(window2, now) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
8422
+ return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
8361
8423
  }
8362
8424
  function pooledMaxUsage(account2, ctx) {
8363
8425
  const teamRouting = ctx.runtime.teamRouting;
@@ -8374,28 +8436,58 @@ function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
8374
8436
  }
8375
8437
  return true;
8376
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
+ }
8377
8467
  function getPoolStatus(provider, model, ctx) {
8378
8468
  const providerStrategy = ctx.providerRegistry.getProvider(provider);
8379
8469
  if (!providerStrategy)
8380
8470
  throw new Error(`Unknown provider '${provider}'`);
8381
8471
  const config = ctx.runtime.teamRouting;
8382
8472
  const now = Date.now();
8383
- const accounts = config?.enabled ? ctx.dbOps.getAvailableAccountsByProvider(provider).filter((account2) => isAllowlisted(account2, config)) : [];
8384
- const eligibleAccounts = accounts.filter((account2) => isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
8385
- 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;
8386
8475
  return {
8387
8476
  version: 1,
8388
8477
  provider,
8389
8478
  routingEnabled: config?.enabled === true,
8390
8479
  eligibleAccounts,
8391
- retryAtMs: eligibleAccounts === 0 && resets.length > 0 ? Math.min(...resets) : null,
8480
+ retryAtMs: eligibleAccounts === 0 ? soonestServableAt(providerStrategy, accounts, accounts, model, ctx, now) : null,
8392
8481
  holdSeconds: config?.holdSeconds ?? 0,
8393
8482
  admissionWaitMs: config?.admissionWaitMs ?? 0
8394
8483
  };
8395
8484
  }
8396
- function getSoonestQuotaReset(meta, ctx, now = Date.now()) {
8397
- 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);
8398
- 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));
8399
8491
  }
8400
8492
  function selectRevalidationProbe(accounts, ctx, now) {
8401
8493
  const probes = ctx.quotaProbeAt;
@@ -8415,7 +8507,7 @@ function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8415
8507
  const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName);
8416
8508
  const now = Date.now();
8417
8509
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8418
- 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);
8419
8511
  const prioritized = [...candidates].sort((left, right) => {
8420
8512
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
8421
8513
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -9628,7 +9720,7 @@ async function classifyUpstreamResponse(input, upstream) {
9628
9720
  retryAfterMs: perMinuteRetryAfterMs
9629
9721
  };
9630
9722
  }
9631
- if (isRateLimited) {
9723
+ if (isRateLimited && !response.ok) {
9632
9724
  return response.status === 429 ? {
9633
9725
  discard: discardUpstreamResponse(state),
9634
9726
  forward,
@@ -9752,9 +9844,15 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9752
9844
  try {
9753
9845
  const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
9754
9846
  if (attempt.kind === "response") {
9847
+ const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
9755
9848
  return {
9756
9849
  ...attempt,
9757
- 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
+ })
9758
9856
  };
9759
9857
  }
9760
9858
  release();
@@ -9930,23 +10028,32 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
9930
10028
  provider: ctx.providerName,
9931
10029
  sessionId
9932
10030
  };
9933
- const selectedAccounts = selectAccountsForRequest(meta, ctx, teamRequest, selectionOptions);
9934
- const threadAccountId = getThreadBoundAccountId(ctx.messageThreads, thread);
9935
- 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
+ };
9936
10041
  return {
9937
- accounts,
9938
- request: {
9939
- body,
9940
- ctx,
9941
- mappedModel,
9942
- meta,
9943
- req,
9944
- teamRequest,
9945
- thread,
9946
- url
9947
- }
10042
+ accounts: selectRequestAccounts(request2, selectionOptions),
10043
+ request: request2
9948
10044
  };
9949
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
+ }
9950
10057
  var init_proxy_request = __esm(() => {
9951
10058
  init_account_selector();
9952
10059
  init_message_thread();
@@ -10068,8 +10175,16 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10068
10175
  const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10069
10176
  const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10070
10177
  const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
10071
- let soonestReset = null;
10178
+ let soonestRetry = null;
10179
+ let soonestFleetReset = null;
10180
+ let everyCandidateFull = true;
10072
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
+ };
10073
10188
  const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10074
10189
  for (const [candidateIndex, candidate] of candidates.entries()) {
10075
10190
  const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
@@ -10081,8 +10196,7 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10081
10196
  }
10082
10197
  accounts = preferPinnedAccount(accounts, pinnedId);
10083
10198
  if (accounts.length === 0) {
10084
- const resetAt3 = getSoonestQuotaReset(candidateMeta, candidateContext);
10085
- soonestReset = resetAt3 !== null && (soonestReset === null || resetAt3 < soonestReset) ? resetAt3 : soonestReset;
10199
+ recordUnserved(prepared.request);
10086
10200
  continue;
10087
10201
  }
10088
10202
  if (!emittedIngress) {
@@ -10103,11 +10217,13 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10103
10217
  }
10104
10218
  return result.response;
10105
10219
  }
10106
- const resetAt2 = getSoonestQuotaReset(candidateMeta, candidateContext);
10107
- 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 });
10108
10224
  }
10109
- if (soonestReset !== null)
10110
- return quotaExhaustionResponse(soonestReset);
10225
+ if (soonestRetry !== null)
10226
+ return quotaExhaustionResponse(soonestRetry);
10111
10227
  log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10112
10228
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
10113
10229
  }
@@ -10121,6 +10237,133 @@ var init_provider_pool = __esm(() => {
10121
10237
  log22 = new Logger("Proxy");
10122
10238
  });
10123
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
+
10124
10367
  // ../../packages/proxy/src/usage-worker.ts
10125
10368
  import { isAbsolute, resolve } from "path";
10126
10369
  import { pathToFileURL } from "url";
@@ -10502,7 +10745,7 @@ function getUsageWorker() {
10502
10745
  }
10503
10746
  if (!usageWorkerInstance) {
10504
10747
  usageWorkerInstance = new UsageWorkerController({
10505
- logger: log23,
10748
+ logger: log24,
10506
10749
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
10507
10750
  onWorkerMessage: (data) => {
10508
10751
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -10573,21 +10816,23 @@ async function handleProxy(req, url, ctx) {
10573
10816
  const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
10574
10817
  let accounts = initiallySelectedAccounts;
10575
10818
  if (accounts.length === 0) {
10576
- const resetAt2 = getSoonestQuotaReset(requestMeta, requestContext);
10577
- if (resetAt2 !== null) {
10578
- const holdMs = requestContext.runtime.teamRouting.holdSeconds * 1000;
10579
- if (requestContext.runtime.teamRouting.enabled && holdMs > 0 && resetAt2 - Date.now() <= holdMs && requestContext.quotaHold) {
10580
- await requestContext.quotaHold.waitUntil(resetAt2, req.signal);
10581
- 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);
10582
10827
  if (resumedAccounts.length > 0) {
10583
10828
  accounts = resumedAccounts;
10584
10829
  }
10585
10830
  }
10586
10831
  if (accounts.length === 0)
10587
- return quotaExhaustionResponse(resetAt2);
10832
+ return quotaExhaustionResponse(retryAt);
10588
10833
  }
10589
10834
  if (accounts.length === 0) {
10590
- log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10835
+ log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
10591
10836
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
10592
10837
  }
10593
10838
  }
@@ -10598,19 +10843,20 @@ async function handleProxy(req, url, ctx) {
10598
10843
  method: requestMeta.method,
10599
10844
  path: requestMeta.path
10600
10845
  });
10601
- log23.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10602
- 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}`);
10603
10848
  return await proxySelectedAccounts(request2, accounts);
10604
10849
  }
10605
- var log23, usageWorkerInstance = null;
10850
+ var log24, usageWorkerInstance = null;
10606
10851
  var init_proxy = __esm(() => {
10607
10852
  init_src2();
10608
10853
  init_src3();
10609
10854
  init_src();
10610
10855
  init_handlers();
10611
10856
  init_provider_pool();
10857
+ init_seat_alerts();
10612
10858
  init_usage_worker();
10613
- log23 = new Logger("Proxy");
10859
+ log24 = new Logger("Proxy");
10614
10860
  });
10615
10861
 
10616
10862
  // ../../packages/proxy/src/quota-hold.ts
@@ -10958,7 +11204,7 @@ function endActiveTurn(session, success, error) {
10958
11204
  if (!activeTurn) {
10959
11205
  return;
10960
11206
  }
10961
- log24.debug("Ending tracked websocket turn", {
11207
+ log25.debug("Ending tracked websocket turn", {
10962
11208
  requestId: activeTurn.requestId,
10963
11209
  provider: session.providerName,
10964
11210
  path: session.path,
@@ -11011,7 +11257,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
11011
11257
  timestamp,
11012
11258
  model: getEventModel(parsed)
11013
11259
  };
11014
- log24.debug("Starting tracked websocket turn", {
11260
+ log25.debug("Starting tracked websocket turn", {
11015
11261
  requestId,
11016
11262
  provider: session.providerName,
11017
11263
  path: session.path,
@@ -11041,7 +11287,7 @@ function handleTrackedUpstreamText(session, data) {
11041
11287
  if (!messageType) {
11042
11288
  return;
11043
11289
  }
11044
- log24.debug("Processing tracked websocket message", {
11290
+ log25.debug("Processing tracked websocket message", {
11045
11291
  provider: session.providerName,
11046
11292
  path: session.path,
11047
11293
  messageType,
@@ -11082,7 +11328,7 @@ function capturePendingRequestBody(session, message) {
11082
11328
  }
11083
11329
  session.pendingRequestBody = Buffer.from(message).toString("base64");
11084
11330
  session.pendingRequestTimestamp = Date.now();
11085
- log24.debug("Captured websocket request body for next tracked turn", {
11331
+ log25.debug("Captured websocket request body for next tracked turn", {
11086
11332
  provider: session.providerName,
11087
11333
  path: session.path,
11088
11334
  size: message.length
@@ -11155,7 +11401,7 @@ async function connectToNextUpstream(ws) {
11155
11401
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
11156
11402
  } catch (error) {
11157
11403
  session.connecting = false;
11158
- log24.warn("Skipping websocket account during upstream connection", {
11404
+ log25.warn("Skipping websocket account during upstream connection", {
11159
11405
  account: account2.name,
11160
11406
  error: error instanceof Error ? error.message : String(error)
11161
11407
  });
@@ -11214,7 +11460,7 @@ async function connectToNextUpstream(ws) {
11214
11460
  }
11215
11461
  });
11216
11462
  upstream.addEventListener("error", () => {
11217
- log24.warn("Upstream websocket error", {
11463
+ log25.warn("Upstream websocket error", {
11218
11464
  account: plan.account.name,
11219
11465
  provider: session.providerName,
11220
11466
  path: session.path
@@ -11223,7 +11469,7 @@ async function connectToNextUpstream(ws) {
11223
11469
  } catch (error) {
11224
11470
  session.connecting = false;
11225
11471
  clearConnectTimeout(session);
11226
- log24.warn("Failed to create upstream websocket", {
11472
+ log25.warn("Failed to create upstream websocket", {
11227
11473
  account: plan.account.name,
11228
11474
  error: error instanceof Error ? error.message : String(error)
11229
11475
  });
@@ -11266,7 +11512,8 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11266
11512
  };
11267
11513
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
11268
11514
  if (accounts.length === 0) {
11269
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11515
+ alertWhenFleetFull(requestMeta, requestContext, 0);
11516
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11270
11517
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
11271
11518
  }
11272
11519
  const protocols = getProtocols(req.headers);
@@ -11304,7 +11551,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server) {
11304
11551
  }
11305
11552
  return;
11306
11553
  }
11307
- 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;
11308
11555
  var init_websocket_proxy = __esm(() => {
11309
11556
  init_src2();
11310
11557
  init_src6();
@@ -11314,7 +11561,8 @@ var init_websocket_proxy = __esm(() => {
11314
11561
  init_request_handler();
11315
11562
  init_token_manager();
11316
11563
  init_openai_usage();
11317
- log24 = new Logger("WebSocketProxy");
11564
+ init_seat_alerts();
11565
+ log25 = new Logger("WebSocketProxy");
11318
11566
  websocketSessions = new Map;
11319
11567
  textEncoder = new TextEncoder;
11320
11568
  websocketProxyHandler = {
@@ -11368,6 +11616,7 @@ var init_src10 = __esm(() => {
11368
11616
  init_proxy();
11369
11617
  init_quota_probe();
11370
11618
  init_response_handler();
11619
+ init_seat_alerts();
11371
11620
  init_strategies();
11372
11621
  init_team_admission();
11373
11622
  init_team_router();
@@ -11491,6 +11740,7 @@ var init_exposure = __esm(() => {
11491
11740
  // ../../packages/runtime-server/src/bootstrap-runtime.ts
11492
11741
  function createRuntimeConfig(config, port) {
11493
11742
  return {
11743
+ blockWhenAllFull: config.getBlockWhenAllFull(),
11494
11744
  clientId: config.get("client_id", "9d1c250a-e61b-44d9-88ed-5944d1962f5e"),
11495
11745
  maxBodyBytes: config.get("max_body_bytes", 64 * 1024 * 1024),
11496
11746
  requestScopedRetryDelayMs: config.get("request_scoped_429_retry_delay_ms", 2000),
@@ -11505,10 +11755,10 @@ function createRuntimeConfig(config, port) {
11505
11755
  teamRouting: config.getTeamRouting()
11506
11756
  };
11507
11757
  }
11508
- function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11758
+ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
11509
11759
  config.on("change", (change) => {
11510
11760
  if (change.key === "lb_strategy") {
11511
- log25.info("Strategy configuration changed");
11761
+ log26.info("Strategy configuration changed");
11512
11762
  const newStrategyName = config.getStrategy();
11513
11763
  if (newStrategyName === "session") {
11514
11764
  const strategy3 = new SessionStrategy;
@@ -11519,7 +11769,7 @@ function wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig
11519
11769
  if (change.key === "team_routing") {
11520
11770
  runtimeConfig2.teamRouting = config.getTeamRouting();
11521
11771
  quotaProbe.reschedule();
11522
- log25.info("Team routing configuration changed");
11772
+ log26.info("Team routing configuration changed");
11523
11773
  }
11524
11774
  });
11525
11775
  }
@@ -11533,7 +11783,7 @@ function bootstrapRuntime(port, serverLog) {
11533
11783
  sessionDurationMs: runtimeConfig2.sessionDurationMs
11534
11784
  });
11535
11785
  const dbOps = DatabaseFactory.getInstance();
11536
- const log25 = container.resolve(SERVICE_KEYS.Logger);
11786
+ const log26 = container.resolve(SERVICE_KEYS.Logger);
11537
11787
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
11538
11788
  const asyncWriter = new AsyncDbWriter;
11539
11789
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -11581,6 +11831,7 @@ function bootstrapRuntime(port, serverLog) {
11581
11831
  teamAdmission,
11582
11832
  quotaHold,
11583
11833
  outsideSpendTracker,
11834
+ seatAlerts: new SeatAlerts(config.getAlerts()),
11584
11835
  asyncWriter,
11585
11836
  usageWorker: getUsageWorker()
11586
11837
  };
@@ -11597,11 +11848,11 @@ function bootstrapRuntime(port, serverLog) {
11597
11848
  });
11598
11849
  quotaProbe.start();
11599
11850
  registerDisposable(quotaProbe);
11600
- wireStrategyHotReload(config, log25, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11851
+ wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
11601
11852
  return {
11602
11853
  config,
11603
11854
  dbOps,
11604
- log: log25,
11855
+ log: log26,
11605
11856
  asyncWriter,
11606
11857
  apiRouter,
11607
11858
  exposureConfig,
@@ -11610,12 +11861,12 @@ function bootstrapRuntime(port, serverLog) {
11610
11861
  runtimeConfig: runtimeConfig2
11611
11862
  };
11612
11863
  }
11613
- function logInitialAccountStatus(log25, dbOps) {
11864
+ function logInitialAccountStatus(log26, dbOps) {
11614
11865
  const accounts = dbOps.getAllAccounts();
11615
11866
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
11616
- log25.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11867
+ log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
11617
11868
  if (activeAccounts.length === 0) {
11618
- 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");
11619
11870
  }
11620
11871
  }
11621
11872
  var init_bootstrap_runtime = __esm(() => {
@@ -11842,20 +12093,20 @@ var init_startup_banner = __esm(() => {
11842
12093
 
11843
12094
  // ../../packages/runtime-server/src/startup-maintenance.ts
11844
12095
  function runStartupMaintenance(config, dbOps) {
11845
- const log25 = new Logger("StartupMaintenance");
12096
+ const log26 = new Logger("StartupMaintenance");
11846
12097
  try {
11847
12098
  const payloadDays = config.getDataRetentionDays();
11848
12099
  const requestDays = config.getRequestRetentionDays();
11849
12100
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
11850
- 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)`);
11851
12102
  } catch (err) {
11852
- log25.error(`Startup cleanup error: ${err}`);
12103
+ log26.error(`Startup cleanup error: ${err}`);
11853
12104
  }
11854
12105
  try {
11855
12106
  dbOps.compact();
11856
- log25.info("Database compacted at startup");
12107
+ log26.info("Database compacted at startup");
11857
12108
  } catch (err) {
11858
- log25.error(`Database compaction error: ${err}`);
12109
+ log26.error(`Database compaction error: ${err}`);
11859
12110
  }
11860
12111
  return () => {};
11861
12112
  }
@@ -11952,7 +12203,7 @@ function startServer(options) {
11952
12203
  const {
11953
12204
  config,
11954
12205
  dbOps,
11955
- log: log25,
12206
+ log: log26,
11956
12207
  apiRouter,
11957
12208
  exposureConfig,
11958
12209
  proxyContext,
@@ -11995,7 +12246,7 @@ function startServer(options) {
11995
12246
  strategy: config.getStrategy(),
11996
12247
  providers: providerRegistry.listProviders()
11997
12248
  }));
11998
- logInitialAccountStatus(log25, dbOps);
12249
+ logInitialAccountStatus(log26, dbOps);
11999
12250
  return {
12000
12251
  port: activePort,
12001
12252
  stop: () => stopServerRuntime(),
@@ -15858,13 +16109,13 @@ function reducer(state, action) {
15858
16109
  function LogsScreen({ refreshKey }) {
15859
16110
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
15860
16111
  const logKeyCounts = new Map;
15861
- const keyedLogs = state.logs.map((log25) => {
15862
- const baseKey = `${log25.ts}-${log25.level ?? ""}-${log25.msg}`;
16112
+ const keyedLogs = state.logs.map((log26) => {
16113
+ const baseKey = `${log26.ts}-${log26.level ?? ""}-${log26.msg}`;
15863
16114
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
15864
16115
  logKeyCounts.set(baseKey, count);
15865
16116
  return {
15866
16117
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
15867
- log: log25
16118
+ log: log26
15868
16119
  };
15869
16120
  });
15870
16121
  useKeyboard3((key) => {
@@ -15888,8 +16139,8 @@ function LogsScreen({ refreshKey }) {
15888
16139
  }, [refreshKey]);
15889
16140
  useEffect3(() => {
15890
16141
  if (!state.paused && !state.loading) {
15891
- const unsubscribe = streamLogs((log25) => {
15892
- dispatch({ type: "new_entry", log: log25 });
16142
+ const unsubscribe = streamLogs((log26) => {
16143
+ dispatch({ type: "new_entry", log: log26 });
15893
16144
  });
15894
16145
  return () => {
15895
16146
  unsubscribe();
@@ -15942,15 +16193,15 @@ function LogsScreen({ refreshKey }) {
15942
16193
  children: "No logs yet..."
15943
16194
  }) : /* @__PURE__ */ jsx7("box", {
15944
16195
  flexDirection: "column",
15945
- children: keyedLogs.map(({ key, log: log25 }) => {
15946
- const sev = getLogSeverityMeta(log25.level);
16196
+ children: keyedLogs.map(({ key, log: log26 }) => {
16197
+ const sev = getLogSeverityMeta(log26.level);
15947
16198
  return /* @__PURE__ */ jsxs7("text", {
15948
16199
  fg: sev.termColor,
15949
16200
  children: [
15950
16201
  "[",
15951
16202
  sev.label,
15952
16203
  "] ",
15953
- log25.msg
16204
+ log26.msg
15954
16205
  ]
15955
16206
  }, key);
15956
16207
  })
@@ -17595,13 +17846,13 @@ Examples:
17595
17846
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
17596
17847
  if (typeof parsed.logs === "number") {
17597
17848
  const history = await getLogHistory(limit);
17598
- for (const log25 of history) {
17599
- console.log(`[${log25.level}] ${log25.msg}`);
17849
+ for (const log26 of history) {
17850
+ console.log(`[${log26.level}] ${log26.msg}`);
17600
17851
  }
17601
17852
  console.log("--- Live logs ---");
17602
17853
  }
17603
- await streamLogs((log25) => {
17604
- console.log(`[${log25.level}] ${log25.msg}`);
17854
+ await streamLogs((log26) => {
17855
+ console.log(`[${log26.level}] ${log26.msg}`);
17605
17856
  });
17606
17857
  return;
17607
17858
  }