@certalis/agent-smith 0.1.18 → 0.1.19

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/pool.js CHANGED
@@ -2779,6 +2779,112 @@ var init_provider4 = __esm(() => {
2779
2779
  };
2780
2780
  });
2781
2781
 
2782
+ // ../../packages/providers/src/connectors/model-studio-capacity.ts
2783
+ function retryAtFromHeader(response, now = Date.now()) {
2784
+ const retryAfter = response.headers.get("retry-after");
2785
+ if (!retryAfter)
2786
+ return;
2787
+ const seconds = Number(retryAfter);
2788
+ if (Number.isFinite(seconds))
2789
+ return now + Math.max(0, seconds) * 1000;
2790
+ const date2 = Date.parse(retryAfter);
2791
+ return Number.isNaN(date2) ? undefined : Math.max(now, date2);
2792
+ }
2793
+ async function readSmallJsonBody(response) {
2794
+ const contentLength = Number(response.headers.get("content-length"));
2795
+ if (Number.isFinite(contentLength) && contentLength > MAX_BLOCK_BODY_BYTES) {
2796
+ return null;
2797
+ }
2798
+ const contentType = response.headers.get("content-type") ?? "";
2799
+ if (!contentType.toLowerCase().includes("application/json"))
2800
+ return null;
2801
+ const reader = response.clone().body?.getReader();
2802
+ if (!reader)
2803
+ return null;
2804
+ const chunks = [];
2805
+ let length = 0;
2806
+ try {
2807
+ while (true) {
2808
+ const { done, value } = await reader.read();
2809
+ if (done)
2810
+ break;
2811
+ length += value.byteLength;
2812
+ if (length > MAX_BLOCK_BODY_BYTES) {
2813
+ await reader.cancel();
2814
+ return null;
2815
+ }
2816
+ chunks.push(value);
2817
+ }
2818
+ } catch {
2819
+ return null;
2820
+ }
2821
+ const bytes = new Uint8Array(length);
2822
+ let offset = 0;
2823
+ for (const chunk of chunks) {
2824
+ bytes.set(chunk, offset);
2825
+ offset += chunk.byteLength;
2826
+ }
2827
+ try {
2828
+ return JSON.parse(new TextDecoder().decode(bytes));
2829
+ } catch {
2830
+ return null;
2831
+ }
2832
+ }
2833
+ function errorCode(payload) {
2834
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
2835
+ return;
2836
+ }
2837
+ const record2 = payload;
2838
+ if (typeof record2.code === "string")
2839
+ return record2.code;
2840
+ const error = record2.error;
2841
+ if (typeof error !== "object" || error === null || Array.isArray(error)) {
2842
+ return;
2843
+ }
2844
+ return typeof error.code === "string" ? error.code : undefined;
2845
+ }
2846
+ async function classifyModelStudioCapacityBlock(response, now = Date.now()) {
2847
+ if (response.status !== 429 && response.status !== 503)
2848
+ return null;
2849
+ const code = errorCode(await readSmallJsonBody(response));
2850
+ const category = code ? MODEL_STUDIO_BLOCK_CATEGORIES[code] : undefined;
2851
+ if (!category) {
2852
+ return response.status === 429 ? { category: "unknown" } : null;
2853
+ }
2854
+ const retryAt = retryAtFromHeader(response, now);
2855
+ return retryAt === undefined ? { category } : { category, retryAt };
2856
+ }
2857
+ var MAX_BLOCK_BODY_BYTES, MODEL_STUDIO_BLOCK_CATEGORIES;
2858
+ var init_model_studio_capacity = __esm(() => {
2859
+ MAX_BLOCK_BODY_BYTES = 64 * 1024;
2860
+ MODEL_STUDIO_BLOCK_CATEGORIES = {
2861
+ "Throttling.RateQuota": "request-rate",
2862
+ "Throttling.AllocationQuota": "token-allocation",
2863
+ "Throttling.BurstRate": "burst",
2864
+ "Throttling.ResourceExhausted": "dynamic-throughput",
2865
+ "Throttling.ServiceOverloaded": "dynamic-throughput",
2866
+ ServiceUnavailable: "temporary-capacity"
2867
+ };
2868
+ });
2869
+
2870
+ // ../../packages/providers/src/providers/model-studio/provider.ts
2871
+ var ModelStudioAnthropicProvider;
2872
+ var init_provider5 = __esm(() => {
2873
+ init_model_studio_capacity();
2874
+ init_provider();
2875
+ ModelStudioAnthropicProvider = class ModelStudioAnthropicProvider extends AnthropicProvider {
2876
+ async getCapacityBlock(response) {
2877
+ return await classifyModelStudioCapacityBlock(response);
2878
+ }
2879
+ parseRateLimit(response) {
2880
+ if (response.status !== 429)
2881
+ return super.parseRateLimit(response);
2882
+ const resetTime = retryAtFromHeader(response);
2883
+ return resetTime === undefined ? { isRateLimited: true } : { isRateLimited: true, resetTime };
2884
+ }
2885
+ };
2886
+ });
2887
+
2782
2888
  // ../../packages/providers/src/registry.ts
