@certalis/agent-smith 0.3.0 → 0.3.3

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
@@ -1792,6 +1792,13 @@ import {
1792
1792
  writeFileSync as writeFileSync2
1793
1793
  } from "fs";
1794
1794
  import { dirname as dirname2 } from "path";
1795
+ function callerWeeklyCap(caps, callerId) {
1796
+ if (!Object.hasOwn(caps, callerId))
1797
+ return;
1798
+ const cap = caps[callerId];
1799
+ const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
1800
+ return typeof shared === "number" ? shared : undefined;
1801
+ }
1795
1802
  function runtimeForProvider(runtime, provider) {
1796
1803
  return {
1797
1804
  ...runtime,
@@ -1978,6 +1985,9 @@ function sanitizeClientRouting(value) {
1978
1985
  if (typeof value.keep_claude_login === "boolean") {
1979
1986
  client.keep_claude_login = value.keep_claude_login;
1980
1987
  }
1988
+ if (typeof value.remote_control === "boolean") {
1989
+ client.remote_control = value.remote_control;
1990
+ }
1981
1991
  if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
1982
1992
  client.pool_ssh_host = value.pool_ssh_host;
1983
1993
  }
@@ -2093,8 +2103,9 @@ function sanitizeTeamRouting(value) {
2093
2103
  if (weeklyMaxUsageByEmail)
2094
2104
  result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
2095
2105
  if (isRecord(value.caller_weekly_max_usage)) {
2096
- const entries = Object.entries(value.caller_weekly_max_usage);
2097
- if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
2106
+ const caps = value.caller_weekly_max_usage;
2107
+ const entries = Object.entries(caps);
2108
+ if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
2098
2109
  result.caller_weekly_max_usage = Object.fromEntries(entries);
2099
2110
  }
2100
2111
  }
@@ -2248,10 +2259,11 @@ function clientRouting(client) {
2248
2259
  ...client?.base_url && { baseUrl: client.base_url },
2249
2260
  ...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
2250
2261
  ...client?.keep_claude_login === true && { keepClaudeLogin: true },
2262
+ ...client?.remote_control === false && { remoteControl: false },
2251
2263
  ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
2252
2264
  };
2253
2265
  }
2254
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
2266
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, isCallerWeeklyCap = (cap) => isFiniteNumber(cap) && cap > 0 && cap <= 0.95, sharesACallerCap = (caps, cap) => typeof cap === "string" && Object.hasOwn(caps, cap) && isCallerWeeklyCap(caps[cap]), POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
2255
2267
  var init_src4 = __esm(() => {
2256
2268
  init_src2();
2257
2269
  init_src3();
@@ -2828,10 +2840,11 @@ function addPerformanceIndexes(db) {
2828
2840
  `);
2829
2841
  log3.info("Added index: idx_accounts_paused");
2830
2842
  db.run(`
2831
- CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp
2832
- ON requests(account_used, timestamp DESC)
2843
+ CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
2844
+ ON requests(account_used, timestamp DESC, cost_usd)
2833
2845
  `);
2834
- log3.info("Added index: idx_requests_account_timestamp");
2846
+ db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
2847
+ log3.info("Added index: idx_requests_account_timestamp_cost");
2835
2848
  db.run(`
2836
2849
  CREATE INDEX IF NOT EXISTS idx_requests_cost_model
2837
2850
  ON requests(cost_usd, model, timestamp DESC)
@@ -3222,6 +3235,13 @@ function ensureAccountExtensionColumns(db) {
3222
3235
  }
3223
3236
  }
3224
3237
  }
3238
+ function backfillRequestLinkageColumnsOnce(db) {
3239
+ const { user_version } = db.query("PRAGMA user_version").get();
3240
+ if (user_version >= LINKAGE_BACKFILLED_VERSION)
3241
+ return;
3242
+ backfillRequestLinkageColumns(db);
3243
+ db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
3244
+ }
3225
3245
  function backfillRequestLinkageColumns(db) {
3226
3246
  const missingCount = db.query(`
3227
3247
  SELECT COUNT(*) AS count
@@ -3645,7 +3665,7 @@ function runMigrations(db) {
3645
3665
  migrateRequestsTable(db, requestsInfo);
3646
3666
  }
3647
3667
  ensureRequestLinkageColumns(db);
3648
- backfillRequestLinkageColumns(db);
3668
+ backfillRequestLinkageColumnsOnce(db);
3649
3669
  db.run("DROP TABLE IF EXISTS agent_preferences");
3650
3670
  db.run("DROP TABLE IF EXISTS oauth_sessions");
3651
3671
  db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
@@ -3661,7 +3681,7 @@ function runMigrations(db) {
3661
3681
  db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
3662
3682
  addPerformanceIndexes(db);
3663
3683
  }
3664
- var log5;
3684
+ var log5, LINKAGE_BACKFILLED_VERSION = 1;
3665
3685
  var init_migrations = __esm(() => {
3666
3686
  init_src3();
3667
3687
  init_src();
@@ -4508,7 +4528,7 @@ function requestLinkageFromPayload(payload) {
4508
4528
  clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
4509
4529
  };
4510
4530
  }
4511
- var log6, RequestRepository;
4531
+ var log6, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
4512
4532
  var init_request_repository = __esm(() => {
4513
4533
  init_src3();
4514
4534
  init_src();
@@ -4883,11 +4903,10 @@ var init_request_repository = __esm(() => {
4883
4903
  return errors.map((e) => e.error_message);
4884
4904
  }
4885
4905
  sumAccountCostSince(accountId, since) {
4886
- return this.get(`
4887
- SELECT SUM(cost_usd) AS cost
4888
- FROM requests
4889
- WHERE account_used = ? AND timestamp >= ?
4890
- `, [accountId, since])?.cost ?? 0;
4906
+ return this.get(ACCOUNT_COST_SINCE_SQL, [
4907
+ accountId,
4908
+ since
4909
+ ])?.cost ?? 0;
4891
4910
  }
4892
4911
  getRequestsByAccount(since) {
4893
4912
  const whereClause = since ? "WHERE r.timestamp > ?" : "";
@@ -4911,23 +4930,26 @@ var init_request_repository = __esm(() => {
4911
4930
  successRate: row.success_rate
4912
4931
  }));
4913
4932
  }
4914
- deleteOlderThan(cutoffTs) {
4915
- return this.runWithChanges(`DELETE FROM requests WHERE timestamp < ?`, [
4916
- cutoffTs
4917
- ]);
4933
+ deleteOlderThan(cutoffTs, limit) {
4934
+ return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
4935
+ SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
4936
+ )`, [cutoffTs, limit]);
4918
4937
  }
4919
4938
  clear() {
4920
4939
  return this.runWithChanges(`DELETE FROM requests`);
4921
4940
  }
4922
- deleteOrphanedPayloads() {
4923
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
4924
- }
4925
- deletePayloadsOlderThan(cutoffTs) {
4926
- return this.runWithChanges(`DELETE FROM request_payloads
4927
- WHERE EXISTS (
4928
- SELECT 1 FROM requests r
4929
- WHERE r.id = request_payloads.id AND r.timestamp < ?
4930
- )`, [cutoffTs]);
4941
+ deleteOldestExpiredPayloads(cutoffTs, limit) {
4942
+ const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
4943
+ FROM request_payloads rp
4944
+ LEFT JOIN requests r ON r.id = rp.id
4945
+ ORDER BY rp.rowid
4946
+ LIMIT ?`, [limit]);
4947
+ const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
4948
+ const expiredCount = firstLive === -1 ? oldest.length : firstLive;
4949
+ const lastExpired = oldest[expiredCount - 1];
4950
+ if (!lastExpired)
4951
+ return 0;
4952
+ return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
4931
4953
  }
4932
4954
  };
4933
4955
  });
@@ -5056,6 +5078,7 @@ var init_strategy_repository = __esm(() => {
5056
5078
  import { Database } from "bun:sqlite";
5057
5079
  import { mkdirSync as mkdirSync3, statfsSync } from "fs";
5058
5080
  import { dirname as dirname3 } from "path";
5081
+ import { setImmediate as yieldToEventLoop } from "timers/promises";
5059
5082
  function freeDiskBytes(directory) {
5060
5083
  const { bavail, bsize } = statfsSync(directory);
5061
5084
  return bavail * bsize;
@@ -5075,7 +5098,7 @@ class DatabaseOperations {
5075
5098
  conversationProviderPreferences;
5076
5099
  strategy;
5077
5100
  stats;
5078
- constructor(dbPath) {
5101
+ constructor(dbPath, { migrate = true } = {}) {
5079
5102
  const resolvedPath = dbPath ?? resolveDbPath();
5080
5103
  this.dbPath = resolvedPath;
5081
5104
  const dir = dirname3(resolvedPath);
@@ -5085,8 +5108,11 @@ class DatabaseOperations {
5085
5108
  this.db.exec("PRAGMA journal_mode = WAL");
5086
5109
  this.db.exec("PRAGMA busy_timeout = 5000");
5087
5110
  this.db.exec("PRAGMA synchronous = NORMAL");
5088
- ensureSchema(this.db);
5089
- runMigrations(this.db);
5111
+ this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
5112
+ if (migrate) {
5113
+ ensureSchema(this.db);
5114
+ runMigrations(this.db);
5115
+ }
5090
5116
  this.accounts = new AccountRepository(this.db);
5091
5117
  this.analytics = new AnalyticsRepository(this.db);
5092
5118
  this.requests = new RequestRepository(this.db);
@@ -5302,18 +5328,40 @@ class DatabaseOperations {
5302
5328
  getAnalytics(options) {
5303
5329
  return this.analytics.getAnalytics(options);
5304
5330
  }
5305
- cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
5306
- const now = Date.now();
5307
- const payloadCutoff = now - payloadRetentionMs;
5308
- let removedRequests = 0;
5309
- if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5310
- const requestCutoff = now - requestRetentionMs;
5311
- removedRequests = this.requests.deleteOlderThan(requestCutoff);
5331
+ cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
5332
+ const total = { removedRequests: 0, removedPayloads: 0 };
5333
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5334
+ total.removedRequests += batch.removedRequests;
5335
+ total.removedPayloads += batch.removedPayloads;
5336
+ }
5337
+ return total;
5338
+ }
5339
+ async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
5340
+ batchRows = CLEANUP_BATCH_ROWS,
5341
+ signal
5342
+ } = {}) {
5343
+ const total = { removedRequests: 0, removedPayloads: 0 };
5344
+ for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
5345
+ total.removedRequests += batch.removedRequests;
5346
+ total.removedPayloads += batch.removedPayloads;
5347
+ await yieldToEventLoop();
5348
+ if (signal?.aborted)
5349
+ break;
5350
+ }
5351
+ return total;
5352
+ }
5353
+ *cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
5354
+ for (;; ) {
5355
+ const now = Date.now();
5356
+ let removedRequests = 0;
5357
+ if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
5358
+ removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
5359
+ }
5360
+ const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
5361
+ yield { removedRequests, removedPayloads };
5362
+ if (removedRequests < batchRows && removedPayloads < batchRows)
5363
+ return;
5312
5364
  }
5313
- const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
5314
- const removedOrphans = this.requests.deleteOrphanedPayloads();
5315
- const removedPayloads = removedPayloadsByAge + removedOrphans;
5316
- return { removedRequests, removedPayloads };
5317
5365
  }
5318
5366
  close() {
5319
5367
  if (this.closed) {
@@ -5352,6 +5400,7 @@ class DatabaseOperations {
5352
5400
  return this.stats;
5353
5401
  }
5354
5402
  }
5403
+ var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
5355
5404
  var init_database_operations = __esm(() => {
5356
5405
  init_migrations();
5357
5406
  init_paths2();
@@ -5364,6 +5413,7 @@ var init_database_operations = __esm(() => {
5364
5413
  init_request_repository();
5365
5414
  init_stats_repository();
5366
5415
  init_strategy_repository();
5416
+ WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
5367
5417
  });
5368
5418
 
5369
5419
  // ../../packages/database/src/factory.ts
@@ -9890,13 +9940,13 @@ var init_logs_history = __esm(() => {
9890
9940
 
9891
9941
  // ../../packages/api/src/handlers/maintenance.ts
9892
9942
  function createCleanupHandler(dbOps, config) {
9893
- return () => {
9943
+ return async () => {
9894
9944
  try {
9895
9945
  const payloadDays = config.getDataRetentionDays();
9896
9946
  const requestDays = config.getRequestRetentionDays();
9897
9947
  const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
9898
9948
  const requestMs = requestDays * 24 * 60 * 60 * 1000;
9899
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadMs, requestMs);
9949
+ const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
9900
9950
  const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
9901
9951
  const cleanupData = {
9902
9952
  removedRequests,
@@ -10415,7 +10465,7 @@ class APIRouter {
10415
10465
  error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
10416
10466
  }, { status: 401 });
10417
10467
  }
10418
- const status = await getCallerPoolStatus(pool, model, callerId);
10468
+ const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
10419
10469
  if (!status) {
10420
10470
  return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
10421
10471
  }
@@ -11445,7 +11495,7 @@ function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
11445
11495
  };
11446
11496
  }
11447
11497
  const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
11448
- const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) && !pacedNight(teamRouting, account2, now, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
11498
+ const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
11449
11499
  return {
11450
11500
  limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
11451
11501
  overridesFleetThreshold: accountOverride !== undefined
@@ -11548,7 +11598,7 @@ function getPoolStatus(provider, model, ctx) {
11548
11598
  admissionWaitMs: config?.admissionWaitMs ?? 0
11549
11599
  };
11550
11600
  }
11551
- function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
11601
+ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
11552
11602
  const strategy3 = ctx.providerRegistry.getProvider(provider);
11553
11603
  if (!strategy3)
11554
11604
  throw new Error(`Unknown provider '${provider}'`);
@@ -11556,7 +11606,7 @@ function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts)
11556
11606
  const now = Date.now();
11557
11607
  const accounts = (config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"))).filter((account2) => servesCaller(account2, ctx, callerId));
11558
11608
  const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
11559
- const nightBudget = callerNightBudget(strategy3, accounts, model, callerId, ctx, now);
11609
+ const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
11560
11610
  return {
11561
11611
  poolEnabled: config.enabled,
11562
11612
  servableSeats,
@@ -11988,7 +12038,7 @@ class ProviderSupply {
11988
12038
  admissionWaitMs: context2.runtime.pool.admissionWaitMs
11989
12039
  };
11990
12040
  if (route.scope.kind === "pool-route" && route.callerId) {
11991
- return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
12041
+ return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
11992
12042
  }
11993
12043
  return getPoolStatus(this.name, mapped, context2);
11994
12044
  }
@@ -12890,7 +12940,9 @@ async function getCallerPoolStatus(input) {
12890
12940
  retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
12891
12941
  holdSeconds: input.holdSeconds,
12892
12942
  admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
12893
- nightBudget: callerNightBudget2(statuses, Date.now())
12943
+ ...input.route.readNightBudget && {
12944
+ nightBudget: callerNightBudget2(statuses, Date.now())
12945
+ }
12894
12946
  };
12895
12947
  }
12896
12948
  function toCents(value) {
@@ -14719,6 +14771,18 @@ var init_router_bridge = __esm(() => {
14719
14771
  // ../../packages/proxy/src/usage-worker.ts
14720
14772
  import { isAbsolute, resolve as resolve2 } from "path";
14721
14773
  import { pathToFileURL } from "url";
14774
+ function heldBytesOf(message) {
14775
+ switch (message.type) {
14776
+ case "start":
14777
+ return MESSAGE_OVERHEAD_BYTES + (message.requestBody?.length ?? 0);
14778
+ case "chunk":
14779
+ return MESSAGE_OVERHEAD_BYTES + message.data.byteLength;
14780
+ case "end":
14781
+ return MESSAGE_OVERHEAD_BYTES + (message.responseBody?.length ?? 0);
14782
+ default:
14783
+ return MESSAGE_OVERHEAD_BYTES;
14784
+ }
14785
+ }
14722
14786
  function noop() {}
14723
14787
  function createDefaultLogger() {
14724
14788
  return {
@@ -14772,6 +14836,7 @@ class UsageWorkerController {
14772
14836
  readyTimeoutMs;
14773
14837
  ackTimeoutMs;
14774
14838
  shutdownDelayMs;
14839
+ maxHeldBytes;
14775
14840
  logger;
14776
14841
  worker = null;
14777
14842
  ready = false;
@@ -14781,6 +14846,9 @@ class UsageWorkerController {
14781
14846
  shutdownTimer = null;
14782
14847
  queuedMessages = [];
14783
14848
  pendingAcks = new Map;
14849
+ heldBytes = 0;
14850
+ droppedRequestIds = new Set;
14851
+ droppedRequests = 0;
14784
14852
  shutdownPromise = null;
14785
14853
  resolveShutdown = null;
14786
14854
  rejectShutdown = null;
@@ -14791,6 +14859,7 @@ class UsageWorkerController {
14791
14859
  this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
14792
14860
  this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
14793
14861
  this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
14862
+ this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
14794
14863
  this.logger = options.logger ?? createDefaultLogger();
14795
14864
  this.startWorker();
14796
14865
  }
@@ -14799,16 +14868,65 @@ class UsageWorkerController {
14799
14868
  this.logger.warn("Dropping usage worker message because the worker is shutting down");
14800
14869
  return;
14801
14870
  }
14871
+ if (!this.admit(message)) {
14872
+ return;
14873
+ }
14802
14874
  const decoratedMessage = {
14803
14875
  ...message,
14804
14876
  messageId: crypto.randomUUID()
14805
14877
  };
14806
14878
  if (!this.ready || !this.worker) {
14807
- this.queuedMessages.push(decoratedMessage);
14879
+ this.queue(decoratedMessage);
14808
14880
  return;
14809
14881
  }
14810
14882
  this.sendMessage(decoratedMessage);
14811
14883
  }
14884
+ admit(message) {
14885
+ if (message.type === "shutdown") {
14886
+ return true;
14887
+ }
14888
+ if (this.droppedRequestIds.has(message.requestId)) {
14889
+ if (message.type === "end") {
14890
+ this.droppedRequestIds.delete(message.requestId);
14891
+ }
14892
+ return false;
14893
+ }
14894
+ if (message.type !== "start") {
14895
+ return true;
14896
+ }
14897
+ if (this.heldBytes + heldBytesOf(message) > this.maxHeldBytes) {
14898
+ if (this.droppedRequests === 0) {
14899
+ this.logger.warn(`Usage worker messages hold ${this.heldBytes} bytes, over the ${this.maxHeldBytes}-byte cap; dropping new requests' usage until the worker catches up`);
14900
+ }
14901
+ this.droppedRequests += 1;
14902
+ this.droppedRequestIds.add(message.requestId);
14903
+ return false;
14904
+ }
14905
+ if (this.droppedRequests > 0) {
14906
+ this.logger.warn(`Dropped the usage of ${this.droppedRequests} requests while usage worker messages were over their byte cap`);
14907
+ this.droppedRequests = 0;
14908
+ }
14909
+ return true;
14910
+ }
14911
+ queue(message) {
14912
+ this.queuedMessages.push(message);
14913
+ this.heldBytes += heldBytesOf(message);
14914
+ }
14915
+ forgetQueuedMessages() {
14916
+ for (const message of this.queuedMessages) {
14917
+ this.heldBytes -= heldBytesOf(message);
14918
+ }
14919
+ this.queuedMessages.length = 0;
14920
+ }
14921
+ forgetPendingAck(messageId) {
14922
+ const pending = this.pendingAcks.get(messageId);
14923
+ if (!pending) {
14924
+ return;
14925
+ }
14926
+ clearTimeout(pending.timer);
14927
+ this.heldBytes -= heldBytesOf(pending.message);
14928
+ this.pendingAcks.delete(messageId);
14929
+ }
14812
14930
  isShuttingDown() {
14813
14931
  return this.shuttingDown;
14814
14932
  }
@@ -14829,7 +14947,7 @@ class UsageWorkerController {
14829
14947
  this.ready = false;
14830
14948
  this.clearReadyTimer();
14831
14949
  this.clearPendingAcks();
14832
- this.queuedMessages.length = 0;
14950
+ this.forgetQueuedMessages();
14833
14951
  const worker = this.worker;
14834
14952
  if (!worker) {
14835
14953
  this.shuttingDown = false;
@@ -14865,7 +14983,7 @@ class UsageWorkerController {
14865
14983
  this.ready = false;
14866
14984
  this.clearReadyTimer();
14867
14985
  this.clearPendingAcks();
14868
- this.queuedMessages.length = 0;
14986
+ this.forgetQueuedMessages();
14869
14987
  if (this.shutdownTimer) {
14870
14988
  clearTimeout(this.shutdownTimer);
14871
14989
  this.shutdownTimer = null;
@@ -14936,10 +15054,9 @@ class UsageWorkerController {
14936
15054
  this.readyTimer = null;
14937
15055
  }
14938
15056
  clearPendingAcks() {
14939
- for (const pending of this.pendingAcks.values()) {
14940
- clearTimeout(pending.timer);
15057
+ for (const messageId of Array.from(this.pendingAcks.keys())) {
15058
+ this.forgetPendingAck(messageId);
14941
15059
  }
14942
- this.pendingAcks.clear();
14943
15060
  }
14944
15061
  handleWorkerMessage(message) {
14945
15062
  if (isShutdownCompleteMessage(message)) {
@@ -14962,12 +15079,7 @@ class UsageWorkerController {
14962
15079
  return;
14963
15080
  }
14964
15081
  if (isAckMessage(message)) {
14965
- const pendingAck = this.pendingAcks.get(message.messageId);
14966
- if (!pendingAck) {
14967
- return;
14968
- }
14969
- clearTimeout(pendingAck.timer);
14970
- this.pendingAcks.delete(message.messageId);
15082
+ this.forgetPendingAck(message.messageId);
14971
15083
  return;
14972
15084
  }
14973
15085
  this.onWorkerMessage?.(message);
@@ -14976,14 +15088,15 @@ class UsageWorkerController {
14976
15088
  if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
14977
15089
  return;
14978
15090
  }
14979
- const queuedMessages = this.queuedMessages.splice(0, this.queuedMessages.length);
15091
+ const queuedMessages = this.queuedMessages.slice();
15092
+ this.forgetQueuedMessages();
14980
15093
  for (const message of queuedMessages) {
14981
15094
  this.sendMessage(message);
14982
15095
  }
14983
15096
  }
14984
15097
  sendMessage(message) {
14985
15098
  if (!this.worker) {
14986
- this.queuedMessages.push(message);
15099
+ this.queue(message);
14987
15100
  return;
14988
15101
  }
14989
15102
  try {
@@ -14997,11 +15110,10 @@ class UsageWorkerController {
14997
15110
  return;
14998
15111
  }
14999
15112
  const timer = setTimeout(() => {
15000
- const pendingAck = this.pendingAcks.get(message.messageId);
15001
- if (!pendingAck) {
15113
+ if (!this.pendingAcks.has(message.messageId)) {
15002
15114
  return;
15003
15115
  }
15004
- this.pendingAcks.delete(message.messageId);
15116
+ this.forgetPendingAck(message.messageId);
15005
15117
  this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
15006
15118
  this.restartWorker();
15007
15119
  }, this.ackTimeoutMs);
@@ -15010,6 +15122,7 @@ class UsageWorkerController {
15010
15122
  message,
15011
15123
  timer
15012
15124
  });
15125
+ this.heldBytes += heldBytesOf(message);
15013
15126
  }
15014
15127
  restartWorker() {
15015
15128
  if (this.shuttingDown) {
@@ -15063,12 +15176,13 @@ class UsageWorkerController {
15063
15176
  resolveShutdown?.();
15064
15177
  }
15065
15178
  }
15066
- var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100;
15179
+ var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100, DEFAULT_MAX_HELD_BYTES, MESSAGE_OVERHEAD_BYTES = 1024;
15067
15180
  var init_usage_worker = __esm(() => {
15068
15181
  init_src2();
15069
15182
  init_src();
15070
15183
  DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15071
15184
  DEFAULT_ACK_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_ACK_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
15185
+ DEFAULT_MAX_HELD_BYTES = Number(process.env.AGENT_SMITH_USAGE_WORKER_MAX_HELD_MB || 256) * 1024 * 1024;
15072
15186
  });
15073
15187
 
15074
15188
  // ../../packages/proxy/src/proxy.ts
@@ -15582,7 +15696,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15582
15696
  admissionWaitMs: status.admissionWaitMs
15583
15697
  };
15584
15698
  },
15585
- getCallerPoolStatus: async (pool, model, callerId) => {
15699
+ getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
15586
15700
  const members = providerRegistry.poolCapacityMembers(pool, model);
15587
15701
  const url = new URL(`http://localhost/v1/pool/${pool}/`);
15588
15702
  const providers2 = members.map(({ provider }) => {
@@ -15592,7 +15706,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
15592
15706
  return supply;
15593
15707
  });
15594
15708
  return getCallerPoolStatus({
15595
- route: createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15709
+ route: {
15710
+ ...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
15711
+ readNightBudget
15712
+ },
15596
15713
  providers: providers2,
15597
15714
  orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
15598
15715
  apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
@@ -15910,35 +16027,49 @@ var init_fetch_handler = __esm(() => {
15910
16027
  });
15911
16028
 
15912
16029
  // ../../packages/runtime-server/src/retention-maintenance.ts
15913
- function removeExpiredRequests(config, dbOps, log27, label) {
15914
- try {
15915
- const payloadDays = config.getDataRetentionDays();
15916
- const requestDays = config.getRequestRetentionDays();
15917
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
15918
- log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
15919
- } catch (err) {
15920
- log27.error(`${label} cleanup error: ${err}`);
15921
- }
16030
+ function retentionWindows(config) {
16031
+ const payloadDays = config.getDataRetentionDays();
16032
+ const requestDays = config.getRequestRetentionDays();
16033
+ return {
16034
+ payloadMs: payloadDays * DAY_MS2,
16035
+ requestMs: requestDays * DAY_MS2,
16036
+ description: `payload=${payloadDays}d, requests=${requestDays}d`
16037
+ };
16038
+ }
16039
+ function logRemoved(log27, label, { removedRequests, removedPayloads }, description) {
16040
+ log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (${description})`);
15922
16041
  }
15923
16042
  function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
15924
16043
  const log27 = new Logger("RetentionMaintenance");
15925
- removeExpiredRequests(config, dbOps, log27, "Startup");
16044
+ try {
16045
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16046
+ logRemoved(log27, "Startup", dbOps.cleanupOldRequests(payloadMs, requestMs), description);
16047
+ } catch (err) {
16048
+ log27.error(`Startup cleanup error: ${err}`);
16049
+ }
15926
16050
  try {
15927
16051
  const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
15928
16052
  log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
15929
16053
  } catch (err) {
15930
16054
  log27.error(`Database compaction error: ${err}`);
15931
16055
  }
16056
+ const stopped = new AbortController;
16057
+ let running;
15932
16058
  const timer = setInterval(() => {
15933
- removeExpiredRequests(config, dbOps, log27, "Periodic");
15934
- try {
15935
- dbOps.checkpointWal();
15936
- } catch (err) {
15937
- log27.error(`WAL checkpoint error: ${err}`);
15938
- }
16059
+ if (running)
16060
+ return;
16061
+ const { payloadMs, requestMs, description } = retentionWindows(config);
16062
+ running = dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs, {
16063
+ signal: stopped.signal
16064
+ }).then((removed) => logRemoved(log27, "Periodic", removed, description), (err) => log27.error(`Periodic cleanup error: ${err}`)).finally(() => {
16065
+ running = undefined;
16066
+ });
15939
16067
  }, intervalMs);
15940
16068
  timer.unref?.();
15941
- return () => clearInterval(timer);
16069
+ return () => {
16070
+ clearInterval(timer);
16071
+ stopped.abort();
16072
+ };
15942
16073
  }
15943
16074
  var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
15944
16075
  var init_retention_maintenance = __esm(() => {
@@ -17802,22 +17933,434 @@ function parseArgs(args) {
17802
17933
  }
17803
17934
  var init_args = () => {};
17804
17935
 
17805
- // src/core/local-routing.ts
17936
+ // src/core/client-relay.ts
17937
+ function forwardedHeaders(original) {
17938
+ const headers3 = new Headers(original);
17939
+ for (const name of UNFORWARDED_REQUEST_HEADERS)
17940
+ headers3.delete(name);
17941
+ return headers3;
17942
+ }
17943
+ async function compressedBody(req, headers3) {
17944
+ const body = new Uint8Array(await req.arrayBuffer());
17945
+ if (body.length === 0)
17946
+ return;
17947
+ if (headers3.has("content-encoding"))
17948
+ return body;
17949
+ headers3.set("content-encoding", "gzip");
17950
+ return Bun.gzipSync(body);
17951
+ }
17952
+ async function fetchUpstream(target, init, unreachable) {
17953
+ try {
17954
+ const upstream = await fetch(target, { ...init, redirect: "manual" });
17955
+ return withSanitizedProxyHeaders(upstream);
17956
+ } catch (error) {
17957
+ const reason = error instanceof Error ? error.message : String(error);
17958
+ return Response.json({
17959
+ type: "error",
17960
+ error: { type: "api_error", message: `${unreachable}: ${reason}` }
17961
+ }, { status: 502 });
17962
+ }
17963
+ }
17964
+ async function relayToPool(req, target, headers3) {
17965
+ const body = await compressedBody(req, headers3);
17966
+ return fetchUpstream(target, { method: req.method, headers: headers3, body, signal: req.signal }, "Agent Smith relay could not reach the pool");
17967
+ }
17968
+ function startClientRelay(remoteBaseUrl) {
17969
+ const remote = remoteBaseUrl.replace(/\/+$/, "");
17970
+ const server = Bun.serve({
17971
+ hostname: "127.0.0.1",
17972
+ port: 0,
17973
+ idleTimeout: 0,
17974
+ fetch(req) {
17975
+ const url = new URL(req.url);
17976
+ return relayToPool(req, `${remote}${url.pathname}${url.search}`, forwardedHeaders(req.headers));
17977
+ }
17978
+ });
17979
+ return {
17980
+ url: `http://127.0.0.1:${server.port}`,
17981
+ stop: () => server.stop(true)
17982
+ };
17983
+ }
17984
+ var UNFORWARDED_REQUEST_HEADERS;
17985
+ var init_client_relay = __esm(() => {
17986
+ init_src6();
17987
+ UNFORWARDED_REQUEST_HEADERS = [
17988
+ "accept-encoding",
17989
+ "connection",
17990
+ "content-length",
17991
+ "host",
17992
+ "keep-alive",
17993
+ "transfer-encoding"
17994
+ ];
17995
+ });
17996
+
17997
+ // src/core/client-forward-proxy.ts
17998
+ import { randomBytes as randomBytes3, timingSafeEqual as timingSafeEqual3, X509Certificate } from "crypto";
17806
17999
  import {
17807
- accessSync as accessSync2,
17808
18000
  chmodSync as chmodSync2,
17809
- constants as constants5,
17810
- copyFileSync,
17811
18001
  existsSync as existsSync3,
17812
18002
  mkdirSync as mkdirSync4,
18003
+ mkdtempSync,
17813
18004
  readFileSync as readFileSync5,
18005
+ renameSync as renameSync3,
17814
18006
  rmSync as rmSync2,
18007
+ writeFileSync as writeFileSync3
18008
+ } from "fs";
18009
+ import {
18010
+ createConnection,
18011
+ createServer
18012
+ } from "net";
18013
+ import { tmpdir as tmpdir3 } from "os";
18014
+ import { join as join9 } from "path";
18015
+ function readCertificate(dir, renewAfter = Number.NEGATIVE_INFINITY) {
18016
+ try {
18017
+ const caFile = join9(dir, "ca.pem");
18018
+ const cert = readFileSync5(join9(dir, "leaf.pem"), "utf8");
18019
+ const key = readFileSync5(join9(dir, "leaf.key"), "utf8");
18020
+ if (!existsSync3(caFile))
18021
+ return;
18022
+ const expiresAt = Date.parse(new X509Certificate(cert).validTo);
18023
+ if (expiresAt - RENEW_BEFORE_MS <= renewAfter)
18024
+ return;
18025
+ return { caFile, cert, key };
18026
+ } catch {
18027
+ return;
18028
+ }
18029
+ }
18030
+ function runOpenssl(dir, args) {
18031
+ let result;
18032
+ try {
18033
+ result = Bun.spawnSync(["openssl", ...args], {
18034
+ cwd: dir,
18035
+ stdout: "ignore",
18036
+ stderr: "pipe"
18037
+ });
18038
+ } catch {
18039
+ throw new Error("Remote Control mode needs openssl on PATH");
18040
+ }
18041
+ if (!result.success)
18042
+ throw new Error(`openssl ${args[0]} failed: ${result.stderr?.toString().trim()}`);
18043
+ }
18044
+ function generateCertificate(dir) {
18045
+ mkdirSync4(dir, { recursive: true, mode: 448 });
18046
+ writeFileSync3(join9(dir, "openssl.cnf"), OPENSSL_CONFIG, { mode: 384 });
18047
+ const newKey = (file) => runOpenssl(dir, [
18048
+ "ecparam",
18049
+ "-name",
18050
+ "prime256v1",
18051
+ "-genkey",
18052
+ "-noout",
18053
+ "-out",
18054
+ file
18055
+ ]);
18056
+ newKey("ca.key");
18057
+ runOpenssl(dir, [
18058
+ "req",
18059
+ "-x509",
18060
+ "-new",
18061
+ "-key",
18062
+ "ca.key",
18063
+ "-sha256",
18064
+ "-days",
18065
+ String(LEAF_DAYS + 1),
18066
+ "-subj",
18067
+ "/CN=Agent Smith Remote Control CA",
18068
+ "-config",
18069
+ "openssl.cnf",
18070
+ "-extensions",
18071
+ "v3_ca",
18072
+ "-out",
18073
+ "ca.pem"
18074
+ ]);
18075
+ newKey("leaf.key");
18076
+ runOpenssl(dir, [
18077
+ "req",
18078
+ "-new",
18079
+ "-key",
18080
+ "leaf.key",
18081
+ "-subj",
18082
+ `/CN=${INTERCEPTED_HOST}`,
18083
+ "-config",
18084
+ "openssl.cnf",
18085
+ "-out",
18086
+ "leaf.csr"
18087
+ ]);
18088
+ runOpenssl(dir, [
18089
+ "x509",
18090
+ "-req",
18091
+ "-in",
18092
+ "leaf.csr",
18093
+ "-CA",
18094
+ "ca.pem",
18095
+ "-CAkey",
18096
+ "ca.key",
18097
+ "-set_serial",
18098
+ `0x${randomBytes3(16).toString("hex")}`,
18099
+ "-days",
18100
+ String(LEAF_DAYS),
18101
+ "-sha256",
18102
+ "-extfile",
18103
+ "openssl.cnf",
18104
+ "-extensions",
18105
+ "v3_leaf",
18106
+ "-out",
18107
+ "leaf.pem"
18108
+ ]);
18109
+ for (const file of ["ca.key", "leaf.csr", "openssl.cnf"])
18110
+ rmSync2(join9(dir, file), { force: true });
18111
+ for (const file of ["ca.pem", "leaf.pem", "leaf.key"])
18112
+ chmodSync2(join9(dir, file), 384);
18113
+ }
18114
+ function ensureInterceptionCertificate(dir, now = Date.now()) {
18115
+ const current = readCertificate(dir, now);
18116
+ if (current)
18117
+ return current;
18118
+ const suffix = `${process.pid}-${randomBytes3(4).toString("hex")}`;
18119
+ const staging = `${dir}.staging-${suffix}`;
18120
+ const retired = `${dir}.retired-${suffix}`;
18121
+ try {
18122
+ generateCertificate(staging);
18123
+ if (existsSync3(dir))
18124
+ renameSync3(dir, retired);
18125
+ renameSync3(staging, dir);
18126
+ } catch (error) {
18127
+ const raced = readCertificate(dir);
18128
+ if (raced)
18129
+ return raced;
18130
+ throw error;
18131
+ } finally {
18132
+ rmSync2(staging, { force: true, recursive: true });
18133
+ rmSync2(retired, { force: true, recursive: true });
18134
+ }
18135
+ const created = readCertificate(dir);
18136
+ if (!created)
18137
+ throw new Error("Agent Smith could not create its interception certificate");
18138
+ return created;
18139
+ }
18140
+ function parseConnectRequest(head) {
18141
+ const [requestLine = "", ...headerLines] = head.split(`\r
18142
+ `);
18143
+ const match = CONNECT_LINE.exec(requestLine);
18144
+ if (!match)
18145
+ return;
18146
+ const port = Number(match[2]);
18147
+ if (port < 1 || port > 65535)
18148
+ return;
18149
+ const authorization = headerLines.map((line) => line.split(/:(.*)/s, 2)).find(([name]) => name?.trim().toLowerCase() === "proxy-authorization");
18150
+ return {
18151
+ host: match[1].replace(/^\[|\]$/g, ""),
18152
+ port,
18153
+ ...authorization?.[1] && {
18154
+ proxyAuthorization: authorization[1].trim()
18155
+ }
18156
+ };
18157
+ }
18158
+ function sameSecret(actual, expected) {
18159
+ if (actual === undefined)
18160
+ return false;
18161
+ const a = Buffer.from(actual);
18162
+ const b = Buffer.from(expected);
18163
+ return a.length === b.length && timingSafeEqual3(a, b);
18164
+ }
18165
+ function poolHeaders(original, deviceKey) {
18166
+ const headers3 = forwardedHeaders(original);
18167
+ headers3.delete("authorization");
18168
+ headers3.set("x-api-key", deviceKey);
18169
+ return headers3;
18170
+ }
18171
+ async function passThrough(req, target) {
18172
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
18173
+ return fetchUpstream(target, {
18174
+ method: req.method,
18175
+ headers: forwardedHeaders(req.headers),
18176
+ body: hasBody ? await req.arrayBuffer() : undefined,
18177
+ signal: req.signal
18178
+ }, "Agent Smith proxy could not reach Anthropic");
18179
+ }
18180
+ function webSocketRelay(req, upstreamUrl) {
18181
+ const headers3 = forwardedHeaders(req.headers);
18182
+ for (const name of [...headers3.keys()])
18183
+ if (name.startsWith("sec-websocket-") || name === "upgrade")
18184
+ headers3.delete(name);
18185
+ const protocols = (req.headers.get("sec-websocket-protocol") ?? "").split(",").map((protocol) => protocol.trim()).filter(Boolean);
18186
+ return {
18187
+ upstreamUrl,
18188
+ headers: Object.fromEntries(headers3),
18189
+ protocols,
18190
+ queued: []
18191
+ };
18192
+ }
18193
+ function refuse(client2, status, extra = "") {
18194
+ client2.end(`HTTP/1.1 ${status}\r
18195
+ ${extra}Connection: close\r
18196
+ \r
18197
+ `);
18198
+ }
18199
+ async function startForwardProxy(options) {
18200
+ const token = randomBytes3(24).toString("hex");
18201
+ const expectedAuthorization = `Basic ${Buffer.from(`${FORWARD_PROXY_USER}:${token}`).toString("base64")}`;
18202
+ const anthropic = (options.anthropicOrigin ?? ANTHROPIC_ORIGIN).replace(/\/+$/, "");
18203
+ const pool = options.poolUrl.replace(/\/+$/, "");
18204
+ const socketDir = mkdtempSync(join9(tmpdir3(), "agent-smith-proxy-"));
18205
+ const interceptSocket = join9(socketDir, "tls.sock");
18206
+ const intercept = Bun.serve({
18207
+ unix: interceptSocket,
18208
+ idleTimeout: 0,
18209
+ tls: { cert: options.certificate.cert, key: options.certificate.key },
18210
+ fetch(req, server) {
18211
+ const url = new URL(req.url);
18212
+ const path = `${url.pathname}${url.search}`;
18213
+ if (POOL_PATHS.has(url.pathname))
18214
+ return relayToPool(req, `${pool}${path}`, poolHeaders(req.headers, options.deviceKey));
18215
+ if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
18216
+ const relay = webSocketRelay(req, `${anthropic.replace(/^http/, "ws")}${path}`);
18217
+ if (server.upgrade(req, { data: relay }))
18218
+ return;
18219
+ return new Response("WebSocket upgrade failed", { status: 400 });
18220
+ }
18221
+ return passThrough(req, `${anthropic}${path}`);
18222
+ },
18223
+ websocket: {
18224
+ open(ws) {
18225
+ const upstream = new WebSocket(ws.data.upstreamUrl, {
18226
+ headers: ws.data.headers,
18227
+ protocols: ws.data.protocols
18228
+ });
18229
+ upstream.binaryType = "arraybuffer";
18230
+ ws.data.upstream = upstream;
18231
+ upstream.onopen = () => {
18232
+ for (const message of ws.data.queued.splice(0))
18233
+ upstream.send(message);
18234
+ };
18235
+ upstream.onmessage = (event) => ws.send(typeof event.data === "string" ? event.data : new Uint8Array(event.data));
18236
+ upstream.onclose = (event) => ws.close(closeCode(event.code), event.reason);
18237
+ upstream.onerror = () => ws.close(1011, "upstream error");
18238
+ },
18239
+ message(ws, message) {
18240
+ const payload = typeof message === "string" ? message : new Uint8Array(message);
18241
+ const upstream = ws.data.upstream;
18242
+ if (upstream?.readyState === WebSocket.OPEN)
18243
+ upstream.send(payload);
18244
+ else
18245
+ ws.data.queued.push(payload);
18246
+ },
18247
+ close(ws, code, reason) {
18248
+ ws.data.upstream?.close(closeCode(code), reason);
18249
+ }
18250
+ }
18251
+ });
18252
+ const sockets = new Set;
18253
+ const front = createServer((client2) => {
18254
+ sockets.add(client2);
18255
+ client2.on("close", () => sockets.delete(client2));
18256
+ client2.on("error", () => client2.destroy());
18257
+ let head = Buffer.alloc(0);
18258
+ const onData = (chunk) => {
18259
+ head = Buffer.concat([head, chunk]);
18260
+ const end = head.indexOf(`\r
18261
+ \r
18262
+ `);
18263
+ if (end === -1) {
18264
+ if (head.length > MAX_CONNECT_HEAD_BYTES)
18265
+ refuse(client2, "431 Request Header Fields Too Large");
18266
+ return;
18267
+ }
18268
+ client2.off("data", onData);
18269
+ client2.pause();
18270
+ const request3 = parseConnectRequest(head.subarray(0, end).toString("latin1"));
18271
+ const rest = head.subarray(end + 4);
18272
+ if (!request3)
18273
+ return refuse(client2, "405 Method Not Allowed");
18274
+ if (!sameSecret(request3.proxyAuthorization, expectedAuthorization))
18275
+ return refuse(client2, "407 Proxy Authentication Required", `Proxy-Authenticate: Basic realm="agent-smith"\r
18276
+ `);
18277
+ const intercepted = request3.host.toLowerCase() === INTERCEPTED_HOST && request3.port === 443;
18278
+ const upstream = createConnection(intercepted ? { path: interceptSocket } : { host: request3.host, port: request3.port });
18279
+ sockets.add(upstream);
18280
+ let connected = false;
18281
+ upstream.on("close", () => {
18282
+ sockets.delete(upstream);
18283
+ if (connected)
18284
+ client2.destroy();
18285
+ });
18286
+ upstream.on("error", () => {
18287
+ if (connected)
18288
+ client2.destroy();
18289
+ else
18290
+ refuse(client2, "502 Bad Gateway");
18291
+ });
18292
+ client2.on("close", () => upstream.destroy());
18293
+ upstream.on("connect", () => {
18294
+ connected = true;
18295
+ client2.write(`HTTP/1.1 200 Connection Established\r
18296
+ \r
18297
+ `);
18298
+ if (rest.length > 0)
18299
+ upstream.write(rest);
18300
+ client2.pipe(upstream);
18301
+ upstream.pipe(client2);
18302
+ client2.resume();
18303
+ });
18304
+ };
18305
+ client2.on("data", onData);
18306
+ });
18307
+ await new Promise((resolve4, reject) => {
18308
+ front.once("error", reject);
18309
+ front.listen(0, "127.0.0.1", () => resolve4());
18310
+ });
18311
+ const { port } = front.address();
18312
+ return {
18313
+ url: `http://${FORWARD_PROXY_USER}:${token}@127.0.0.1:${port}`,
18314
+ stop: () => {
18315
+ front.close();
18316
+ for (const socket of sockets)
18317
+ socket.destroy();
18318
+ intercept.stop(true);
18319
+ rmSync2(socketDir, { force: true, recursive: true });
18320
+ }
18321
+ };
18322
+ }
18323
+ var INTERCEPTED_HOST = "api.anthropic.com", FORWARD_PROXY_USER = "agent-smith", ANTHROPIC_ORIGIN, POOL_PATHS, MAX_CONNECT_HEAD_BYTES = 8192, LEAF_DAYS = 397, RENEW_BEFORE_MS, CONNECT_LINE, OPENSSL_CONFIG, closeCode = (code) => code >= 1000 && code <= 4999 && ![1004, 1005, 1006, 1015].includes(code) ? code : 1000;
18324
+ var init_client_forward_proxy = __esm(() => {
18325
+ init_client_relay();
18326
+ ANTHROPIC_ORIGIN = `https://${INTERCEPTED_HOST}`;
18327
+ POOL_PATHS = new Set(["/v1/messages", "/v1/messages/count_tokens"]);
18328
+ RENEW_BEFORE_MS = 30 * 24 * 60 * 60 * 1000;
18329
+ CONNECT_LINE = /^CONNECT ([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\]):(\d{1,5}) HTTP\/1\.[01]$/;
18330
+ OPENSSL_CONFIG = `[req]
18331
+ distinguished_name = dn
18332
+ [dn]
18333
+ [v3_ca]
18334
+ basicConstraints = critical,CA:TRUE,pathlen:0
18335
+ keyUsage = critical,keyCertSign,cRLSign
18336
+ subjectKeyIdentifier = hash
18337
+ nameConstraints = critical,permitted;DNS:${INTERCEPTED_HOST}
18338
+ [v3_leaf]
18339
+ basicConstraints = critical,CA:FALSE
18340
+ keyUsage = critical,digitalSignature
18341
+ extendedKeyUsage = serverAuth
18342
+ subjectAltName = DNS:${INTERCEPTED_HOST}
18343
+ authorityKeyIdentifier = keyid
18344
+ subjectKeyIdentifier = hash
18345
+ `;
18346
+ });
18347
+
18348
+ // src/core/local-routing.ts
18349
+ import {
18350
+ accessSync as accessSync2,
18351
+ chmodSync as chmodSync3,
18352
+ constants as constants5,
18353
+ copyFileSync,
18354
+ existsSync as existsSync4,
18355
+ mkdirSync as mkdirSync5,
18356
+ readFileSync as readFileSync6,
18357
+ rmSync as rmSync3,
17815
18358
  statSync as statSync4,
17816
18359
  unlinkSync as unlinkSync3,
17817
- writeFileSync as writeFileSync3
18360
+ writeFileSync as writeFileSync4
17818
18361
  } from "fs";
17819
18362
  import { homedir as homedir2 } from "os";
17820
- import { dirname as dirname5, join as join9 } from "path";
18363
+ import { dirname as dirname5, join as join10 } from "path";
17821
18364
  import { fileURLToPath } from "url";
17822
18365
  function shellQuote(value) {
17823
18366
  return `'${value.replaceAll("'", `'"'"'`)}'`;
@@ -17830,7 +18373,7 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
17830
18373
  return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
17831
18374
  }
17832
18375
  function validateProxyKeyFile(proxyKeyFile) {
17833
- const resolvedPath = proxyKeyFile.startsWith("~/") ? join9(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
18376
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join10(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
17834
18377
  let metadata;
17835
18378
  try {
17836
18379
  metadata = statSync4(resolvedPath);
@@ -17843,7 +18386,7 @@ function validateProxyKeyFile(proxyKeyFile) {
17843
18386
  if ((metadata.mode & 63) !== 0) {
17844
18387
  throw new Error("Agent Smith forwarding-key file must be owner-only");
17845
18388
  }
17846
- const key = readFileSync5(resolvedPath, "utf8").trim();
18389
+ const key = readFileSync6(resolvedPath, "utf8").trim();
17847
18390
  if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
17848
18391
  throw new Error("Agent Smith forwarding-key file is invalid");
17849
18392
  }
@@ -17868,32 +18411,32 @@ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_
17868
18411
  }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
17869
18412
  }
17870
18413
  function claudeCompanionSourceDir() {
17871
- const bundled = join9(import.meta.dir, "claude-companion");
17872
- if (existsSync3(join9(bundled, ".claude-plugin", "plugin.json"))) {
18414
+ const bundled = join10(import.meta.dir, "claude-companion");
18415
+ if (existsSync4(join10(bundled, ".claude-plugin", "plugin.json"))) {
17873
18416
  return bundled;
17874
18417
  }
17875
- const source = join9(import.meta.dir, "..", "claude-companion");
17876
- if (existsSync3(join9(source, ".claude-plugin", "plugin.json"))) {
18418
+ const source = join10(import.meta.dir, "..", "claude-companion");
18419
+ if (existsSync4(join10(source, ".claude-plugin", "plugin.json"))) {
17877
18420
  return source;
17878
18421
  }
17879
18422
  throw new Error("Agent-smith Claude companion files are missing");
17880
18423
  }
17881
18424
  function installClaudeCompanion(binDir) {
17882
18425
  const sourceDir = claudeCompanionSourceDir();
17883
- const targetDir = join9(binDir, CLAUDE_COMPANION_DIRNAME);
17884
- rmSync2(targetDir, { force: true, recursive: true });
18426
+ const targetDir = join10(binDir, CLAUDE_COMPANION_DIRNAME);
18427
+ rmSync3(targetDir, { force: true, recursive: true });
17885
18428
  for (const relativePath of CLAUDE_COMPANION_FILES) {
17886
- const target = join9(targetDir, relativePath);
17887
- mkdirSync4(dirname5(target), { recursive: true, mode: 448 });
17888
- copyFileSync(join9(sourceDir, relativePath), target, constants5.COPYFILE_FICLONE);
17889
- chmodSync2(target, 384);
18429
+ const target = join10(targetDir, relativePath);
18430
+ mkdirSync5(dirname5(target), { recursive: true, mode: 448 });
18431
+ copyFileSync(join10(sourceDir, relativePath), target, constants5.COPYFILE_FICLONE);
18432
+ chmodSync3(target, 384);
17890
18433
  }
17891
18434
  for (const directory of [
17892
18435
  targetDir,
17893
- join9(targetDir, ".claude-plugin"),
17894
- join9(targetDir, "hooks")
18436
+ join10(targetDir, ".claude-plugin"),
18437
+ join10(targetDir, "hooks")
17895
18438
  ]) {
17896
- chmodSync2(directory, 448);
18439
+ chmodSync3(directory, 448);
17897
18440
  }
17898
18441
  return targetDir;
17899
18442
  }
@@ -17910,6 +18453,36 @@ export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
17910
18453
  exec ${shellQuote(claudePath)} --plugin-dir ${shellQuote(companionDir)} "$@"
17911
18454
  `;
17912
18455
  }
18456
+ function dropInheritedForwardProxy(env) {
18457
+ for (const name of PROXY_VARIABLES)
18458
+ if (env[name]?.startsWith(`http://${FORWARD_PROXY_USER}:`))
18459
+ delete env[name];
18460
+ }
18461
+ function remoteControlCertificate(configPath) {
18462
+ try {
18463
+ return ensureInterceptionCertificate(join10(dirname5(configPath), "remote-control"));
18464
+ } catch (error) {
18465
+ const reason = error instanceof Error ? error.message : String(error);
18466
+ console.error(`Agent Smith: Remote Control is off for this session: ${reason}`);
18467
+ return;
18468
+ }
18469
+ }
18470
+ function forwardProxyClientEnv(env, proxyUrl, caFile) {
18471
+ const routed = { ...env };
18472
+ for (const name of [
18473
+ "ANTHROPIC_API_KEY",
18474
+ "ANTHROPIC_AUTH_TOKEN",
18475
+ "ANTHROPIC_BASE_URL",
18476
+ "ANTHROPIC_UNIX_SOCKET"
18477
+ ])
18478
+ delete routed[name];
18479
+ for (const name of PROXY_VARIABLES)
18480
+ routed[name] = proxyUrl;
18481
+ routed.NO_PROXY = NO_PROXY_HOSTS;
18482
+ routed.no_proxy = NO_PROXY_HOSTS;
18483
+ routed.NODE_EXTRA_CA_CERTS = caFile;
18484
+ return routed;
18485
+ }
17913
18486
  function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
17914
18487
  const config = [
17915
18488
  'model_provider="agent_smith"',
@@ -17934,58 +18507,58 @@ ${overrides} \\
17934
18507
  async function installClientWrappers(options) {
17935
18508
  if (options.clientConfigPath) {
17936
18509
  const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
17937
- mkdirSync4(options.binDir, { recursive: true, mode: 448 });
18510
+ mkdirSync5(options.binDir, { recursive: true, mode: 448 });
17938
18511
  for (const [tool, target] of [
17939
18512
  ["claude", options.claudePath],
17940
18513
  ["codex", options.codexPath]
17941
18514
  ]) {
17942
18515
  if (!target)
17943
18516
  continue;
17944
- if (target === join9(options.binDir, tool))
18517
+ if (target === join10(options.binDir, tool))
17945
18518
  throw new Error("A client launcher cannot call itself");
17946
- const wrapper = join9(options.binDir, tool);
18519
+ const wrapper = join10(options.binDir, tool);
17947
18520
  const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
17948
- writeFileSync3(wrapper, `#!/bin/sh
18521
+ writeFileSync4(wrapper, `#!/bin/sh
17949
18522
  ${CONFIG_CLIENT_MARKER}
17950
18523
  exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
17951
18524
  `, { encoding: "utf8", mode: 448 });
17952
- chmodSync2(wrapper, 448);
18525
+ chmodSync3(wrapper, 448);
17953
18526
  }
17954
18527
  return;
17955
18528
  }
17956
18529
  if (options.baseUrl && !options.proxyKeyFile) {
17957
18530
  throw new Error("A configured Agent Smith server requires a forwarding key file");
17958
18531
  }
17959
- mkdirSync4(options.binDir, { recursive: true, mode: 448 });
18532
+ mkdirSync5(options.binDir, { recursive: true, mode: 448 });
17960
18533
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
17961
18534
  if (options.claudePath) {
17962
- const claude = join9(options.binDir, "claude");
18535
+ const claude = join10(options.binDir, "claude");
17963
18536
  const companionDir = installClaudeCompanion(options.binDir);
17964
- writeFileSync3(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
18537
+ writeFileSync4(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
17965
18538
  encoding: "utf8",
17966
18539
  mode: 448
17967
18540
  });
17968
- chmodSync2(claude, 448);
18541
+ chmodSync3(claude, 448);
17969
18542
  }
17970
18543
  if (options.codexPath) {
17971
- const codex = join9(options.binDir, "codex");
17972
- writeFileSync3(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
18544
+ const codex = join10(options.binDir, "codex");
18545
+ writeFileSync4(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
17973
18546
  encoding: "utf8",
17974
18547
  mode: 448
17975
18548
  });
17976
- chmodSync2(codex, 448);
18549
+ chmodSync3(codex, 448);
17977
18550
  }
17978
18551
  }
17979
18552
  function defaultShellProfile() {
17980
18553
  const shell = process.env.SHELL?.split("/").pop();
17981
- return join9(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
18554
+ return join10(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
17982
18555
  }
17983
18556
  function getLocalRoutingPaths() {
17984
18557
  const configDir = dirname5(resolveConfigPath());
17985
18558
  return {
17986
- binDir: join9(configDir, "client-bin"),
18559
+ binDir: join10(configDir, "client-bin"),
17987
18560
  shellProfile: defaultShellProfile(),
17988
- statePath: join9(configDir, "client-routing.json")
18561
+ statePath: join10(configDir, "client-routing.json")
17989
18562
  };
17990
18563
  }
17991
18564
  function isExecutable(path) {
@@ -18000,17 +18573,17 @@ function findClientExecutable(name, binDir, path) {
18000
18573
  for (const directory of path.split(":")) {
18001
18574
  if (!directory || directory === binDir)
18002
18575
  continue;
18003
- const candidate = join9(directory, name);
18576
+ const candidate = join10(directory, name);
18004
18577
  if (isExecutable(candidate))
18005
18578
  return candidate;
18006
18579
  }
18007
18580
  throw new Error(`${name} was not found in PATH`);
18008
18581
  }
18009
18582
  function readSavedClientPaths(statePath) {
18010
- if (!existsSync3(statePath))
18583
+ if (!existsSync4(statePath))
18011
18584
  return null;
18012
18585
  try {
18013
- const saved = JSON.parse(readFileSync5(statePath, "utf8"));
18586
+ const saved = JSON.parse(readFileSync6(statePath, "utf8"));
18014
18587
  if (typeof saved === "object" && saved !== null) {
18015
18588
  const { claudePath, codexPath } = saved;
18016
18589
  const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
@@ -18028,10 +18601,10 @@ function installedRoutingStatus(paths2 = {}) {
18028
18601
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
18029
18602
  let shellProfileHasRouting = false;
18030
18603
  try {
18031
- shellProfileHasRouting = existsSync3(shellProfile) && readFileSync5(shellProfile, "utf8").includes(ROUTING_BEGIN);
18604
+ shellProfileHasRouting = existsSync4(shellProfile) && readFileSync6(shellProfile, "utf8").includes(ROUTING_BEGIN);
18032
18605
  } catch {}
18033
18606
  return {
18034
- enabled: shellProfileHasRouting && (existsSync3(join9(binDir, "claude")) || existsSync3(join9(binDir, "codex"))),
18607
+ enabled: shellProfileHasRouting && (existsSync4(join10(binDir, "claude")) || existsSync4(join10(binDir, "codex"))),
18035
18608
  binDir,
18036
18609
  shellProfile
18037
18610
  };
@@ -18048,25 +18621,48 @@ function getLocalRoutingStatus(paths2 = {}) {
18048
18621
  }
18049
18622
  function configClientWrappersInstalled(paths2 = {}) {
18050
18623
  const binDir = paths2.binDir ?? getLocalRoutingPaths().binDir;
18051
- const files = ["claude", "codex"].map((name) => join9(binDir, name)).filter(existsSync3);
18052
- return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync5(path, "utf8").includes(CONFIG_CLIENT_MARKER));
18624
+ const files = ["claude", "codex"].map((name) => join10(binDir, name)).filter(existsSync4);
18625
+ return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync6(path, "utf8").includes(CONFIG_CLIENT_MARKER));
18053
18626
  }
18054
18627
  async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
18055
18628
  if (tool !== "claude" && tool !== "codex")
18056
18629
  throw new Error("Unknown Agent Smith client");
18630
+ dropInheritedForwardProxy(process.env);
18057
18631
  const client2 = readClientRouting(configPath);
18058
- const env = { ...process.env };
18632
+ let env = { ...process.env };
18059
18633
  delete env.AGENT_SMITH_ADMIN_KEY;
18060
18634
  delete env.AGENT_SMITH_PROXY_KEY;
18061
18635
  let command = [target, ...args];
18636
+ let relay;
18637
+ let forwardProxy;
18062
18638
  if (client2.enabled) {
18063
18639
  if (!client2.baseUrl || !client2.proxyKeyFile)
18064
18640
  throw new Error("client.base_url and client.proxy_key_file are required");
18065
18641
  const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
18066
18642
  const wires = Object.keys(new Config(configPath).getProviderPools());
18067
- const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
18068
- const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
18069
- command = ["/bin/sh", "-c", script, "--", ...args];
18643
+ const certificate = tool === "claude" && client2.remoteControl !== false ? remoteControlCertificate(configPath) : undefined;
18644
+ if (certificate) {
18645
+ forwardProxy = await startForwardProxy({
18646
+ poolUrl: proxyBaseUrl(8080, client2.baseUrl, "claude-code", "anthropic-messages", wires),
18647
+ deviceKey: readFileSync6(keyFile, "utf8").trim(),
18648
+ certificate
18649
+ });
18650
+ env = forwardProxyClientEnv(env, forwardProxy.url, certificate.caFile);
18651
+ command = [
18652
+ target,
18653
+ "--settings",
18654
+ BASH_WITHOUT_PROXY_SETTINGS,
18655
+ "--plugin-dir",
18656
+ claudeCompanionDir,
18657
+ ...args
18658
+ ];
18659
+ } else {
18660
+ if (client2.baseUrl.startsWith("https://"))
18661
+ relay = startClientRelay(client2.baseUrl);
18662
+ const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
18663
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
18664
+ command = ["/bin/sh", "-c", script, "--", ...args];
18665
+ }
18070
18666
  }
18071
18667
  const child = Bun.spawn(command, {
18072
18668
  env,
@@ -18086,6 +18682,8 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
18086
18682
  } finally {
18087
18683
  for (const [signal, listener] of Object.entries(forward))
18088
18684
  process.off(signal, listener);
18685
+ relay?.stop();
18686
+ forwardProxy?.stop();
18089
18687
  }
18090
18688
  }
18091
18689
  async function enableLocalClientRouting(options) {
@@ -18118,14 +18716,14 @@ async function enableLocalClientRouting(options) {
18118
18716
  clientConfigPath: options.clientConfigPath,
18119
18717
  providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
18120
18718
  });
18121
- const existingProfile = existsSync3(shellProfile) ? readFileSync5(shellProfile, "utf8") : "";
18122
- writeFileSync3(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
18123
- mkdirSync4(dirname5(statePath), { recursive: true, mode: 448 });
18124
- writeFileSync3(statePath, JSON.stringify({ claudePath, codexPath }), {
18719
+ const existingProfile = existsSync4(shellProfile) ? readFileSync6(shellProfile, "utf8") : "";
18720
+ writeFileSync4(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
18721
+ mkdirSync5(dirname5(statePath), { recursive: true, mode: 448 });
18722
+ writeFileSync4(statePath, JSON.stringify({ claudePath, codexPath }), {
18125
18723
  encoding: "utf8",
18126
18724
  mode: 384
18127
18725
  });
18128
- chmodSync2(statePath, 384);
18726
+ chmodSync3(statePath, 384);
18129
18727
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
18130
18728
  }
18131
18729
  function disableLocalClientRouting(paths2 = {}) {
@@ -18133,19 +18731,19 @@ function disableLocalClientRouting(paths2 = {}) {
18133
18731
  const binDir = paths2.binDir ?? defaults.binDir;
18134
18732
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
18135
18733
  const statePath = paths2.statePath ?? defaults.statePath;
18136
- if (existsSync3(shellProfile)) {
18137
- writeFileSync3(shellProfile, removeRoutingFromShellProfile(readFileSync5(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
18734
+ if (existsSync4(shellProfile)) {
18735
+ writeFileSync4(shellProfile, removeRoutingFromShellProfile(readFileSync6(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
18138
18736
  }
18139
18737
  for (const name of ["claude", "codex"]) {
18140
- const wrapper = join9(binDir, name);
18141
- if (existsSync3(wrapper))
18738
+ const wrapper = join10(binDir, name);
18739
+ if (existsSync4(wrapper))
18142
18740
  unlinkSync3(wrapper);
18143
18741
  }
18144
- rmSync2(join9(binDir, CLAUDE_COMPANION_DIRNAME), {
18742
+ rmSync3(join10(binDir, CLAUDE_COMPANION_DIRNAME), {
18145
18743
  force: true,
18146
18744
  recursive: true
18147
18745
  });
18148
- if (existsSync3(statePath))
18746
+ if (existsSync4(statePath))
18149
18747
  unlinkSync3(statePath);
18150
18748
  return getLocalRoutingStatus({ binDir, shellProfile, statePath });
18151
18749
  }
@@ -18171,15 +18769,32 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
18171
18769
  ${ROUTING_END}
18172
18770
  `;
18173
18771
  }
18174
- 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";
18772
+ 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", PROXY_VARIABLES, NO_PROXY_HOSTS = "localhost,127.0.0.1,::1", BASH_WITHOUT_PROXY_SETTINGS;
18175
18773
  var init_local_routing = __esm(() => {
18176
18774
  init_src4();
18775
+ init_client_forward_proxy();
18776
+ init_client_relay();
18177
18777
  CLAUDE_COMPANION_FILES = [
18178
18778
  ".claude-plugin/plugin.json",
18179
18779
  "hooks/hooks.json",
18180
18780
  "hooks/provider-choice.js",
18181
18781
  "hooks/register.js"
18182
18782
  ];
18783
+ PROXY_VARIABLES = ["HTTPS_PROXY", "https_proxy"];
18784
+ BASH_WITHOUT_PROXY_SETTINGS = JSON.stringify({
18785
+ hooks: {
18786
+ SessionStart: [
18787
+ {
18788
+ hooks: [
18789
+ {
18790
+ type: "command",
18791
+ command: `[ -z "$CLAUDE_ENV_FILE" ] || echo 'unset ${PROXY_VARIABLES.join(" ")}' >> "$CLAUDE_ENV_FILE"`
18792
+ }
18793
+ ]
18794
+ }
18795
+ ]
18796
+ }
18797
+ });
18183
18798
  });
18184
18799
 
18185
18800
  // src/core/logs.ts
@@ -18387,7 +19002,7 @@ var init_core = __esm(() => {
18387
19002
  });
18388
19003
 
18389
19004
  // src/core/client-command.ts
18390
- import { existsSync as existsSync4 } from "fs";
19005
+ import { existsSync as existsSync5 } from "fs";
18391
19006
  import { parseArgs as parseArgs2 } from "util";
18392
19007
  async function runClientCommand(argv) {
18393
19008
  const { positionals, values } = parseArgs2({
@@ -18400,7 +19015,7 @@ async function runClientCommand(argv) {
18400
19015
  if (positionals.length !== 1 || !["on", "off", "status"].includes(command ?? ""))
18401
19016
  throw new Error("usage: agent-smith client on|off|status [--raw]");
18402
19017
  const configPath = resolveConfigPath();
18403
- const client2 = existsSync4(configPath) ? readClientRouting(configPath) : { enabled: false };
19018
+ const client2 = existsSync5(configPath) ? readClientRouting(configPath) : { enabled: false };
18404
19019
  let installed = configClientWrappersInstalled();
18405
19020
  if (command !== "status") {
18406
19021
  const enabled = command === "on";
@@ -18606,15 +19221,15 @@ var init_menubar = __esm(() => {
18606
19221
 
18607
19222
  // src/core/menubar-command.ts
18608
19223
  import {
18609
- chmodSync as chmodSync3,
18610
- existsSync as existsSync5,
18611
- mkdirSync as mkdirSync5,
18612
- readFileSync as readFileSync6,
18613
- rmSync as rmSync3,
18614
- writeFileSync as writeFileSync4
19224
+ chmodSync as chmodSync4,
19225
+ existsSync as existsSync6,
19226
+ mkdirSync as mkdirSync6,
19227
+ readFileSync as readFileSync7,
19228
+ rmSync as rmSync4,
19229
+ writeFileSync as writeFileSync5
18615
19230
  } from "fs";
18616
19231
  import { homedir as homedir3 } from "os";
18617
- import { dirname as dirname6, join as join10 } from "path";
19232
+ import { dirname as dirname6, join as join11 } from "path";
18618
19233
  import { fileURLToPath as fileURLToPath2 } from "url";
18619
19234
  import { parseArgs as parseArgs3 } from "util";
18620
19235
  function swiftBarPluginDirectory() {
@@ -18629,12 +19244,12 @@ function swiftBarPluginDirectory() {
18629
19244
  const path = result.exitCode === 0 ? result.stdout.toString().trim() : "";
18630
19245
  if (!path)
18631
19246
  return null;
18632
- return path.startsWith("~/") ? join10(homedir3(), path.slice(2)) : path;
19247
+ return path.startsWith("~/") ? join11(homedir3(), path.slice(2)) : path;
18633
19248
  }
18634
19249
  async function remoteScript() {
18635
19250
  const built = new URL("./pool-status.js", import.meta.url);
18636
- if (existsSync5(built))
18637
- return readFileSync6(built, "utf8");
19251
+ if (existsSync6(built))
19252
+ return readFileSync7(built, "utf8");
18638
19253
  const output = await Bun.build({
18639
19254
  entrypoints: [fileURLToPath2(new URL("../pool-status.ts", import.meta.url))],
18640
19255
  target: "bun"
@@ -18662,7 +19277,7 @@ function cliBinDirectories() {
18662
19277
  return [
18663
19278
  ...new Set([
18664
19279
  ...found,
18665
- join10(homedir3(), ".bun", "bin"),
19280
+ join11(homedir3(), ".bun", "bin"),
18666
19281
  "/opt/homebrew/bin",
18667
19282
  "/usr/local/bin"
18668
19283
  ])
@@ -18671,7 +19286,7 @@ function cliBinDirectories() {
18671
19286
  function defaultDeps() {
18672
19287
  return {
18673
19288
  configPath: resolveConfigPath(),
18674
- cachePath: join10(homedir3(), "Library", "Caches", "agent-smith", "menubar-status.json"),
19289
+ cachePath: join11(homedir3(), "Library", "Caches", "agent-smith", "menubar-status.json"),
18675
19290
  binDirectories: cliBinDirectories,
18676
19291
  pluginDirectory: swiftBarPluginDirectory,
18677
19292
  fetchStatus: fetchPoolStatus,
@@ -18681,7 +19296,7 @@ function defaultDeps() {
18681
19296
  }
18682
19297
  function readCache(path) {
18683
19298
  try {
18684
- const cached = JSON.parse(readFileSync6(path, "utf8"));
19299
+ const cached = JSON.parse(readFileSync7(path, "utf8"));
18685
19300
  return typeof cached?.fetchedAt === "number" && Array.isArray(cached?.status?.accounts) ? cached : null;
18686
19301
  } catch {
18687
19302
  return null;
@@ -18696,8 +19311,8 @@ async function loadSnapshot(deps) {
18696
19311
  fetchedAt: deps.now(),
18697
19312
  status: await deps.fetchStatus(host)
18698
19313
  };
18699
- mkdirSync5(dirname6(deps.cachePath), { recursive: true, mode: 448 });
18700
- writeFileSync4(deps.cachePath, JSON.stringify(cached), { mode: 384 });
19314
+ mkdirSync6(dirname6(deps.cachePath), { recursive: true, mode: 448 });
19315
+ writeFileSync5(deps.cachePath, JSON.stringify(cached), { mode: 384 });
18701
19316
  return { cached, error: null };
18702
19317
  } catch (error) {
18703
19318
  return {
@@ -18723,19 +19338,19 @@ function install(deps) {
18723
19338
  throw new Error("SwiftBar has no plugin folder. On macOS, install it (brew install --cask swiftbar), open it once and pick a plugin folder, then run this again.");
18724
19339
  if (!readClientRouting(deps.configPath).poolSshHost)
18725
19340
  throw new Error(`Set client.pool_ssh_host in ${deps.configPath} first`);
18726
- const path = join10(directory, PLUGIN_FILE);
18727
- writeFileSync4(path, pluginScript(deps.binDirectories()));
18728
- chmodSync3(path, 493);
19341
+ const path = join11(directory, PLUGIN_FILE);
19342
+ writeFileSync5(path, pluginScript(deps.binDirectories()));
19343
+ chmodSync4(path, 493);
18729
19344
  deps.log(`Installed ${path}. SwiftBar shows the pool shortly and refreshes it every 5 minutes.`);
18730
19345
  }
18731
19346
  function uninstall(deps) {
18732
19347
  const directory = deps.pluginDirectory();
18733
- const path = directory ? join10(directory, PLUGIN_FILE) : null;
18734
- if (!path || !existsSync5(path) || !readFileSync6(path, "utf8").includes(PLUGIN_MARKER)) {
19348
+ const path = directory ? join11(directory, PLUGIN_FILE) : null;
19349
+ if (!path || !existsSync6(path) || !readFileSync7(path, "utf8").includes(PLUGIN_MARKER)) {
18735
19350
  deps.log("No Agent Smith menu bar plugin is installed.");
18736
19351
  return;
18737
19352
  }
18738
- rmSync3(path);
19353
+ rmSync4(path);
18739
19354
  deps.log(`Removed ${path}.`);
18740
19355
  }
18741
19356
  async function runMenubarCommand(argv, overrides = {}) {
@@ -18793,13 +19408,13 @@ __export(exports_theme, {
18793
19408
  NAV_ITEMS: () => NAV_ITEMS,
18794
19409
  C: () => C
18795
19410
  });
18796
- import { existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";
19411
+ import { existsSync as existsSync7, mkdirSync as mkdirSync7, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "fs";
18797
19412
  import { homedir as homedir4 } from "os";
18798
- import { join as join11 } from "path";
19413
+ import { join as join12 } from "path";
18799
19414
  function loadPersistedThemeId() {
18800
19415
  try {
18801
- if (existsSync6(CONFIG_FILE)) {
18802
- const data = JSON.parse(readFileSync7(CONFIG_FILE, "utf-8"));
19416
+ if (existsSync7(CONFIG_FILE)) {
19417
+ const data = JSON.parse(readFileSync8(CONFIG_FILE, "utf-8"));
18803
19418
  if (data?.themeId && getThemeById(data.themeId)) {
18804
19419
  return data.themeId;
18805
19420
  }
@@ -18809,10 +19424,10 @@ function loadPersistedThemeId() {
18809
19424
  }
18810
19425
  function persistThemeId(themeId) {
18811
19426
  try {
18812
- if (!existsSync6(CONFIG_DIR)) {
18813
- mkdirSync6(CONFIG_DIR, { recursive: true });
19427
+ if (!existsSync7(CONFIG_DIR)) {
19428
+ mkdirSync7(CONFIG_DIR, { recursive: true });
18814
19429
  }
18815
- writeFileSync5(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
19430
+ writeFileSync6(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
18816
19431
  } catch {}
18817
19432
  }
18818
19433
  function setTuiTheme(themeId) {
@@ -18837,8 +19452,8 @@ function getAvailableThemes() {
18837
19452
  var CONFIG_DIR, CONFIG_FILE, currentThemeId, currentColors, C, NAV_ITEMS, SCREEN_TITLES;
18838
19453
  var init_theme = __esm(() => {
18839
19454
  init_src16();
18840
- CONFIG_DIR = join11(homedir4(), ".config", "agent-smith");
18841
- CONFIG_FILE = join11(CONFIG_DIR, "theme.json");
19455
+ CONFIG_DIR = join12(homedir4(), ".config", "agent-smith");
19456
+ CONFIG_FILE = join12(CONFIG_DIR, "theme.json");
18842
19457
  currentThemeId = loadPersistedThemeId();
18843
19458
  currentColors = themeToTuiColors(getThemeById(currentThemeId) ?? getDefaultTheme("dark"));
18844
19459
  C = new Proxy({}, {