@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/bin.js CHANGED
@@ -1627,7 +1627,7 @@ function sanitizeProviderPools(value) {
1627
1627
  return pools;
1628
1628
  }
1629
1629
  function wireForStrategy(strategy3) {
1630
- return strategy3 === "anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1630
+ return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1631
1631
  }
1632
1632
  function isNonNegativeFiniteNumber(value) {
1633
1633
  return isFiniteNumber(value) && value >= 0;
@@ -1666,6 +1666,12 @@ function sanitizeTeamRouting(value) {
1666
1666
  result.caller_weekly_max_usage = Object.fromEntries(entries);
1667
1667
  }
1668
1668
  }
1669
+ if (isRecord(value.caller_provider_fallback)) {
1670
+ const entries = Object.entries(value.caller_provider_fallback);
1671
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
1672
+ result.caller_provider_fallback = Object.fromEntries(entries);
1673
+ }
1674
+ }
1669
1675
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1670
1676
  result.admission_cap = Math.floor(value.admission_cap);
1671
1677
  }
@@ -1720,6 +1726,7 @@ var init_src4 = __esm(() => {
1720
1726
  log2 = new Logger("Config");
1721
1727
  PROVIDER_STRATEGIES = [
1722
1728
  "anthropic-api",
1729
+ "model-studio-anthropic-api",
1723
1730
  "openai-api",
1724
1731
  "claude-code",
1725
1732
  "codex"
@@ -1743,6 +1750,7 @@ var init_src4 = __esm(() => {
1743
1750
  weeklyMaxUsage: 0.95,
1744
1751
  weeklyMaxUsageByEmail: {},
1745
1752
  callerWeeklyMaxUsage: {},
1753
+ callerProviderFallback: {},
1746
1754
  admissionCap: 5,
1747
1755
  admissionQueueLimit: 25,
1748
1756
  admissionWaitMs: 30000,
@@ -1906,6 +1914,7 @@ var init_src4 = __esm(() => {
1906
1914
  weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1907
1915
  weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1908
1916
  callerWeeklyMaxUsage: { ...file?.caller_weekly_max_usage },
1917
+ callerProviderFallback: { ...file?.caller_provider_fallback },
1909
1918
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1910
1919
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1911
1920
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
@@ -1976,6 +1985,7 @@ var init_src4 = __esm(() => {
1976
1985
  "weekly_max_usage",
1977
1986
  "weekly_max_usage_by_email",
1978
1987
  "caller_weekly_max_usage",
1988
+ "caller_provider_fallback",
1979
1989
  "admission_cap",
1980
1990
  "admission_queue_limit",
1981
1991
  "admission_wait_ms",
@@ -2006,6 +2016,11 @@ var init_src4 = __esm(() => {
2006
2016
  ...oldValue.caller_weekly_max_usage
2007
2017
  };
2008
2018
  }
2019
+ if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
2020
+ sanitized.caller_provider_fallback = {
2021
+ ...oldValue.caller_provider_fallback
2022
+ };
2023
+ }
2009
2024
  this.persistStrictly("team_routing", sanitized);
2010
2025
  }
2011
2026
  allowAccountUuid(accountUuid) {
@@ -2884,6 +2899,30 @@ function ensureConversationPinsTable(db) {
2884
2899
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_account ON conversation_pins(account_id)`);
2885
2900
  db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_pins_last_seen ON conversation_pins(last_seen_at)`);
2886
2901
  }
2902
+ function ensureConversationProviderPreferencesTable(db) {
2903
+ db.run(`
2904
+ CREATE TABLE IF NOT EXISTS conversation_provider_preferences (
2905
+ pin_key TEXT PRIMARY KEY,
2906
+ provider TEXT NOT NULL,
2907
+ promotion_declined INTEGER NOT NULL DEFAULT 0,
2908
+ last_seen_at INTEGER NOT NULL
2909
+ )
2910
+ `);
2911
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_preferences_last_seen ON conversation_provider_preferences(last_seen_at)`);
2912
+ }
2913
+ function ensureConversationProviderBlocksTable(db) {
2914
+ db.run(`
2915
+ CREATE TABLE IF NOT EXISTS conversation_provider_blocks (
2916
+ pin_key TEXT NOT NULL,
2917
+ provider TEXT NOT NULL,
2918
+ category TEXT NOT NULL DEFAULT 'unknown',
2919
+ retry_at INTEGER,
2920
+ last_seen_at INTEGER NOT NULL,
2921
+ PRIMARY KEY (pin_key, provider)
2922
+ )
2923
+ `);
2924
+ db.run(`CREATE INDEX IF NOT EXISTS idx_conversation_provider_blocks_last_seen ON conversation_provider_blocks(last_seen_at)`);
2925
+ }
2887
2926
  function remediateDuplicateAccountNames(db) {
2888
2927
  const accounts = db.query(`
2889
2928
  SELECT id, name, created_at
@@ -3009,6 +3048,8 @@ function ensureSchema(db) {
3009
3048
  `);
3010
3049
  ensureAuthSessionsTable(db);
3011
3050
  ensureConversationPinsTable(db);
3051
+ ensureConversationProviderPreferencesTable(db);
3052
+ ensureConversationProviderBlocksTable(db);
3012
3053
  }
3013
3054
  function runMigrations(db) {
3014
3055
  ensureSchema(db);
@@ -3028,6 +3069,8 @@ function runMigrations(db) {
3028
3069
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
3029
3070
  ensureAuthSessionsTable(db);
3030
3071
  ensureConversationPinsTable(db);
3072
+ ensureConversationProviderPreferencesTable(db);
3073
+ ensureConversationProviderBlocksTable(db);
3031
3074
  ensureAccountsNameUniqueness(db);
3032
3075
  db.run(`CREATE TABLE IF NOT EXISTS enrollment_contacts (
3033
3076
  account_id TEXT PRIMARY KEY REFERENCES accounts(id) ON DELETE CASCADE,
@@ -3723,6 +3766,85 @@ var init_conversation_pin_repository = __esm(() => {
3723
3766
  };
3724
3767
  });
3725
3768
 
3769
+ // ../../packages/database/src/repositories/conversation-provider-block.repository.ts
3770
+ var ConversationProviderBlockRepository;
3771
+ var init_conversation_provider_block_repository = __esm(() => {
3772
+ ConversationProviderBlockRepository = class ConversationProviderBlockRepository extends BaseRepository {
3773
+ find(pinKey, provider) {
3774
+ const row = this.get(`SELECT category, retry_at, last_seen_at FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
3775
+ return row ? {
3776
+ category: row.category,
3777
+ lastSeenAt: row.last_seen_at,
3778
+ retryAt: row.retry_at ?? undefined
3779
+ } : null;
3780
+ }
3781
+ upsert(pinKey, provider, category, retryAt, lastSeenAt) {
3782
+ this.run(`
3783
+ INSERT INTO conversation_provider_blocks (
3784
+ pin_key, provider, category, retry_at, last_seen_at
3785
+ )
3786
+ VALUES (?, ?, ?, ?, ?)
3787
+ ON CONFLICT(pin_key, provider) DO UPDATE SET
3788
+ category = excluded.category,
3789
+ retry_at = excluded.retry_at,
3790
+ last_seen_at = excluded.last_seen_at
3791
+ `, [pinKey, provider, category, retryAt ?? null, lastSeenAt]);
3792
+ }
3793
+ delete(pinKey, provider) {
3794
+ this.run(`DELETE FROM conversation_provider_blocks WHERE pin_key = ? AND provider = ?`, [pinKey, provider]);
3795
+ }
3796
+ deleteExpired(before) {
3797
+ this.run(`DELETE FROM conversation_provider_blocks WHERE last_seen_at < ?`, [before]);
3798
+ }
3799
+ deleteForAccount(accountId) {
3800
+ this.run(`
3801
+ DELETE FROM conversation_provider_blocks
3802
+ WHERE pin_key IN (
3803
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
3804
+ )
3805
+ `, [accountId]);
3806
+ }
3807
+ };
3808
+ });
3809
+
3810
+ // ../../packages/database/src/repositories/conversation-provider-preference.repository.ts
3811
+ var ConversationProviderPreferenceRepository;
3812
+ var init_conversation_provider_preference_repository = __esm(() => {
3813
+ ConversationProviderPreferenceRepository = class ConversationProviderPreferenceRepository extends BaseRepository {
3814
+ find(pinKey) {
3815
+ const row = this.get(`SELECT provider, promotion_declined, last_seen_at FROM conversation_provider_preferences WHERE pin_key = ?`, [pinKey]);
3816
+ return row ? {
3817
+ provider: row.provider,
3818
+ promotionDeclined: row.promotion_declined === 1,
3819
+ lastSeenAt: row.last_seen_at
3820
+ } : null;
3821
+ }
3822
+ upsert(pinKey, provider, promotionDeclined, lastSeenAt) {
3823
+ this.run(`
3824
+ INSERT INTO conversation_provider_preferences (
3825
+ pin_key, provider, promotion_declined, last_seen_at
3826
+ )
3827
+ VALUES (?, ?, ?, ?)
3828
+ ON CONFLICT(pin_key) DO UPDATE SET
3829
+ provider = excluded.provider,
3830
+ promotion_declined = excluded.promotion_declined,
3831
+ last_seen_at = excluded.last_seen_at
3832
+ `, [pinKey, provider, promotionDeclined ? 1 : 0, lastSeenAt]);
3833
+ }
3834
+ deleteExpired(before) {
3835
+ this.run(`DELETE FROM conversation_provider_preferences WHERE last_seen_at < ?`, [before]);
3836
+ }
3837
+ deleteForAccount(accountId) {
3838
+ this.run(`
3839
+ DELETE FROM conversation_provider_preferences
3840
+ WHERE pin_key IN (
3841
+ SELECT pin_key FROM conversation_pins WHERE account_id = ?
3842
+ )
3843
+ `, [accountId]);
3844
+ }
3845
+ };
3846
+ });
3847
+
3726
3848
  // ../../packages/database/src/models/request-row.ts
3727
3849
  function toRequest(row) {
3728
3850
  return {
@@ -4333,6 +4455,8 @@ class DatabaseOperations {
4333
4455
  requests;
4334
4456
  authSessions;
4335
4457
  conversationPins;
4458
+ conversationProviderBlocks;
4459
+ conversationProviderPreferences;
4336
4460
  strategy;
4337
4461
  stats;
4338
4462
  constructor(dbPath) {
@@ -4352,6 +4476,8 @@ class DatabaseOperations {
4352
4476
  this.requests = new RequestRepository(this.db);
4353
4477
  this.authSessions = new AuthSessionRepository(this.db);
4354
4478
  this.conversationPins = new ConversationPinRepository(this.db);
4479
+ this.conversationProviderBlocks = new ConversationProviderBlockRepository(this.db);
4480
+ this.conversationProviderPreferences = new ConversationProviderPreferenceRepository(this.db);
4355
4481
  this.strategy = new StrategyRepository(this.db);
4356
4482
  this.stats = new StatsRepository(this.db);
4357
4483
  }
@@ -4395,6 +4521,8 @@ class DatabaseOperations {
4395
4521
  return this.accounts.update(accountId, data);
4396
4522
  }
4397
4523
  deleteAccount(accountId) {
4524
+ this.conversationProviderBlocks.deleteForAccount(accountId);
4525
+ this.conversationProviderPreferences.deleteForAccount(accountId);
4398
4526
  this.conversationPins.deleteForAccount(accountId);
4399
4527
  return this.accounts.delete(accountId);
4400
4528
  }
@@ -4409,6 +4537,23 @@ class DatabaseOperations {
4409
4537
  }
4410
4538
  deleteExpiredConversationPins(before) {
4411
4539
  this.conversationPins.deleteExpired(before);
4540
+ this.conversationProviderBlocks.deleteExpired(before);
4541
+ this.conversationProviderPreferences.deleteExpired(before);
4542
+ }
4543
+ getConversationProviderPreference(pinKey) {
4544
+ return this.conversationProviderPreferences.find(pinKey);
4545
+ }
4546
+ upsertConversationProviderPreference(pinKey, provider, promotionDeclined, lastSeenAt) {
4547
+ this.conversationProviderPreferences.upsert(pinKey, provider, promotionDeclined, lastSeenAt);
4548
+ }
4549
+ getConversationProviderBlock(pinKey, provider) {
4550
+ return this.conversationProviderBlocks.find(pinKey, provider);
4551
+ }
4552
+ upsertConversationProviderBlock(pinKey, provider, category, retryAt, lastSeenAt) {
4553
+ this.conversationProviderBlocks.upsert(pinKey, provider, category, retryAt, lastSeenAt);
4554
+ }
4555
+ deleteConversationProviderBlock(pinKey, provider) {
4556
+ this.conversationProviderBlocks.delete(pinKey, provider);
4412
4557
  }
4413
4558
  countAccounts() {
4414
4559
  return this.accounts.count();
@@ -4594,6 +4739,8 @@ var init_database_operations = __esm(() => {
4594
4739
  init_analytics_repository();
4595
4740
  init_auth_session_repository();
4596
4741
  init_conversation_pin_repository();
4742
+ init_conversation_provider_block_repository();
4743
+ init_conversation_provider_preference_repository();
4597
4744
  init_request_repository();
4598
4745
  init_stats_repository();
4599
4746
  init_strategy_repository();
@@ -6197,6 +6344,112 @@ var init_provider4 = __esm(() => {
6197
6344
  };
6198
6345
  });
6199
6346
 
6347
+ // ../../packages/providers/src/connectors/model-studio-capacity.ts
6348
+ function retryAtFromHeader(response, now = Date.now()) {
6349
+ const retryAfter = response.headers.get("retry-after");
6350
+ if (!retryAfter)
6351
+ return;
6352
+ const seconds = Number(retryAfter);
6353
+ if (Number.isFinite(seconds))
6354
+ return now + Math.max(0, seconds) * 1000;
6355
+ const date2 = Date.parse(retryAfter);
6356
+ return Number.isNaN(date2) ? undefined : Math.max(now, date2);
6357
+ }
6358
+ async function readSmallJsonBody(response) {
6359
+ const contentLength = Number(response.headers.get("content-length"));
6360
+ if (Number.isFinite(contentLength) && contentLength > MAX_BLOCK_BODY_BYTES) {
6361
+ return null;
6362
+ }
6363
+ const contentType = response.headers.get("content-type") ?? "";
6364
+ if (!contentType.toLowerCase().includes("application/json"))
6365
+ return null;
6366
+ const reader = response.clone().body?.getReader();
6367
+ if (!reader)
6368
+ return null;
6369
+ const chunks = [];
6370
+ let length = 0;
6371
+ try {
6372
+ while (true) {
6373
+ const { done, value } = await reader.read();
6374
+ if (done)
6375
+ break;
6376
+ length += value.byteLength;
6377
+ if (length > MAX_BLOCK_BODY_BYTES) {
6378
+ await reader.cancel();
6379
+ return null;
6380
+ }
6381
+ chunks.push(value);
6382
+ }
6383
+ } catch {
6384
+ return null;
6385
+ }
6386
+ const bytes = new Uint8Array(length);
6387
+ let offset = 0;
6388
+ for (const chunk of chunks) {
6389
+ bytes.set(chunk, offset);
6390
+ offset += chunk.byteLength;
6391
+ }
6392
+ try {
6393
+ return JSON.parse(new TextDecoder().decode(bytes));
6394
+ } catch {
6395
+ return null;
6396
+ }
6397
+ }
6398
+ function errorCode(payload) {
6399
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
6400
+ return;
6401
+ }
6402
+ const record2 = payload;
6403
+ if (typeof record2.code === "string")
6404
+ return record2.code;
6405
+ const error = record2.error;
6406
+ if (typeof error !== "object" || error === null || Array.isArray(error)) {
6407
+ return;
6408
+ }
6409
+ return typeof error.code === "string" ? error.code : undefined;
6410
+ }
6411
+ async function classifyModelStudioCapacityBlock(response, now = Date.now()) {
6412
+ if (response.status !== 429 && response.status !== 503)
6413
+ return null;
6414
+ const code = errorCode(await readSmallJsonBody(response));
6415
+ const category = code ? MODEL_STUDIO_BLOCK_CATEGORIES[code] : undefined;
6416
+ if (!category) {
6417
+ return response.status === 429 ? { category: "unknown" } : null;
6418
+ }
6419
+ const retryAt = retryAtFromHeader(response, now);
6420
+ return retryAt === undefined ? { category } : { category, retryAt };
6421
+ }
6422
+ var MAX_BLOCK_BODY_BYTES, MODEL_STUDIO_BLOCK_CATEGORIES;
6423
+ var init_model_studio_capacity = __esm(() => {
6424
+ MAX_BLOCK_BODY_BYTES = 64 * 1024;
6425
+ MODEL_STUDIO_BLOCK_CATEGORIES = {
6426
+ "Throttling.RateQuota": "request-rate",
6427
+ "Throttling.AllocationQuota": "token-allocation",
6428
+ "Throttling.BurstRate": "burst",
6429
+ "Throttling.ResourceExhausted": "dynamic-throughput",
6430
+ "Throttling.ServiceOverloaded": "dynamic-throughput",
6431
+ ServiceUnavailable: "temporary-capacity"
6432
+ };
6433
+ });
6434
+
6435
+ // ../../packages/providers/src/providers/model-studio/provider.ts
6436
+ var ModelStudioAnthropicProvider;
6437
+ var init_provider5 = __esm(() => {
6438
+ init_model_studio_capacity();
6439
+ init_provider();
6440
+ ModelStudioAnthropicProvider = class ModelStudioAnthropicProvider extends AnthropicProvider {
6441
+ async getCapacityBlock(response) {
6442
+ return await classifyModelStudioCapacityBlock(response);
6443
+ }
6444
+ parseRateLimit(response) {
6445
+ if (response.status !== 429)
6446
+ return super.parseRateLimit(response);
6447
+ const resetTime = retryAtFromHeader(response);
6448
+ return resetTime === undefined ? { isRateLimited: true } : { isRateLimited: true, resetTime };
6449
+ }
6450
+ };
6451
+ });
6452
+
6200
6453
  // ../../packages/providers/src/registry.ts
6201
6454
  function supportsOAuth(provider) {
6202
6455
  return "supportsOAuth" in provider && typeof provider.supportsOAuth === "function" && "getOAuthProvider" in provider && typeof provider.getOAuthProvider === "function";
@@ -6314,6 +6567,8 @@ function createProvider(definition) {
6314
6567
  switch (definition.strategy) {
6315
6568
  case "anthropic-api":
6316
6569
  return new AnthropicProvider;
6570
+ case "model-studio-anthropic-api":
6571
+ return new ModelStudioAnthropicProvider;
6317
6572
  case "openai-api":
6318
6573
  return new OpenAIProvider;
6319
6574
  case "claude-code":
@@ -6341,6 +6596,7 @@ var init_configured_registry = __esm(() => {
6341
6596
  init_provider();
6342
6597
  init_provider2();
6343
6598
  init_provider4();
6599
+ init_provider5();
6344
6600
  init_provider3();
6345
6601
  init_registry();
6346
6602
  });
@@ -6388,6 +6644,11 @@ var init_codex = __esm(() => {
6388
6644
  init_provider4();
6389
6645
  });
6390
6646
 
6647
+ // ../../packages/providers/src/providers/model-studio/index.ts
6648
+ var init_model_studio = __esm(() => {
6649
+ init_provider5();
6650
+ });
6651
+
6391
6652
  // ../../packages/providers/src/providers/openai/index.ts
6392
6653
  var init_openai = __esm(() => {
6393
6654
  init_oauth2();
@@ -6399,6 +6660,7 @@ var init_providers = __esm(() => {
6399
6660
  init_anthropic();
6400
6661
  init_claude_code();
6401
6662
  init_codex();
6663
+ init_model_studio();
6402
6664
  init_openai();
6403
6665
  });
6404
6666
  // ../../packages/providers/src/index.ts
@@ -7439,6 +7701,7 @@ var init_analytics = __esm(() => {
7439
7701
  // ../../packages/api/src/handlers/config.ts
7440
7702
  function publicTeamRouting(config) {
7441
7703
  const {
7704
+ callerProviderFallback: _callerProviderFallback,
7442
7705
  callerWeeklyMaxUsage: _callerWeeklyMaxUsage,
7443
7706
  weeklyMaxUsageByEmail: _weeklyMaxUsageByEmail,
7444
7707
  ...routing
@@ -9065,6 +9328,11 @@ function pinKey(request3, provider) {
9065
9328
  digest
9066
9329
  ].join("\x00")).digest("hex");
9067
9330
  }
9331
+ function providerConversationKey(request3) {
9332
+ if (!request3.sessionId)
9333
+ return null;
9334
+ return createHash2("sha256").update([request3.pinScope ?? request3.provider, request3.sessionId].join("\x00")).digest("hex");
9335
+ }
9068
9336
  function isAllowlisted(account2, config) {
9069
9337
  return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
9070
9338
  }
@@ -9111,9 +9379,20 @@ class TeamRouter {
9111
9379
  return;
9112
9380
  }
9113
9381
  this.removeExpiredPins(now, store);
9114
- const key = pinKey(request3, provider);
9382
+ const key = this.getConversationPinKey(request3, config, provider);
9115
9383
  return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
9116
9384
  }
9385
+ getConversationPinKey(request3, _config, provider) {
9386
+ if (!request3?.sessionId || request3.manualAccountName) {
9387
+ return;
9388
+ }
9389
+ return pinKey(request3, provider) ?? undefined;
9390
+ }
9391
+ getConversationProviderKey(request3, _config) {
9392
+ if (!request3?.sessionId || request3.manualAccountName)
9393
+ return;
9394
+ return providerConversationKey(request3) ?? undefined;
9395
+ }
9117
9396
  begin(accountId) {
9118
9397
  this.inFlight.set(accountId, (this.inFlight.get(accountId) ?? 0) + 1);
9119
9398
  }
@@ -9347,6 +9626,25 @@ function isServableSeat(provider, account2, model, ctx, now) {
9347
9626
  function blockingResets(provider, account2, model, ctx, now, callerId) {
9348
9627
  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);
9349
9628
  }
9629
+ function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
9630
+ 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)));
9631
+ if (blocking.length === 0)
9632
+ return null;
9633
+ const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
9634
+ const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
9635
+ const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
9636
+ return rightReset - leftReset;
9637
+ })[0];
9638
+ const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
9639
+ return window2.resetAt === null ? { category } : { category, retryAt: window2.resetAt };
9640
+ }
9641
+ function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
9642
+ const now = Date.now();
9643
+ const blocks = seatsFor(fleetAccounts(ctx.providerName, ctx)).map((account2) => quotaBlockForAccount(ctx.provider, account2, meta.model, ctx, now, callerId)).filter((block) => block !== null);
9644
+ if (blocks.length === 0)
9645
+ return null;
9646
+ return [...blocks].sort((left, right) => (left.retryAt ?? Number.POSITIVE_INFINITY) - (right.retryAt ?? Number.POSITIVE_INFINITY))[0];
9647
+ }
9350
9648
  function servableAt(provider, account2, model, ctx, now, callerId) {
9351
9649
  const cooldown = cooldownEnd(account2, now);
9352
9650
  if (isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx, callerId)) {
@@ -9725,6 +10023,7 @@ class TeamAdmission {
9725
10023
  weeklyMaxUsage: 0.95,
9726
10024
  weeklyMaxUsageByEmail: {},
9727
10025
  callerWeeklyMaxUsage: {},
10026
+ callerProviderFallback: {},
9728
10027
  admissionCap: 1,
9729
10028
  admissionQueueLimit: 0,
9730
10029
  admissionWaitMs: 0,
@@ -9832,6 +10131,206 @@ var init_team_admission = __esm(() => {
9832
10131
  };
9833
10132
  });
9834
10133
 
10134
+ // ../../packages/routing/src/conversation-provider-routing.ts
10135
+ class ConversationProviderRouting {
10136
+ store;
10137
+ constructor(store) {
10138
+ this.store = store;
10139
+ }
10140
+ getPreference(conversationKey) {
10141
+ return this.store.getPreference(conversationKey);
10142
+ }
10143
+ getBlock(conversationKey, provider) {
10144
+ return this.store.getBlock(conversationKey, provider);
10145
+ }
10146
+ selectProvider(conversationKey, provider, now) {
10147
+ this.store.upsertPreference(conversationKey, {
10148
+ lastSeenAt: now,
10149
+ promotionDeclined: false,
10150
+ provider
10151
+ });
10152
+ }
10153
+ declinePromotion(conversationKey, now) {
10154
+ const preference = this.store.getPreference(conversationKey);
10155
+ if (!preference)
10156
+ return;
10157
+ this.store.upsertPreference(conversationKey, {
10158
+ ...preference,
10159
+ lastSeenAt: now,
10160
+ promotionDeclined: true
10161
+ });
10162
+ }
10163
+ recordBlock(conversationKey, provider, block, now) {
10164
+ this.store.upsertBlock(conversationKey, provider, {
10165
+ ...block,
10166
+ lastSeenAt: now
10167
+ });
10168
+ }
10169
+ clearBlock(conversationKey, provider) {
10170
+ this.store.deleteBlock(conversationKey, provider);
10171
+ }
10172
+ canOfferProvider(conversationKey, provider, now) {
10173
+ const block = this.store.getBlock(conversationKey, provider);
10174
+ return block === null || block.retryAt !== undefined && block.retryAt <= now;
10175
+ }
10176
+ }
10177
+
10178
+ // ../../packages/routing/src/provider-choice.ts
10179
+ function encodeCapacityDetails(problem) {
10180
+ return Buffer.from(JSON.stringify({
10181
+ kind: problem.kind,
10182
+ blockedProvider: problem.blockedProvider,
10183
+ category: problem.category,
10184
+ choices: problem.choices,
10185
+ wait: problem.retryAt === undefined ? null : { retryAt: problem.retryAt }
10186
+ })).toString("base64url");
10187
+ }
10188
+ function interactiveProviderChoiceRequested(headers3) {
10189
+ return headers3.get(INTERACTIVE_PROVIDER_CHOICE_HEADER) === "v1";
10190
+ }
10191
+ function manualProviderChoiceRequested(headers3) {
10192
+ return headers3.get(PROVIDER_CHOICE_MENU_HEADER) === "v1";
10193
+ }
10194
+ function providerWaitRequested(headers3) {
10195
+ return headers3.get(PROVIDER_WAIT_HEADER) === "v1";
10196
+ }
10197
+ function capacityChoices(candidates, blockedProvider, eligibleProviders) {
10198
+ return candidates.filter((candidate) => candidate.provider !== blockedProvider && eligibleProviders.has(candidate.provider));
10199
+ }
10200
+ function readProviderChoice(headers3, choices) {
10201
+ const selected = headers3.get(PROVIDER_CHOICE_HEADER);
10202
+ return selected && choices.some((choice) => choice.provider === selected) ? selected : null;
10203
+ }
10204
+ function providerPromotionDeclined(headers3) {
10205
+ return headers3.get(PROVIDER_PROMOTION_DECLINED_HEADER) === "v1";
10206
+ }
10207
+ function stripProviderChoiceHeaders(headers3) {
10208
+ const forwarded = new Headers(headers3);
10209
+ forwarded.delete(INTERACTIVE_PROVIDER_CHOICE_HEADER);
10210
+ forwarded.delete(PROVIDER_CHOICE_HEADER);
10211
+ forwarded.delete(PROVIDER_CHOICE_MENU_HEADER);
10212
+ forwarded.delete(PROVIDER_WAIT_HEADER);
10213
+ forwarded.delete(PROVIDER_PROMOTION_DECLINED_HEADER);
10214
+ return forwarded;
10215
+ }
10216
+ function withServedProviderHeaders(response, choice) {
10217
+ const headers3 = new Headers(response.headers);
10218
+ headers3.set(SERVED_PROVIDER_HEADER, choice.provider);
10219
+ headers3.set(SERVED_MODEL_HEADER, choice.model);
10220
+ return new Response(response.body, {
10221
+ status: response.status,
10222
+ statusText: response.statusText,
10223
+ headers: headers3
10224
+ });
10225
+ }
10226
+ function withProviderPromotionDetails(response, choices) {
10227
+ if (choices.length === 0)
10228
+ return response;
10229
+ const headers3 = new Headers(response.headers);
10230
+ headers3.set(PROVIDER_PROMOTION_DETAILS_HEADER, Buffer.from(JSON.stringify({ choices })).toString("base64url"));
10231
+ return new Response(response.body, {
10232
+ status: response.status,
10233
+ statusText: response.statusText,
10234
+ headers: headers3
10235
+ });
10236
+ }
10237
+ function createProviderCapacityProblem({
10238
+ blockedProvider,
10239
+ category,
10240
+ choices,
10241
+ retryAt
10242
+ }) {
10243
+ const retryAfter = retryAt === undefined ? undefined : String(Math.max(1, Math.ceil((retryAt - Date.now()) / 1000)));
10244
+ return Response.json({
10245
+ type: "urn:agent-smith:provider-capacity:v1",
10246
+ title: "Current provider cannot serve this turn",
10247
+ status: 429,
10248
+ blockedProvider,
10249
+ category,
10250
+ choices,
10251
+ wait: retryAt === undefined ? null : { retryAt }
10252
+ }, {
10253
+ status: 429,
10254
+ headers: {
10255
+ "cache-control": "no-store",
10256
+ "content-type": "application/problem+json",
10257
+ "x-should-retry": "false",
10258
+ ...retryAfter ? { "retry-after": retryAfter } : {},
10259
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10260
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10261
+ kind: "capacity",
10262
+ blockedProvider,
10263
+ category,
10264
+ choices,
10265
+ retryAt
10266
+ })
10267
+ }
10268
+ });
10269
+ }
10270
+ function createProviderChoiceProblem({
10271
+ activeProvider,
10272
+ choices
10273
+ }) {
10274
+ return Response.json({
10275
+ type: "urn:agent-smith:provider-choice:v1",
10276
+ title: "Choose provider for this conversation",
10277
+ status: 409,
10278
+ activeProvider,
10279
+ choices,
10280
+ wait: null
10281
+ }, {
10282
+ status: 409,
10283
+ headers: {
10284
+ "cache-control": "no-store",
10285
+ "content-type": "application/problem+json",
10286
+ "x-should-retry": "false",
10287
+ [PROVIDER_CAPACITY_HEADER]: "v1",
10288
+ [PROVIDER_CAPACITY_DETAILS_HEADER]: encodeCapacityDetails({
10289
+ kind: "manual",
10290
+ blockedProvider: activeProvider,
10291
+ category: "unknown",
10292
+ choices
10293
+ })
10294
+ }
10295
+ });
10296
+ }
10297
+ 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";
10298
+
10299
+ // ../../packages/routing/src/provider-selection.ts
10300
+ function preferProviders(providers2, providerName, pinnedProvider, preferredProvider) {
10301
+ const pinFirst = pinnedProvider ? [
10302
+ ...providers2.filter((provider) => providerName(provider) === pinnedProvider),
10303
+ ...providers2.filter((provider) => providerName(provider) !== pinnedProvider)
10304
+ ] : [...providers2];
10305
+ if (!preferredProvider)
10306
+ return pinFirst;
10307
+ return [
10308
+ ...pinFirst.filter((provider) => providerName(provider) === preferredProvider),
10309
+ ...pinFirst.filter((provider) => providerName(provider) !== preferredProvider)
10310
+ ];
10311
+ }
10312
+ function selectPoolProviders(providers2, providerName, selection) {
10313
+ if (selection.requestedProvider) {
10314
+ return providers2.filter((provider) => providerName(provider) === selection.requestedProvider);
10315
+ }
10316
+ const preferred = preferProviders(providers2, providerName, selection.pinnedProvider, selection.preferredProvider);
10317
+ if (selection.orderedFallback) {
10318
+ const currentProvider = selection.pinnedProvider ?? selection.preferredProvider;
10319
+ const currentIndex = currentProvider ? providers2.findIndex((provider) => providerName(provider) === currentProvider) : -1;
10320
+ return currentIndex < 0 ? [...providers2] : providers2.slice(currentIndex);
10321
+ }
10322
+ return preferred.slice(0, 1);
10323
+ }
10324
+ function higherRankedProviderChoices(choices, selectedProvider, eligibleProviders, canOffer) {
10325
+ const selectedIndex = choices.findIndex((choice) => choice.provider === selectedProvider);
10326
+ if (selectedIndex <= 0)
10327
+ return [];
10328
+ return choices.slice(0, selectedIndex).filter((choice) => eligibleProviders.has(choice.provider) && canOffer(choice.provider));
10329
+ }
10330
+
10331
+ // ../../packages/routing/src/index.ts
10332
+ var init_src10 = () => {};
10333
+
9835
10334
  // ../../packages/proxy/src/response-handler.ts
9836
10335
  function isExpectedResponse(path, response) {
9837
10336
  if (path.startsWith("/.well-known/") && response.status === 404) {
@@ -10435,7 +10934,7 @@ function createUpstreamSender(input) {
10435
10934
  const targetUrl = input.ctx.provider.buildUrl(input.ctx.upstreamPath, input.url.search, input.account);
10436
10935
  return async (token) => {
10437
10936
  const requestAccount = token === input.account.access_token ? input.account : { ...input.account, access_token: token };
10438
- const headers3 = input.ctx.provider.prepareHeaders(input.req.headers, requestAccount);
10937
+ const headers3 = input.ctx.provider.prepareHeaders(stripProviderChoiceHeaders(input.req.headers), requestAccount);
10439
10938
  const upstreamRequestStartedAt = Date.now();
10440
10939
  const response = await makeProxyRequest(targetUrl, input.req.method, headers3, () => input.createBodyStream(input.requestBody), !!input.req.body, input.req.signal);
10441
10940
  return {
@@ -10502,6 +11001,28 @@ async function classifyUpstreamResponse(input, upstream) {
10502
11001
  }
10503
11002
  let response = state.response;
10504
11003
  const forward = createForwarder(input, upstream, state);
11004
+ const interactive = interactiveProviderChoiceRequested(input.req.headers);
11005
+ const capacityBlock = await input.ctx.provider.getCapacityBlock?.(response);
11006
+ if (capacityBlock) {
11007
+ const quotaRejected2 = await isQuotaRejection(response, input.ctx.provider);
11008
+ processProxyResponse(response, input.account, input.ctx, quotaRejected2);
11009
+ const perMinuteRetryAfterMs2 = getPerMinuteRetryAfterMs(response, quotaRejected2);
11010
+ if (interactive && (capacityBlock.category === "request-rate" || capacityBlock.category === "burst")) {
11011
+ if (perMinuteRetryAfterMs2 !== undefined) {
11012
+ return {
11013
+ forward,
11014
+ kind: "per-minute-rate-limit",
11015
+ retryAfterMs: perMinuteRetryAfterMs2
11016
+ };
11017
+ }
11018
+ }
11019
+ return {
11020
+ block: capacityBlock,
11021
+ discard: discardUpstreamResponse(state),
11022
+ forward,
11023
+ kind: "provider-capacity-block"
11024
+ };
11025
+ }
10505
11026
  if (isRequestScopedRateLimit(response, input.ctx.provider)) {
10506
11027
  return { forward, kind: "request-scoped-rate-limit" };
10507
11028
  }
@@ -10567,6 +11088,7 @@ var API_KEY_AUTH_COOLDOWN_MS, ORGANIZATION_QUARANTINE_MS, log20;
10567
11088
  var init_proxy_operations = __esm(() => {
10568
11089
  init_src2();
10569
11090
  init_src3();
11091
+ init_src10();
10570
11092
  init_response_handler();
10571
11093
  init_message_thread();
10572
11094
  init_request_handler();
@@ -10806,6 +11328,9 @@ async function proxySelectedAccounts(request3, accounts) {
10806
11328
  if (attempt.kind === "authentication-failure") {
10807
11329
  return new Response("Bad Gateway", { status: 502 });
10808
11330
  }
11331
+ if (attempt.kind === "provider-capacity-block") {
11332
+ return await attempt.forward();
11333
+ }
10809
11334
  if (attempt.kind === "per-minute-rate-limit") {
10810
11335
  return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
10811
11336
  }
@@ -10874,6 +11399,10 @@ function getRequestRetryAt(request3) {
10874
11399
  const { ctx, teamRequest } = request3;
10875
11400
  return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
10876
11401
  }
11402
+ function getRequestQuotaCapacityBlock(request3) {
11403
+ const { ctx, teamRequest } = request3;
11404
+ return getQuotaCapacityBlock(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet), teamRequest.callerId);
11405
+ }
10877
11406
  var init_proxy_request = __esm(() => {
10878
11407
  init_account_selector();
10879
11408
  init_message_thread();
@@ -10892,32 +11421,139 @@ var init_handlers = __esm(() => {
10892
11421
  init_token_manager();
10893
11422
  });
10894
11423
 
10895
- // ../../packages/proxy/src/provider-pool.ts
10896
- function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
10897
- return {
10898
- body,
10899
- callerId,
10900
- contentType: req.headers.get("content-type"),
10901
- manualAccountName,
10902
- model: requestedModel,
10903
- pinBucket: requestedModel,
10904
- pinScope: `pool:${pool.wire}`,
10905
- provider: `pool:${pool.wire}`,
10906
- sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
10907
- };
11424
+ // ../../packages/capacity/src/index.ts
11425
+ function isProviderBlockCategory(value) {
11426
+ return typeof value === "string" && PROVIDER_BLOCK_CATEGORIES.includes(value);
11427
+ }
11428
+ var PROVIDER_BLOCK_CATEGORIES;
11429
+ var init_src11 = __esm(() => {
11430
+ PROVIDER_BLOCK_CATEGORIES = [
11431
+ "five-hour-limit",
11432
+ "weekly-limit",
11433
+ "request-rate",
11434
+ "token-allocation",
11435
+ "burst",
11436
+ "dynamic-throughput",
11437
+ "temporary-capacity",
11438
+ "unknown"
11439
+ ];
11440
+ });
11441
+
11442
+ // ../../packages/proxy/src/pool/conversation-provider-routing-store.ts
11443
+ class PoolConversationProviderRoutingStore {
11444
+ dbOps;
11445
+ constructor(dbOps) {
11446
+ this.dbOps = dbOps;
11447
+ }
11448
+ getPreference(conversationKey) {
11449
+ return this.dbOps.getConversationProviderPreference(conversationKey);
11450
+ }
11451
+ upsertPreference(conversationKey, preference) {
11452
+ this.dbOps.upsertConversationProviderPreference(conversationKey, preference.provider, preference.promotionDeclined, preference.lastSeenAt);
11453
+ }
11454
+ getBlock(conversationKey, provider) {
11455
+ const block = this.dbOps.getConversationProviderBlock(conversationKey, provider);
11456
+ if (!block)
11457
+ return null;
11458
+ return {
11459
+ ...block,
11460
+ category: isProviderBlockCategory(block.category) ? block.category : "unknown"
11461
+ };
11462
+ }
11463
+ upsertBlock(conversationKey, provider, block) {
11464
+ this.dbOps.upsertConversationProviderBlock(conversationKey, provider, block.category, block.retryAt, block.lastSeenAt);
11465
+ }
11466
+ deleteBlock(conversationKey, provider) {
11467
+ this.dbOps.deleteConversationProviderBlock(conversationKey, provider);
11468
+ }
11469
+ }
11470
+ var init_conversation_provider_routing_store = __esm(() => {
11471
+ init_src11();
11472
+ });
11473
+
11474
+ // ../../packages/proxy/src/pool/interactive-provider-pool.ts
11475
+ function configuredPoolChoices(pool, fallbackModel) {
11476
+ return pool.providers.map((candidate) => ({
11477
+ model: candidate.model ?? fallbackModel ?? "",
11478
+ provider: candidate.provider.name
11479
+ }));
11480
+ }
11481
+ function eligiblePoolProviders({
11482
+ body,
11483
+ ctx,
11484
+ manualAccountName,
11485
+ meta,
11486
+ pool,
11487
+ req,
11488
+ teamRequest,
11489
+ url
11490
+ }) {
11491
+ const eligibleProviders = new Set;
11492
+ for (const candidate of pool.providers) {
11493
+ const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
11494
+ const prepared = prepareProxyRequest(req, url, candidateContext, { ...meta, model: candidate.model }, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11495
+ if (prepared.request.thread || prepared.accounts.length === 0)
11496
+ continue;
11497
+ const accounts = candidateContext.teamRouter ? candidateContext.teamRouter.eligibleAccounts(prepared.accounts, teamRequest, candidateContext.runtime.teamRouting) : prepared.accounts;
11498
+ if (accounts.length > 0)
11499
+ eligibleProviders.add(candidate.provider.name);
11500
+ }
11501
+ return eligibleProviders;
11502
+ }
11503
+ function eligiblePoolChoices(input, blockedProvider) {
11504
+ return capacityChoices(configuredPoolChoices(input.pool, input.meta.model), blockedProvider, eligiblePoolProviders(input));
11505
+ }
11506
+ function createManualProviderChoiceResponse(input, pinnedAccount, preferredProvider) {
11507
+ const ordered = preferProviders(input.pool.providers, (candidate) => candidate.provider.name, pinnedAccount?.provider, preferredProvider);
11508
+ const activeProvider = ordered[0]?.provider.name ?? input.pool.providers[0]?.provider.name ?? "";
11509
+ const eligible = eligiblePoolProviders(input);
11510
+ return createProviderChoiceProblem({
11511
+ activeProvider,
11512
+ choices: configuredPoolChoices(input.pool, input.meta.model).filter((choice) => eligible.has(choice.provider))
11513
+ });
11514
+ }
11515
+ async function waitOrReturnProviderCapacity({
11516
+ candidates,
11517
+ conversationKey,
11518
+ input,
11519
+ providerWaited,
11520
+ retry,
11521
+ routing
11522
+ }) {
11523
+ if (!providerWaitRequested(input.req.headers) || providerWaited || !candidates[0]) {
11524
+ return null;
11525
+ }
11526
+ const provider = candidates[0].provider.name;
11527
+ const blocked = conversationKey ? routing.getBlock(conversationKey, provider) : null;
11528
+ const retryAt = blocked?.retryAt;
11529
+ const holdMs = input.ctx.runtime.teamRouting.holdSeconds * 1000;
11530
+ if (input.ctx.quotaHold && retryAt !== undefined && retryAt > Date.now() && holdMs > 0 && retryAt - Date.now() <= holdMs) {
11531
+ await input.ctx.quotaHold.waitUntil(retryAt, input.req.signal);
11532
+ return await retry();
11533
+ }
11534
+ if (retryAt === undefined || retryAt > Date.now()) {
11535
+ return createProviderCapacityProblem({
11536
+ blockedProvider: provider,
11537
+ category: blocked?.category ?? "unknown",
11538
+ choices: eligiblePoolChoices(input, provider),
11539
+ ...retryAt !== undefined && { retryAt }
11540
+ });
11541
+ }
11542
+ return null;
10908
11543
  }
11544
+ var init_interactive_provider_pool = __esm(() => {
11545
+ init_src10();
11546
+ init_handlers();
11547
+ init_proxy_request();
11548
+ });
11549
+
11550
+ // ../../packages/proxy/src/pool/provider-pool-attempts.ts
10909
11551
  function preferPinnedAccount(accounts, pinnedId) {
10910
11552
  if (!pinnedId)
10911
11553
  return accounts;
10912
11554
  const pinned = accounts.find((account2) => account2.id === pinnedId);
10913
11555
  return pinned ? [pinned, ...accounts.filter((account2) => account2.id !== pinned.id)] : accounts;
10914
11556
  }
10915
- function preferPinnedProvider(pool, pinnedAccount) {
10916
- if (!pinnedAccount)
10917
- return pool.providers;
10918
- const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
10919
- return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
10920
- }
10921
11557
  async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10922
11558
  for (let index = 0;index < accounts.length; index += 1) {
10923
11559
  const account2 = accounts[index];
@@ -10931,6 +11567,15 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10931
11567
  response: new Response("Bad Gateway", { status: 502 })
10932
11568
  };
10933
11569
  }
11570
+ if (attempt.kind === "provider-capacity-block") {
11571
+ await attempt.discard?.();
11572
+ if (accounts[index + 1])
11573
+ continue;
11574
+ if (allowNextProvider) {
11575
+ return { block: attempt.block, kind: "next-provider" };
11576
+ }
11577
+ return { block: attempt.block, kind: "capacity-block" };
11578
+ }
10934
11579
  if (attempt.kind === "per-minute-rate-limit") {
10935
11580
  return {
10936
11581
  kind: "response",
@@ -10987,77 +11632,303 @@ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10987
11632
  response: new Response("Bad Gateway", { status: 502 })
10988
11633
  };
10989
11634
  }
10990
- async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
10991
- const firstCandidate = pool.providers[0];
10992
- if (!firstCandidate) {
10993
- return new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 });
11635
+ function resolvePoolCandidateResult({
11636
+ candidate,
11637
+ candidateContext,
11638
+ conversationKey,
11639
+ interactive,
11640
+ interactiveInput,
11641
+ providerPreference,
11642
+ requestedChoice,
11643
+ result,
11644
+ routing
11645
+ }) {
11646
+ if (result.kind === "capacity-block") {
11647
+ if (conversationKey) {
11648
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11649
+ }
11650
+ return createProviderCapacityProblem({
11651
+ blockedProvider: candidate.provider.name,
11652
+ category: result.block.category,
11653
+ choices: eligiblePoolChoices(interactiveInput, candidate.provider.name),
11654
+ ...result.block.retryAt !== undefined && {
11655
+ retryAt: result.block.retryAt
11656
+ }
11657
+ });
10994
11658
  }
10995
- const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
10996
- const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
10997
- const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
10998
- const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11659
+ if (result.kind !== "response")
11660
+ return null;
11661
+ if (result.account) {
11662
+ if (conversationKey) {
11663
+ routing.clearBlock(conversationKey, candidate.provider.name);
11664
+ }
11665
+ if (conversationKey && requestedChoice) {
11666
+ routing.selectProvider(conversationKey, candidate.provider.name, Date.now());
11667
+ }
11668
+ candidateContext.teamRouter?.rebind(interactiveInput.teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11669
+ }
11670
+ if (!interactive)
11671
+ return result.response;
11672
+ const served = withServedProviderHeaders(result.response, {
11673
+ model: candidate.model ?? interactiveInput.meta.model ?? "",
11674
+ provider: candidate.provider.name
11675
+ });
11676
+ if (!conversationKey || !providerPreference || providerPreference.promotionDeclined || requestedChoice || providerPreference.provider !== candidate.provider.name) {
11677
+ return served;
11678
+ }
11679
+ return withProviderPromotionDetails(served, higherRankedProviderChoices(configuredPoolChoices(interactiveInput.pool, interactiveInput.meta.model), candidate.provider.name, eligiblePoolProviders(interactiveInput), (provider) => routing.canOfferProvider(conversationKey, provider, Date.now())));
11680
+ }
11681
+ function preparePoolCandidate(input, candidate, pinnedId, orderedFallback) {
11682
+ const context2 = createResolvedProxyContext(input.ctx, candidate.provider, input.pool.upstreamPath);
11683
+ 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 });
11684
+ const pooledAccounts = context2.teamRouter ? context2.teamRouter.eligibleAccounts(prepared.accounts, input.teamRequest, context2.runtime.teamRouting) : prepared.accounts;
11685
+ const eligibleAccounts = orderedFallback ? prepared.accounts.filter((account2) => account2.auth_method === "api_key" || pooledAccounts.includes(account2)) : pooledAccounts;
11686
+ return {
11687
+ accounts: preferPinnedAccount(eligibleAccounts, pinnedId),
11688
+ context: context2,
11689
+ request: prepared.request
11690
+ };
11691
+ }
11692
+ async function proxyPoolCandidates({
11693
+ candidates,
11694
+ conversationKey,
11695
+ interactive,
11696
+ interactiveInput,
11697
+ orderedFallback,
11698
+ pinnedId,
11699
+ providerPreference,
11700
+ requestedChoice,
11701
+ routing
11702
+ }) {
10999
11703
  let soonestRetry = null;
11000
11704
  let soonestFleetReset = null;
11001
11705
  let everyCandidateFull = true;
11706
+ let firstCapacityBlock = null;
11002
11707
  let emittedIngress = false;
11003
11708
  const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
11004
11709
  const recordUnserved = (request3) => {
11710
+ firstCapacityBlock ??= getRequestQuotaCapacityBlock(request3);
11005
11711
  everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
11006
11712
  soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
11007
11713
  soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
11008
11714
  };
11009
- const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
11010
11715
  for (const [candidateIndex, candidate] of candidates.entries()) {
11011
- const candidateContext = createResolvedProxyContext(ctx, candidate.provider, pool.upstreamPath);
11012
- const candidateMeta = { ...meta, model: candidate.model };
11013
- const prepared = prepareProxyRequest(req, url, candidateContext, candidateMeta, body, manualAccountName, teamRequest, candidate.model, { allowRevalidationProbe: false, applyTeamRouting: false });
11014
- let accounts = prepared.accounts;
11015
- if (candidateContext.teamRouter) {
11016
- accounts = candidateContext.teamRouter.eligibleAccounts(accounts, teamRequest, candidateContext.runtime.teamRouting);
11017
- }
11018
- accounts = preferPinnedAccount(accounts, pinnedId);
11716
+ const { accounts, context: context2, request: request3 } = preparePoolCandidate(interactiveInput, candidate, pinnedId, orderedFallback);
11019
11717
  if (accounts.length === 0) {
11020
- recordUnserved(prepared.request);
11718
+ recordUnserved(request3);
11021
11719
  continue;
11022
11720
  }
11023
11721
  if (!emittedIngress) {
11024
11722
  requestEvents.emit("event", {
11025
11723
  type: "ingress",
11026
- id: meta.id,
11027
- timestamp: meta.timestamp,
11028
- method: meta.method,
11029
- path: meta.path
11724
+ id: interactiveInput.meta.id,
11725
+ timestamp: interactiveInput.meta.timestamp,
11726
+ method: interactiveInput.meta.method,
11727
+ path: interactiveInput.meta.path
11030
11728
  });
11031
11729
  emittedIngress = true;
11032
11730
  }
11033
11731
  log22.info(`Selected ${accounts.length} accounts: ${accounts.map((account2) => account2.name).join(", ")}`);
11034
- const result = await proxyPoolCandidate(prepared.request, accounts, candidateIndex === 0);
11035
- if (result.kind === "response") {
11036
- if (result.account) {
11037
- candidateContext.teamRouter?.rebind(teamRequest, result.account.id, candidateContext.runtime.teamRouting, candidateContext.provider, candidateContext.dbOps);
11732
+ const result = await proxyPoolCandidate(request3, accounts, candidateIndex < candidates.length - 1);
11733
+ if (result.kind === "next-provider" && result.block) {
11734
+ firstCapacityBlock ??= result.block;
11735
+ if (conversationKey) {
11736
+ routing.recordBlock(conversationKey, candidate.provider.name, result.block, Date.now());
11038
11737
  }
11039
- return result.response;
11040
11738
  }
11041
- recordUnserved(prepared.request);
11042
- }
11043
- if (everyCandidateFull && soonestFleetReset !== null) {
11044
- ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, soonestFleetReset, { blocked: true, holdSeconds: 0 });
11739
+ const response = resolvePoolCandidateResult({
11740
+ candidate,
11741
+ candidateContext: context2,
11742
+ conversationKey,
11743
+ interactive,
11744
+ interactiveInput,
11745
+ providerPreference,
11746
+ requestedChoice,
11747
+ result,
11748
+ routing
11749
+ });
11750
+ if (response)
11751
+ return { kind: "response", response };
11752
+ recordUnserved(request3);
11045
11753
  }
11046
- if (soonestRetry !== null)
11047
- return quotaExhaustionResponse(soonestRetry);
11048
- log22.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11049
- throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
11754
+ return {
11755
+ everyCandidateFull,
11756
+ kind: "unserved",
11757
+ firstCapacityBlock,
11758
+ soonestFleetReset,
11759
+ soonestRetry
11760
+ };
11050
11761
  }
11051
11762
  var log22;
11052
- var init_provider_pool = __esm(() => {
11763
+ var init_provider_pool_attempts = __esm(() => {
11053
11764
  init_src2();
11054
11765
  init_src3();
11766
+ init_src10();
11055
11767
  init_handlers();
11056
11768
  init_proxy_attempts();
11057
11769
  init_proxy_request();
11770
+ init_interactive_provider_pool();
11058
11771
  log22 = new Logger("Proxy");
11059
11772
  });
11060
11773
 
11774
+ // ../../packages/proxy/src/provider-pool.ts
11775
+ function poolTeamRequest(req, body, pool, requestedModel, manualAccountName, callerId) {
11776
+ return {
11777
+ body,
11778
+ callerId,
11779
+ contentType: req.headers.get("content-type"),
11780
+ manualAccountName,
11781
+ model: requestedModel,
11782
+ pinBucket: requestedModel,
11783
+ pinScope: `pool:${pool.wire}`,
11784
+ provider: `pool:${pool.wire}`,
11785
+ sessionId: pool.providers[0]?.provider.getClientSessionId?.(req.headers) ?? null
11786
+ };
11787
+ }
11788
+ function hasOrderedCallerFallback(ctx, callerId) {
11789
+ const routing = ctx.runtime.teamRouting;
11790
+ return routing.enabled && callerId !== undefined && Object.hasOwn(routing.callerProviderFallback, callerId) && routing.callerProviderFallback[callerId] === "ordered";
11791
+ }
11792
+ function prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId) {
11793
+ const firstCandidate = pool.providers[0];
11794
+ if (!firstCandidate) {
11795
+ return {
11796
+ kind: "response",
11797
+ response: new Response(`No provider in provider_pools.${pool.wire} serves the requested model`, { status: 400 })
11798
+ };
11799
+ }
11800
+ const teamRequest = poolTeamRequest(req, body, pool, meta.model, manualAccountName, callerId);
11801
+ const interactiveInput = {
11802
+ body,
11803
+ ctx,
11804
+ manualAccountName,
11805
+ meta,
11806
+ pool,
11807
+ req,
11808
+ teamRequest,
11809
+ url
11810
+ };
11811
+ const firstContext = createResolvedProxyContext(ctx, firstCandidate.provider, pool.upstreamPath);
11812
+ const pinnedId = firstContext.teamRouter?.getPinnedAccountId(teamRequest, firstContext.runtime.teamRouting, firstContext.provider, firstContext.dbOps);
11813
+ const pinnedAccount = pinnedId ? ctx.dbOps.getAccount(pinnedId) : null;
11814
+ const conversationKey = firstContext.teamRouter?.getConversationProviderKey(teamRequest, firstContext.runtime.teamRouting);
11815
+ const routing = new ConversationProviderRouting(new PoolConversationProviderRoutingStore(ctx.dbOps));
11816
+ let providerPreference = conversationKey ? routing.getPreference(conversationKey) : null;
11817
+ const interactive = interactiveProviderChoiceRequested(req.headers);
11818
+ if (interactive && conversationKey && providerPreference && providerPromotionDeclined(req.headers)) {
11819
+ routing.declinePromotion(conversationKey, Date.now());
11820
+ providerPreference = routing.getPreference(conversationKey);
11821
+ }
11822
+ const requestedChoice = interactive ? req.headers.get("x-agent-smith-provider-choice") : null;
11823
+ const configuredChoices = configuredPoolChoices(pool, meta.model);
11824
+ if (requestedChoice && !readProviderChoice(req.headers, configuredChoices)) {
11825
+ return {
11826
+ kind: "response",
11827
+ response: new Response("Selected provider is not available for this request", { status: 409 })
11828
+ };
11829
+ }
11830
+ if (interactive && manualProviderChoiceRequested(req.headers)) {
11831
+ return {
11832
+ kind: "response",
11833
+ response: createManualProviderChoiceResponse(interactiveInput, pinnedAccount, providerPreference?.provider)
11834
+ };
11835
+ }
11836
+ const orderedFallback = !interactive && hasOrderedCallerFallback(ctx, callerId);
11837
+ return {
11838
+ candidates: selectPoolProviders(pool.providers, (candidate) => candidate.provider.name, {
11839
+ orderedFallback,
11840
+ pinnedProvider: pinnedAccount?.provider,
11841
+ preferredProvider: providerPreference?.provider,
11842
+ requestedProvider: requestedChoice
11843
+ }),
11844
+ conversationKey,
11845
+ interactive,
11846
+ interactiveInput,
11847
+ kind: "selection",
11848
+ orderedFallback,
11849
+ pinnedId,
11850
+ providerPreference,
11851
+ requestedChoice,
11852
+ routing
11853
+ };
11854
+ }
11855
+ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, providerWaited = false) {
11856
+ const selection = prepareProviderPoolSelection(req, url, ctx, meta, body, pool, manualAccountName, callerId);
11857
+ if (selection.kind === "response")
11858
+ return selection.response;
11859
+ const {
11860
+ candidates,
11861
+ conversationKey,
11862
+ interactive,
11863
+ interactiveInput,
11864
+ orderedFallback,
11865
+ pinnedId,
11866
+ providerPreference,
11867
+ requestedChoice,
11868
+ routing
11869
+ } = selection;
11870
+ if (interactive) {
11871
+ const waitResponse = await waitOrReturnProviderCapacity({
11872
+ candidates,
11873
+ conversationKey,
11874
+ input: interactiveInput,
11875
+ providerWaited,
11876
+ retry: () => proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountName, callerId, true),
11877
+ routing
11878
+ });
11879
+ if (waitResponse)
11880
+ return waitResponse;
11881
+ }
11882
+ const candidateAttempt = await proxyPoolCandidates({
11883
+ candidates,
11884
+ conversationKey,
11885
+ interactive,
11886
+ interactiveInput,
11887
+ orderedFallback,
11888
+ pinnedId,
11889
+ providerPreference,
11890
+ requestedChoice,
11891
+ routing
11892
+ });
11893
+ if (candidateAttempt.kind === "response")
11894
+ return candidateAttempt.response;
11895
+ if (candidateAttempt.everyCandidateFull && candidateAttempt.soonestFleetReset !== null) {
11896
+ ctx.seatAlerts?.allAccountsFull(`provider_pools.${pool.wire}`, candidateAttempt.soonestFleetReset, { blocked: true, holdSeconds: 0 });
11897
+ }
11898
+ if (interactive) {
11899
+ const blockedProvider = candidates[0]?.provider.name;
11900
+ if (blockedProvider) {
11901
+ const block = candidateAttempt.firstCapacityBlock;
11902
+ const retryAt = block?.retryAt ?? candidateAttempt.soonestRetry;
11903
+ return createProviderCapacityProblem({
11904
+ blockedProvider,
11905
+ category: block?.category ?? "unknown",
11906
+ choices: eligiblePoolChoices(interactiveInput, blockedProvider),
11907
+ ...retryAt !== null && retryAt !== undefined && {
11908
+ retryAt
11909
+ }
11910
+ });
11911
+ }
11912
+ }
11913
+ if (candidateAttempt.soonestRetry !== null) {
11914
+ return quotaExhaustionResponse(candidateAttempt.soonestRetry);
11915
+ }
11916
+ log23.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11917
+ throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, `pool:${pool.wire}`);
11918
+ }
11919
+ var log23;
11920
+ var init_provider_pool = __esm(() => {
11921
+ init_src2();
11922
+ init_src3();
11923
+ init_src10();
11924
+ init_handlers();
11925
+ init_proxy_attempts();
11926
+ init_conversation_provider_routing_store();
11927
+ init_interactive_provider_pool();
11928
+ init_provider_pool_attempts();
11929
+ log23 = new Logger("Proxy");
11930
+ });
11931
+
11061
11932
  // ../../packages/proxy/src/seat-alerts.ts
11062
11933
  function alertWhenFleetFull(meta, ctx, holdSeconds) {
11063
11934
  const resetAt2 = getSoonestQuotaReset(meta, ctx);
@@ -11080,10 +11951,10 @@ class SeatAlerts {
11080
11951
  this.config = config;
11081
11952
  this.send = send;
11082
11953
  if (config.email && !(config.emailFrom && config.resendApiKey)) {
11083
- log23.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11954
+ log24.warn("alerts.email is set without alerts.email_from and alerts.resend_api_key: email alerts are off");
11084
11955
  }
11085
11956
  if (!config.slackBotToken !== !config.slackChannel) {
11086
- log23.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11957
+ log24.warn("alerts.slack_bot_token and alerts.slack_channel go together: Slack bot alerts are off");
11087
11958
  }
11088
11959
  }
11089
11960
  extraUsageSpent(account2, provider) {
@@ -11106,7 +11977,7 @@ class SeatAlerts {
11106
11977
  });
11107
11978
  }
11108
11979
  notify(alert) {
11109
- log23.warn(alert.text);
11980
+ log24.warn(alert.text);
11110
11981
  for (const delivery of this.deliveries(alert)) {
11111
11982
  trackProxyBackgroundTask(this.deliver(delivery));
11112
11983
  }
@@ -11161,7 +12032,7 @@ class SeatAlerts {
11161
12032
  signal: AbortSignal.timeout(SEND_TIMEOUT_MS)
11162
12033
  });
11163
12034
  if (!response.ok) {
11164
- log23.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
12035
+ log24.warn(`${delivery.channel} alert was refused with HTTP ${response.status}`);
11165
12036
  return;
11166
12037
  }
11167
12038
  if (!delivery.repliesOk)
@@ -11169,19 +12040,19 @@ class SeatAlerts {
11169
12040
  const reply2 = await response.json();
11170
12041
  if (reply2.ok !== true) {
11171
12042
  const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
11172
- log23.warn(`${delivery.channel} alert was refused (${code})`);
12043
+ log24.warn(`${delivery.channel} alert was refused (${code})`);
11173
12044
  }
11174
12045
  } catch (error) {
11175
- log23.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
12046
+ log24.warn(`${delivery.channel} alert could not be sent (${error instanceof Error ? error.name : "unknown error"})`);
11176
12047
  }
11177
12048
  }
11178
12049
  }
11179
- 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;
12050
+ 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;
11180
12051
  var init_seat_alerts = __esm(() => {
11181
12052
  init_src3();
11182
12053
  init_background_tasks();
11183
12054
  init_account_selector();
11184
- log23 = new Logger("SeatAlerts");
12055
+ log24 = new Logger("SeatAlerts");
11185
12056
  SLACK_ERROR_CODE = /^[a-z_]{1,64}$/;
11186
12057
  });
11187
12058
 
@@ -11566,7 +12437,7 @@ function getUsageWorker() {
11566
12437
  }
11567
12438
  if (!usageWorkerInstance) {
11568
12439
  usageWorkerInstance = new UsageWorkerController({
11569
- logger: log24,
12440
+ logger: log25,
11570
12441
  shutdownDelayMs: TIMING.WORKER_SHUTDOWN_DELAY,
11571
12442
  onWorkerMessage: (data) => {
11572
12443
  if (data.type === "summary" && isRequestSummary(data.summary)) {
@@ -11653,7 +12524,7 @@ async function handleProxy(req, url, ctx, callerId) {
11653
12524
  return quotaExhaustionResponse(retryAt);
11654
12525
  }
11655
12526
  if (accounts.length === 0) {
11656
- log24.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12527
+ log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
11657
12528
  throw new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName);
11658
12529
  }
11659
12530
  }
@@ -11664,11 +12535,11 @@ async function handleProxy(req, url, ctx, callerId) {
11664
12535
  method: requestMeta.method,
11665
12536
  path: requestMeta.path
11666
12537
  });
11667
- log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
11668
- log24.info(`Request: ${req.method} ${url.pathname}`);
12538
+ log25.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
12539
+ log25.info(`Request: ${req.method} ${url.pathname}`);
11669
12540
  return await proxySelectedAccounts(request3, accounts);
11670
12541
  }
11671
- var log24, usageWorkerInstance = null;
12542
+ var log25, usageWorkerInstance = null;
11672
12543
  var init_proxy = __esm(() => {
11673
12544
  init_src2();
11674
12545
  init_src3();
@@ -11677,7 +12548,7 @@ var init_proxy = __esm(() => {
11677
12548
  init_provider_pool();
11678
12549
  init_seat_alerts();
11679
12550
  init_usage_worker();
11680
- log24 = new Logger("Proxy");
12551
+ log25 = new Logger("Proxy");
11681
12552
  });
11682
12553
 
11683
12554
  // ../../packages/proxy/src/quota-hold.ts
@@ -12029,7 +12900,7 @@ function endActiveTurn(session, success, error) {
12029
12900
  if (!activeTurn) {
12030
12901
  return;
12031
12902
  }
12032
- log25.debug("Ending tracked websocket turn", {
12903
+ log26.debug("Ending tracked websocket turn", {
12033
12904
  requestId: activeTurn.requestId,
12034
12905
  provider: session.providerName,
12035
12906
  path: session.path,
@@ -12083,7 +12954,7 @@ function startActiveTurn(session, messageType, messageData, parsed) {
12083
12954
  timestamp,
12084
12955
  model: getEventModel(parsed)
12085
12956
  };
12086
- log25.debug("Starting tracked websocket turn", {
12957
+ log26.debug("Starting tracked websocket turn", {
12087
12958
  requestId,
12088
12959
  provider: session.providerName,
12089
12960
  path: session.path,
@@ -12113,7 +12984,7 @@ function handleTrackedUpstreamText(session, data) {
12113
12984
  if (!messageType) {
12114
12985
  return;
12115
12986
  }
12116
- log25.debug("Processing tracked websocket message", {
12987
+ log26.debug("Processing tracked websocket message", {
12117
12988
  provider: session.providerName,
12118
12989
  path: session.path,
12119
12990
  messageType,
@@ -12154,7 +13025,7 @@ function capturePendingRequestBody(session, message) {
12154
13025
  }
12155
13026
  session.pendingRequestBody = Buffer.from(message).toString("base64");
12156
13027
  session.pendingRequestTimestamp = Date.now();
12157
- log25.debug("Captured websocket request body for next tracked turn", {
13028
+ log26.debug("Captured websocket request body for next tracked turn", {
12158
13029
  provider: session.providerName,
12159
13030
  path: session.path,
12160
13031
  size: message.length
@@ -12227,7 +13098,7 @@ async function connectToNextUpstream(ws) {
12227
13098
  plan = await buildWebSocketPlan(new Headers(session.requestHeaders), session.query, session.requestContext, account2);
12228
13099
  } catch (error) {
12229
13100
  session.connecting = false;
12230
- log25.warn("Skipping websocket account during upstream connection", {
13101
+ log26.warn("Skipping websocket account during upstream connection", {
12231
13102
  account: account2.name,
12232
13103
  error: error instanceof Error ? error.message : String(error)
12233
13104
  });
@@ -12286,7 +13157,7 @@ async function connectToNextUpstream(ws) {
12286
13157
  }
12287
13158
  });
12288
13159
  upstream.addEventListener("error", () => {
12289
- log25.warn("Upstream websocket error", {
13160
+ log26.warn("Upstream websocket error", {
12290
13161
  account: plan.account.name,
12291
13162
  provider: session.providerName,
12292
13163
  path: session.path
@@ -12295,7 +13166,7 @@ async function connectToNextUpstream(ws) {
12295
13166
  } catch (error) {
12296
13167
  session.connecting = false;
12297
13168
  clearConnectTimeout(session);
12298
- log25.warn("Failed to create upstream websocket", {
13169
+ log26.warn("Failed to create upstream websocket", {
12299
13170
  account: plan.account.name,
12300
13171
  error: error instanceof Error ? error.message : String(error)
12301
13172
  });
@@ -12340,7 +13211,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12340
13211
  const accounts = selectAccountsForRequest(requestMeta, requestContext, teamRequest);
12341
13212
  if (accounts.length === 0) {
12342
13213
  alertWhenFleetFull(requestMeta, requestContext, 0);
12343
- log25.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
13214
+ log26.warn(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT);
12344
13215
  return errorResponse(new ServiceUnavailableError(ERROR_MESSAGES.NO_ELIGIBLE_ACCOUNT, requestContext.providerName));
12345
13216
  }
12346
13217
  const protocols = getProtocols(req.headers);
@@ -12378,7 +13249,7 @@ function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
12378
13249
  }
12379
13250
  return;
12380
13251
  }
12381
- 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;
13252
+ 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;
12382
13253
  var init_websocket_proxy = __esm(() => {
12383
13254
  init_src2();
12384
13255
  init_src6();
@@ -12389,7 +13260,7 @@ var init_websocket_proxy = __esm(() => {
12389
13260
  init_token_manager();
12390
13261
  init_openai_usage();
12391
13262
  init_seat_alerts();
12392
- log25 = new Logger("WebSocketProxy");
13263
+ log26 = new Logger("WebSocketProxy");
12393
13264
  websocketSessions = new Map;
12394
13265
  textEncoder = new TextEncoder;
12395
13266
  websocketProxyHandler = {
@@ -12503,16 +13374,16 @@ class WindowWarmup {
12503
13374
  try {
12504
13375
  const accessToken = await this.readToken(account2);
12505
13376
  if (!accessToken) {
12506
- log26.warn(`Window warm-up skipped ${account2.name}: no access token`);
13377
+ log27.warn(`Window warm-up skipped ${account2.name}: no access token`);
12507
13378
  return;
12508
13379
  }
12509
13380
  const quota2 = await this.startWindow(provider, account2, accessToken, model);
12510
- log26.info(`Window warm-up started ${account2.name}'s five-hour window`);
13381
+ log27.info(`Window warm-up started ${account2.name}'s five-hour window`);
12511
13382
  if (quota2) {
12512
13383
  recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
12513
13384
  }
12514
13385
  } catch (error) {
12515
- log26.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
13386
+ log27.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
12516
13387
  }
12517
13388
  }
12518
13389
  async startWindow(provider, account2, accessToken, model) {
@@ -12524,18 +13395,18 @@ class WindowWarmup {
12524
13395
  }
12525
13396
  }
12526
13397
  }
12527
- var log26;
13398
+ var log27;
12528
13399
  var init_window_warmup2 = __esm(() => {
12529
13400
  init_src4();
12530
13401
  init_src3();
12531
13402
  init_src();
12532
13403
  init_account_selector();
12533
13404
  init_quota_probe();
12534
- log26 = new Logger("WindowWarmup");
13405
+ log27 = new Logger("WindowWarmup");
12535
13406
  });
12536
13407
 
12537
13408
  // ../../packages/proxy/src/index.ts
12538
- var init_src10 = __esm(() => {
13409
+ var init_src12 = __esm(() => {
12539
13410
  init_background_tasks();
12540
13411
  init_account_selector();
12541
13412
  init_request_handler();
@@ -12776,10 +13647,10 @@ function createRuntimeConfig(config, port) {
12776
13647
  teamRouting: config.getTeamRouting()
12777
13648
  };
12778
13649
  }
12779
- function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
13650
+ function wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
12780
13651
  config.on("change", (change) => {
12781
13652
  if (change.key === "lb_strategy") {
12782
- log27.info("Strategy configuration changed");
13653
+ log28.info("Strategy configuration changed");
12783
13654
  const newStrategyName = config.getStrategy();
12784
13655
  if (newStrategyName === "session") {
12785
13656
  const strategy3 = new SessionStrategy;
@@ -12794,7 +13665,7 @@ function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig
12794
13665
  runtimeConfig2.teamRouting = config.getTeamRouting();
12795
13666
  quotaProbe.reschedule();
12796
13667
  windowWarmup.reschedule();
12797
- log27.info("Team routing configuration changed");
13668
+ log28.info("Team routing configuration changed");
12798
13669
  }
12799
13670
  });
12800
13671
  }
@@ -12829,7 +13700,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12829
13700
  sessionDurationMs: runtimeConfig2.sessionDurationMs
12830
13701
  });
12831
13702
  const dbOps = DatabaseFactory.getInstance();
12832
- const log27 = container.resolve(SERVICE_KEYS.Logger);
13703
+ const log28 = container.resolve(SERVICE_KEYS.Logger);
12833
13704
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
12834
13705
  const asyncWriter = new AsyncDbWriter;
12835
13706
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -12894,11 +13765,11 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12894
13765
  usageWorker: getUsageWorker()
12895
13766
  };
12896
13767
  const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
12897
- wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
13768
+ wireStrategyHotReload(config, log28, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
12898
13769
  return {
12899
13770
  config,
12900
13771
  dbOps,
12901
- log: log27,
13772
+ log: log28,
12902
13773
  asyncWriter,
12903
13774
  apiRouter,
12904
13775
  exposureConfig,
@@ -12907,12 +13778,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12907
13778
  runtimeConfig: runtimeConfig2
12908
13779
  };
12909
13780
  }
12910
- function logInitialAccountStatus(log27, dbOps) {
13781
+ function logInitialAccountStatus(log28, dbOps) {
12911
13782
  const accounts = dbOps.getAllAccounts();
12912
13783
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
12913
- log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
13784
+ log28.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
12914
13785
  if (activeAccounts.length === 0) {
12915
- log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
13786
+ log28.warn("No active accounts available - requests will be refused with a 503 until an account is added");
12916
13787
  }
12917
13788
  }
12918
13789
  var init_bootstrap_runtime = __esm(() => {
@@ -12922,7 +13793,7 @@ var init_bootstrap_runtime = __esm(() => {
12922
13793
  init_src5();
12923
13794
  init_src3();
12924
13795
  init_src7();
12925
- init_src10();
13796
+ init_src12();
12926
13797
  init_exposure();
12927
13798
  });
12928
13799
 
@@ -13148,38 +14019,38 @@ function createServerFetchHandler({
13148
14019
  var init_fetch_handler = __esm(() => {
13149
14020
  init_src2();
13150
14021
  init_src6();
13151
- init_src10();
14022
+ init_src12();
13152
14023
  init_dashboard_assets();
13153
14024
  init_exposure();
13154
14025
  init_oauth_token();
13155
14026
  });
13156
14027
 
13157
14028
  // ../../packages/runtime-server/src/retention-maintenance.ts
13158
- function removeExpiredRequests(config, dbOps, log27, label) {
14029
+ function removeExpiredRequests(config, dbOps, log28, label) {
13159
14030
  try {
13160
14031
  const payloadDays = config.getDataRetentionDays();
13161
14032
  const requestDays = config.getRequestRetentionDays();
13162
14033
  const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
13163
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
14034
+ log28.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
13164
14035
  } catch (err) {
13165
- log27.error(`${label} cleanup error: ${err}`);
14036
+ log28.error(`${label} cleanup error: ${err}`);
13166
14037
  }
13167
14038
  }
13168
14039
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
13169
- const log27 = new Logger("RetentionMaintenance");
13170
- removeExpiredRequests(config, dbOps, log27, "Startup");
14040
+ const log28 = new Logger("RetentionMaintenance");
14041
+ removeExpiredRequests(config, dbOps, log28, "Startup");
13171
14042
  try {
13172
14043
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
13173
- log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
14044
+ log28.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
13174
14045
  } catch (err) {
13175
- log27.error(`Database compaction error: ${err}`);
14046
+ log28.error(`Database compaction error: ${err}`);
13176
14047
  }
13177
14048
  const timer = setInterval(() => {
13178
- removeExpiredRequests(config, dbOps, log27, "Periodic");
14049
+ removeExpiredRequests(config, dbOps, log28, "Periodic");
13179
14050
  try {
13180
14051
  dbOps.checkpointWal();
13181
14052
  } catch (err) {
13182
- log27.error(`WAL checkpoint error: ${err}`);
14053
+ log28.error(`WAL checkpoint error: ${err}`);
13183
14054
  }
13184
14055
  }, intervalMs);
13185
14056
  timer.unref?.();
@@ -13337,7 +14208,7 @@ function startServer(options) {
13337
14208
  const {
13338
14209
  config,
13339
14210
  dbOps,
13340
- log: log27,
14211
+ log: log28,
13341
14212
  apiRouter,
13342
14213
  exposureConfig,
13343
14214
  proxyContext,
@@ -13382,7 +14253,7 @@ function startServer(options) {
13382
14253
  strategy: config.getStrategy(),
13383
14254
  providers: providerRegistry.listProviders()
13384
14255
  }));
13385
- logInitialAccountStatus(log27, dbOps);
14256
+ logInitialAccountStatus(log28, dbOps);
13386
14257
  return {
13387
14258
  port: activePort,
13388
14259
  stop: () => stopServerRuntime(),
@@ -13405,12 +14276,12 @@ async function handleGracefulShutdown(signal) {
13405
14276
  }
13406
14277
  }
13407
14278
  var serverLog, lifecycleLog, serverInstance = null, unixServerInstance = null, stopRetentionJob = null, serverStopPromise = null, deploymentDrain, checkShutdownDrain;
13408
- var init_src11 = __esm(() => {
14279
+ var init_src13 = __esm(() => {
13409
14280
  init_src9();
13410
14281
  init_src2();
13411
14282
  init_src5();
13412
14283
  init_src3();
13413
- init_src10();
14284
+ init_src12();
13414
14285
  init_bootstrap_runtime();
13415
14286
  init_dashboard_assets();
13416
14287
  init_deployment_drain();
@@ -14539,7 +15410,7 @@ var init_themes = __esm(() => {
14539
15410
  THEME_FAMILIES = [...new Set(THEME_REGISTRY.map((t) => t.family))];
14540
15411
  });
14541
15412
  // ../../packages/ui/src/index.ts
14542
- var init_src12 = __esm(() => {
15413
+ var init_src14 = __esm(() => {
14543
15414
  init_account_display();
14544
15415
  init_analytics_display();
14545
15416
  init_TokenUsageDisplay();
@@ -14675,7 +15546,7 @@ var init_account2 = __esm(() => {
14675
15546
  init_src8();
14676
15547
  init_src7();
14677
15548
  init_src();
14678
- init_src12();
15549
+ init_src14();
14679
15550
  init_std_adapter();
14680
15551
  init_browser();
14681
15552
  });
@@ -14726,6 +15597,7 @@ function teamRoutingFileConfig(routing) {
14726
15597
  weekly_max_usage: routing.weeklyMaxUsage,
14727
15598
  weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
14728
15599
  caller_weekly_max_usage: routing.callerWeeklyMaxUsage,
15600
+ caller_provider_fallback: routing.callerProviderFallback,
14729
15601
  admission_cap: routing.admissionCap,
14730
15602
  admission_queue_limit: routing.admissionQueueLimit,
14731
15603
  admission_wait_ms: routing.admissionWaitMs,
@@ -14925,7 +15797,7 @@ var init_accounts2 = __esm(() => {
14925
15797
  init_src8();
14926
15798
  init_src7();
14927
15799
  init_src();
14928
- init_src12();
15800
+ init_src14();
14929
15801
  init_cli();
14930
15802
  init_cli();
14931
15803
  init_local_pool();
@@ -15047,9 +15919,11 @@ import {
15047
15919
  accessSync,
15048
15920
  chmodSync as chmodSync2,
15049
15921
  constants as constants3,
15922
+ copyFileSync,
15050
15923
  existsSync as existsSync3,
15051
15924
  mkdirSync as mkdirSync4,
15052
15925
  readFileSync as readFileSync4,
15926
+ rmSync as rmSync2,
15053
15927
  statSync as statSync3,
15054
15928
  unlinkSync as unlinkSync2,
15055
15929
  writeFileSync as writeFileSync2
@@ -15105,7 +15979,37 @@ function claudeProxyCredential(keepClaudeLogin) {
15105
15979
  export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
15106
15980
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
15107
15981
  }
15108
- function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
15982
+ function claudeCompanionSourceDir() {
15983
+ const bundled = join8(import.meta.dir, "claude-companion");
15984
+ if (existsSync3(join8(bundled, ".claude-plugin", "plugin.json"))) {
15985
+ return bundled;
15986
+ }
15987
+ const source = join8(import.meta.dir, "..", "claude-companion");
15988
+ if (existsSync3(join8(source, ".claude-plugin", "plugin.json"))) {
15989
+ return source;
15990
+ }
15991
+ throw new Error("Agent-smith Claude companion files are missing");
15992
+ }
15993
+ function installClaudeCompanion(binDir) {
15994
+ const sourceDir = claudeCompanionSourceDir();
15995
+ const targetDir = join8(binDir, CLAUDE_COMPANION_DIRNAME);
15996
+ rmSync2(targetDir, { force: true, recursive: true });
15997
+ for (const relativePath of CLAUDE_COMPANION_FILES) {
15998
+ const target = join8(targetDir, relativePath);
15999
+ mkdirSync4(dirname4(target), { recursive: true, mode: 448 });
16000
+ copyFileSync(join8(sourceDir, relativePath), target, constants3.COPYFILE_FICLONE);
16001
+ chmodSync2(target, 384);
16002
+ }
16003
+ for (const directory of [
16004
+ targetDir,
16005
+ join8(targetDir, ".claude-plugin"),
16006
+ join8(targetDir, "hooks")
16007
+ ]) {
16008
+ chmodSync2(directory, 448);
16009
+ }
16010
+ return targetDir;
16011
+ }
16012
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin, companionDir) {
15109
16013
  return `#!/bin/sh
15110
16014
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
15111
16015
  unset AGENT_SMITH_ADMIN_KEY
@@ -15115,7 +16019,7 @@ ${proxyKeySetup(proxyKeyFile)}
15115
16019
  ${claudeProxyCredential(keepClaudeLogin)}
15116
16020
  unset AGENT_SMITH_PROXY_KEY
15117
16021
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
15118
- exec ${shellQuote(claudePath)} "$@"
16022
+ exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
15119
16023
  `;
15120
16024
  }
15121
16025
  function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
@@ -15152,9 +16056,10 @@ async function installClientWrappers(options) {
15152
16056
  if (target === join8(options.binDir, tool))
15153
16057
  throw new Error("A client launcher cannot call itself");
15154
16058
  const wrapper = join8(options.binDir, tool);
16059
+ const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
15155
16060
  writeFileSync2(wrapper, `#!/bin/sh
15156
16061
  ${CONFIG_CLIENT_MARKER}
15157
- exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
16062
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
15158
16063
  `, { encoding: "utf8", mode: 448 });
15159
16064
  chmodSync2(wrapper, 448);
15160
16065
  }
@@ -15167,7 +16072,8 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(
15167
16072
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
15168
16073
  if (options.claudePath) {
15169
16074
  const claude = join8(options.binDir, "claude");
15170
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
16075
+ const companionDir = installClaudeCompanion(options.binDir);
16076
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
15171
16077
  encoding: "utf8",
15172
16078
  mode: 448
15173
16079
  });
@@ -15257,7 +16163,7 @@ function configClientWrappersInstalled(paths2 = {}) {
15257
16163
  const files = ["claude", "codex"].map((name) => join8(binDir, name)).filter(existsSync3);
15258
16164
  return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync4(path, "utf8").includes(CONFIG_CLIENT_MARKER));
15259
16165
  }
15260
- async function launchConfiguredClient(configPath, tool, target, args) {
16166
+ async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
15261
16167
  if (tool !== "claude" && tool !== "codex")
15262
16168
  throw new Error("Unknown Agent Smith client");
15263
16169
  const client2 = readClientRouting(configPath);
@@ -15271,7 +16177,7 @@ async function launchConfiguredClient(configPath, tool, target, args) {
15271
16177
  const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
15272
16178
  const wires = Object.keys(new Config(configPath).getProviderPools());
15273
16179
  const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
15274
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
16180
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
15275
16181
  command = ["/bin/sh", "-c", script, "--", ...args];
15276
16182
  }
15277
16183
  const child = Bun.spawn(command, {
@@ -15347,6 +16253,10 @@ function disableLocalClientRouting(paths2 = {}) {
15347
16253
  if (existsSync3(wrapper))
15348
16254
  unlinkSync2(wrapper);
15349
16255
  }
16256
+ rmSync2(join8(binDir, CLAUDE_COMPANION_DIRNAME), {
16257
+ force: true,
16258
+ recursive: true
16259
+ });
15350
16260
  if (existsSync3(statePath))
15351
16261
  unlinkSync2(statePath);
15352
16262
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
@@ -15373,9 +16283,15 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
15373
16283
  ${ROUTING_END}
15374
16284
  `;
15375
16285
  }
15376
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
16286
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
15377
16287
  var init_local_routing = __esm(() => {
15378
16288
  init_src4();
16289
+ CLAUDE_COMPANION_FILES = [
16290
+ ".claude-plugin/plugin.json",
16291
+ "hooks/hooks.json",
16292
+ "hooks/provider-choice.js",
16293
+ "hooks/register.js"
16294
+ ];
15379
16295
  });
15380
16296
 
15381
16297
  // src/core/logs.ts
@@ -15807,7 +16723,7 @@ import {
15807
16723
  mkdirSync as mkdirSync5,
15808
16724
  readFileSync as readFileSync5,
15809
16725
  realpathSync,
15810
- rmSync as rmSync2,
16726
+ rmSync as rmSync3,
15811
16727
  writeFileSync as writeFileSync3
15812
16728
  } from "fs";
15813
16729
  import { homedir as homedir3 } from "os";
@@ -15921,7 +16837,7 @@ function uninstall(deps) {
15921
16837
  deps.log("No Agent Smith menu bar plugin is installed.");
15922
16838
  return;
15923
16839
  }
15924
- rmSync2(path);
16840
+ rmSync3(path);
15925
16841
  deps.log(`Removed ${path}.`);
15926
16842
  }
15927
16843
  async function runMenubarCommand(argv, overrides = {}) {
@@ -16022,7 +16938,7 @@ function getAvailableThemes() {
16022
16938
  }
16023
16939
  var CONFIG_DIR, CONFIG_FILE, currentThemeId, currentColors, C, NAV_ITEMS, SCREEN_TITLES;
16024
16940
  var init_theme = __esm(() => {
16025
- init_src12();
16941
+ init_src14();
16026
16942
  CONFIG_DIR = join10(homedir4(), ".config", "agent-smith");
16027
16943
  CONFIG_FILE = join10(CONFIG_DIR, "theme.json");
16028
16944
  currentThemeId = loadPersistedThemeId();
@@ -17728,7 +18644,7 @@ function AnalyticsScreen({ refreshKey }) {
17728
18644
  var TIME_RANGES3, VIEW_MODES;
17729
18645
  var init_AnalyticsScreen = __esm(() => {
17730
18646
  init_src2();
17731
- init_src12();
18647
+ init_src14();
17732
18648
  init_core();
17733
18649
  init_theme();
17734
18650
  init_BarChart();
@@ -17760,13 +18676,13 @@ function reducer(state, action) {
17760
18676
  function LogsScreen({ refreshKey }) {
17761
18677
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
17762
18678
  const logKeyCounts = new Map;
17763
- const keyedLogs = state.logs.map((log27) => {
17764
- const baseKey = `${log27.ts}-${log27.level ?? ""}-${log27.msg}`;
18679
+ const keyedLogs = state.logs.map((log28) => {
18680
+ const baseKey = `${log28.ts}-${log28.level ?? ""}-${log28.msg}`;
17765
18681
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
17766
18682
  logKeyCounts.set(baseKey, count);
17767
18683
  return {
17768
18684
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
17769
- log: log27
18685
+ log: log28
17770
18686
  };
17771
18687
  });
17772
18688
  useKeyboard3((key) => {
@@ -17790,8 +18706,8 @@ function LogsScreen({ refreshKey }) {
17790
18706
  }, [refreshKey]);
17791
18707
  useEffect3(() => {
17792
18708
  if (!state.paused && !state.loading) {
17793
- const unsubscribe = streamLogs((log27) => {
17794
- dispatch({ type: "new_entry", log: log27 });
18709
+ const unsubscribe = streamLogs((log28) => {
18710
+ dispatch({ type: "new_entry", log: log28 });
17795
18711
  });
17796
18712
  return () => {
17797
18713
  unsubscribe();
@@ -17844,15 +18760,15 @@ function LogsScreen({ refreshKey }) {
17844
18760
  children: "No logs yet..."
17845
18761
  }) : /* @__PURE__ */ jsx7("box", {
17846
18762
  flexDirection: "column",
17847
- children: keyedLogs.map(({ key, log: log27 }) => {
17848
- const sev = getLogSeverityMeta(log27.level);
18763
+ children: keyedLogs.map(({ key, log: log28 }) => {
18764
+ const sev = getLogSeverityMeta(log28.level);
17849
18765
  return /* @__PURE__ */ jsxs7("text", {
17850
18766
  fg: sev.termColor,
17851
18767
  children: [
17852
18768
  "[",
17853
18769
  sev.label,
17854
18770
  "] ",
17855
- log27.msg
18771
+ log28.msg
17856
18772
  ]
17857
18773
  }, key);
17858
18774
  })
@@ -17863,7 +18779,7 @@ function LogsScreen({ refreshKey }) {
17863
18779
  }
17864
18780
  var MAX_LOGS = 200;
17865
18781
  var init_LogsScreen = __esm(() => {
17866
- init_src12();
18782
+ init_src14();
17867
18783
  init_core();
17868
18784
  init_theme();
17869
18785
  });
@@ -18299,7 +19215,7 @@ function TokenBar({
18299
19215
  }
18300
19216
  var init_OverviewScreen = __esm(() => {
18301
19217
  init_src2();
18302
- init_src12();
19218
+ init_src14();
18303
19219
  init_App();
18304
19220
  init_core();
18305
19221
  init_theme();
@@ -18478,7 +19394,7 @@ function TokenUsageDisplay2({ summary }) {
18478
19394
  });
18479
19395
  }
18480
19396
  var init_TokenUsageDisplay2 = __esm(() => {
18481
- init_src12();
19397
+ init_src14();
18482
19398
  init_theme();
18483
19399
  });
18484
19400
 
@@ -18877,7 +19793,7 @@ function RequestsScreen({ refreshKey }) {
18877
19793
  }
18878
19794
  var init_RequestsScreen = __esm(() => {
18879
19795
  init_src2();
18880
- init_src12();
19796
+ init_src14();
18881
19797
  init_core();
18882
19798
  init_theme();
18883
19799
  init_TokenUsageDisplay2();
@@ -19136,7 +20052,7 @@ function ThemePicker({ onClose }) {
19136
20052
  });
19137
20053
  }
19138
20054
  var init_ThemePicker = __esm(() => {
19139
- init_src12();
20055
+ init_src14();
19140
20056
  init_theme();
19141
20057
  init_TuiPrimitives();
19142
20058
  });
@@ -19533,13 +20449,13 @@ Examples:
19533
20449
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
19534
20450
  if (typeof parsed.logs === "number") {
19535
20451
  const history = await getLogHistory(limit);
19536
- for (const log27 of history) {
19537
- console.log(`[${log27.level}] ${log27.msg}`);
20452
+ for (const log28 of history) {
20453
+ console.log(`[${log28.level}] ${log28.msg}`);
19538
20454
  }
19539
20455
  console.log("--- Live logs ---");
19540
20456
  }
19541
- await streamLogs((log27) => {
19542
- console.log(`[${log27.level}] ${log27.msg}`);
20457
+ await streamLogs((log28) => {
20458
+ console.log(`[${log28.level}] ${log28.msg}`);
19543
20459
  });
19544
20460
  return;
19545
20461
  }
@@ -19638,7 +20554,7 @@ var init_main = __esm(() => {
19638
20554
  init_src2();
19639
20555
  init_src5();
19640
20556
  init_src3();
19641
- init_src11();
20557
+ init_src13();
19642
20558
  init_core();
19643
20559
  init_core();
19644
20560
  init_client_command();