2783
2889
  function supportsOAuth(provider) {
2784
2890
  return "supportsOAuth" in provider && typeof provider.supportsOAuth === "function" && "getOAuthProvider" in provider && typeof provider.getOAuthProvider === "function";
@@ -2896,6 +3002,8 @@ function createProvider(definition) {
2896
3002
  switch (definition.strategy) {
2897
3003
  case "anthropic-api":
2898
3004
  return new AnthropicProvider;
3005
+ case "model-studio-anthropic-api":
3006
+ return new ModelStudioAnthropicProvider;
2899
3007
  case "openai-api":
2900
3008
  return new OpenAIProvider;
2901
3009
  case "claude-code":
@@ -2923,6 +3031,7 @@ var init_configured_registry = __esm(() => {
2923
3031
  init_provider();
2924
3032
  init_provider2();
2925
3033
  init_provider4();
3034
+ init_provider5();
2926
3035
  init_provider3();
2927
3036
  init_registry();
2928
3037
  });
@@ -2970,6 +3079,11 @@ var init_codex = __esm(() => {
2970
3079
  init_provider4();
2971
3080
  });
2972
3081
 
3082
+ // ../../packages/providers/src/providers/model-studio/index.ts
3083
+ var init_model_studio = __esm(() => {
3084
+ init_provider5();
3085
+ });
3086
+
2973
3087
  // ../../packages/providers/src/providers/openai/index.ts
2974
3088
  var init_openai = __esm(() => {
2975
3089
  init_oauth2();
@@ -2981,6 +3095,7 @@ var init_providers = __esm(() => {
2981
3095
  init_anthropic();
2982
3096
  init_claude_code();
2983
3097
  init_codex();
3098
+ init_model_studio();
2984
3099
  init_openai();
2985
3100
  });
2986
3101
  // ../../packages/providers/src/index.ts
@@ -4343,7 +4458,7 @@ function sanitizeProviderPools(value) {
4343
4458
  return pools;
4344
4459
  }
4345
4460
  function wireForStrategy(strategy3) {
4346
- return strategy3 === "anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
4461
+ return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
4347
4462
  }
4348
4463
  function isNonNegativeFiniteNumber(value) {
4349
4464
  return isFiniteNumber(value) && value >= 0;
@@ -4382,6 +4497,12 @@ function sanitizeTeamRouting(value) {
4382
4497
  result.caller_weekly_max_usage = Object.fromEntries(entries);
4383
4498
  }
4384
4499
  }
4500
+ if (isRecord(value.caller_provider_fallback)) {
4501
+ const entries = Object.entries(value.caller_provider_fallback);
4502
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
4503
+ result.caller_provider_fallback = Object.fromEntries(entries);
4504
+ }
4505
+ }
4385
4506
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
4386
4507
  result.admission_cap = Math.floor(value.admission_cap);
4387
4508
  }
@@ -4436,6 +4557,7 @@ var init_src7 = __esm(() => {
4436
4557
  log6 = new Logger("Config");
4437
4558
  PROVIDER_STRATEGIES = [
4438
4559
  "anthropic-api",
4560
+ "model-studio-anthropic-api",
4439
4561
  "openai-api",
4440
4562
  "claude-code",
4441
4563
  "codex"
@@ -4459,6 +4581,7 @@ var init_src7 = __esm(() => {
4459
4581
  weeklyMaxUsage: 0.95,
4460
4582
  weeklyMaxUsageByEmail: {},
4461
4583
  callerWeeklyMaxUsage: {},
4584
+ callerProviderFallback: {},
4462
4585
  admissionCap: 5,
4463
4586
  admissionQueueLimit: 25,
4464
4587
  admissionWaitMs: 30000,
@@ -4622,6 +4745,7 @@ var init_src7 = __esm(() => {
4622
4745
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
4623
4746
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
4624
4747
  callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
4748
+ callerProviderFallback: { ...file?.caller_provider_fallback },
4625
4749
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
4626
4750
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
4627
4751
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -4692,6 +4816,7 @@ var init_src7 = __esm(() => {
4692
4816
  "weekly_max_usage",
4693
4817
  "weekly_max_usage_by_email",
4694
4818
  "caller_weekly_max_usage",
4819
+ "caller_provider_fallback",
4695
4820
  "admission_cap",
4696
4821
  "admission_queue_limit",
4697
4822
  "admission_wait_ms",
@@ -4722,6 +4847,11 @@ var init_src7 = __esm(() => {
4722
4847
  ...oldValue.caller_weekly_max_usage
4723
4848
  };
4724
4849
  }
4850
+ if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
4851
+ sanitized.caller_provider_fallback = {
4852
+ ...oldValue.caller_provider_fallback
4853
+ };
4854
+ }
4725
4855
  this.persistStrictly("team_routing", sanitized);
4726
4856
  }
4727
4857
  allowAccountUuid(accountUuid) {
@@ -5547,6 +5677,30 @@ function ensureConversationPinsTable(db) {
5547
5677
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_account ON conversation_pins(account_id)`);
5548
5678
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_last_seen ON conversation_pins(last_seen_at)`);
5549
5679
  }
5680
+ function ensureConversationProviderPreferencesTable(db) {
5681
+ db.run(`
5682
+ CREATE TABLE IF NOT EXISTS conversation_provider_preferences (
5683
+ pin_key TEXT PRIMARY KEY,
5684
+ provider TEXT NOT NULL,
5685
+ promotion_declined INTEGER NOT NULL DEFAULT 0,
5686
+ last_seen_at INTEGER NOT NULL
5687
+ )
5688
+ `);
5689
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_preferences_last_seen ON conversation_provider_preferences(last_seen_at)`);
5690
+ }
5691
+ function ensureConversationProviderBlocksTable(db) {
5692
+ db.run(`
5693
+ CREATE TABLE IF NOT EXISTS conversation_provider_blocks (
5694
+ pin_key TEXT NOT NULL,
5695
+ provider TEXT NOT NULL,
5696
+ category TEXT NOT NULL DEFAULT 'unknown',
5697
+ retry_at INTEGER,
5698
+ last_seen_at INTEGER NOT NULL,
5699
+ PRIMARY KEY (pin_key, provider)
5700
+ )
5701
+ `);
5702
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_blocks_last_seen ON conversation_provider_blocks(last_seen_at)`);
5703
+ }
5550
5704
  function remediateDuplicateAccountNames(db) {
5551
5705
  const accounts = db.query(`
5552
5706
  SELECT id, name, created_at
@@ -5672,6 +5826,8 @@ function ensureSchema(db) {
5672
5826
  `);
5673
5827
  ensureAuthSessionsTable(db);
5674
5828
  ensureConversationPinsTable(db);
5829
+ ensureConversationProviderPreferencesTable(db);
5830
+ ensureConversationProviderBlocksTable(db);
5675
5831
  }
5676
5832
  function runMigrations(db) {
5677
5833
  ensureSchema(db);
@@ -5691,6 +5847,8 @@ function runMigrations(db) {
5691
5847
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
5692
5848
  ensureAuthSessionsTable(db);
5693
5849
  ensureConversationPinsTable(db);
5850
+ ensureConversationProviderPreferencesTable(db);
5851
+ ensureConversationProviderBlocksTable(db);
5694
5852
  ensureAccountsNameUniqueness(db);
5695
5853
  db.run(`CREATE TABLE IF NOT EXISTS enrollment_contacts (
5696
5854
  account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
@@ -6386,6 +6544,85 @@ var init_conversation_pin_repository = __esm(() => {
6386
6544
  };
6387
6545
  });
6388
6546
 
6547
+ // ../../packages/database/src/repositories/conversation-provider-block.repository.ts
6548
+ var ConversationProviderBlockRepository;
6549
+ var init_conversation_provider_block_repository = __esm(() => {
6550
+ ConversationProviderBlockRepository = class ConversationProviderBlockRepository extends BaseRepository {
6551
+ find(pinKey, provider) {
6552
+ const row = this.get(`SELECT category, retry_at, last_seen_at FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
6553
+ return row ? {
6554
+ category: row.category,
6555
+ lastSeenAt: row.last_seen_at,
6556
+ retryAt: row.retry_at ?? undefined
6557
+ } : null;
6558
+ }
6559
+ upsert(pinKey, provider, category, retryAt, lastSeenAt) {
6560
+ this.run(`
6561
+ INSERT INTO conversation_provider_blocks (
6562
+ pin_key, provider, category, retry_at, last_seen_at
6563
+ )
6564
+ VALUES (?, ?, ?, ?, ?)
6565
+ ON CONFLICT(pin_key, provider) DO UPDATE SET
6566
+ category = excluded.category,
6567
+ retry_at = excluded.retry_at,
6568
+ last_seen_at = excluded.last_seen_at
6569
+ `, [pinKey, provider, category, retryAt ?? null, lastSeenAt]);
6570
+ }
6571
+ delete(pinKey, provider) {
6572
+ this.run(`DELETE FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
6573
+ }
6574
+ deleteExpired(before) {
6575
+ this.run(`DELETE FROM conversation_provider_blocks WHERE last_seen_at < ?`, [before]);
6576
+ }
6577
+ deleteForAccount(accountId) {
6578
+ this.run(`
6579
+ DELETE FROM conversation_provider_blocks
6580
+ WHERE pin_key IN (
6581
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
6582
+ )
6583
+ `, [accountId]);
6584
+ }
6585
+ };
6586
+ });
6587
+
6588
+ // ../../packages/database/src/repositories/conversation-provider-preference.repository.ts
6589
+ var ConversationProviderPreferenceRepository;
6590
+ var init_conversation_provider_preference_repository = __esm(() => {
6591
+ ConversationProviderPreferenceRepository = class ConversationProviderPreferenceRepository extends BaseRepository {
6592
+ find(pinKey) {
6593
+ const row = this.get(`SELECT provider, promotion_declined, last_seen_at FROM conversation_provider_preferences WHERE pin_key = ?`, [pinKey]);
6594
+ return row ? {
6595
+ provider: row.provider,
6596
+ promotionDeclined: row.promotion_declined === 1,
6597
+ lastSeenAt: row.last_seen_at
6598
+ } : null;
6599
+ }
6600
+ upsert(pinKey, provider, promotionDeclined, lastSeenAt) {
6601
+ this.run(`
6602
+ INSERT INTO conversation_provider_preferences (
6603
+ pin_key, provider, promotion_declined, last_seen_at
6604
+ )
6605
+ VALUES (?, ?, ?, ?)
6606
+ ON CONFLICT(pin_key) DO UPDATE SET
6607
+ provider = excluded.provider,
6608
+ promotion_declined = excluded.promotion_declined,
6609
+ last_seen_at = excluded.last_seen_at
6610
+ `, [pinKey, provider, promotionDeclined ? 1 : 0, lastSeenAt]);
6611
+ }
6612
+ deleteExpired(before) {
6613
+ this.run(`DELETE FROM conversation_provider_preferences WHERE last_seen_at < ?`, [before]);
6614
+ }
6615
+ deleteForAccount(accountId) {
6616
+ this.run(`
6617
+ DELETE FROM conversation_provider_preferences
6618
+ WHERE pin_key IN (
6619
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
6620
+ )
6621
+ `, [accountId]);
6622
+ }
6623
+ };
6624
+ });
6625
+
6389
6626
  // ../../packages/database/src/models/request-row.ts
6390
6627
  function toRequest(row) {
6391
6628
  return {
@@ -6996,6 +7233,8 @@ class DatabaseOperations {
6996
7233
  requests;
6997
7234
  authSessions;
6998
7235
  conversationPins;
7236
+ conversationProviderBlocks;
7237
+ conversationProviderPreferences;
6999
7238
  strategy;
7000
7239
  stats;
7001
7240
  constructor(dbPath) {
@@ -7015,6 +7254,8 @@ class DatabaseOperations {
7015
7254
  this.requests = new RequestRepository(this.db);
7016
7255
  this.authSessions = new AuthSessionRepository(this.db);
7017
7256
  this.conversationPins = new ConversationPinRepository(this.db);
7257
+ this.conversationProviderBlocks = new ConversationProviderBlockRepository(this.db);
7258
+ this.conversationProviderPreferences = new ConversationProviderPreferenceRepository(this.db);
7018
7259
  this.strategy = new StrategyRepository(this.db);
7019
7260
  this.stats = new StatsRepository(this.db);
7020
7261
  }
@@ -7058,6 +7299,8 @@ class DatabaseOperations {
7058
7299
  return this.accounts.update(accountId, data);
7059
7300
  }
7060
7301
  deleteAccount(accountId) {
7302
+ this.conversationProviderBlocks.deleteForAccount(accountId);
7303
+ this.conversationProviderPreferences.deleteForAccount(accountId);
7061
7304
  this.conversationPins.deleteForAccount(accountId);
7062
7305
  return this.accounts.delete(accountId);
7063
7306
  }
@@ -7072,6 +7315,23 @@ class DatabaseOperations {
7072
7315
  }
7073
7316
  deleteExpiredConversationPins(before) {
7074
7317
  this.conversationPins.deleteExpired(before);
7318
+ this.conversationProviderBlocks.deleteExpired(before);
7319
+ this.conversationProviderPreferences.deleteExpired(before);
7320
+ }
7321
+ getConversationProviderPreference(pinKey) {
7322
+ return this.conversationProviderPreferences.find(pinKey);
7323
+ }
7324
+ upsertConversationProviderPreference(pinKey, provider, promotionDeclined, lastSeenAt) {
7325
+ this.conversationProviderPreferences.upsert(pinKey, provider, promotionDeclined, lastSeenAt);
7326
+ }
7327
+ getConversationProviderBlock(pinKey, provider) {
7328
+ return this.conversationProviderBlocks.find(pinKey, provider);
7329
+ }
7330
+ upsertConversationProviderBlock(pinKey, provider, category, retryAt, lastSeenAt) {
7331
+ this.conversationProviderBlocks.upsert(pinKey, provider, category, retryAt, lastSeenAt);
7332
+ }
7333
+ deleteConversationProviderBlock(pinKey, provider) {
7334
+ this.conversationProviderBlocks.delete(pinKey, provider);
7075
7335
  }
7076
7336
  countAccounts() {
7077
7337
  return this.accounts.count();
@@ -7257,6 +7517,8 @@ var init_database_operations = __esm(() => {
7257
7517
  init_analytics_repository();
7258
7518
  init_auth_session_repository();
7259
7519
  init_conversation_pin_repository();
7520
+ init_conversation_provider_block_repository();
7521
+ init_conversation_provider_preference_repository();
7260
7522
  init_request_repository();
7261
7523
  init_stats_repository();
7262
7524
  init_strategy_repository();
@@ -7438,6 +7700,7 @@ var init_analytics = __esm(() => {
7438
7700
  // ../../packages/api/src/handlers/config.ts
7439
7701
  function publicTeamRouting(config) {
7440
7702
  const {
7703
+ callerProviderFallback: _callerProviderFallback,
7441
7704
  callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7442
7705
  weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7443
7706
  ...routing
@@ -9064,6 +9327,11 @@ function pinKey(request3, provider) {
9064
9327
  digest
9065
9328
  ].join("\x00")).digest("hex");
9066
9329
  }
9330
+ function providerConversationKey(request3) {
9331
+ if (!request3.sessionId)
9332
+ return null;
9333
+ return createHash2("sha256").update([request3.pinScope ?? request3.provider, request3.sessionId].join("\x00")).digest("hex");
9334
+ }
9067
9335
  function isAllowlisted(account2, config) {
9068
9336
  return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
9069
9337
  }
@@ -9110,9 +9378,20 @@ class TeamRouter {
9110
9378
  return;
9111
9379
  }
9112
9380
  this.removeExpiredPins(now, store);
9113
- const key = pinKey(request3, provider);
9381
+ const key = this.getConversationPinKey(request3, config, provider);
9114
9382
  return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
9115
9383
  }
9384
+ getConversationPinKey(request3, _config, provider) {
9385
+ if (!request3?.sessionId || request3.manualAccountName) {
9386
+ return;
9387
+ }
9388
+ return pinKey(request3, provider) ?? undefined;
9389
+ }
9390
+ getConversationProviderKey(request3, _config) {
9391
+ if (!request3?.sessionId || request3.manualAccountName)
9392
+ return;
9393
+ return providerConversationKey(request3) ?? undefined;
9394
+ }
9116
9395
  begin(accountId) {
9117
9396
  this.inFlight.set(accountId, (this.inFlight.get(accountId) ?? 0) + 1);
9118
9397
  }
@@ -9346,6 +9625,25 @@ function isServableSeat(provider, account2, model, ctx, now) {
9346
9625
  function blockingResets(provider, account2, model, ctx, now, callerId) {
9347
9626
  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(provider, account2, bucket, ctx, callerId))).map(([, window2]) => window2.resetAt);
9348
9627
  }
9628
+ function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
9629
+ const blocking = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket2, window3]) => isQuotaBlocking(provider, account2, bucket2, window3, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket2, ctx, callerId)));
9630
+ if (blocking.length === 0)
9631
+ return null;
9632
+ const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
9633
+ const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
9634
+ const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
9635
+ return rightReset - leftReset;
9636
+ })[0];
9637
+ const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
9638
+ return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
9639
+ }
9640
+ function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9641
+ const now = Date.now();
9642
+ const blocks = seatsFor(fleetAccounts(ctx.providerName, ctx)).map((account2) => quotaBlockForAccount(ctx.provider, account2, meta.model, ctx, now, callerId)).filter((block) => block !== null);
9643
+ if (blocks.length === 0)
9644
+ return null;
9645
+ return [...blocks].sort((left, right) => (left.retryAt ?? Number.POSITIVE_INFINITY) - (right.retryAt ?? Number.POSITIVE_INFINITY))[0];
9646
+ }
9349
9647
  function servableAt(provider, account2, model, ctx, now, callerId) {
9350
9648
  const cooldown = cooldownEnd(account2, now);
9351
9649
  if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
@@ -9724,6 +10022,7 @@ class TeamAdmission {
9724
10022
  weeklyMaxUsage: 0.95,
9725
10023
  weeklyMaxUsageByEmail: {},
9726
10024
  callerWeeklyMaxUsage: {},
10025
+ callerProviderFallback: {},
9727
10026
  admissionCap: 1,
9728
10027
  admissionQueueLimit: 0,
9729
10028
  admissionWaitMs: 0,
@@ -9831,6 +10130,206 @@ var init_team_admission = __esm(() => {
9831
10130
  };
9832
10131
  });
9833
10132
 
10133
+ // ../../packages/routing/src/conversation-provider-routing.ts
10134
+ class ConversationProviderRouting {
10135
+ store;
10136
+ constructor(store) {
10137
+ this.store = store;
10138
+ }
10139
+ getPreference(conversationKey) {
10140
+ return this.store.getPreference(conversationKey);
10141
+ }
10142
+ getBlock(conversationKey, provider) {
10143
+ return this.store.getBlock(conversationKey, provider);
10144
+ }
10145
+ selectProvider(conversationKey, provider, now) {
10146
+ this.store.upsertPreference(conversationKey, {
10147
+ lastSeenAt: now,
10148
+ promotionDeclined: false,
10149
+ provider
10150
+ });
10151
+ }
10152
+ declinePromotion(conversationKey, now) {
10153
+ const preference = this.store.getPreference(conversationKey);
10154
+ if (!preference)
10155
+ return;
10156
+ this.store.upsertPreference(conversationKey, {
10157
+ ...preference,
10158
+ lastSeenAt: now,
10159
+ promotionDeclined: true
10160
+ });
10161
+ }
10162
+ recordBlock(conversationKey, provider, block, now) {
10163
+ this.store.upsertBlock(conversationKey, provider, {
10164
+ ...block,
10165
+ lastSeenAt: now
10166
+ });
10167
+ }
10168
+ clearBlock(conversationKey, provider) {
10169
+ this.store.deleteBlock(conversationKey, provider);
10170
+ }
10171
+ canOfferProvider(conversationKey, provider, now) {
10172
+ const block = this.store.getBlock(conversationKey, provider);
10173
+ return block === null || block.retryAt !== undefined && block.retryAt <= now;
10174
+ }
10175
+ }
10176
+
10177
+ // ../../packages/routing/src/provider-choice.ts
10178
+ function encodeCapacityDetails(problem) {
10179
+ return Buffer.from(JSON.stringify({
10180
+ kind: problem.kind,
10181
+ blockedProvider: problem.blockedProvider,
10182
+ category: problem.category,
10183
+ choices: problem.choices,
10184
+ wait: problem.retryAt === undefined ? null : { retryAt: problem.retryAt }
10185
+ })).toString("base64url");
10186
+ }
10187
+ function interactiveProviderChoiceRequested(headers3) {
10188
+ return headers3.get(INTERACTIVE_PROVIDER_CHOICE_HEADER) === "v1";
10189
+ }
10190
+ function manualProviderChoiceRequested(headers3) {
10191
+ return headers3.get(PROVIDER_CHOICE_MENU_HEADER) === "v1";
10192
+ }
10193
+ function providerWaitRequested(headers3) {
10194
+ return headers3.get(PROVIDER_WAIT_HEADER) === "v1";
10195
+ }
10196
+ function capacityChoices(candidates, blockedProvider, eligibleProviders) {
10197
+ return candidates.filter((candidate) => candidate.provider !== blockedProvider && eligibleProviders.has(candidate.provider));
10198
+ }
10199
+ function readProviderChoice(headers3, choices) {
10200
+ const selected = headers3.get(PROVIDER_CHOICE_HEADER);
10201
+ return selected && choices.some((choice) => choice.provider === selected) ? selected : null;
10202
+ }
10203
+ function providerPromotionDeclined(headers3) {
10204
+ return headers3.get(PROVIDER_PROMOTION_DECLINED_HEADER) === "v1";
10205
+ }
10206
+ function stripProviderChoiceHeaders(headers3) {
10207
+ const forwarded = new Headers(headers3);
10208
+ forwarded.delete(INTERACTIVE_PROVIDER_CHOICE_HEADER);
10209
+ forwarded.delete(PROVIDER_CHOICE_HEADER);
10210
+ forwarded.delete(PROVIDER_CHOICE_MENU_HEADER);
10211
+ forwarded.delete(PROVIDER_WAIT_HEADER);
10212
+ forwarded.delete(PROVIDER_PROMOTION_DECLINED_HEADER);
10213
+ return forwarded;
10214
+ }
10215
+ function withServedProviderHeaders(response, choice) {
10216
+ const headers3 = new Headers(response.headers);
10217
+ headers3.set(SERVED_PROVIDER_HEADER, choice.provider);
10218
+ headers3.set(SERVED_MODEL_HEADER, choice.model);
10219
+ return new Response(response.body, {
10220
+ status: response.status,
10221
+ statusText: response.statusText,
10222
+ headers: headers3
10223
+ });
10224
+ }
10225
+ function withProviderPromotionDetails(response, choices) {
10226
+ if (choices.length === 0)
10227
+ return response;
10228
+ const headers3 = new Headers(response.headers);
10229
+ headers3.set(PROVIDER_PROMOTION_DETAILS_HEADER, Buffer.from(JSON.stringify({ choices })).toString("base64url"));
10230
+ return new Response(response.body, {
10231
+ status: response.status,
10232
+ statusText: response.statusText,
10233
+ headers: headers3
10234
+ });
10235
+ }
10236
+ function createProviderCapacityProblem({
10237
+ blockedProvider,
10238
+ category,
10239
+ choices,
10240
+ retryAt
10241
+ }) {
10242
+ const retryAfter = retryAt === undefined ? undefined : String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000)));
10243
+ return Response.json({
10244
+ type: "urn:agent-smith:provider-capacity:v1",
10245
+ title: "Current provider cannot serve this turn",
10246
+ status: 429,
10247
+ blockedProvider,
10248
+ category,
10249
+ choices,
10250
+ wait: retryAt === undefined ? null : { retryAt }
10251
+ }, {
10252
+ status: 429,
10253
+ headers: {
10254
+ "cache-control": "no-store",
10255
+ "content-type": "application/problem+json",
10256
+ "x-should-retry": "false",
10257
+ ...retryAfter ? { "retry-after": retryAfter } : {},
10258
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10259
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10260
+ kind: "capacity",
10261
+ blockedProvider,
10262
+ category,
10263
+ choices,
10264
+ retryAt
10265
+ })
10266
+ }
10267
+ });
10268
+ }
10269
+ function createProviderChoiceProblem({
10270
+ activeProvider,
10271
+ choices
10272
+ }) {
10273
+ return Response.json({
10274
+ type: "urn:agent-smith:provider-choice:v1",
10275
+ title: "Choose provider for this conversation",
10276
+ status: 409,
10277
+ activeProvider,
10278
+ choices,
10279
+ wait: null
10280
+ }, {
10281
+ status: 409,
10282
+ headers: {
10283
+ "cache-control": "no-store",
10284
+ "content-type": "application/problem+json",
10285
+ "x-should-retry": "false",
10286
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10287
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10288
+ kind: "manual",
10289
+ blockedProvider: activeProvider,
10290
+ category: "unknown",
10291
+ choices
10292
+ })
10293
+ }
10294
+ });
10295
+ }
10296
+ var INTERACTIVE_PROVIDER_CHOICE_HEADER = "x-agent-smith-interactive-provider-choice", PROVIDER_CHOICE_HEADER = "x-agent-smith-provider-choice", PROVIDER_CHOICE_MENU_HEADER = "x-agent-smith-provider-menu", PROVIDER_WAIT_HEADER = "x-agent-smith-provider-wait", PROVIDER_PROMOTION_DECLINED_HEADER = "x-agent-smith-provider-promotion-declined", PROVIDER_CAPACITY_HEADER = "x-agent-smith-provider-capacity", PROVIDER_CAPACITY_DETAILS_HEADER = "x-agent-smith-provider-capacity-details", PROVIDER_PROMOTION_DETAILS_HEADER = "x-agent-smith-provider-promotion-details", SERVED_PROVIDER_HEADER = "x-agent-smith-served-provider", SERVED_MODEL_HEADER = "x-agent-smith-served-model";
10297
+
10298
+ // ../../packages/routing/src/provider-selection.ts
10299
+ function preferProviders(providers2, providerName, pinnedProvider, preferredProvider) {
10300
+ const pinFirst = pinnedProvider ? [
10301
+ ...providers2.filter((provider) => providerName(provider) === pinnedProvider),
10302
+ ...providers2.filter((provider) => providerName(provider) !== pinnedProvider)
10303
+ ] : [...providers2];
10304
+ if (!preferredProvider)
10305
+ return pinFirst;
10306
+ return [
10307
+ ...pinFirst.filter((provider) => providerName(provider) === preferredProvider),
10308
+ ...pinFirst.filter((provider) => providerName(provider) !== preferredProvider)
10309
+ ];
10310
+ }
10311
+ function selectPoolProviders(providers2, providerName, selection) {
10312
+ if (selection.requestedProvider) {
10313
+ return providers2.filter((provider) => providerName(provider) === selection.requestedProvider);
10314
+ }
10315
+ const preferred = preferProviders(providers2, providerName, selection.pinnedProvider, selection.preferredProvider);
10316
+ if (selection.orderedFallback) {
10317
+ const currentProvider = selection.pinnedProvider ?? selection.preferredProvider;
10318
+ const currentIndex = currentProvider ? providers2.findIndex((provider) => providerName(provider) === currentProvider) : -1;
10319
+ return currentIndex < 0 ? [...providers2] : providers2.slice(currentIndex);
10320
+ }
10321
+ return preferred.slice(0, 1);
10322
+ }
10323
+ function higherRankedProviderChoices(choices, selectedProvider, eligibleProviders, canOffer) {
10324
+ const selectedIndex = choices.findIndex((choice) => choice.provider === selectedProvider);
10325
+ if (selectedIndex <= 0)
10326
+ return [];
10327
+ return choices.slice(0, selectedIndex).filter((choice) => eligibleProviders.has(choice.provider) && canOffer(choice.provider));
10328
+ }
10329
+
10330
+ // ../../packages/routing/src/index.ts
10331
+ var init_src10 = () => {};
10332
+
9834
10333
  // ../../packages/proxy/src/response-handler.ts
9835
10334
  function isExpectedResponse(path, response) {
9836
10335
  if (path.startsWith("/.well-known/") && response.status === 404) {
@@ -10434,7 +10933,7 @@ function createUpstreamSender(input) {
10434
10933
  const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
10435
10934
  return async (token) => {
10436
10935
  const requestAccount = token === input.account.access_token ? input.account : { ...input.account, access_token: token };
10437
- const headers3 = input.ctx.provider.prepareHeaders(input.req.headers, requestAccount);
10936
+ const headers3 = input.ctx.provider.prepareHeaders(stripProviderChoiceHeaders(input.req.headers), requestAccount);
10438
10937
  const upstreamRequestStartedAt = Date.now();
10439
10938
  const response = await makeProxyRequest(targetUrl, input.req.method, headers3, () => input.createBodyStream(input.requestBody), !!input.req.body, input.req.signal);
10440
10939
  return {
@@ -10501,6 +11000,28 @@ async function classifyUpstreamResponse(input, upstream) {
10501
11000
  }
10502
11001
  let response = state.response;
10503
11002
  const forward = createForwarder(input, upstream, state);
11003
+ const interactive = interactiveProviderChoiceRequested(input.req.headers);
11004
+ const capacityBlock = await input.ctx.provider.getCapacityBlock?.(response);
11005
+ if (capacityBlock) {
11006
+ const quotaRejected2 = await isQuotaRejection(response, input.ctx.provider);
11007
+ processProxyResponse(response, input.account, input.ctx, quotaRejected2);
11008
+ const perMinuteRetryAfterMs2 = getPerMinuteRetryAfterMs(response, quotaRejected2);
11009
+ if (interactive && (capacityBlock.category === "request-rate" || capacityBlock.category === "burst")) {
11010
+ if (perMinuteRetryAfterMs2 !== undefined) {
11011
+ return {
11012
+ forward,
11013
+ kind: "per-minute-rate-limit",
11014
+ retryAfterMs: perMinuteRetryAfterMs2
11015
+ };
11016
+ }
11017
+ }
11018
+ return {
11019
+ block: capacityBlock,
11020
+ discard: discardUpstreamResponse(state),
11021
+ forward,
11022
+ kind: "provider-capacity-block"
11023
+ };
11024
+ }
10504
11025
  if (isRequestScopedRateLimit(response, input.ctx.provider)) {
10505
11026
  return { forward, kind: "request-scoped-rate-limit" };
10506
11027
  }
@@ -10566,6 +11087,7 @@ var API_KEY_AUTH_COOLDOWN_MS, ORGANIZATION_QUARANTINE_MS, log20;
10566
11087
  var init_proxy_operations = __esm(() => {
10567
11088
  init_src2();
10568
11089
  init_src4();
11090
+ init_src10();
10569
11091
  init_response_handler();
10570
11092
  init_message_thread();
10571
11093
  init_request_handler();
@@ -10805,6 +11327,9 @@ async function proxySelectedAccounts(request3, accounts) {
10805
11327
  if (attempt.kind === "authentication-failure") {
10806
11328
  return new Response("Bad Gateway", { status: 502 });
10807
11329
  }
11330
+ if (attempt.kind === "provider-capacity-block") {
11331
+ return await attempt.forward();
11332
+ }
10808
11333
  if (attempt.kind === "per-minute-rate-limit") {
10809
11334
  return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
10810
11335
  }
@@ -10873,6 +11398,10 @@ function getRequestRetryAt(request3) {
10873
11398
  const { ctx, teamRequest } = request3;
10874
11399
  return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10875
11400
  }
11401
+ function getRequestQuotaCapacityBlock(request3) {
11402
+ const { ctx, teamRequest } = request3;
11403
+ return getQuotaCapacityBlock(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
11404
+ }
10876
11405
  var init_proxy_request = __esm(() => {
10877
11406
  init_account_selector();
10878
11407
  init_message_thread();
@@ -10891,32 +11420,139 @@ var init_handlers = __esm(() => {
10891
11420
  init_token_manager();
10892
11421
  });
10893
11422
 
10894
- // ../../packages/proxy/src/provider-pool.ts
10895
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
10896
- return {
10897
- body,
10898
- callerId,
10899
- contentType: req.headers.get("content-type"),
10900
- manualAccountName,
10901
- model: requestedModel,
10902
- pinBucket: requestedModel,
10903
- pinScope: `pool:${pool.wire}`,
10904
- provider: `pool:${pool.wire}`,
10905
- sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
10906
- };
11423
+ // ../../packages/capacity/src/index.ts
11424
+ function isProviderBlockCategory(value) {
11425
+ return typeof value === "string" && PROVIDER_BLOCK_CATEGORIES.includes(value);
10907
11426
  }
11427
+ var PROVIDER_BLOCK_CATEGORIES;
11428
+ var init_src11 = __esm(() => {
11429
+ PROVIDER_BLOCK_CATEGORIES = [
11430
+ "five-hour-limit",
11431
+ "weekly-limit",
11432
+ "request-rate",
11433
+ "token-allocation",
11434
+ "burst",
11435
+ "dynamic-throughput",
11436
+ "temporary-capacity",
11437
+ "unknown"
11438
+ ];
11439
+ });
11440
+
11441
+ // ../../packages/proxy/src/pool/conversation-provider-routing-store.ts
11442
+ class PoolConversationProviderRoutingStore {
11443
+ dbOps;
11444
+ constructor(dbOps) {
11445
+ this.dbOps = dbOps;
11446
+ }
11447
+ getPreference(conversationKey) {
11448
+ return this.dbOps.getConversationProviderPreference(conversationKey);
11449
+ }
11450
+ upsertPreference(conversationKey, preference) {
11451
+ this.dbOps.upsertConversationProviderPreference(conversationKey, preference.provider, preference.promotionDeclined, preference.lastSeenAt);
11452
+ }
11453
+ getBlock(conversationKey, provider) {
11454
+ const block = this.dbOps.getConversationProviderBlock(conversationKey, provider);
11455
+ if (!block)
11456
+ return null;
11457
+ return {
11458
+ ...block,
11459
+ category: isProviderBlockCategory(block.category) ? block.category : "unknown"
11460
+ };
11461
+ }
11462
+ upsertBlock(conversationKey, provider, block) {
11463
+ this.dbOps.upsertConversationProviderBlock(conversationKey, provider, block.category, block.retryAt, block.lastSeenAt);
11464
+ }
11465
+ deleteBlock(conversationKey, provider) {
11466
+ this.dbOps.deleteConversationProviderBlock(conversationKey, provider);
11467
+ }
11468
+ }
11469
+ var init_conversation_provider_routing_store = __esm(() => {
11470
+ init_src11();
11471
+ });
11472
+
11473
+ // ../../packages/proxy/src/pool/interactive-provider-pool.ts
11474
+ function configuredPoolChoices(pool, fallbackModel) {
11475
+ return pool.providers.map((candidate) => ({
11476
+ model: candidate.model ?? fallbackModel ?? "",
11477
+ provider: candidate.provider.name
11478
+ }));
11479
+ }
11480
+ function eligiblePoolProviders({
11481
+ body,
11482
+ ctx,
11483
+ manualAccountName,
11484
+ meta,
11485
+ pool,
11486
+ req,
11487
+ teamRequest,
11488
+ url
11489
+ }) {
11490
+ const eligibleProviders = new Set;
11491
+ for (const candidate of pool.providers) {
11492
+ const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
11493
+ const prepared = prepareProxyRequest(req, url, candidateContext, { ...meta, model: candidate.model }, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11494
+ if (prepared.request.thread || prepared.accounts.length === 0)
11495
+ continue;
11496
+ const accounts = candidateContext.teamRouter ? candidateContext.teamRouter.eligibleAccounts(prepared.accounts, teamRequest, candidateContext.runtime.teamRouting) : prepared.accounts;
11497
+ if (accounts.length > 0)
11498
+ eligibleProviders.add(candidate.provider.name);
11499
+ }
11500
+ return eligibleProviders;
11501
+ }
11502
+ function eligiblePoolChoices(input, blockedProvider) {
11503
+ return capacityChoices(configuredPoolChoices(input.pool, input.meta.model), blockedProvider, eligiblePoolProviders(input));
11504
+ }
11505
+ function createManualProviderChoiceResponse(input, pinnedAccount, preferredProvider) {
11506
+ const ordered = preferProviders(input.pool.providers, (candidate) => candidate.provider.name, pinnedAccount?.provider, preferredProvider);
11507
+ const activeProvider = ordered[0]?.provider.name ?? input.pool.providers[0]?.provider.name ?? "";
11508
+ const eligible = eligiblePoolProviders(input);
11509
+ return createProviderChoiceProblem({
11510
+ activeProvider,
11511
+ choices: configuredPoolChoices(input.pool, input.meta.model).filter((choice) => eligible.has(choice.provider))
11512
+ });
11513
+ }
11514
+ async function waitOrReturnProviderCapacity({
11515
+ candidates,
11516
+ conversationKey,
11517
+ input,
11518
+ providerWaited,
11519
+ retry,
11520
+ routing
11521
+ }) {
11522
+ if (!providerWaitRequested(input.req.headers) || providerWaited || !candidates[0]) {
11523
+ return null;
11524
+ }
11525
+ const provider = candidates[0].provider.name;
11526
+ const blocked = conversationKey ? routing.getBlock(conversationKey, provider) : null;
11527
+ const retryAt = blocked?.retryAt;
11528
+ const holdMs = input.ctx.runtime.teamRouting.holdSeconds * 1000;
11529
+ if (input.ctx.quotaHold && retryAt !== undefined && retryAt > Date.now() && holdMs > 0 && retryAt - Date.now() <= holdMs) {
11530
+ await input.ctx.quotaHold.waitUntil(retryAt, input.req.signal);
11531
+ return await retry();
11532
+ }
11533
+ if (retryAt === undefined || retryAt > Date.now()) {
11534
+ return createProviderCapacityProblem({
11535
+ blockedProvider: provider,
11536
+ category: blocked?.category ?? "unknown",
11537
+ choices: eligiblePoolChoices(input, provider),
11538
+ ...retryAt !== undefined && { retryAt }
11539
+ });
11540
+ }
11541
+ return null;
11542
+ }
11543
+ var init_interactive_provider_pool = __esm(() => {
11544
+ init_src10();
11545
+ init_handlers();
11546
+ init_proxy_request();
11547
+ });
11548
+
11549
+ // ../../packages/proxy/src/pool/provider-pool-attempts.ts
10908
11550
  function preferPinnedAccount(accounts, pinnedId) {
10909
11551
  if (!pinnedId)
10910
11552
  return accounts;
10911
11553
  const pinned = accounts.find((account2) => account2.id === pinnedId);
10912
11554
  return pinned ? [pinned, ...accounts.filter((account2) => account2.id !== pinned.id)] : accounts;
10913
11555
  }
10914
- function preferPinnedProvider(pool, pinnedAccount) {
10915
- if (!pinnedAccount)
10916
- return pool.providers;
10917
- const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
10918
- return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
10919
- }
10920
11556
  async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10921
11557
  for (let index = 0;index < accounts.length; index += 1) {
10922
11558
  const account2 = accounts[index];
@@ -10930,6 +11566,15 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10930
11566
  response: new Response("Bad Gateway", { status: 502 })
10931
11567
  };
10932
11568
  }
11569
+ if (attempt.kind === "provider-capacity-block") {
11570
+ await attempt.discard?.();
11571
+ if (accounts[index + 1])
11572
+ continue;
11573
+ if (allowNextProvider) {
11574
+ return { block: attempt.block, kind: "next-provider" };
11575
+ }
11576
+ return { block: attempt.block, kind: "capacity-block" };
11577
+ }
10933
11578
  if (attempt.kind === "per-minute-rate-limit") {
10934
11579
  return {
10935
11580
  kind: "response",
@@ -10986,75 +11631,301 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10986
11631
  response: new Response("Bad Gateway", { status: 502 })
10987
11632
  };
10988
11633
  }
10989
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
10990
- const firstCandidate = pool.providers[0];
10991
- if (!firstCandidate) {
10992
- return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11634
+ function resolvePoolCandidateResult({
11635
+ candidate,
11636
+ candidateContext,
11637
+ conversationKey,
11638
+ interactive,
11639
+ interactiveInput,
11640
+ providerPreference,
11641
+ requestedChoice,
11642
+ result,
11643
+ routing
11644
+ }) {
11645
+ if (result.kind === "capacity-block") {
11646
+ if (conversationKey) {
11647
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11648
+ }
11649
+ return createProviderCapacityProblem({
11650
+ blockedProvider: candidate.provider.name,
11651
+ category: result.block.category,
11652
+ choices: eligiblePoolChoices(interactiveInput, candidate.provider.name),
11653
+ ...result.block.retryAt !== undefined && {
11654
+ retryAt: result.block.retryAt
11655
+ }
11656
+ });
10993
11657
  }
10994
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
10995
- const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10996
- const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10997
- const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11658
+ if (result.kind !== "response")
11659
+ return null;
11660
+ if (result.account) {
11661
+ if (conversationKey) {
11662
+ routing.clearBlock(conversationKey, candidate.provider.name);
11663
+ }
11664
+ if (conversationKey && requestedChoice) {
11665
+ routing.selectProvider(conversationKey, candidate.provider.name, Date.now());
11666
+ }
11667
+ candidateContext.teamRouter?.rebind(interactiveInput.teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11668
+ }
11669
+ if (!interactive)
11670
+ return result.response;
11671
+ const served = withServedProviderHeaders(result.response, {
11672
+ model: candidate.model ?? interactiveInput.meta.model ?? "",
11673
+ provider: candidate.provider.name
11674
+ });
11675
+ if (!conversationKey || !providerPreference || providerPreference.promotionDeclined || requestedChoice || providerPreference.provider !== candidate.provider.name) {
11676
+ return served;
11677
+ }
11678
+ return withProviderPromotionDetails(served, higherRankedProviderChoices(configuredPoolChoices(interactiveInput.pool, interactiveInput.meta.model), candidate.provider.name, eligiblePoolProviders(interactiveInput), (provider) => routing.canOfferProvider(conversationKey, provider, Date.now())));
11679
+ }
11680
+ function preparePoolCandidate(input, candidate, pinnedId, orderedFallback) {
11681
+ const context2 = createResolvedProxyContext(input.ctx, candidate.provider, input.pool.upstreamPath);
11682
+ const prepared = prepareProxyRequest(input.req, input.url, context2, { ...input.meta, model: candidate.model }, input.body, input.manualAccountName, input.teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11683
+ const pooledAccounts = context2.teamRouter ? context2.teamRouter.eligibleAccounts(prepared.accounts, input.teamRequest, context2.runtime.teamRouting) : prepared.accounts;
11684
+ const eligibleAccounts = orderedFallback ? prepared.accounts.filter((account2) => account2.auth_method === "api_key" || pooledAccounts.includes(account2)) : pooledAccounts;
11685
+ return {
11686
+ accounts: preferPinnedAccount(eligibleAccounts, pinnedId),
11687
+ context: context2,
11688
+ request: prepared.request
11689
+ };
11690
+ }
11691
+ async function proxyPoolCandidates({
11692
+ candidates,
11693
+ conversationKey,
11694
+ interactive,
11695
+ interactiveInput,
11696
+ orderedFallback,
11697
+ pinnedId,
11698
+ providerPreference,
11699
+ requestedChoice,
11700
+ routing
11701
+ }) {
10998
11702
  let soonestRetry = null;
10999
11703
  let soonestFleetReset = null;
11000
11704
  let everyCandidateFull = true;
11705
+ let firstCapacityBlock = null;
11001
11706
  let emittedIngress = false;
11002
11707
  const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
11003
11708
  const recordUnserved = (request3) => {
11709
+ firstCapacityBlock ??= getRequestQuotaCapacityBlock(request3);
11004
11710
  everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
11005
11711
  soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
11006
11712
  soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
11007
11713
  };
11008
- const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
11009
11714
  for (const [candidateIndex, candidate] of candidates.entries()) {
11010
- const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
11011
- const candidateMeta = { ...meta, model: candidate.model };
11012
- const prepared = prepareProxyRequest(req, url, candidateContext, candidateMeta, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11013
- let accounts = prepared.accounts;
11014
- if (candidateContext.teamRouter) {
11015
- accounts = candidateContext.teamRouter.eligibleAccounts(accounts, teamRequest, candidateContext.runtime.teamRouting);
11016
- }
11017
- accounts = preferPinnedAccount(accounts, pinnedId);
11715
+ const { accounts, context: context2, request: request3 } = preparePoolCandidate(interactiveInput, candidate, pinnedId, orderedFallback);
11018
11716
  if (accounts.length === 0) {
11019
- recordUnserved(prepared.request);
11717
+ recordUnserved(request3);
11020
11718
  continue;
11021
11719
  }
11022
11720
  if (!emittedIngress) {
11023
11721
  requestEvents.emit("event", {
11024
11722
  type: "ingress",
11025
- id: meta.id,
11026
- timestamp: meta.timestamp,
11027
- method: meta.method,
11028
- path: meta.path
11723
+ id: interactiveInput.meta.id,
11724
+ timestamp: interactiveInput.meta.timestamp,
11725
+ method: interactiveInput.meta.method,
11726
+ path: interactiveInput.meta.path
11029
11727
  });
11030
11728
  emittedIngress = true;
11031
11729
  }
11032
11730
  log22.info(`Selected ${accounts.length} accounts: ${accounts.map((account2) => account2.name).join(", ")}`);
11033
- const result = await proxyPoolCandidate(prepared.request, accounts, candidateIndex === 0);
11034
- if (result.kind === "response") {
11035
- if (result.account) {
11036
- candidateContext.teamRouter?.rebind(teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11037
- }
11038
- return result.response;
11731
+ const result = await proxyPoolCandidate(request3, accounts, candidateIndex < candidates.length - 1);
11732
+ if (result.kind === "next-provider" && result.block) {
11733
+ firstCapacityBlock ??= result.block;
11734
+ if (conversationKey) {
11735
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11736
+ }
11737
+ }
11738
+ const response = resolvePoolCandidateResult({
11739
+ candidate,
11740
+ candidateContext: context2,
11741
+ conversationKey,
11742
+ interactive,
11743
+ interactiveInput,
11744
+ providerPreference,
11745
+ requestedChoice,
11746
+ result,
11747
+ routing
11748
+ });
11749
+ if (response)
11750
+ return { kind: "response", response };
11751
+ recordUnserved(request3);
11752
+ }
11753
+ return {
11754
+ everyCandidateFull,
11755
+ kind: "unserved",
11756
+ firstCapacityBlock,
11757
+ soonestFleetReset,
11758
+ soonestRetry
11759
+ };
11760
+ }
11761
+ var log22;
11762
+ var init_provider_pool_attempts = __esm(() => {
11763
+ init_src2();
11764
+ init_src4();
11765
+ init_src10();
11766
+ init_handlers();
11767
+ init_proxy_attempts();
11768
+ init_proxy_request();
11769
+ init_interactive_provider_pool();
11770
+ log22 = new Logger("Proxy");
11771
+ });
11772
+
11773
+ // ../../packages/proxy/src/provider-pool.ts
11774
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
11775
+ return {
11776
+ body,
11777
+ callerId,
11778
+ contentType: req.headers.get("content-type"),
11779
+ manualAccountName,
11780
+ model: requestedModel,
11781
+ pinBucket: requestedModel,
11782
+ pinScope: `pool:${pool.wire}`,
11783
+ provider: `pool:${pool.wire}`,
11784
+ sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
11785
+ };
11786
+ }
11787
+ function hasOrderedCallerFallback(ctx, callerId) {
11788
+ const routing = ctx.runtime.teamRouting;
11789
+ return routing.enabled && callerId !== undefined && Object.hasOwn(routing.callerProviderFallback, callerId) && routing.callerProviderFallback[callerId] === "ordered";
11790
+ }
11791
+ function prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
11792
+ const firstCandidate = pool.providers[0];
11793
+ if (!firstCandidate) {
11794
+ return {
11795
+ kind: "response",
11796
+ response: new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 })
11797
+ };
11798
+ }
11799
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
11800
+ const interactiveInput = {
11801
+ body,
11802
+ ctx,
11803
+ manualAccountName,
11804
+ meta,
11805
+ pool,
11806
+ req,
11807
+ teamRequest,
11808
+ url
11809
+ };
11810
+ const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
11811
+ const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
11812
+ const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11813
+ const conversationKey = firstContext.teamRouter?.getConversationProviderKey(teamRequest, firstContext.runtime.teamRouting);
11814
+ const routing = new ConversationProviderRouting(new PoolConversationProviderRoutingStore(ctx.dbOps));
11815
+ let providerPreference = conversationKey ? routing.getPreference(conversationKey) : null;
11816
+ const interactive = interactiveProviderChoiceRequested(req.headers);
11817
+ if (interactive && conversationKey && providerPreference && providerPromotionDeclined(req.headers)) {
11818
+ routing.declinePromotion(conversationKey, Date.now());
11819
+ providerPreference = routing.getPreference(conversationKey);
11820
+ }
11821
+ const requestedChoice = interactive ? req.headers.get("x-agent-smith-provider-choice") : null;
11822
+ const configuredChoices = configuredPoolChoices(pool, meta.model);
11823
+ if (requestedChoice && !readProviderChoice(req.headers, configuredChoices)) {
11824
+ return {
11825
+ kind: "response",
11826
+ response: new Response("Selected provider is not available for this request", { status: 409 })
11827
+ };
11828
+ }
11829
+ if (interactive && manualProviderChoiceRequested(req.headers)) {
11830
+ return {
11831
+ kind: "response",
11832
+ response: createManualProviderChoiceResponse(interactiveInput, pinnedAccount, providerPreference?.provider)
11833
+ };
11834
+ }
11835
+ const orderedFallback = !interactive && hasOrderedCallerFallback(ctx, callerId);
11836
+ return {
11837
+ candidates: selectPoolProviders(pool.providers, (candidate) => candidate.provider.name, {
11838
+ orderedFallback,
11839
+ pinnedProvider: pinnedAccount?.provider,
11840
+ preferredProvider: providerPreference?.provider,
11841
+ requestedProvider: requestedChoice
11842
+ }),
11843
+ conversationKey,
11844
+ interactive,
11845
+ interactiveInput,
11846
+ kind: "selection",
11847
+ orderedFallback,
11848
+ pinnedId,
11849
+ providerPreference,
11850
+ requestedChoice,
11851
+ routing
11852
+ };
11853
+ }
11854
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, providerWaited = false) {
11855
+ const selection = prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId);
11856
+ if (selection.kind === "response")
11857
+ return selection.response;
11858
+ const {
11859
+ candidates,
11860
+ conversationKey,
11861
+ interactive,
11862
+ interactiveInput,
11863
+ orderedFallback,
11864
+ pinnedId,
11865
+ providerPreference,
11866
+ requestedChoice,
11867
+ routing
11868
+ } = selection;
11869
+ if (interactive) {
11870
+ const waitResponse = await waitOrReturnProviderCapacity({
11871
+ candidates,
11872
+ conversationKey,
11873
+ input: interactiveInput,
11874
+ providerWaited,
11875
+ retry: () => proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, true),
11876
+ routing
11877
+ });
11878
+ if (waitResponse)
11879
+ return waitResponse;
11880
+ }
11881
+ const candidateAttempt = await proxyPoolCandidates({
11882
+ candidates,
11883
+ conversationKey,
11884
+ interactive,
11885
+ interactiveInput,
11886
+ orderedFallback,
11887
+ pinnedId,
11888
+ providerPreference,
11889
+ requestedChoice,
11890
+ routing
11891
+ });
11892
+ if (candidateAttempt.kind === "response")
11893
+ return candidateAttempt.response;
11894
+ if (candidateAttempt.everyCandidateFull && candidateAttempt.soonestFleetReset !== null) {
11895
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, candidateAttempt.soonestFleetReset, { blocked: true, holdSeconds: 0 });
11896
+ }
11897
+ if (interactive) {
11898
+ const blockedProvider = candidates[0]?.provider.name;
11899
+ if (blockedProvider) {
11900
+ const block = candidateAttempt.firstCapacityBlock;
11901
+ const retryAt = block?.retryAt ?? candidateAttempt.soonestRetry;
11902
+ return createProviderCapacityProblem({
11903
+ blockedProvider,
11904
+ category: block?.category ?? "unknown",
11905
+ choices: eligiblePoolChoices(interactiveInput, blockedProvider),
11906
+ ...retryAt !== null && retryAt !== undefined && {
11907
+ retryAt
11908
+ }
11909
+ });
11039
11910
  }
11040
- recordUnserved(prepared.request);
11041
11911
  }
11042
- if (everyCandidateFull && soonestFleetReset !== null) {
11043
- ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
11912
+ if (candidateAttempt.soonestRetry !== null) {
11913
+ return quotaExhaustionResponse(candidateAttempt.soonestRetry);
11044
11914
  }
11045
- if (soonestRetry !== null)
11046
- return quotaExhaustionResponse(soonestRetry);
11047
- log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11915
+ log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11048
11916
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
11049
11917
  }
11050
- var log22;
11918
+ var log23;
11051
11919
  var init_provider_pool = __esm(() => {
11052
11920
  init_src2();
11053
11921
  init_src4();
11922
+ init_src10();
11054
11923
  init_handlers();
11055
11924
  init_proxy_attempts();
11056
- init_proxy_request();
11057
- log22 = new Logger("Proxy");
11925
+ init_conversation_provider_routing_store();
11926
+ init_interactive_provider_pool();
11927
+ init_provider_pool_attempts();
11928
+ log23 = new Logger("Proxy");
11058
11929
  });
11059
11930
 
11060
11931
  // ../../packages/proxy/src/seat-alerts.ts
@@ -11079,10 +11950,10 @@ class SeatAlerts {
11079
11950
  this.config = config;
11080
11951
  this.send = send;
11081
11952
  if (config.email && !(config.emailFrom && config.resendApiKey)) {
11082
- log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11953
+ log24.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11083
11954
  }
11084
11955
  if (!config.slackBotToken !== !config.slackChannel) {
11085
- log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11956
+ log24.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11086
11957
  }
11087
11958
  }
11088
11959
  extraUsageSpent(account2, provider) {
@@ -11105,7 +11976,7 @@ class SeatAlerts {
11105
11976
  });
11106
11977
  }
11107
11978
  notify(alert) {
11108
- log23.warn(alert.text);
11979
+ log24.warn(alert.text);
11109
11980
  for (const delivery of this.deliveries(alert)) {
11110
11981
  trackProxyBackgroundTask(this.deliver(delivery));
11111
11982
  }
@@ -11160,7 +12031,7 @@ class SeatAlerts {
11160
12031
  signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
11161
12032
  });
11162
12033
  if (!response.ok) {
11163
- log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
12034
+ log24.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
11164
12035
  return;
11165
12036
  }
11166
12037
  if (!delivery.repliesOk)
@@ -11168,19 +12039,19 @@ class SeatAlerts {
11168
12039
  const reply2 = await response.json();
11169
12040
  if (reply2.ok !== true) {
11170
12041
  const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
11171
- log23.warn(`${delivery.channel} alert was refused (${code})`);
12042
+ log24.warn(`${delivery.channel} alert was refused (${code})`);
11172
12043
  }
11173
12044
  } catch (error) {
11174
- log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
12045
+ log24.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
11175
12046
  }
11176
12047
  }
11177
12048
  }
11178
- 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;
12049
+ var log24, 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;
11179
12050
  var init_seat_alerts = __esm(() => {
11180
12051
  init_src4();
11181
12052
  init_background_tasks();
11182
12053
  init_account_selector();
11183
- log23 = new Logger("SeatAlerts");
12054
+ log24 = new Logger("SeatAlerts");
11184
12055
  SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
11185
12056
  });
11186
12057
 
@@ -11565,7 +12436,7 @@ function getUsageWorker() {
11565
12436
  }
11566
12437
  if (!usageWorkerInstance) {
11567
12438
  usageWorkerInstance = new UsageWorkerController({
11568
- logger: log24,
12439
+ logger: log25,
11569
12440
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
11570
12441
  onWorkerMessage: (data) => {
11571
12442
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -11652,7 +12523,7 @@ async function handleProxy(req, url, ctx, callerId) {
11652
12523
  return quotaExhaustionResponse(retryAt);
11653
12524
  }
11654
12525
  if (accounts.length === 0) {
11655
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12526
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11656
12527
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
11657
12528
  }
11658
12529
  }
@@ -11663,11 +12534,11 @@ async function handleProxy(req, url, ctx, callerId) {
11663
12534
  method: requestMeta.method,
11664
12535
  path: requestMeta.path
11665
12536
  });
11666
- log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
11667
- log24.info(`Request: ${req.method} ${url.pathname}`);
12537
+ log25.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
12538
+ log25.info(`Request: ${req.method} ${url.pathname}`);
11668
12539
  return await proxySelectedAccounts(request3, accounts);
11669
12540
  }
11670
- var log24, usageWorkerInstance = null;
12541
+ var log25, usageWorkerInstance = null;
11671
12542
  var init_proxy = __esm(() => {
11672
12543
  init_src2();
11673
12544
  init_src4();
@@ -11676,7 +12547,7 @@ var init_proxy = __esm(() => {
11676
12547
  init_provider_pool();
11677
12548
  init_seat_alerts();
11678
12549
  init_usage_worker();
11679
- log24 = new Logger("Proxy");
12550
+ log25 = new Logger("Proxy");
11680
12551
  });
11681
12552
 
11682
12553
  // ../../packages/proxy/src/quota-hold.ts
@@ -12028,7 +12899,7 @@ function endActiveTurn(session, success, error) {
12028
12899
  if (!activeTurn) {
12029
12900
  return;
12030
12901
  }
12031
- log25.debug("Ending tracked websocket turn", {
12902
+ log26.debug("Ending tracked websocket turn", {
12032
12903
  requestId: activeTurn.requestId,
12033
12904
  provider: session.providerName,
12034
12905
  path: session.path,
@@ -12082,7 +12953,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
12082
12953
  timestamp,
12083
12954
  model: getEventModel(parsed)
12084
12955
  };
12085
- log25.debug("Starting tracked websocket turn", {
12956
+ log26.debug("Starting tracked websocket turn", {
12086
12957
  requestId,
12087
12958
  provider: session.providerName,
12088
12959
  path: session.path,
@@ -12112,7 +12983,7 @@ function handleTrackedUpstreamText(session, data) {
12112
12983
  if (!messageType) {
12113
12984
  return;
12114
12985
  }
12115
- log25.debug("Processing tracked websocket message", {
12986
+ log26.debug("Processing tracked websocket message", {
12116
12987
  provider: session.providerName,
12117
12988
  path: session.path,
12118
12989
  messageType,
@@ -12153,7 +13024,7 @@ function capturePendingRequestBody(session, message) {
12153
13024
  }
12154
13025
  session.pendingRequestBody = Buffer.from(message).toString("base64");
12155
13026
  session.pendingRequestTimestamp = Date.now();
12156
- log25.debug("Captured websocket request body for next tracked turn", {
13027
+ log26.debug("Captured websocket request body for next tracked turn", {
12157
13028
  provider: session.providerName,
12158
13029
  path: session.path,
12159
13030
  size: message.length
@@ -12226,7 +13097,7 @@ async function connectToNextUpstream(ws) {
12226
13097
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
12227
13098
  } catch (error) {
12228
13099
  session.connecting = false;
12229
- log25.warn("Skipping websocket account during upstream connection", {
13100
+ log26.warn("Skipping websocket account during upstream connection", {
12230
13101
  account: account2.name,
12231
13102
  error: error instanceof Error ? error.message : String(error)
12232
13103
  });
@@ -12285,7 +13156,7 @@ async function connectToNextUpstream(ws) {
12285
13156
  }
12286
13157
  });
12287
13158
  upstream.addEventListener("error", () => {
12288
- log25.warn("Upstream websocket error", {
13159
+ log26.warn("Upstream websocket error", {
12289
13160
  account: plan.account.name,
12290
13161
  provider: session.providerName,
12291
13162
  path: session.path
@@ -12294,7 +13165,7 @@ async function connectToNextUpstream(ws) {
12294
13165
  } catch (error) {
12295
13166
  session.connecting = false;
12296
13167
  clearConnectTimeout(session);
12297
- log25.warn("Failed to create upstream websocket", {
13168
+ log26.warn("Failed to create upstream websocket", {
12298
13169
  account: plan.account.name,
12299
13170
  error: error instanceof Error ? error.message : String(error)
12300
13171
  });
@@ -12339,7 +13210,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12339
13210
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
12340
13211
  if (accounts.length === 0) {
12341
13212
  alertWhenFleetFull(requestMeta, requestContext, 0);
12342
- log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
13213
+ log26.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12343
13214
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
12344
13215
  }
12345
13216
  const protocols = getProtocols(req.headers);
@@ -12377,7 +13248,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12377
13248
  }
12378
13249
  return;
12379
13250
  }
12380
- 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;
13251
+ var log26, 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;
12381
13252
  var init_websocket_proxy = __esm(() => {
12382
13253
  init_src2();
12383
13254
  init_src3();
@@ -12388,7 +13259,7 @@ var init_websocket_proxy = __esm(() => {
12388
13259
  init_token_manager();
12389
13260
  init_openai_usage();
12390
13261
  init_seat_alerts();
12391
- log25 = new Logger("WebSocketProxy");
13262
+ log26 = new Logger("WebSocketProxy");
12392
13263
  websocketSessions = new Map;
12393
13264
  textEncoder = new TextEncoder;
12394
13265
  websocketProxyHandler = {
@@ -12502,16 +13373,16 @@ class WindowWarmup {
12502
13373
  try {
12503
13374
  const accessToken = await this.readToken(account2);
12504
13375
  if (!accessToken) {
12505
- log26.warn(`Window warm-up skipped ${account2.name}: no access token`);
13376
+ log27.warn(`Window warm-up skipped ${account2.name}: no access token`);
12506
13377
  return;
12507
13378
  }
12508
13379
  const quota2 = await this.startWindow(provider, account2, accessToken, model);
12509
- log26.info(`Window warm-up started ${account2.name}'s five-hour window`);
13380
+ log27.info(`Window warm-up started ${account2.name}'s five-hour window`);
12510
13381
  if (quota2) {
12511
13382
  recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
12512
13383
  }
12513
13384
  } catch (error) {
12514
- log26.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
13385
+ log27.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
12515
13386
  }
12516
13387
  }
12517
13388
  async startWindow(provider, account2, accessToken, model) {
@@ -12523,18 +13394,18 @@ class WindowWarmup {
12523
13394
  }
12524
13395
  }
12525
13396
  }
12526
- var log26;
13397
+ var log27;
12527
13398
  var init_window_warmup2 = __esm(() => {
12528
13399
  init_src7();
12529
13400
  init_src4();
12530
13401
  init_src();
12531
13402
  init_account_selector();
12532
13403
  init_quota_probe();
12533
- log26 = new Logger("WindowWarmup");
13404
+ log27 = new Logger("WindowWarmup");
12534
13405
  });
12535
13406
 
12536
13407
  // ../../packages/proxy/src/index.ts
12537
- var init_src10 = __esm(() => {
13408
+ var init_src12 = __esm(() => {
12538
13409
  init_background_tasks();
12539
13410
  init_account_selector();
12540
13411
  init_request_handler();
@@ -12775,10 +13646,10 @@ function createRuntimeConfig(config, port) {
12775
13646
  teamRouting: config.getTeamRouting()
12776
13647
  };
12777
13648
  }
12778
- function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
13649
+ function wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
12779
13650
  config.on("change", (change) => {
12780
13651
  if (change.key === "lb_strategy") {
12781
- log27.info("Strategy configuration changed");
13652
+ log28.info("Strategy configuration changed");
12782
13653
  const newStrategyName = config.getStrategy();
12783
13654
  if (newStrategyName === "session") {
12784
13655
  const strategy3 = new SessionStrategy;
@@ -12793,7 +13664,7 @@ function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig
12793
13664
  runtimeConfig2.teamRouting = config.getTeamRouting();
12794
13665
  quotaProbe.reschedule();
12795
13666
  windowWarmup.reschedule();
12796
- log27.info("Team routing configuration changed");
13667
+ log28.info("Team routing configuration changed");
12797
13668
  }
12798
13669
  });
12799
13670
  }
@@ -12828,7 +13699,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12828
13699
  sessionDurationMs: runtimeConfig2.sessionDurationMs
12829
13700
  });
12830
13701
  const dbOps = DatabaseFactory.getInstance();
12831
- const log27 = container.resolve(SERVICE_KEYS.Logger);
13702
+ const log28 = container.resolve(SERVICE_KEYS.Logger);
12832
13703
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
12833
13704
  const asyncWriter = new AsyncDbWriter;
12834
13705
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -12893,11 +13764,11 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12893
13764
  usageWorker: getUsageWorker()
12894
13765
  };
12895
13766
  const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
12896
- wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
13767
+ wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
12897
13768
  return {
12898
13769
  config,
12899
13770
  dbOps,
12900
- log: log27,
13771
+ log: log28,
12901
13772
  asyncWriter,
12902
13773
  apiRouter,
12903
13774
  exposureConfig,
@@ -12906,12 +13777,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12906
13777
  runtimeConfig: runtimeConfig2
12907
13778
  };
12908
13779
  }
12909
- function logInitialAccountStatus(log27, dbOps) {
13780
+ function logInitialAccountStatus(log28, dbOps) {
12910
13781
  const accounts = dbOps.getAllAccounts();
12911
13782
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
12912
- log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
13783
+ log28.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
12913
13784
  if (activeAccounts.length === 0) {
12914
- log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
13785
+ log28.warn("No active accounts available - requests will be refused with a 503 until an account is added");
12915
13786
  }
12916
13787
  }
12917
13788
  var init_bootstrap_runtime = __esm(() => {
@@ -12921,7 +13792,7 @@ var init_bootstrap_runtime = __esm(() => {
12921
13792
  init_src8();
12922
13793
  init_src4();
12923
13794
  init_src5();
12924
- init_src10();
13795
+ init_src12();
12925
13796
  init_exposure();
12926
13797
  });
12927
13798
 
@@ -13147,38 +14018,38 @@ function createServerFetchHandler({
13147
14018
  var init_fetch_handler = __esm(() => {
13148
14019
  init_src2();
13149
14020
  init_src3();
13150
- init_src10();
14021
+ init_src12();
13151
14022
  init_dashboard_assets();
13152
14023
  init_exposure();
13153
14024
  init_oauth_token();
13154
14025
  });
13155
14026
 
13156
14027
  // ../../packages/runtime-server/src/retention-maintenance.ts
13157
- function removeExpiredRequests(config, dbOps, log27, label) {
14028
+ function removeExpiredRequests(config, dbOps, log28, label) {
13158
14029
  try {
13159
14030
  const payloadDays = config.getDataRetentionDays();
13160
14031
  const requestDays = config.getRequestRetentionDays();
13161
14032
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
13162
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
14033
+ log28.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
13163
14034
  } catch (err) {
13164
- log27.error(`${label} cleanup error: ${err}`);
14035
+ log28.error(`${label} cleanup error: ${err}`);
13165
14036
  }
13166
14037
  }
13167
14038
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
13168
- const log27 = new Logger("RetentionMaintenance");
13169
- removeExpiredRequests(config, dbOps, log27, "Startup");
14039
+ const log28 = new Logger("RetentionMaintenance");
14040
+ removeExpiredRequests(config, dbOps, log28, "Startup");
13170
14041
  try {
13171
14042
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
13172
- log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
14043
+ log28.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
13173
14044
  } catch (err) {
13174
- log27.error(`Database compaction error: ${err}`);
14045
+ log28.error(`Database compaction error: ${err}`);
13175
14046
  }
13176
14047
  const timer = setInterval(() => {
13177
- removeExpiredRequests(config, dbOps, log27, "Periodic");
14048
+ removeExpiredRequests(config, dbOps, log28, "Periodic");
13178
14049
  try {
13179
14050
  dbOps.checkpointWal();
13180
14051
  } catch (err) {
13181
- log27.error(`WAL checkpoint error: ${err}`);
14052
+ log28.error(`WAL checkpoint error: ${err}`);
13182
14053
  }
13183
14054
  }, intervalMs);
13184
14055
  timer.unref?.();
@@ -13336,7 +14207,7 @@ function startServer(options) {
13336
14207
  const {
13337
14208
  config,
13338
14209
  dbOps,
13339
- log: log27,
14210
+ log: log28,
13340
14211
  apiRouter,
13341
14212
  exposureConfig,
13342
14213
  proxyContext,
@@ -13381,7 +14252,7 @@ function startServer(options) {
13381
14252
  strategy: config.getStrategy(),
13382
14253
  providers: providerRegistry.listProviders()
13383
14254
  }));
13384
- logInitialAccountStatus(log27, dbOps);
14255
+ logInitialAccountStatus(log28, dbOps);
13385
14256
  return {
13386
14257
  port: activePort,
13387
14258
  stop: () => stopServerRuntime(),
@@ -13404,12 +14275,12 @@ async function handleGracefulShutdown(signal) {
13404
14275
  }
13405
14276
  }
13406
14277
  var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
13407
- var init_src11 = __esm(() => {
14278
+ var init_src13 = __esm(() => {
13408
14279
  init_src9();
13409
14280
  init_src2();
13410
14281
  init_src8();
13411
14282
  init_src4();
13412
- init_src10();
14283
+ init_src12();
13413
14284
  init_bootstrap_runtime();
13414
14285
  init_dashboard_assets();
13415
14286
  init_deployment_drain();
@@ -13433,7 +14304,7 @@ process.env.AGENT_SMITH_DASHBOARD_DIST_DIR ??= join(import.meta.dir, "dashboard"
13433
14304
  process.env.AGENT_SMITH_USAGE_WORKER_PATH ??= join(import.meta.dir, "post-processor.worker.js");
13434
14305
 
13435
14306
  // src/pool.ts
13436
- init_src11();
14307
+ init_src13();
13437
14308
  process.umask(63);
13438
14309
  var server = startServer({
13439
14310
  port: Number(process.env.AGENT_SMITH_POOL_PORT),