@certalis/agent-smith 0.1.14 → 0.1.16

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
@@ -842,7 +842,6 @@ function isRequestStreamEvent(value) {
842
842
  var init_request_events2 = __esm(() => {
843
843
  init_request();
844
844
  });
845
-
846
845
  // ../../packages/types/src/stats.ts
847
846
  function isTimeRange(value) {
848
847
  return TIME_RANGES.includes(value);
@@ -1262,6 +1261,129 @@ var init_paths = __esm(() => {
1262
1261
  init_paths_common();
1263
1262
  });
1264
1263
 
1264
+ // ../../packages/config/src/window-warmup.ts
1265
+ function isLocalTimes(value) {
1266
+ return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
1267
+ }
1268
+ function isTimeZone(value) {
1269
+ if (typeof value !== "string" || value.length === 0 || value.length > 64) {
1270
+ return false;
1271
+ }
1272
+ try {
1273
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
1274
+ return true;
1275
+ } catch {
1276
+ return false;
1277
+ }
1278
+ }
1279
+ function sanitizeWindowWarmup(value) {
1280
+ if (!isRecord(value))
1281
+ return;
1282
+ const result = {};
1283
+ if (typeof value.enabled === "boolean")
1284
+ result.enabled = value.enabled;
1285
+ if (isLocalTimes(value.times))
1286
+ result.times = [...new Set(value.times)];
1287
+ if (isTimeZone(value.time_zone))
1288
+ result.time_zone = value.time_zone;
1289
+ if (typeof value.weekdays_only === "boolean") {
1290
+ result.weekdays_only = value.weekdays_only;
1291
+ }
1292
+ if (typeof value.model === "string" && MODEL_NAME.test(value.model)) {
1293
+ result.model = value.model;
1294
+ }
1295
+ return Object.keys(value).every((key) => (key in result)) ? result : undefined;
1296
+ }
1297
+ function windowWarmupConfig(file) {
1298
+ return {
1299
+ enabled: file?.enabled ?? WINDOW_WARMUP_DEFAULTS.enabled,
1300
+ times: [...file?.times ?? WINDOW_WARMUP_DEFAULTS.times],
1301
+ timeZone: file?.time_zone ?? WINDOW_WARMUP_DEFAULTS.timeZone,
1302
+ weekdaysOnly: file?.weekdays_only ?? WINDOW_WARMUP_DEFAULTS.weekdaysOnly,
1303
+ model: file?.model ?? WINDOW_WARMUP_DEFAULTS.model
1304
+ };
1305
+ }
1306
+ function windowWarmupFileConfig(config) {
1307
+ return {
1308
+ enabled: config.enabled,
1309
+ times: [...config.times],
1310
+ time_zone: config.timeZone,
1311
+ weekdays_only: config.weekdaysOnly,
1312
+ ...config.model && { model: config.model }
1313
+ };
1314
+ }
1315
+ function wallClockFormat(timeZone) {
1316
+ let format = wallClockFormats.get(timeZone);
1317
+ if (!format) {
1318
+ format = new Intl.DateTimeFormat("en-US", {
1319
+ timeZone,
1320
+ hourCycle: "h23",
1321
+ year: "numeric",
1322
+ month: "numeric",
1323
+ day: "numeric",
1324
+ hour: "numeric",
1325
+ minute: "numeric",
1326
+ second: "numeric"
1327
+ });
1328
+ wallClockFormats.set(timeZone, format);
1329
+ }
1330
+ return format;
1331
+ }
1332
+ function wallClock(at, timeZone) {
1333
+ const parts = wallClockFormat(timeZone).formatToParts(at);
1334
+ const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
1335
+ return {
1336
+ year: part("year"),
1337
+ month: part("month"),
1338
+ day: part("day"),
1339
+ hour: part("hour") % 24,
1340
+ minute: part("minute"),
1341
+ second: part("second")
1342
+ };
1343
+ }
1344
+ function zoneOffsetMs(at, timeZone) {
1345
+ const wall = wallClock(at, timeZone);
1346
+ return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
1347
+ }
1348
+ function zonedInstant(wall, timeZone) {
1349
+ return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
1350
+ }
1351
+ function nextWindowWarmupAt(routing, after) {
1352
+ const warmup = routing.windowWarmup;
1353
+ if (!routing.enabled || !warmup.enabled)
1354
+ return null;
1355
+ const today = wallClock(after, warmup.timeZone);
1356
+ for (let offset = 0;offset < 8; offset++) {
1357
+ const day = Date.UTC(today.year, today.month - 1, today.day + offset);
1358
+ const weekday = new Date(day).getUTCDay();
1359
+ if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
1360
+ continue;
1361
+ }
1362
+ const instants = warmup.times.map((time) => {
1363
+ const [hour = 0, minute = 0] = time.split(":").map(Number);
1364
+ return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
1365
+ }).filter((at) => at > after);
1366
+ if (instants.length > 0)
1367
+ return Math.min(...instants);
1368
+ }
1369
+ return null;
1370
+ }
1371
+ var WINDOW_WARMUP_DEFAULTS, LOCAL_TIME, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0, wallClockFormats;
1372
+ var init_window_warmup = __esm(() => {
1373
+ init_src2();
1374
+ init_src();
1375
+ WINDOW_WARMUP_DEFAULTS = {
1376
+ enabled: false,
1377
+ times: ["06:00"],
1378
+ timeZone: "Europe/Paris",
1379
+ weekdaysOnly: true,
1380
+ model: null
1381
+ };
1382
+ LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1383
+ MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
1384
+ wallClockFormats = new Map;
1385
+ });
1386
+
1265
1387
  // ../../packages/config/src/index.ts
1266
1388
  import { EventEmitter as EventEmitter3 } from "events";
1267
1389
  import {
@@ -1288,10 +1410,20 @@ function normalizeEnrollmentEmail(value) {
1288
1410
  const email = value.trim().toLowerCase();
1289
1411
  return email.length <= 254 && patterns.email.test(email) ? email : undefined;
1290
1412
  }
1413
+ function normalizeEnrollmentRule(value) {
1414
+ const rule = normalizeEnrollmentEmail(value);
1415
+ if (!rule?.includes("*"))
1416
+ return rule;
1417
+ if (!rule.startsWith("*@"))
1418
+ return;
1419
+ const labels = rule.slice(2).split(".");
1420
+ const label = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
1421
+ return labels.length >= 2 && labels.every((part) => label.test(part)) ? rule : undefined;
1422
+ }
1291
1423
  function sanitizeEnrollmentEmails(value) {
1292
1424
  if (!Array.isArray(value))
1293
1425
  return;
1294
- const emails = value.map(normalizeEnrollmentEmail).filter((email) => email !== undefined);
1426
+ const emails = value.map(normalizeEnrollmentRule).filter((email) => email !== undefined);
1295
1427
  return [...new Set(emails)].slice(0, MAX_ENROLLMENT_EMAILS);
1296
1428
  }
1297
1429
  function sanitizeConfigData(value) {
@@ -1436,6 +1568,12 @@ function sanitizeClientRouting(value) {
1436
1568
  if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1437
1569
  client.proxy_key_file = value.proxy_key_file;
1438
1570
  }
1571
+ if (typeof value.keep_claude_login === "boolean") {
1572
+ client.keep_claude_login = value.keep_claude_login;
1573
+ }
1574
+ if (typeof value.pool_ssh_host === "string" && POOL_SSH_HOST_PATTERN.test(value.pool_ssh_host)) {
1575
+ client.pool_ssh_host = value.pool_ssh_host;
1576
+ }
1439
1577
  return Object.keys(client).length > 0 ? client : undefined;
1440
1578
  }
1441
1579
  function sanitizeProviderModels(value) {
@@ -1503,12 +1641,25 @@ function sanitizeTeamRouting(value) {
1503
1641
  if (typeof value.distribution_enabled === "boolean") {
1504
1642
  result.distribution_enabled = value.distribution_enabled;
1505
1643
  }
1644
+ if (typeof value.prefer_expiring_quota === "boolean") {
1645
+ result.prefer_expiring_quota = value.prefer_expiring_quota;
1646
+ }
1506
1647
  if (Array.isArray(value.allowlisted_account_uuids) && value.allowlisted_account_uuids.every((entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 200)) {
1507
1648
  result.allowlisted_account_uuids = [...value.allowlisted_account_uuids];
1508
1649
  }
1509
1650
  if (isFiniteNumber(value.max_usage) && value.max_usage > 0 && value.max_usage <= 0.9) {
1510
1651
  result.max_usage = value.max_usage;
1511
1652
  }
1653
+ if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
1654
+ result.weekly_max_usage = value.weekly_max_usage;
1655
+ }
1656
+ if (isRecord(value.weekly_max_usage_by_email)) {
1657
+ const entries = Object.entries(value.weekly_max_usage_by_email);
1658
+ const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
1659
+ if (normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= 0.95) && new Set(normalized.map(([email]) => email)).size === entries.length) {
1660
+ result.weekly_max_usage_by_email = Object.fromEntries(normalized);
1661
+ }
1662
+ }
1512
1663
  if (isNonNegativeFiniteNumber(value.admission_cap)) {
1513
1664
  result.admission_cap = Math.floor(value.admission_cap);
1514
1665
  }
@@ -1524,16 +1675,42 @@ function sanitizeTeamRouting(value) {
1524
1675
  if (isNonNegativeFiniteNumber(value.quota_probe_seconds)) {
1525
1676
  result.quota_probe_seconds = Math.min(Math.floor(value.quota_probe_seconds), 7 * 24 * 60 * 60);
1526
1677
  }
1678
+ const windowWarmup = sanitizeWindowWarmup(value.window_warmup);
1679
+ if (windowWarmup)
1680
+ result.window_warmup = windowWarmup;
1527
1681
  return result;
1528
1682
  }
1529
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1683
+ function readClientRouting(configPath = resolveConfigPath()) {
1684
+ let data;
1685
+ try {
1686
+ data = JSON.parse(readFileSync(configPath, "utf8"));
1687
+ } catch {
1688
+ throw new Error("Agent Smith client config could not be read");
1689
+ }
1690
+ if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1691
+ throw new Error("Agent Smith client config is invalid");
1692
+ }
1693
+ return clientRouting(sanitizeClientRouting(data.client));
1694
+ }
1695
+ function clientRouting(client) {
1696
+ return {
1697
+ enabled: client?.enabled === true,
1698
+ ...client?.base_url && { baseUrl: client.base_url },
1699
+ ...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
1700
+ ...client?.keep_claude_login === true && { keepClaudeLogin: true },
1701
+ ...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
1702
+ };
1703
+ }
1704
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1530
1705
  var init_src4 = __esm(() => {
1531
1706
  init_src2();
1532
1707
  init_src3();
1533
1708
  init_src();
1534
1709
  init_paths();
1710
+ init_window_warmup();
1535
1711
  init_paths();
1536
1712
  init_paths_common();
1713
+ init_window_warmup();
1537
1714
  log2 = new Logger("Config");
1538
1715
  PROVIDER_STRATEGIES = [
1539
1716
  "anthropic-api",
@@ -1549,16 +1726,21 @@ var init_src4 = __esm(() => {
1549
1726
  ];
1550
1727
  BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1551
1728
  PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1729
+ POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
1552
1730
  TEAM_ROUTING_DEFAULTS = {
1553
1731
  enabled: false,
1554
1732
  distributionEnabled: true,
1733
+ preferExpiringQuota: false,
1555
1734
  allowlistedAccountUuids: [],
1556
1735
  maxUsage: 0.9,
1736
+ weeklyMaxUsage: 0.95,
1737
+ weeklyMaxUsageByEmail: {},
1557
1738
  admissionCap: 5,
1558
1739
  admissionQueueLimit: 25,
1559
1740
  admissionWaitMs: 30000,
1560
1741
  holdSeconds: 0,
1561
- quotaProbeSeconds: 0
1742
+ quotaProbeSeconds: 0,
1743
+ windowWarmup: WINDOW_WARMUP_DEFAULTS
1562
1744
  };
1563
1745
  Config = class Config extends EventEmitter3 {
1564
1746
  configPath;
@@ -1664,17 +1846,20 @@ var init_src4 = __esm(() => {
1664
1846
  if (fromEnv) {
1665
1847
  const n = parseInt(fromEnv, 10);
1666
1848
  if (!Number.isNaN(n))
1667
- return this.clamp(n, 1, 365);
1849
+ return this.clamp(n, 0, 365);
1668
1850
  }
1669
1851
  const fromFile = this.data.data_retention_days;
1670
1852
  if (typeof fromFile === "number")
1671
- return this.clamp(fromFile, 1, 365);
1853
+ return this.clamp(fromFile, 0, 365);
1672
1854
  return 7;
1673
1855
  }
1674
1856
  setDataRetentionDays(days) {
1675
- const clamped = this.clamp(days, 1, 365);
1857
+ const clamped = this.clamp(days, 0, 365);
1676
1858
  this.set("data_retention_days", clamped);
1677
1859
  }
1860
+ storesRequestPayloads() {
1861
+ return this.getDataRetentionDays() > 0;
1862
+ }
1678
1863
  getRequestRetentionDays() {
1679
1864
  const fromEnv = process.env.AGENT_SMITH_REQUEST_RETENTION_DAYS;
1680
1865
  if (fromEnv) {
@@ -1705,15 +1890,19 @@ var init_src4 = __esm(() => {
1705
1890
  return {
1706
1891
  enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1707
1892
  distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1893
+ preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
1708
1894
  allowlistedAccountUuids: [
1709
1895
  ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1710
1896
  ],
1711
1897
  maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1898
+ weeklyMaxUsage: file?.weekly_max_usage ?? TEAM_ROUTING_DEFAULTS.weeklyMaxUsage,
1899
+ weeklyMaxUsageByEmail: { ...file?.weekly_max_usage_by_email },
1712
1900
  admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1713
1901
  admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1714
1902
  admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1715
1903
  holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1716
- quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
1904
+ quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds,
1905
+ windowWarmup: windowWarmupConfig(file?.window_warmup)
1717
1906
  };
1718
1907
  }
1719
1908
  getAlerts() {
@@ -1728,14 +1917,10 @@ var init_src4 = __esm(() => {
1728
1917
  };
1729
1918
  }
1730
1919
  getClientRouting() {
1731
- const client = this.data.client;
1732
- return {
1733
- enabled: client?.enabled === true,
1734
- ...client?.base_url && { baseUrl: client.base_url },
1735
- ...client?.proxy_key_file && {
1736
- proxyKeyFile: client.proxy_key_file
1737
- }
1738
- };
1920
+ return clientRouting(this.data.client);
1921
+ }
1922
+ setClientRoutingEnabled(enabled) {
1923
+ this.persistStrictly("client", { ...this.data.client, enabled });
1739
1924
  }
1740
1925
  getBlockWhenAllFull() {
1741
1926
  return this.data.block_when_all_full !== false;
@@ -1776,13 +1961,17 @@ var init_src4 = __esm(() => {
1776
1961
  const allowed = new Set([
1777
1962
  "enabled",
1778
1963
  "distribution_enabled",
1964
+ "prefer_expiring_quota",
1779
1965
  "allowlisted_account_uuids",
1780
1966
  "max_usage",
1967
+ "weekly_max_usage",
1968
+ "weekly_max_usage_by_email",
1781
1969
  "admission_cap",
1782
1970
  "admission_queue_limit",
1783
1971
  "admission_wait_ms",
1784
1972
  "hold_seconds",
1785
- "quota_probe_seconds"
1973
+ "quota_probe_seconds",
1974
+ "window_warmup"
1786
1975
  ]);
1787
1976
  if (Object.keys(value).some((key) => !allowed.has(key))) {
1788
1977
  throw new Error("team routing configuration contains an unknown field");
@@ -1797,13 +1986,12 @@ var init_src4 = __esm(() => {
1797
1986
  }
1798
1987
  }
1799
1988
  const oldValue = this.data.team_routing;
1800
- this.data.team_routing = sanitized;
1801
- this.saveConfig();
1802
- this.emit("change", {
1803
- key: "team_routing",
1804
- oldValue,
1805
- newValue: sanitized
1806
- });
1989
+ if (!("weekly_max_usage_by_email" in value) && oldValue?.weekly_max_usage_by_email) {
1990
+ sanitized.weekly_max_usage_by_email = {
1991
+ ...oldValue.weekly_max_usage_by_email
1992
+ };
1993
+ }
1994
+ this.persistStrictly("team_routing", sanitized);
1807
1995
  }
1808
1996
  allowAccountUuid(accountUuid) {
1809
1997
  const current = this.getTeamRouting().allowlistedAccountUuids;
@@ -1826,10 +2014,18 @@ var init_src4 = __esm(() => {
1826
2014
  getEnrollmentEmails() {
1827
2015
  return [...this.data.enrollment_emails ?? []];
1828
2016
  }
2017
+ isEnrollmentEmailAllowed(value) {
2018
+ const email = normalizeEnrollmentEmail(value);
2019
+ if (!email || email.includes("*"))
2020
+ return false;
2021
+ const rules = this.data.enrollment_emails ?? [];
2022
+ const domainRule = `*${email.slice(email.indexOf("@"))}`;
2023
+ return rules.includes(email) || rules.includes(domainRule);
2024
+ }
1829
2025
  setEnrollmentEmails(emails) {
1830
- const normalized = emails.map(normalizeEnrollmentEmail);
2026
+ const normalized = emails.map(normalizeEnrollmentRule);
1831
2027
  if (normalized.some((email) => email === undefined)) {
1832
- throw new ValidationError("Invalid enrollment email", "enrollment_emails");
2028
+ throw new ValidationError("Invalid enrollment email or exact-domain rule (use *@example.com)", "enrollment_emails");
1833
2029
  }
1834
2030
  const unique = [...new Set(normalized)];
1835
2031
  if (unique.length > MAX_ENROLLMENT_EMAILS) {
@@ -1859,6 +2055,7 @@ var init_src4 = __esm(() => {
1859
2055
  },
1860
2056
  sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
1861
2057
  port: NETWORK.DEFAULT_PORT,
2058
+ storeRequestPayloads: this.storesRequestPayloads(),
1862
2059
  teamRouting: this.getTeamRouting()
1863
2060
  };
1864
2061
  if (process.env.AGENT_SMITH_CLIENT_ID) {
@@ -2435,7 +2632,7 @@ function backfillRequestLinkageColumns(db) {
2435
2632
  FROM requests r
2436
2633
  LEFT JOIN request_payloads rp ON rp.id = r.id
2437
2634
  ORDER BY r.timestamp ASC
2438
- `).all();
2635
+ `).iterate();
2439
2636
  const responseToChain = new Map;
2440
2637
  let updatedRows = 0;
2441
2638
  const updateStmt = db.prepare(`
@@ -3593,7 +3790,7 @@ var init_request_repository = __esm(() => {
3593
3790
  }
3594
3791
  save(data) {
3595
3792
  const { usage, timings } = data;
3596
- const payloadJson = data.payload === undefined ? undefined : JSON.stringify(data.payload);
3793
+ const payloadJson = data.payload === undefined || data.storePayload === false ? undefined : JSON.stringify(data.payload);
3597
3794
  const linkage = requestLinkageFromPayload(data.payload);
3598
3795
  const responseChainId = this.resolveResponseChainId(linkage.previousResponseId, linkage.responseId, data.id);
3599
3796
  this.db.run("BEGIN");
@@ -3973,7 +4170,11 @@ var init_request_repository = __esm(() => {
3973
4170
  return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
3974
4171
  }
3975
4172
  deletePayloadsOlderThan(cutoffTs) {
3976
- return this.runWithChanges(`DELETE FROM request_payloads WHERE id IN (SELECT id FROM requests WHERE timestamp < ?)`, [cutoffTs]);
4173
+ return this.runWithChanges(`DELETE FROM request_payloads
4174
+ WHERE EXISTS (
4175
+ SELECT 1 FROM requests r
4176
+ WHERE r.id = request_payloads.id AND r.timestamp < ?
4177
+ )`, [cutoffTs]);
3977
4178
  }
3978
4179
  };
3979
4180
  });
@@ -4100,11 +4301,16 @@ var init_strategy_repository = __esm(() => {
4100
4301
 
4101
4302
  // ../../packages/database/src/database-operations.ts
4102
4303
  import { Database } from "bun:sqlite";
4103
- import { mkdirSync as mkdirSync3 } from "fs";
4304
+ import { mkdirSync as mkdirSync3, statfsSync } from "fs";
4104
4305
  import { dirname as dirname2 } from "path";
4306
+ function freeDiskBytes(directory) {
4307
+ const { bavail, bsize } = statfsSync(directory);
4308
+ return bavail * bsize;
4309
+ }
4105
4310
 
4106
4311
  class DatabaseOperations {
4107
4312
  db;
4313
+ dbPath;
4108
4314
  runtime;
4109
4315
  closed = false;
4110
4316
  accounts;
@@ -4116,6 +4322,7 @@ class DatabaseOperations {
4116
4322
  stats;
4117
4323
  constructor(dbPath) {
4118
4324
  const resolvedPath = dbPath ?? resolveDbPath();
4325
+ this.dbPath = resolvedPath;
4119
4326
  const dir = dirname2(resolvedPath);
4120
4327
  mkdirSync3(dir, { recursive: true });
4121
4328
  this.db = new Database(resolvedPath, { create: true });
@@ -4248,6 +4455,7 @@ class DatabaseOperations {
4248
4455
  usage,
4249
4456
  timestamp: options?.timestamp,
4250
4457
  payload: options?.payload,
4458
+ storePayload: options?.storePayload,
4251
4459
  timings: options?.timings
4252
4460
  });
4253
4461
  }
@@ -4332,7 +4540,7 @@ class DatabaseOperations {
4332
4540
  return;
4333
4541
  }
4334
4542
  this.closed = true;
4335
- this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
4543
+ this.checkpointWal();
4336
4544
  this.db.close();
4337
4545
  }
4338
4546
  dispose() {
@@ -4342,9 +4550,23 @@ class DatabaseOperations {
4342
4550
  this.db.exec("PRAGMA optimize");
4343
4551
  this.db.exec("PRAGMA wal_checkpoint(PASSIVE)");
4344
4552
  }
4345
- compact() {
4553
+ checkpointWal() {
4346
4554
  this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
4555
+ }
4556
+ compact(freeBytes = freeDiskBytes(dirname2(this.dbPath))) {
4557
+ this.checkpointWal();
4558
+ const requiredBytes = 2 * this.liveDataBytes();
4559
+ if (freeBytes < requiredBytes) {
4560
+ return { vacuumed: false, freeBytes, requiredBytes };
4561
+ }
4347
4562
  this.db.exec("VACUUM");
4563
+ this.checkpointWal();
4564
+ return { vacuumed: true, freeBytes, requiredBytes };
4565
+ }
4566
+ liveDataBytes() {
4567
+ const row = this.db.query(`SELECT (page_count - freelist_count) * page_size AS bytes
4568
+ FROM pragma_page_count(), pragma_freelist_count(), pragma_page_size()`).get();
4569
+ return row.bytes;
4348
4570
  }
4349
4571
  getStatsRepository() {
4350
4572
  return this.stats;
@@ -4412,7 +4634,7 @@ var init_src5 = __esm(() => {
4412
4634
  });
4413
4635
 
4414
4636
  // ../../packages/http/src/errors.ts
4415
- var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), DEFAULT_ERROR_MESSAGES;
4637
+ var ERROR_TYPES, HttpError, BadRequest = (message, details) => new HttpError(400, message, details), NotFound = (message, details) => new HttpError(404, message, details), InternalServerError = (message, details) => new HttpError(500, message, details), ServiceUnavailable = (message, details) => new HttpError(503, message, details), DEFAULT_ERROR_MESSAGES;
4416
4638
  var init_errors2 = __esm(() => {
4417
4639
  ERROR_TYPES = {
4418
4640
  NETWORK: "network",
@@ -5178,7 +5400,7 @@ async function fetchClaudeCodeUsage(accessToken) {
5178
5400
  var CLAUDE_CODE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
5179
5401
 
5180
5402
  // ../../packages/providers/src/providers/claude-code/provider.ts
5181
- var log7, PROVIDER_NAME2 = "claude-code", DEFAULT_BASE_URL2, CLAUDE_CODE_REFRESH_CONFIG, ClaudeCodeProvider;
5403
+ var log7, PROVIDER_NAME2 = "claude-code", DEFAULT_BASE_URL2, CHEAPEST_MODEL = "claude-haiku-5-5", WINDOW_WARMUP_TIMEOUT_MS = 30000, CLAUDE_CODE_REFRESH_CONFIG, ClaudeCodeProvider;
5182
5404
  var init_provider2 = __esm(() => {
5183
5405
  init_src3();
5184
5406
  init_src();
@@ -5219,6 +5441,27 @@ var init_provider2 = __esm(() => {
5219
5441
  async probeQuota(_account, accessToken) {
5220
5442
  return await fetchClaudeCodeUsage(accessToken);
5221
5443
  }
5444
+ async startQuotaWindow(account2, accessToken, model) {
5445
+ const response = await fetch(this.buildUrl("/v1/messages", "", account2), {
5446
+ method: "POST",
5447
+ headers: {
5448
+ authorization: `Bearer ${accessToken}`,
5449
+ "anthropic-beta": "oauth-2025-04-20",
5450
+ "anthropic-version": "2023-06-01",
5451
+ "content-type": "application/json"
5452
+ },
5453
+ body: JSON.stringify({
5454
+ model: model ?? CHEAPEST_MODEL,
5455
+ max_tokens: 1,
5456
+ messages: [{ role: "user", content: "hi" }]
5457
+ }),
5458
+ signal: AbortSignal.timeout(WINDOW_WARMUP_TIMEOUT_MS)
5459
+ });
5460
+ await response.body?.cancel();
5461
+ if (!response.ok)
5462
+ throw new Error(`HTTP ${response.status}`);
5463
+ return this.parseRateLimit(response).quotaState ?? null;
5464
+ }
5222
5465
  async refreshToken(account2, clientId) {
5223
5466
  return executeTokenRefresh(account2, clientId, CLAUDE_CODE_REFRESH_CONFIG, log7);
5224
5467
  }
@@ -5632,6 +5875,107 @@ var init_oauth3 = __esm(() => {
5632
5875
  };
5633
5876
  });
5634
5877
 
5878
+ // ../../packages/providers/src/providers/codex/reset-credits.ts
5879
+ function string(value) {
5880
+ return typeof value === "string" && value.length > 0 && value.length <= 2000;
5881
+ }
5882
+ function date(value) {
5883
+ return string(value) && Number.isFinite(Date.parse(value));
5884
+ }
5885
+ function nullableText(value) {
5886
+ if (value === undefined || value === null)
5887
+ return null;
5888
+ if (typeof value !== "string" || value.length > 4000)
5889
+ throw new Error(INVALID);
5890
+ return value;
5891
+ }
5892
+ function nonnegativeInteger(value) {
5893
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
5894
+ }
5895
+ function credit(value) {
5896
+ if (!isRecord(value) || !string(value.id) || !string(value.reset_type) || !string(value.status) || !date(value.granted_at) || value.expires_at !== null && !date(value.expires_at))
5897
+ throw new Error(INVALID);
5898
+ return {
5899
+ id: value.id,
5900
+ resetType: value.reset_type,
5901
+ status: value.status,
5902
+ grantedAt: value.granted_at,
5903
+ expiresAt: value.expires_at,
5904
+ title: nullableText(value.title),
5905
+ description: nullableText(value.description)
5906
+ };
5907
+ }
5908
+ async function request2(account2, token, path, body) {
5909
+ const response = await fetch(`${BACKEND}/${path}`, {
5910
+ method: body === undefined ? "GET" : "POST",
5911
+ headers: {
5912
+ authorization: `Bearer ${token}`,
5913
+ "chatgpt-account-id": account2.account_uuid ?? "",
5914
+ "content-type": "application/json"
5915
+ },
5916
+ body: body === undefined ? undefined : JSON.stringify(body),
5917
+ redirect: "error",
5918
+ signal: AbortSignal.timeout(1e4)
5919
+ });
5920
+ if (!response.ok) {
5921
+ await response.body?.cancel();
5922
+ throw new Error(`Codex reset request failed (${response.status})`);
5923
+ }
5924
+ try {
5925
+ return await response.json();
5926
+ } catch {
5927
+ throw new Error(INVALID);
5928
+ }
5929
+ }
5930
+ async function listCodexResetCredits(account2, token) {
5931
+ const payload = await request2(account2, token, "rate-limit-reset-credits");
5932
+ if (!isRecord(payload) || !nonnegativeInteger(payload.available_count) || !Array.isArray(payload.credits) || payload.credits.length > 1000)
5933
+ throw new Error(INVALID);
5934
+ return {
5935
+ availableCount: payload.available_count,
5936
+ credits: payload.credits.map(credit)
5937
+ };
5938
+ }
5939
+ async function consumeCodexResetCredit(account2, token, attempt) {
5940
+ const payload = await request2(account2, token, "rate-limit-reset-credits/consume", {
5941
+ credit_id: attempt.creditId,
5942
+ redeem_request_id: attempt.requestId
5943
+ });
5944
+ if (!isRecord(payload) || !["reset", "nothing_to_reset", "no_credit", "already_redeemed"].includes(String(payload.code)) || !nonnegativeInteger(payload.windows_reset ?? 0))
5945
+ throw new Error(INVALID);
5946
+ return {
5947
+ code: payload.code,
5948
+ windowsReset: payload.windows_reset ?? 0
5949
+ };
5950
+ }
5951
+ async function readCodexResetQuota(account2, token) {
5952
+ const payload = await request2(account2, token, "usage");
5953
+ if (!isRecord(payload) || !isRecord(payload.rate_limit))
5954
+ return null;
5955
+ const windows = {};
5956
+ for (const value of [
5957
+ payload.rate_limit.primary_window,
5958
+ payload.rate_limit.secondary_window
5959
+ ]) {
5960
+ if (!isRecord(value))
5961
+ continue;
5962
+ const bucket = value.limit_window_seconds === 18000 ? "unified5h" : value.limit_window_seconds === 604800 ? "unified7d" : null;
5963
+ if (!bucket || typeof value.used_percent !== "number" || !Number.isFinite(value.used_percent) || value.used_percent < 0 || value.used_percent > 100 || typeof value.reset_at !== "number" || !Number.isSafeInteger(value.reset_at) || value.reset_at * 1000 <= Date.now())
5964
+ continue;
5965
+ windows[bucket] = {
5966
+ utilization: value.used_percent / 100,
5967
+ resetAt: value.reset_at * 1000,
5968
+ seenAt: Date.now(),
5969
+ status: null
5970
+ };
5971
+ }
5972
+ return Object.keys(windows).length > 0 ? { windows } : null;
5973
+ }
5974
+ var BACKEND = "https://chatgpt.com/backend-api/wham", INVALID = "Invalid Codex reset response";
5975
+ var init_reset_credits = __esm(() => {
5976
+ init_src();
5977
+ });
5978
+
5635
5979
  // ../../packages/providers/src/providers/codex/provider.ts
5636
5980
  function isEnvironmentContext(value) {
5637
5981
  return isRecord(value) && value.type === "input_text" && typeof value.text === "string" && /^<environment_context>\r?\n[\s\S]*<\/environment_context>\s*$/.test(value.text);
@@ -5697,6 +6041,7 @@ var init_provider4 = __esm(() => {
5697
6041
  init_base();
5698
6042
  init_provider3();
5699
6043
  init_oauth3();
6044
+ init_reset_credits();
5700
6045
  CODEX_USER_AGENT = `codex_cli_rs/${CODEX_CLIENT_VERSION} (Mac OS; arm64)`;
5701
6046
  log8 = new Logger("CodexProvider");
5702
6047
  DEFAULT_BASE_URL4 = getProviderDefaultBaseUrl(PROVIDER_NAME4);
@@ -5728,6 +6073,25 @@ var init_provider4 = __esm(() => {
5728
6073
  name = PROVIDER_NAME4;
5729
6074
  defaultBaseUrl = DEFAULT_BASE_URL4;
5730
6075
  wire = "openai-responses";
6076
+ supportsResetCredits(account2) {
6077
+ return account2.auth_method === "oauth" && !!account2.account_uuid && this.defaultBaseUrl.replace(/\/$/, "") === DEFAULT_BASE_URL4.replace(/\/$/, "") && (account2.base_url === null || account2.base_url.replace(/\/$/, "") === DEFAULT_BASE_URL4.replace(/\/$/, ""));
6078
+ }
6079
+ requireResetAccount(account2) {
6080
+ if (!this.supportsResetCredits(account2))
6081
+ throw new Error("Reset credits require a direct Codex subscription");
6082
+ }
6083
+ async listResetCredits(account2, accessToken) {
6084
+ this.requireResetAccount(account2);
6085
+ return listCodexResetCredits(account2, accessToken);
6086
+ }
6087
+ async consumeResetCredit(account2, accessToken, attempt) {
6088
+ this.requireResetAccount(account2);
6089
+ return consumeCodexResetCredit(account2, accessToken, attempt);
6090
+ }
6091
+ async readResetQuota(account2, accessToken) {
6092
+ this.requireResetAccount(account2);
6093
+ return readCodexResetQuota(account2, accessToken);
6094
+ }
5731
6095
  getClientSessionId(headers2) {
5732
6096
  return headers2.get("session-id");
5733
6097
  }
@@ -6294,9 +6658,9 @@ function startCallbackForwarder(provider, providerRegistry) {
6294
6658
  try {
6295
6659
  const server = Bun.serve({
6296
6660
  port,
6297
- fetch(request2) {
6298
- const url = new URL(request2.url);
6299
- if (request2.method !== "GET" || url.pathname !== "/auth/callback") {
6661
+ fetch(request3) {
6662
+ const url = new URL(request3.url);
6663
+ if (request3.method !== "GET" || url.pathname !== "/auth/callback") {
6300
6664
  return new Response("Not Found", { status: 404 });
6301
6665
  }
6302
6666
  const target = new URL(`http://localhost:8080${targetPath}`);
@@ -6508,6 +6872,7 @@ function serializeAccount(account2, providerRegistry, now = Date.now()) {
6508
6872
  name: account2.name,
6509
6873
  provider: account2.provider,
6510
6874
  providerDisabled: !providerRegistry.getProvider(account2.provider),
6875
+ resetCreditsSupported: providerRegistry.getProvider(account2.provider)?.supportsResetCredits?.(account2) ?? false,
6511
6876
  auth_method: account2.auth_method,
6512
6877
  base_url: account2.base_url,
6513
6878
  requestCount: account2.request_count,
@@ -7097,7 +7462,10 @@ function createConfigHandlers(config) {
7097
7462
  getStrategies: () => {
7098
7463
  return jsonResponse(LB_STRATEGIES);
7099
7464
  },
7100
- getTeamRouting: () => jsonResponse(config.getTeamRouting()),
7465
+ getTeamRouting: () => {
7466
+ const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
7467
+ return jsonResponse(routing);
7468
+ },
7101
7469
  setTeamRouting: async (req) => {
7102
7470
  try {
7103
7471
  const body = await parseJsonObject(req);
@@ -7127,7 +7495,7 @@ function createConfigHandlers(config) {
7127
7495
  let updated = false;
7128
7496
  if (body.payloadDays !== undefined) {
7129
7497
  const payloadDays = validateNumber(body.payloadDays, "payloadDays", {
7130
- min: 1,
7498
+ min: 0,
7131
7499
  max: 365,
7132
7500
  integer: true
7133
7501
  });
@@ -7193,7 +7561,7 @@ function enrollmentPage() {
7193
7561
  <section class="card" id="step-email" hidden>
7194
7562
  <div class="avatar">${icon("mail")}</div>
7195
7563
  <h1 tabindex="-1">Connect your Claude subscription</h1>
7196
- <p class="lead">This adds your subscription to the shared agents pool. Start with your work email: if it is on this pool's list, the next step lets you sign in with Claude.</p>
7564
+ <p class="lead">Connect or reconnect your subscription to the shared agents pool. Already connected or paused? Use the same email to renew your login without adding a second account.</p>
7197
7565
  <form id="request">
7198
7566
  <p class="notice err" id="email-error" role="alert" hidden></p>
7199
7567
  <label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
@@ -7206,16 +7574,16 @@ function enrollmentPage() {
7206
7574
  <h1 tabindex="-1">Sign in with Claude</h1>
7207
7575
  <p class="lead" id="signin-for" hidden>Use the Claude account of <strong id="signin-email"></strong>. Only connect an account you have permission to share.</p>
7208
7576
  <ul class="facts">
7209
- <li>Claude opens in a new tab. Sign in and pick the account to share.</li>
7577
+ <li>Claude opens in a new tab. Sign in with the email shown above.</li>
7210
7578
  <li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
7211
- <li>Claude then shows a code: you paste it here in the next step.</li>
7579
+ <li>Copy the code Claude shows, then return to this page to paste it. Reopening this link in the same browser brings you back to your current step.</li>
7212
7580
  </ul>
7213
7581
  <button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
7214
7582
  </section>
7215
7583
  <section class="card" id="step-code" hidden>
7216
7584
  <div class="avatar">${icon("code")}</div>
7217
7585
  <h1 tabindex="-1">Paste the code from Claude</h1>
7218
- <p class="lead" id="code-lead">Claude opened in a new tab. Once you have signed in, it shows an authorization code: copy it and paste it below.</p>
7586
+ <p class="lead" id="code-lead">Finish signing in in the Claude tab, copy its authorization code, then return here to paste it. Reopened this page? Your current step is restored.</p>
7219
7587
  <form id="verify">
7220
7588
  <label for="code">Authorization code<input id="code" type="password" autocomplete="off" spellcheck="false" required maxlength="4096"><span class="hint">The code stays hidden on screen. Never paste it into chat.</span></label>
7221
7589
  <button class="button" type="submit">Verify account</button>
@@ -7225,42 +7593,47 @@ function enrollmentPage() {
7225
7593
  <section class="card" id="step-confirm" hidden>
7226
7594
  <div class="avatar">${icon("person")}</div>
7227
7595
  <h1 tabindex="-1">Is this the right account?</h1>
7228
- <p class="lead">Claude verified the account below. Check it before adding it to the pool.</p>
7596
+ <p class="lead">Claude verified this account. Confirm to save its login. An existing account is updated, not duplicated; an operator's manual pause stays in place.</p>
7229
7597
  <form id="confirm">
7230
7598
  <div class="account">${icon("check")}<span id="account"></span></div>
7231
7599
  <label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
7232
- <button class="button" type="submit">Add to the pool</button>
7600
+ <button class="button" type="submit">Confirm connection</button>
7233
7601
  </form>
7234
- <p class="aside">Wrong account? Do not confirm: start again and sign in with the right one.<a class="button secondary" href="/pool-enroll">Start again</a></p>
7602
+ <p class="aside">Wrong account? Do not confirm. Use \u201CStart again\u201D below to choose the right one.</p>
7235
7603
  </section>
7236
7604
  <section class="card" id="step-done" hidden>
7237
7605
  <div class="avatar ok">${icon("check")}</div>
7238
- <h1 tabindex="-1">Subscription connected</h1>
7239
- <p class="lead"><strong id="connected-account"></strong> is now part of the shared agents pool. You can close this page.</p>
7240
- <div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership. It stays available for 24 hours while this page is open; it does not sign you out of Claude or cancel your subscription.<button class="button secondary" id="disconnect" type="button">Disconnect</button></div>
7606
+ <h1 id="done-title" tabindex="-1">Subscription connected</h1>
7607
+ <p class="lead"><strong id="connected-account"></strong><span id="connected-message"></span></p>
7608
+ <div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership. This browser can disconnect it for 24 hours, unless the server restarts or the account reconnects elsewhere. It does not sign you out of Claude or cancel your subscription.<button class="button secondary" id="disconnect" type="button">Disconnect</button></div>
7241
7609
  </section>
7242
7610
  <section class="card" id="step-error" hidden>
7243
7611
  <div class="avatar err">${icon("alert")}</div>
7244
7612
  <h1 tabindex="-1">This sign-in can't continue</h1>
7245
7613
  <p class="lead" id="error-message"></p>
7246
- <p class="aside">Nothing was added to the pool from this step.<a class="button secondary" href="/pool-enroll">Start again</a></p>
7614
+ <p class="aside">Resume to check your progress. Starting again does not disconnect a saved subscription.</p>
7615
+ <button class="button" id="recover" type="button">Resume sign-in</button>
7247
7616
  </section>
7248
7617
  <p id="status" class="notice err" role="alert" hidden></p>
7618
+ <p id="recovery" class="notice" role="status" hidden></p>
7619
+ <button class="button secondary" id="restart" type="button" hidden>Start again</button>
7249
7620
  </main>
7250
- <footer>Each step expires after 10 minutes. Nothing is added to the pool until you confirm.</footer>
7621
+ <footer>Sign-in steps expire after 10 minutes and can be resumed in the same browser. Allow cookies for this site. No subscription is added or updated until you confirm.</footer>
7251
7622
  <noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
7252
7623
  <script nonce="${nonce}">
7253
7624
  let token = location.hash.slice(1);
7254
- history.replaceState(null, '', location.pathname);
7625
+ if (!/^[A-Za-z0-9_-]{43}$/.test(token)) { token = ''; history.replaceState(null, '', location.pathname); }
7255
7626
  addEventListener('hashchange', () => { if (location.hash) location.reload(); });
7256
7627
  const get = id => document.getElementById(id);
7257
7628
  const steps = ['email', 'signin', 'code', 'confirm', 'done'];
7258
7629
  let current = 'email';
7630
+ let pending = 0;
7259
7631
  function show(step) {
7260
7632
  const failed = step === 'error';
7261
7633
  const index = steps.indexOf(failed ? current : step);
7262
7634
  if (!failed) current = step;
7263
7635
  for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
7636
+ get('restart').hidden = step === 'email';
7264
7637
  document.querySelectorAll('#stepper li').forEach((item, position) => {
7265
7638
  item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
7266
7639
  item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
@@ -7270,23 +7643,78 @@ function show(step) {
7270
7643
  (step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
7271
7644
  }
7272
7645
  async function send(step, body) {
7273
- const response = await fetch('/pool-enroll/' + step, {method:'POST', credentials:'omit', cache:'no-store', redirect:'error', headers:{'content-type':'application/json'}, body:JSON.stringify(body)});
7274
- const data = await response.json();
7275
- if (!response.ok) throw new Error(data.error || 'Sign-in failed. Start again.');
7276
- token = data.token || '';
7646
+ pending++;
7647
+ try {
7648
+ const response = await fetch('/pool-enroll/' + step, {method:'POST', credentials:'same-origin', cache:'no-store', redirect:'error', headers:{'content-type':'application/json'}, body:JSON.stringify(body)});
7649
+ const data = await response.json();
7650
+ if (!response.ok) { const error = new Error(data.error || 'Sign-in failed. Try resuming.'); error.status = response.status; throw error; }
7651
+ return data;
7652
+ } finally { pending--; }
7653
+ }
7654
+ async function post(step, values) {
7655
+ const data = await send(step, {...(token ? {token} : {}), ...values});
7656
+ token = ''; history.replaceState(null, '', location.pathname);
7277
7657
  return data;
7278
7658
  }
7279
- const post = (step, values) => send(step, {token, ...values});
7280
- function fail(error) {
7659
+ function destination(value) {
7660
+ const url = new URL(value);
7661
+ if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask for help.');
7662
+ return url.href;
7663
+ }
7664
+ function connected(data) {
7665
+ get('connected-account').textContent = data.email || '';
7666
+ get('done-title').textContent = data.paused ? 'Login saved \u2014 account still paused' : !data.inPool ? 'Login saved \u2014 account not in pool' : data.reconnected ? 'Subscription reconnected' : 'Subscription connected';
7667
+ get('connected-message').textContent = data.paused ? ' has a renewed login, but is still paused. Ask the pool operator to resume it.' : !data.inPool ? ' has a renewed login, but the operator has kept it outside the pool.' : ' is connected to the shared agents pool. You can close this page.';
7668
+ get('disconnect').disabled = false;
7669
+ show('done');
7670
+ }
7671
+ function restore(data) {
7672
+ get('signin-email').textContent = data.email || ''; get('signin-for').hidden = !data.email;
7673
+ get('consent').checked = false;
7674
+ if (data.stage === 'invited') show('signin');
7675
+ else if (data.stage === 'started') { get('reopen').href = destination(data.authUrl); show('code'); }
7676
+ else if (data.stage === 'verified') { get('account').textContent = data.email; show('confirm'); }
7677
+ else if (data.stage === 'connected') connected(data);
7678
+ else throw new Error('Sign-in state could not be restored. Start again.');
7679
+ }
7680
+ async function recover() {
7681
+ const data = await send('resume', {});
7682
+ token = ''; restore(data);
7683
+ get('recovery').textContent = 'Your progress is restored in this browser. Continue from this step.'; get('recovery').hidden = false;
7684
+ get('status').hidden = true;
7685
+ }
7686
+ function showError(error) {
7281
7687
  token = ''; get('code').value = '';
7282
- get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Start again.';
7688
+ get('recovery').hidden = true;
7689
+ get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Try resuming.';
7283
7690
  show('error');
7284
7691
  }
7285
- show(/^[A-Za-z0-9_-]{43}$/.test(token) ? 'signin' : 'email');
7692
+ async function fail(error) {
7693
+ try { await recover(); } catch { showError(error); }
7694
+ }
7695
+ if (/^[A-Za-z0-9_-]{43}$/.test(token)) show('signin');
7696
+ else { token = ''; recover().catch(error => { if (error.status === 410) show('email'); else showError(error); }); }
7697
+ addEventListener('pageshow', event => { if (event.persisted && !pending && !token) recover().catch(showError); });
7698
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible' && !pending && !token) recover().catch(error => { if (error.status === 410) show('email'); else showError(error); }); });
7699
+ get('recover').addEventListener('click', async () => {
7700
+ get('recover').disabled = true;
7701
+ try { await recover(); } catch (error) { showError(error); }
7702
+ finally { get('recover').disabled = false; }
7703
+ });
7704
+ get('restart').addEventListener('click', async () => {
7705
+ get('restart').disabled = true;
7706
+ try {
7707
+ await send('reset', {}); token = ''; get('code').value = ''; get('consent').checked = false;
7708
+ get('recovery').hidden = true; get('status').hidden = true; get('email-error').hidden = true; get('signin-notice').hidden = true;
7709
+ show('email');
7710
+ } catch (error) { showError(error); }
7711
+ finally { get('restart').disabled = false; }
7712
+ });
7286
7713
  get('request').addEventListener('submit', async event => {
7287
7714
  event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
7288
7715
  try {
7289
7716
  const data = await send('request', {email: get('email').value});
7717
+ token = ''; history.replaceState(null, '', location.pathname); get('recovery').hidden = true;
7290
7718
  get('signin-email').textContent = data.email; get('signin-for').hidden = false;
7291
7719
  show('signin');
7292
7720
  } catch (error) {
@@ -7299,24 +7727,26 @@ get('start').addEventListener('click', async () => {
7299
7727
  get('start').disabled = true;
7300
7728
  try {
7301
7729
  const data = await post('start', {});
7302
- const url = new URL(data.authUrl);
7303
- if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask for help.');
7304
- get('reopen').href = url.href;
7305
- if (tab) { tab.opener = null; tab.location.href = url.href; }
7306
- else get('code-lead').textContent = 'Your browser blocked the new tab. Open Claude sign-in with the link below, sign in, then paste the code it shows.';
7730
+ const url = destination(data.authUrl);
7731
+ get('reopen').href = url;
7732
+ if (tab) { tab.opener = null; tab.location.href = url; }
7733
+ else get('code-lead').textContent = 'The new tab was blocked. Use \u201COpen Claude sign-in again\u201D below. Copy the code Claude shows, then come back here to paste it.';
7307
7734
  show('code');
7308
- } catch (error) { if (tab) tab.close(); fail(error); }
7735
+ } catch (error) { if (tab) tab.close(); await fail(error); }
7736
+ finally { get('start').disabled = false; }
7309
7737
  });
7310
7738
  get('verify').addEventListener('submit', async event => {
7311
7739
  event.preventDefault(); event.submitter.disabled = true;
7312
7740
  const code = get('code').value.trim(); get('code').value = '';
7313
7741
  try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
7314
- catch (error) { fail(error); }
7742
+ catch (error) { await fail(error); }
7743
+ finally { event.submitter.disabled = false; }
7315
7744
  });
7316
7745
  get('confirm').addEventListener('submit', async event => {
7317
7746
  event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
7318
- try { await post('confirm', {consent:true}); get('connected-account').textContent = get('account').textContent; show('done'); }
7319
- catch (error) { fail(error); }
7747
+ try { connected(await post('confirm', {consent:true})); }
7748
+ catch (error) { await fail(error); }
7749
+ finally { event.submitter.disabled = false; }
7320
7750
  });
7321
7751
  get('disconnect').addEventListener('click', async () => {
7322
7752
  get('disconnect').disabled = true; get('status').hidden = true;
@@ -7428,12 +7858,68 @@ class EnrollmentHandlers {
7428
7858
  if (entry.expiresAt <= this.now())
7429
7859
  this.entries.delete(key);
7430
7860
  }
7431
- mint(details, state, duration) {
7861
+ mint(details, state, duration, browserSession) {
7432
7862
  const token = randomBytes2(32).toString("base64url");
7433
7863
  const expiresAt = this.now() + duration;
7434
- this.entries.set(hash(token), { details, state, expiresAt });
7864
+ this.entries.set(hash(token), {
7865
+ details,
7866
+ state,
7867
+ expiresAt,
7868
+ browserSession
7869
+ });
7435
7870
  return { token, expiresAt };
7436
7871
  }
7872
+ cookieToken(req) {
7873
+ const cookies = (req.headers.get("cookie") ?? "").split(";").map((part) => part.trim()).filter((part) => part.startsWith(`${sessionCookie}=`));
7874
+ const token = cookies.length === 1 ? cookies[0]?.slice(sessionCookie.length + 1) ?? "" : "";
7875
+ return /^[A-Za-z0-9_-]{43}$/.test(token) ? token : "";
7876
+ }
7877
+ cookieHeader(token, duration) {
7878
+ return `${sessionCookie}=${token}; Path=/pool-enroll; HttpOnly; SameSite=Strict; Max-Age=${Math.floor(duration / 1000)}${this.origin.protocol === "https:" ? "; Secure" : ""}`;
7879
+ }
7880
+ browserEntry(req) {
7881
+ const token = this.cookieToken(req);
7882
+ if (!token)
7883
+ return;
7884
+ const session = hash(token);
7885
+ return [...this.entries].find(([, entry]) => entry.browserSession === session);
7886
+ }
7887
+ mintBrowser(details, state, duration, extra, session = randomBytes2(32).toString("base64url")) {
7888
+ const response = json({
7889
+ ...this.mint(details, state, duration, hash(session)),
7890
+ ...extra
7891
+ });
7892
+ response.headers.set("set-cookie", this.cookieHeader(session, duration));
7893
+ return response;
7894
+ }
7895
+ next(entry, state, duration, req, extra) {
7896
+ const session = this.cookieToken(req);
7897
+ return this.mintBrowser(entry.details, state, duration, extra, session && entry.browserSession === hash(session) ? session : undefined);
7898
+ }
7899
+ resume(req) {
7900
+ const found = this.browserEntry(req);
7901
+ if (!found)
7902
+ throw new EnrollmentError(410, "No active sign-in. Enter your email to start again.");
7903
+ const [, entry] = found;
7904
+ const { state, details, expiresAt } = entry;
7905
+ if (state.kind === "busy")
7906
+ throw new EnrollmentError(409, "Sign-in is being updated in another tab. Try resuming in a moment.");
7907
+ if (state.kind === "connected") {
7908
+ const account2 = this.context.dbOps.getAccount(state.accountId);
7909
+ if (!account2 || account2.account_uuid !== state.accountUuid)
7910
+ throw new EnrollmentError(410, "This subscription has changed or was removed. Start again.");
7911
+ }
7912
+ return json({
7913
+ stage: state.kind,
7914
+ expiresAt,
7915
+ email: state.kind === "verified" ? state.seat.identity.email : state.kind === "connected" ? state.email : details.email,
7916
+ ...state.kind === "started" ? { authUrl: state.flow.authUrl } : {},
7917
+ ...state.kind === "connected" ? {
7918
+ reconnected: !!details.reconnect,
7919
+ ...this.connectionStatus(state.accountId)
7920
+ } : {}
7921
+ });
7922
+ }
7437
7923
  async guarded(action) {
7438
7924
  try {
7439
7925
  this.prune();
@@ -7448,14 +7934,14 @@ class EnrollmentHandlers {
7448
7934
  if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
7449
7935
  throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
7450
7936
  }
7451
- reserve(name) {
7452
- if (this.context.dbOps.getAccountByName(name))
7937
+ reserve(name, reconnect = false) {
7938
+ if (!reconnect && this.context.dbOps.getAccountByName(name))
7453
7939
  throw new EnrollmentError(409, "This seat is already in the pool.");
7454
7940
  for (const entry of this.entries.values())
7455
7941
  if (entry.details.name === name && entry.state.kind === "busy")
7456
7942
  throw new EnrollmentError(409, "Sign-in is already in progress");
7457
7943
  for (const [key, entry] of this.entries)
7458
- if (entry.details.name === name)
7944
+ if (entry.details.name === name && entry.state.kind !== "connected")
7459
7945
  this.entries.delete(key);
7460
7946
  if (this.entries.size >= 100)
7461
7947
  throw new EnrollmentError(429, "Too many pending invitations");
@@ -7465,12 +7951,32 @@ class EnrollmentHandlers {
7465
7951
  if (Object.keys(body).some((key) => key !== "email"))
7466
7952
  throw new EnrollmentError(400, "Unknown request field");
7467
7953
  const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
7468
- if (!this.context.config.getEnrollmentEmails().includes(email))
7469
- throw new EnrollmentError(403, "This email is not on the list. Ask the operator to add it.");
7954
+ if (!this.context.config.isEnrollmentEmailAllowed(email))
7955
+ throw new EnrollmentError(403, "This email is not allowed. Ask the operator to add its address or domain.");
7470
7956
  const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
7471
- this.reserve(name);
7472
- const issued = this.mint({ name, email, contactEmail: email }, { kind: "invited" }, tenMinutes);
7473
- return json({ ...issued, email });
7957
+ const { dbOps } = this.context;
7958
+ const contacts = dbOps.getAccountsByProvider("claude-code").filter((account2) => dbOps.getEnrollmentContact(account2.id)?.email?.toLowerCase() === email);
7959
+ if (contacts.length > 1)
7960
+ throw new EnrollmentError(409, "This email matches several seats. Ask the operator to check them.");
7961
+ const existing = contacts[0] ?? dbOps.getAccountByName(name);
7962
+ if (existing && (existing.provider !== "claude-code" || existing.auth_method !== "oauth" || !existing.account_uuid))
7963
+ throw new EnrollmentError(409, "This seat needs the operator's help to reconnect.");
7964
+ const details = {
7965
+ name: existing?.name ?? name,
7966
+ email,
7967
+ contactEmail: email,
7968
+ ...existing ? {
7969
+ reconnect: {
7970
+ id: existing.id,
7971
+ accountUuid: existing.account_uuid ?? null,
7972
+ organizationUuid: existing.organization_uuid ?? null
7973
+ }
7974
+ } : {}
7975
+ };
7976
+ this.reserve(details.name, !!existing);
7977
+ return this.mintBrowser(details, { kind: "invited" }, tenMinutes, {
7978
+ email
7979
+ });
7474
7980
  }
7475
7981
  emails = (req) => this.guarded(async () => {
7476
7982
  const body = await readBody(req);
@@ -7539,9 +8045,20 @@ class EnrollmentHandlers {
7539
8045
  const body = await readBody(req);
7540
8046
  if (url.pathname === "/pool-enroll/request")
7541
8047
  return this.request(body);
8048
+ if (url.pathname === "/pool-enroll/resume" || url.pathname === "/pool-enroll/reset") {
8049
+ if (Object.keys(body).length)
8050
+ throw new EnrollmentError(400, "No fields expected");
8051
+ if (url.pathname === "/pool-enroll/resume")
8052
+ return this.resume(req);
8053
+ const found = this.browserEntry(req);
8054
+ if (found)
8055
+ this.entries.delete(found[0]);
8056
+ const response = json({ reset: true });
8057
+ response.headers.set("set-cookie", this.cookieHeader("", 0));
8058
+ return response;
8059
+ }
7542
8060
  const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
7543
- const key = hash(token);
7544
- const entry = this.entries.get(key);
8061
+ const [key, entry] = body.token === undefined ? this.browserEntry(req) ?? ["", undefined] : [hash(token), this.entries.get(hash(token))];
7545
8062
  const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
7546
8063
  if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
7547
8064
  throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
@@ -7551,8 +8068,7 @@ class EnrollmentHandlers {
7551
8068
  if (state.kind === "invited") {
7552
8069
  const flow = await this.oauth.beginClaudeSeat();
7553
8070
  this.assertCurrent(key, entry);
7554
- return json({
7555
- ...this.mint(entry.details, { kind: "started", flow }, tenMinutes),
8071
+ return this.next(entry, { kind: "started", flow }, tenMinutes, req, {
7556
8072
  authUrl: flow.authUrl
7557
8073
  });
7558
8074
  }
@@ -7569,9 +8085,8 @@ class EnrollmentHandlers {
7569
8085
  const { email } = seat.identity;
7570
8086
  if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
7571
8087
  throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
7572
- this.assertNewSeat(entry.details.name, seat);
7573
- return json({
7574
- ...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
8088
+ this.assertSeat(entry.details, seat);
8089
+ return this.next(entry, { kind: "verified", seat }, tenMinutes, req, {
7575
8090
  email
7576
8091
  });
7577
8092
  }
@@ -7579,13 +8094,16 @@ class EnrollmentHandlers {
7579
8094
  if (body.consent !== true)
7580
8095
  throw new EnrollmentError(400, "Confirm the displayed account before adding it");
7581
8096
  const accountId = this.save(entry.details, state.seat);
7582
- return json({
8097
+ return this.next(entry, {
8098
+ kind: "connected",
8099
+ accountId,
8100
+ accountUuid: state.seat.identity.accountUuid,
8101
+ email: state.seat.identity.email ?? ""
8102
+ }, oneDay, req, {
7583
8103
  connected: true,
7584
- ...this.mint(entry.details, {
7585
- kind: "connected",
7586
- accountId,
7587
- accountUuid: state.seat.identity.accountUuid
7588
- }, oneDay)
8104
+ email: state.seat.identity.email,
8105
+ reconnected: !!entry.details.reconnect,
8106
+ ...this.connectionStatus(accountId)
7589
8107
  });
7590
8108
  }
7591
8109
  if (state.kind === "connected") {
@@ -7597,9 +8115,8 @@ class EnrollmentHandlers {
7597
8115
  entry.state = state;
7598
8116
  throw new EnrollmentError(500, "Removal could not be saved. Retry here or ask the operator to check this seat.");
7599
8117
  }
7600
- return json({
7601
- disconnected: true,
7602
- ...this.mint(entry.details, { kind: "invited" }, oneDay)
8118
+ return this.next({ ...entry, details: { ...entry.details, reconnect: undefined } }, { kind: "invited" }, oneDay, req, {
8119
+ disconnected: true
7603
8120
  });
7604
8121
  }
7605
8122
  throw new EnrollmentError(410, "Link already used");
@@ -7613,14 +8130,40 @@ class EnrollmentHandlers {
7613
8130
  if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
7614
8131
  throw new EnrollmentError(410, "Sign-in expired. Start again.");
7615
8132
  }
7616
- assertNewSeat(name, seat) {
7617
- if (this.context.dbOps.getAccountByName(name) || this.context.dbOps.getAccountsByProvider("claude-code").some((account2) => account2.account_uuid === seat.identity.accountUuid))
8133
+ assertSeat(details, seat) {
8134
+ if (details.reconnect) {
8135
+ const account2 = this.context.dbOps.getAccount(details.reconnect.id);
8136
+ if (!account2 || account2.provider !== "claude-code" || account2.auth_method !== "oauth" || account2.account_uuid !== details.reconnect.accountUuid || account2.organization_uuid !== details.reconnect.organizationUuid || account2.account_uuid !== seat.identity.accountUuid || account2.organization_uuid && account2.organization_uuid !== seat.identity.organizationUuid)
8137
+ throw new EnrollmentError(409, "This is not the saved Claude account, or the seat has changed. Ask the operator to check it.");
8138
+ return account2;
8139
+ }
8140
+ if (this.context.dbOps.getAccountByName(details.name) || this.context.dbOps.getAccountsByProvider("claude-code").some((account2) => account2.account_uuid === seat.identity.accountUuid))
7618
8141
  throw new EnrollmentError(409, "This seat is already connected. Ask the operator for help.");
8142
+ return null;
8143
+ }
8144
+ connectionStatus(accountId) {
8145
+ const account2 = this.context.dbOps.getAccount(accountId);
8146
+ return {
8147
+ paused: account2?.paused ?? false,
8148
+ inPool: !!account2?.account_uuid && this.context.config.getTeamRouting().allowlistedAccountUuids.includes(account2.account_uuid)
8149
+ };
7619
8150
  }
7620
8151
  save(details, seat) {
7621
8152
  const { dbOps, config } = this.context;
7622
8153
  return dbOps.getDatabase().transaction(() => {
7623
- this.assertNewSeat(details.name, seat);
8154
+ const existing = this.assertSeat(details, seat);
8155
+ if (existing) {
8156
+ dbOps.updateAccountTokens(existing.id, seat.tokens.accessToken, seat.tokens.expiresAt ?? null, seat.tokens.refreshToken ?? undefined);
8157
+ if ([
8158
+ "OAuth refresh was rejected by the upstream",
8159
+ "missing OAuth refresh token"
8160
+ ].includes(existing.error_reason ?? ""))
8161
+ dbOps.resumeAccount(existing.id);
8162
+ for (const [key, entry] of this.entries)
8163
+ if (entry.state.kind === "connected" && entry.state.accountId === existing.id)
8164
+ this.entries.delete(key);
8165
+ return existing.id;
8166
+ }
7624
8167
  const account2 = dbOps.createOAuthAccount({
7625
8168
  name: details.name,
7626
8169
  provider: "claude-code",
@@ -7689,7 +8232,7 @@ async function readBody(req) {
7689
8232
  reader.releaseLock();
7690
8233
  }
7691
8234
  }
7692
- var paths, tenMinutes = 600000, oneDay = 86400000, headers2, json = (value, status = 200) => Response.json(value, { status, headers: headers2 }), hash = (token) => createHash("sha256").update(token).digest("hex"), EnrollmentError;
8235
+ var paths, tenMinutes = 600000, oneDay = 86400000, sessionCookie = "agent_smith_enrollment", headers2, json = (value, status = 200) => Response.json(value, { status, headers: headers2 }), hash = (token) => createHash("sha256").update(token).digest("hex"), EnrollmentError;
7693
8236
  var init_enrollment = __esm(() => {
7694
8237
  init_src2();
7695
8238
  init_src8();
@@ -7701,7 +8244,9 @@ var init_enrollment = __esm(() => {
7701
8244
  "/pool-enroll/start",
7702
8245
  "/pool-enroll/verify",
7703
8246
  "/pool-enroll/confirm",
7704
- "/pool-enroll/disconnect"
8247
+ "/pool-enroll/disconnect",
8248
+ "/pool-enroll/resume",
8249
+ "/pool-enroll/reset"
7705
8250
  ]);
7706
8251
  headers2 = {
7707
8252
  "cache-control": "no-store",
@@ -7854,7 +8399,13 @@ function createCleanupHandler(dbOps, config) {
7854
8399
  function createCompactHandler(dbOps) {
7855
8400
  return () => {
7856
8401
  try {
7857
- dbOps.compact();
8402
+ const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
8403
+ if (!vacuumed) {
8404
+ return errorResponse(ServiceUnavailable("Not enough free disk space to compact", {
8405
+ freeBytes,
8406
+ requiredBytes
8407
+ }));
8408
+ }
7858
8409
  const result = {
7859
8410
  success: true,
7860
8411
  message: "Database compacted successfully"
@@ -7874,10 +8425,10 @@ var init_maintenance = __esm(() => {
7874
8425
  });
7875
8426
 
7876
8427
  // ../../packages/api/src/serializers/request.ts
7877
- function serializeRequestResponse(request2) {
8428
+ function serializeRequestResponse(request3) {
7878
8429
  return {
7879
- ...toRequestSummary(request2),
7880
- accountName: request2.accountName ?? null
8430
+ ...toRequestSummary(request3),
8431
+ accountName: request3.accountName ?? null
7881
8432
  };
7882
8433
  }
7883
8434
  function enrichRequestPayload(payload, accountName = null) {
@@ -7999,6 +8550,94 @@ var init_requests_stream = __esm(() => {
7999
8550
  init_src();
8000
8551
  });
8001
8552
 
8553
+ // ../../packages/api/src/handlers/reset-credits.ts
8554
+ function createResetCreditHandlers(context2) {
8555
+ const pending = new Set;
8556
+ const accountFor = (id) => {
8557
+ const account2 = context2.dbOps.getAccount(id);
8558
+ if (!account2)
8559
+ return { error: reply({ error: "Account not found" }, 404) };
8560
+ const provider = context2.providerRegistry.getProvider(account2.provider);
8561
+ if (!provider?.supportsResetCredits?.(account2) || !provider.listResetCredits || !provider.consumeResetCredit || !provider.readResetQuota)
8562
+ return {
8563
+ error: reply({ error: "Reset credits require a direct Codex subscription" }, 400)
8564
+ };
8565
+ return { account: account2, provider };
8566
+ };
8567
+ const accessToken = async (account2) => {
8568
+ if (!context2.getAccountAccessToken)
8569
+ throw new Error("Token service unavailable");
8570
+ return context2.getAccountAccessToken(account2);
8571
+ };
8572
+ return {
8573
+ list: async (id) => {
8574
+ const resolved = accountFor(id);
8575
+ if (resolved.error)
8576
+ return resolved.error;
8577
+ try {
8578
+ const { account: account2, provider } = resolved;
8579
+ return reply(await provider.listResetCredits?.(account2, await accessToken(account2)));
8580
+ } catch {
8581
+ return reply({
8582
+ error: "Could not read Codex reset credits. Check this account's sign-in and try again."
8583
+ }, 502);
8584
+ }
8585
+ },
8586
+ consume: async (req, id) => {
8587
+ const resolved = accountFor(id);
8588
+ if (resolved.error)
8589
+ return resolved.error;
8590
+ let attempt;
8591
+ try {
8592
+ const body = await parseJsonObject(req);
8593
+ if (body.confirmed !== true || typeof body.creditId !== "string" || body.creditId.trim().length === 0 || body.creditId.length > 256 || typeof body.requestId !== "string" || !UUID.test(body.requestId) || Object.keys(body).some((key) => !["confirmed", "creditId", "requestId"].includes(key)))
8594
+ return reply({
8595
+ error: "Confirm the selected creditId and supply a UUID requestId"
8596
+ }, 400);
8597
+ attempt = { creditId: body.creditId, requestId: body.requestId };
8598
+ } catch {
8599
+ return reply({ error: "Invalid reset request" }, 400);
8600
+ }
8601
+ if (pending.has(id))
8602
+ return reply({ error: "A reset is already in progress for this account" }, 409);
8603
+ pending.add(id);
8604
+ try {
8605
+ const { account: account2, provider } = resolved;
8606
+ const token = await accessToken(account2);
8607
+ const result = await provider.consumeResetCredit?.(account2, token, attempt);
8608
+ if (!result)
8609
+ throw new Error("Reset service unavailable");
8610
+ let quotaRefreshed = false;
8611
+ if (result.code === "reset" || result.code === "already_redeemed") {
8612
+ try {
8613
+ const quota2 = await provider.readResetQuota?.(account2, token);
8614
+ const saved = context2.dbOps.getAccount(id);
8615
+ if (quota2 && saved && saved.account_uuid === account2.account_uuid && saved.provider === account2.provider) {
8616
+ context2.dbOps.updateAccountQuotaState(id, {
8617
+ ...saved.quota_state,
8618
+ windows: { ...saved.quota_state?.windows, ...quota2.windows }
8619
+ });
8620
+ quotaRefreshed = true;
8621
+ }
8622
+ } catch {}
8623
+ }
8624
+ return reply({ ...result, quotaRefreshed });
8625
+ } catch {
8626
+ return reply({
8627
+ error: "Codex reset outcome is unconfirmed. Retry the same creditId and requestId; do not use another reset to test."
8628
+ }, 502);
8629
+ } finally {
8630
+ pending.delete(id);
8631
+ }
8632
+ }
8633
+ };
8634
+ }
8635
+ var UUID, reply = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
8636
+ var init_reset_credits2 = __esm(() => {
8637
+ init_json();
8638
+ UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8639
+ });
8640
+
8002
8641
  // ../../packages/api/src/handlers/stats.ts
8003
8642
  function createStatsHandler(dbOps) {
8004
8643
  return () => {
@@ -8074,17 +8713,22 @@ function blockedReason(account2, threshold, now) {
8074
8713
  function createFleetStatusHandler(dbOps, config, providerRegistry) {
8075
8714
  return () => {
8076
8715
  const now = Date.now();
8077
- const quotaThreshold = config.getRuntime().quotaThreshold;
8716
+ const { quotaThreshold, teamRouting } = config.getRuntime();
8078
8717
  const accounts = dbOps.getAllAccounts().map((account2) => ({
8079
8718
  ...serializeAccount(account2, providerRegistry, now),
8080
8719
  blockedReason: blockedReason(account2, quotaThreshold, now),
8081
8720
  quotaWindows: account2.quota_state?.windows ?? {},
8082
8721
  outsideSpend: account2.quota_state?.outsideSpend ?? {}
8083
8722
  }));
8084
- return jsonResponse({ accounts, quotaThreshold });
8723
+ return jsonResponse({
8724
+ accounts,
8725
+ quotaThreshold,
8726
+ nextWindowWarmupAt: nextWindowWarmupAt(teamRouting, now)
8727
+ });
8085
8728
  };
8086
8729
  }
8087
8730
  var init_status = __esm(() => {
8731
+ init_src4();
8088
8732
  init_src6();
8089
8733
  init_src();
8090
8734
  init_account();
@@ -8136,6 +8780,9 @@ class APIRouter {
8136
8780
  const statsResetHandler = createStatsResetHandler(dbOps);
8137
8781
  const fleetStatusHandler = createFleetStatusHandler(dbOps, config, providerRegistry);
8138
8782
  const accountsHandler = createAccountsListHandler(dbOps, providerRegistry);
8783
+ const resetCredits = createResetCreditHandlers(this.context);
8784
+ this.addDynamicRoute("GET", "/api/accounts/:accountId/reset-credits", (_req, _url, params) => resetCredits.list(params.accountId));
8785
+ this.addDynamicRoute("POST", "/api/accounts/:accountId/reset-credits/consume", (req, _url, params) => resetCredits.consume(req, params.accountId));
8139
8786
  const accountAddHandler = createAccountAddHandler(dbOps, config, providerRegistry);
8140
8787
  const requestsSummaryHandler = createRequestsSummaryHandler(dbOps);
8141
8788
  const requestsDetailHandler = createRequestsDetailHandler(dbOps);
@@ -8294,6 +8941,7 @@ var init_router = __esm(() => {
8294
8941
  init_oauth6();
8295
8942
  init_requests();
8296
8943
  init_requests_stream();
8944
+ init_reset_credits2();
8297
8945
  init_stats2();
8298
8946
  init_status();
8299
8947
  });
@@ -8324,6 +8972,14 @@ var init_background_tasks = __esm(() => {
8324
8972
  });
8325
8973
 
8326
8974
  // ../../packages/proxy/src/seat-usage.ts
8975
+ function expiringReset(provider, account2, model, now) {
8976
+ const buckets = provider.quotaBucketsFor(model);
8977
+ const resets = Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
8978
+ const horizon = provider.isFiveHourBucket(bucket) ? 60 * 60000 : provider.isWeeklyBucket(bucket) ? 24 * 60 * 60000 : 0;
8979
+ return horizon > 0 && (buckets?.includes(bucket) ?? true) && window2.resetAt !== null && window2.resetAt > now && window2.resetAt - now <= horizon && window2.seenAt <= now && isCurrentQuotaWindow(window2, now) && window2.status !== "rejected" && window2.utilization !== null && window2.utilization >= 0 && window2.utilization < 1 ? [window2.resetAt] : [];
8980
+ });
8981
+ return Math.min(...resets, Number.POSITIVE_INFINITY);
8982
+ }
8327
8983
  function liveUtilization(window2, now) {
8328
8984
  if (window2.utilization === null)
8329
8985
  return 0;
@@ -8346,11 +9002,11 @@ function soonestWeeklyReset(provider, account2, now) {
8346
9002
  const resets = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => provider.isWeeklyBucket(bucket) && window2.resetAt !== null && window2.resetAt > now).map(([, window2]) => window2.resetAt);
8347
9003
  return Math.min(...resets, Number.POSITIVE_INFINITY);
8348
9004
  }
8349
- function compareSeatUsage(provider, model, now) {
9005
+ function compareSeatUsage(provider, model, now, preferExpiringQuota = false) {
8350
9006
  return (left, right) => {
8351
9007
  const a = seatUsage(provider, left, model, now);
8352
9008
  const b = seatUsage(provider, right, model, now);
8353
- return a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
9009
+ return (preferExpiringQuota ? expiringReset(provider, left, model, now) - expiringReset(provider, right, model, now) : 0) || a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
8354
9010
  };
8355
9011
  }
8356
9012
  var init_seat_usage = __esm(() => {
@@ -8362,12 +9018,12 @@ import { createHash as createHash2 } from "crypto";
8362
9018
  function isRecord5(value) {
8363
9019
  return typeof value === "object" && value !== null && !Array.isArray(value);
8364
9020
  }
8365
- function openingDigest(request2, provider) {
8366
- if (!request2.body || request2.body.byteLength > MAX_OPENING_BYTES || !request2.contentType?.toLowerCase().includes("application/json")) {
9021
+ function openingDigest(request3, provider) {
9022
+ if (!request3.body || request3.body.byteLength > MAX_OPENING_BYTES || !request3.contentType?.toLowerCase().includes("application/json")) {
8367
9023
  return null;
8368
9024
  }
8369
9025
  try {
8370
- const parsed = JSON.parse(new TextDecoder().decode(request2.body));
9026
+ const parsed = JSON.parse(new TextDecoder().decode(request3.body));
8371
9027
  if (!isRecord5(parsed))
8372
9028
  return null;
8373
9029
  const opening = provider.getConversationOpening?.(parsed);
@@ -8378,14 +9034,14 @@ function openingDigest(request2, provider) {
8378
9034
  return null;
8379
9035
  }
8380
9036
  }
8381
- function pinKey(request2, provider) {
8382
- if (!request2.sessionId)
9037
+ function pinKey(request3, provider) {
9038
+ if (!request3.sessionId)
8383
9039
  return null;
8384
- const digest = openingDigest(request2, provider) ?? "no-opening";
9040
+ const digest = openingDigest(request3, provider) ?? "no-opening";
8385
9041
  return createHash2("sha256").update([
8386
- request2.pinScope ?? request2.provider,
8387
- request2.pinBucket ?? provider.weeklyBucketFor(request2.model) ?? "",
8388
- request2.sessionId,
9042
+ request3.pinScope ?? request3.provider,
9043
+ request3.pinBucket ?? provider.weeklyBucketFor(request3.model) ?? "",
9044
+ request3.sessionId,
8389
9045
  digest
8390
9046
  ].join("\x00")).digest("hex");
8391
9047
  }
@@ -8396,15 +9052,15 @@ function isAllowlisted(account2, config) {
8396
9052
  class TeamRouter {
8397
9053
  inFlight = new Map;
8398
9054
  pins = new Map;
8399
- order(accounts, request2, config, provider, store, now = Date.now()) {
8400
- if (!config.enabled || !request2)
9055
+ order(accounts, request3, config, provider, store, now = Date.now()) {
9056
+ if (!config.enabled || !request3)
8401
9057
  return accounts;
8402
9058
  this.removeExpiredPins(now, store);
8403
- const eligible = this.eligibleAccounts(accounts, request2, config);
9059
+ const eligible = this.eligibleAccounts(accounts, request3, config);
8404
9060
  if (eligible.length === 0)
8405
9061
  return [];
8406
- const key = pinKey(request2, provider);
8407
- const pinnedId = this.getPinnedAccountId(request2, config, provider, store, now);
9062
+ const key = pinKey(request3, provider);
9063
+ const pinnedId = this.getPinnedAccountId(request3, config, provider, store, now);
8408
9064
  const pinned = pinnedId ? eligible.find((account2) => account2.id === pinnedId) : undefined;
8409
9065
  if (pinned && key) {
8410
9066
  this.touchPin(key, pinned.id, now, store);
@@ -8415,27 +9071,27 @@ class TeamRouter {
8415
9071
  }
8416
9072
  if (!config.distributionEnabled || !key)
8417
9073
  return eligible;
8418
- const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request2.model, now), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
9074
+ const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
8419
9075
  this.touchPin(key, selected.id, now, store);
8420
9076
  return [
8421
9077
  selected,
8422
9078
  ...eligible.filter((account2) => account2.id !== selected.id)
8423
9079
  ];
8424
9080
  }
8425
- eligibleAccounts(accounts, request2, config) {
9081
+ eligibleAccounts(accounts, request3, config) {
8426
9082
  if (!config.enabled)
8427
9083
  return accounts;
8428
9084
  const eligible = accounts.filter((account2) => isAllowlisted(account2, config));
8429
- if (!request2?.manualAccountName)
9085
+ if (!request3?.manualAccountName)
8430
9086
  return eligible;
8431
- return eligible.filter((account2) => account2.name === request2.manualAccountName);
9087
+ return eligible.filter((account2) => account2.name === request3.manualAccountName);
8432
9088
  }
8433
- getPinnedAccountId(request2, config, provider, store, now = Date.now()) {
8434
- if (!config.enabled || !request2?.sessionId || request2.manualAccountName) {
9089
+ getPinnedAccountId(request3, config, provider, store, now = Date.now()) {
9090
+ if (!config.enabled || !request3?.sessionId || request3.manualAccountName) {
8435
9091
  return;
8436
9092
  }
8437
9093
  this.removeExpiredPins(now, store);
8438
- const key = pinKey(request2, provider);
9094
+ const key = pinKey(request3, provider);
8439
9095
  return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
8440
9096
  }
8441
9097
  begin(accountId) {
@@ -8449,10 +9105,10 @@ class TeamRouter {
8449
9105
  }
8450
9106
  this.inFlight.set(accountId, current - 1);
8451
9107
  }
8452
- rebind(request2, accountId, config, provider, store, now = Date.now()) {
8453
- if (!config.enabled || request2?.manualAccountName)
9108
+ rebind(request3, accountId, config, provider, store, now = Date.now()) {
9109
+ if (!config.enabled || request3?.manualAccountName)
8454
9110
  return;
8455
- const key = request2 ? pinKey(request2, provider) : null;
9111
+ const key = request3 ? pinKey(request3, provider) : null;
8456
9112
  if (key)
8457
9113
  this.touchPin(key, accountId, now, store);
8458
9114
  }
@@ -8523,18 +9179,32 @@ var init_proxy_types = __esm(() => {
8523
9179
  });
8524
9180
 
8525
9181
  // ../../packages/proxy/src/handlers/token-manager.ts
8526
- function refreshBackoffUntil(accountId, now = Date.now()) {
8527
- const failure = refreshFailures.get(accountId);
9182
+ function refreshBackoffUntil(account2, now = Date.now()) {
9183
+ const failure = refreshFailures.get(account2.id);
9184
+ if (failure && (failure.accessToken !== account2.access_token || failure.refreshToken !== account2.refresh_token)) {
9185
+ refreshFailures.delete(account2.id);
9186
+ return null;
9187
+ }
8528
9188
  return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
8529
9189
  }
8530
9190
  function quarantineAccount(account2, ctx, reason) {
9191
+ const { access_token: accessToken, refresh_token: refreshToken } = account2;
8531
9192
  account2.paused = true;
8532
9193
  account2.error_reason = reason;
8533
- ctx.asyncWriter.enqueue(() => ctx.dbOps.markAccountError(account2.id, reason));
9194
+ ctx.asyncWriter.enqueue(() => {
9195
+ const saved = ctx.dbOps.getAccount(account2.id);
9196
+ if (saved?.access_token === accessToken && saved.refresh_token === refreshToken && !(saved.paused && !saved.error_reason))
9197
+ ctx.dbOps.markAccountError(account2.id, reason);
9198
+ });
8534
9199
  }
8535
9200
  function recordRefreshFailure(account2, ctx, error) {
8536
9201
  const refreshError = new TokenRefreshError(account2.id, error);
8537
- refreshFailures.set(account2.id, { at: Date.now(), error: refreshError });
9202
+ refreshFailures.set(account2.id, {
9203
+ at: Date.now(),
9204
+ error: refreshError,
9205
+ accessToken: account2.access_token,
9206
+ refreshToken: account2.refresh_token
9207
+ });
8538
9208
  const status = error?.status;
8539
9209
  if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
8540
9210
  quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
@@ -8544,7 +9214,7 @@ function recordRefreshFailure(account2, ctx, error) {
8544
9214
  }
8545
9215
  async function refreshAccessTokenSafe(account2, ctx) {
8546
9216
  const lastFailure = refreshFailures.get(account2.id);
8547
- if (lastFailure && refreshBackoffUntil(account2.id) !== null) {
9217
+ if (lastFailure && refreshBackoffUntil(account2) !== null) {
8548
9218
  log18.warn(`Account ${account2.name} is in refresh backoff period`);
8549
9219
  throw lastFailure.error;
8550
9220
  }
@@ -8552,8 +9222,20 @@ async function refreshAccessTokenSafe(account2, ctx) {
8552
9222
  if (!ctx.provider.refreshToken) {
8553
9223
  throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
8554
9224
  }
9225
+ const { access_token: accessToken, refresh_token: refreshToken } = account2;
9226
+ const reconnected = () => {
9227
+ const saved = ctx.dbOps.getAccount(account2.id);
9228
+ return saved && (saved.access_token !== accessToken || saved.refresh_token !== refreshToken) ? saved : null;
9229
+ };
8555
9230
  const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
8556
- ctx.asyncWriter.enqueue(() => ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken));
9231
+ const saved = reconnected();
9232
+ if (saved?.access_token)
9233
+ return saved.access_token;
9234
+ ctx.asyncWriter.enqueue(() => {
9235
+ if (reconnected())
9236
+ return;
9237
+ ctx.dbOps.updateAccountTokens(account2.id, result.accessToken, result.expiresAt, result.refreshToken);
9238
+ });
8557
9239
  account2.access_token = result.accessToken;
8558
9240
  account2.expires_at = result.expiresAt;
8559
9241
  if (result.refreshToken) {
@@ -8564,6 +9246,9 @@ async function refreshAccessTokenSafe(account2, ctx) {
8564
9246
  log18.info(`Successfully refreshed token for account: ${account2.name}`);
8565
9247
  return result.accessToken;
8566
9248
  }).catch((error) => {
9249
+ const saved = reconnected();
9250
+ if (saved?.access_token)
9251
+ return saved.access_token;
8567
9252
  throw recordRefreshFailure(account2, ctx, error);
8568
9253
  }).finally(() => {
8569
9254
  ctx.refreshInFlight.delete(account2.id);
@@ -8602,32 +9287,44 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
8602
9287
  const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
8603
9288
  return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
8604
9289
  }
8605
- function pooledMaxUsage(account2, ctx) {
9290
+ function pooledMaxUsage(provider, account2, bucket, ctx) {
8606
9291
  const teamRouting = ctx.runtime.teamRouting;
8607
- return teamRouting?.enabled === true && isAllowlisted(account2, teamRouting) ? teamRouting.maxUsage : undefined;
9292
+ if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
9293
+ return;
9294
+ if (!provider.isWeeklyBucket(bucket))
9295
+ return teamRouting.maxUsage;
9296
+ const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
9297
+ const override = email ? teamRouting.weeklyMaxUsageByEmail[email] : undefined;
9298
+ return Math.min(teamRouting.weeklyMaxUsage, override ?? teamRouting.weeklyMaxUsage);
8608
9299
  }
8609
9300
  function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
8610
9301
  const quota2 = account2.quota_state;
8611
9302
  if (!quota2)
8612
9303
  return true;
8613
9304
  for (const [name, window2] of Object.entries(quota2.windows)) {
8614
- if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(account2, ctx))) {
9305
+ if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx))) {
8615
9306
  return false;
8616
9307
  }
8617
9308
  }
8618
9309
  return true;
8619
9310
  }
8620
9311
  function fleetAccounts(provider, ctx) {
9312
+ return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
9313
+ }
9314
+ function isFleetSeat(account2, ctx) {
8621
9315
  const teamRouting = ctx.runtime.teamRouting;
8622
- return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting)));
9316
+ return !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting));
8623
9317
  }
8624
9318
  function cooldownEnd(account2, now) {
8625
9319
  const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
8626
- const refreshEnd = refreshBackoffUntil(account2.id, now);
9320
+ const refreshEnd = refreshBackoffUntil(account2, now);
8627
9321
  return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
8628
9322
  }
9323
+ function isServableSeat(provider, account2, model, ctx, now) {
9324
+ return isFleetSeat(account2, ctx) && cooldownEnd(account2, now) === null && isQuotaEligible(provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
9325
+ }
8629
9326
  function blockingResets(provider, account2, model, ctx, now) {
8630
- return Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(account2, ctx))).map(([, window2]) => window2.resetAt);
9327
+ 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))).map(([, window2]) => window2.resetAt);
8631
9328
  }
8632
9329
  function servableAt(provider, account2, model, ctx, now) {
8633
9330
  const cooldown = cooldownEnd(account2, now);
@@ -8654,7 +9351,7 @@ function getPoolStatus(provider, model, ctx) {
8654
9351
  const config = ctx.runtime.teamRouting;
8655
9352
  const now = Date.now();
8656
9353
  const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
8657
- const eligibleAccounts = accounts.filter((account2) => cooldownEnd(account2, now) === null && isQuotaEligible(providerStrategy, account2, ctx.runtime.quotaThreshold, now, model, ctx)).length;
9354
+ const eligibleAccounts = accounts.filter((account2) => isServableSeat(providerStrategy, account2, model, ctx, now)).length;
8658
9355
  return {
8659
9356
  version: 1,
8660
9357
  provider,
@@ -8672,14 +9369,14 @@ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
8672
9369
  function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
8673
9370
  return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8674
9371
  }
8675
- function selectRevalidationProbe(accounts, ctx, now) {
9372
+ function selectRevalidationProbe(accounts, ctx, now, model) {
8676
9373
  const probes = ctx.quotaProbeAt;
8677
9374
  const lastProbeAt = probes?.get(ctx.providerName);
8678
9375
  if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
8679
9376
  return [];
8680
9377
  }
8681
9378
  const [probe] = accounts.filter((account2) => {
8682
- return pooledMaxUsage(account2, ctx) === undefined || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, undefined, ctx);
9379
+ return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
8683
9380
  }).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
8684
9381
  if (!probe)
8685
9382
  return [];
@@ -8688,9 +9385,9 @@ function selectRevalidationProbe(accounts, ctx, now) {
8688
9385
  }
8689
9386
  function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
8690
9387
  const now = Date.now();
8691
- const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2.id, now) === null);
9388
+ const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
8692
9389
  const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
8693
- const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now);
9390
+ const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model);
8694
9391
  const prioritized = [...candidates].sort((left, right) => {
8695
9392
  const priority = (left.priority ?? 0) - (right.priority ?? 0);
8696
9393
  return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
@@ -8999,13 +9696,17 @@ class TeamAdmission {
8999
9696
  const account2 = this.account(accountId, {
9000
9697
  enabled: true,
9001
9698
  distributionEnabled: true,
9699
+ preferExpiringQuota: false,
9002
9700
  allowlistedAccountUuids: [],
9003
9701
  maxUsage: 0.9,
9702
+ weeklyMaxUsage: 0.95,
9703
+ weeklyMaxUsageByEmail: {},
9004
9704
  admissionCap: 1,
9005
9705
  admissionQueueLimit: 0,
9006
9706
  admissionWaitMs: 0,
9007
9707
  holdSeconds: 0,
9008
- quotaProbeSeconds: 0
9708
+ quotaProbeSeconds: 0,
9709
+ windowWarmup: WINDOW_WARMUP_DEFAULTS
9009
9710
  });
9010
9711
  if (account2.active > 0 || account2.queue.length > 0)
9011
9712
  return;
@@ -9098,6 +9799,7 @@ class TeamAdmission {
9098
9799
  }
9099
9800
  var RAMP_INTERVAL_MS = 250, RAMP_WINDOW_MS = 30000, TeamAdmissionError;
9100
9801
  var init_team_admission = __esm(() => {
9802
+ init_src4();
9101
9803
  TeamAdmissionError = class TeamAdmissionError extends Error {
9102
9804
  constructor(message) {
9103
9805
  super(message);
@@ -9151,7 +9853,8 @@ async function forwardToClient(options, ctx) {
9151
9853
  isStream,
9152
9854
  providerName: ctx.providerName,
9153
9855
  retryAttempt,
9154
- failoverAttempts
9856
+ failoverAttempts,
9857
+ storePayload: ctx.runtime.storeRequestPayloads
9155
9858
  };
9156
9859
  ctx.usageWorker.postMessage(startMessage);
9157
9860
  requestEvents.emit("event", {
@@ -9454,8 +10157,8 @@ function retryAfterMs(response) {
9454
10157
  if (Number.isFinite(seconds)) {
9455
10158
  return Math.max(0, seconds) * 1000;
9456
10159
  }
9457
- const date = Date.parse(value);
9458
- return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
10160
+ const date2 = Date.parse(value);
10161
+ return Number.isNaN(date2) ? undefined : Math.max(0, date2 - Date.now());
9459
10162
  }
9460
10163
  async function isQuotaRejection(response, provider) {
9461
10164
  return await provider.isQuotaRejection?.(response) ?? false;
@@ -9912,37 +10615,37 @@ function quotaExhaustionResponse(resetAt2) {
9912
10615
  headers: { "retry-after": String(retryAfterSeconds) }
9913
10616
  });
9914
10617
  }
9915
- async function attemptAccount(request2, account2, failoverAttempts) {
9916
- request2.req.signal.throwIfAborted();
9917
- const admission = request2.ctx.teamAdmission;
10618
+ async function attemptAccount(request3, account2, failoverAttempts) {
10619
+ request3.req.signal.throwIfAborted();
10620
+ const admission = request3.ctx.teamAdmission;
9918
10621
  let permit;
9919
10622
  try {
9920
- permit = request2.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request2.ctx.runtime.teamRouting, request2.req.signal) : undefined;
10623
+ permit = request3.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request3.ctx.runtime.teamRouting, request3.req.signal) : undefined;
9921
10624
  } catch (error) {
9922
10625
  if (error instanceof TeamAdmissionError) {
9923
- throw new ServiceUnavailableError(error.message, request2.ctx.providerName, admissionRetrySeconds(request2.req));
10626
+ throw new ServiceUnavailableError(error.message, request3.ctx.providerName, admissionRetrySeconds(request3.req));
9924
10627
  }
9925
10628
  throw error;
9926
10629
  }
9927
10630
  if (permit)
9928
- request2.ctx.teamRouter?.begin(account2.id);
9929
- request2.ctx.outsideSpendTracker?.begin(account2.id);
10631
+ request3.ctx.teamRouter?.begin(account2.id);
10632
+ request3.ctx.outsideSpendTracker?.begin(account2.id);
9930
10633
  const release = () => {
9931
10634
  permit?.release();
9932
10635
  if (permit)
9933
- request2.ctx.teamRouter?.end(account2.id);
9934
- request2.ctx.outsideSpendTracker?.end(account2.id);
10636
+ request3.ctx.teamRouter?.end(account2.id);
10637
+ request3.ctx.outsideSpendTracker?.end(account2.id);
9935
10638
  };
9936
10639
  try {
9937
- const attempt = await proxyWithAccount(request2.req, request2.url, account2, request2.meta, request2.body, (body) => createBodyStream(body), request2.thread, failoverAttempts, request2.mappedModel, request2.ctx);
10640
+ const attempt = await proxyWithAccount(request3.req, request3.url, account2, request3.meta, request3.body, (body) => createBodyStream(body), request3.thread, failoverAttempts, request3.mappedModel, request3.ctx);
9938
10641
  if (attempt.kind === "response") {
9939
- const spentExtraUsage = request2.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
10642
+ const spentExtraUsage = request3.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
9940
10643
  return {
9941
10644
  ...attempt,
9942
10645
  response: releaseAfterResponse(attempt.response, () => {
9943
10646
  release();
9944
10647
  if (spentExtraUsage) {
9945
- request2.ctx.seatAlerts?.extraUsageSpent(account2, request2.ctx.providerName);
10648
+ request3.ctx.seatAlerts?.extraUsageSpent(account2, request3.ctx.providerName);
9946
10649
  }
9947
10650
  })
9948
10651
  };
@@ -9954,14 +10657,14 @@ async function attemptAccount(request2, account2, failoverAttempts) {
9954
10657
  throw error;
9955
10658
  }
9956
10659
  }
9957
- async function resolvePerMinuteRateLimit(request2, account2, failoverAttempts, attempt) {
10660
+ async function resolvePerMinuteRateLimit(request3, account2, failoverAttempts, attempt) {
9958
10661
  if (attempt.retryAfterMs > MAX_INLINE_RATE_LIMIT_RETRY_MS) {
9959
10662
  return await attempt.forward();
9960
10663
  }
9961
10664
  if (attempt.retryAfterMs > 0) {
9962
10665
  await Bun.sleep(attempt.retryAfterMs);
9963
10666
  }
9964
- const retryAttempt = await attemptAccount(request2, account2, failoverAttempts);
10667
+ const retryAttempt = await attemptAccount(request3, account2, failoverAttempts);
9965
10668
  if (retryAttempt.kind === "response") {
9966
10669
  return retryAttempt.response;
9967
10670
  }
@@ -9970,26 +10673,26 @@ async function resolvePerMinuteRateLimit(request2, account2, failoverAttempts, a
9970
10673
  }
9971
10674
  return await attempt.forward();
9972
10675
  }
9973
- async function resolveRequestScopedRateLimit(request2, accounts, index, attempt) {
10676
+ async function resolveRequestScopedRateLimit(request3, accounts, index, attempt) {
9974
10677
  const sibling = accounts[index + 1];
9975
10678
  if (!sibling) {
9976
10679
  return await attempt.forward();
9977
10680
  }
9978
- request2.ctx.teamAdmission?.armSwitch(sibling.id);
9979
- const siblingAttempt = await attemptAccount(request2, sibling, index + 1);
10681
+ request3.ctx.teamAdmission?.armSwitch(sibling.id);
10682
+ const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
9980
10683
  if (siblingAttempt.kind === "response") {
9981
10684
  return siblingAttempt.response;
9982
10685
  }
9983
10686
  if (siblingAttempt.kind === "per-minute-rate-limit") {
9984
- return await resolvePerMinuteRateLimit(request2, sibling, index + 1, siblingAttempt);
10687
+ return await resolvePerMinuteRateLimit(request3, sibling, index + 1, siblingAttempt);
9985
10688
  }
9986
10689
  if (siblingAttempt.kind !== "request-scoped-rate-limit") {
9987
10690
  return await attempt.forward();
9988
10691
  }
9989
- if (request2.ctx.runtime.requestScopedRetryDelayMs > 0) {
9990
- await Bun.sleep(request2.ctx.runtime.requestScopedRetryDelayMs);
10692
+ if (request3.ctx.runtime.requestScopedRetryDelayMs > 0) {
10693
+ await Bun.sleep(request3.ctx.runtime.requestScopedRetryDelayMs);
9991
10694
  }
9992
- const retryAttempt = await attemptAccount(request2, sibling, index + 1);
10695
+ const retryAttempt = await attemptAccount(request3, sibling, index + 1);
9993
10696
  if (retryAttempt.kind === "response") {
9994
10697
  return retryAttempt.response;
9995
10698
  }
@@ -9998,14 +10701,14 @@ async function resolveRequestScopedRateLimit(request2, accounts, index, attempt)
9998
10701
  }
9999
10702
  return await attempt.forward();
10000
10703
  }
10001
- async function resolveQuotaRateLimit(request2, accounts, index, attempt) {
10704
+ async function resolveQuotaRateLimit(request3, accounts, index, attempt) {
10002
10705
  const sibling = accounts[index + 1];
10003
10706
  if (!sibling)
10004
10707
  return await attempt.forward();
10005
- request2.ctx.teamAdmission?.armSwitch(sibling.id);
10006
- const siblingAttempt = await attemptAccount(request2, sibling, index + 1);
10708
+ request3.ctx.teamAdmission?.armSwitch(sibling.id);
10709
+ const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
10007
10710
  if (siblingAttempt.kind === "response") {
10008
- request2.ctx.teamRouter?.rebind(request2.teamRequest, sibling.id, request2.ctx.runtime.teamRouting, request2.ctx.provider, request2.ctx.dbOps);
10711
+ request3.ctx.teamRouter?.rebind(request3.teamRequest, sibling.id, request3.ctx.runtime.teamRouting, request3.ctx.provider, request3.ctx.dbOps);
10009
10712
  return siblingAttempt.response;
10010
10713
  }
10011
10714
  if (siblingAttempt.kind === "authentication-failure") {
@@ -10021,13 +10724,13 @@ async function resolveQuotaRateLimit(request2, accounts, index, attempt) {
10021
10724
  return await attempt.forward();
10022
10725
  }
10023
10726
  }
10024
- async function resolveUpstreamFailure(request2, accounts, index, attempt) {
10727
+ async function resolveUpstreamFailure(request3, accounts, index, attempt) {
10025
10728
  const sibling = accounts[index + 1];
10026
10729
  if (!sibling) {
10027
10730
  return await attempt.forward();
10028
10731
  }
10029
- request2.ctx.teamAdmission?.armSwitch(sibling.id);
10030
- const siblingAttempt = await attemptAccount(request2, sibling, index + 1);
10732
+ request3.ctx.teamAdmission?.armSwitch(sibling.id);
10733
+ const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
10031
10734
  if (siblingAttempt.kind === "response") {
10032
10735
  await discardAttempt(attempt);
10033
10736
  return siblingAttempt.response;
@@ -10054,12 +10757,12 @@ async function discardAttempt(attempt) {
10054
10757
  log21.warn(`Could not close a discarded upstream stream: ${error instanceof Error ? error.message : String(error)}`);
10055
10758
  }
10056
10759
  }
10057
- async function resolveTransportFailure(request2, accounts, index) {
10760
+ async function resolveTransportFailure(request3, accounts, index) {
10058
10761
  const sibling = accounts[index + 1];
10059
10762
  if (!sibling)
10060
10763
  return new Response("Bad Gateway", { status: 502 });
10061
- request2.ctx.teamAdmission?.armSwitch(sibling.id);
10062
- const siblingAttempt = await attemptAccount(request2, sibling, index + 1);
10764
+ request3.ctx.teamAdmission?.armSwitch(sibling.id);
10765
+ const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
10063
10766
  if (siblingAttempt.kind === "response")
10064
10767
  return siblingAttempt.response;
10065
10768
  switch (siblingAttempt.kind) {
@@ -10071,31 +10774,31 @@ async function resolveTransportFailure(request2, accounts, index) {
10071
10774
  return new Response("Bad Gateway", { status: 502 });
10072
10775
  }
10073
10776
  }
10074
- async function proxySelectedAccounts(request2, accounts) {
10777
+ async function proxySelectedAccounts(request3, accounts) {
10075
10778
  for (let index = 0;index < accounts.length; index += 1) {
10076
- const attempt = await attemptAccount(request2, accounts[index], index);
10779
+ const attempt = await attemptAccount(request3, accounts[index], index);
10077
10780
  if (attempt.kind === "response")
10078
10781
  return attempt.response;
10079
10782
  if (attempt.kind === "authentication-failure") {
10080
10783
  return new Response("Bad Gateway", { status: 502 });
10081
10784
  }
10082
10785
  if (attempt.kind === "per-minute-rate-limit") {
10083
- return await resolvePerMinuteRateLimit(request2, accounts[index], index, attempt);
10786
+ return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
10084
10787
  }
10085
10788
  if (attempt.kind === "request-scoped-rate-limit") {
10086
- return await resolveRequestScopedRateLimit(request2, accounts, index, attempt);
10789
+ return await resolveRequestScopedRateLimit(request3, accounts, index, attempt);
10087
10790
  }
10088
10791
  if (attempt.kind === "quota-rate-limit") {
10089
- return await resolveQuotaRateLimit(request2, accounts, index, attempt);
10792
+ return await resolveQuotaRateLimit(request3, accounts, index, attempt);
10090
10793
  }
10091
10794
  if (attempt.kind === "upstream-failure") {
10092
- return await resolveUpstreamFailure(request2, accounts, index, attempt);
10795
+ return await resolveUpstreamFailure(request3, accounts, index, attempt);
10093
10796
  }
10094
10797
  if (attempt.kind === "transport-failure") {
10095
- return await resolveTransportFailure(request2, accounts, index);
10798
+ return await resolveTransportFailure(request3, accounts, index);
10096
10799
  }
10097
10800
  }
10098
- throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`, request2.ctx.providerName);
10801
+ throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`, request3.ctx.providerName);
10099
10802
  }
10100
10803
  var log21;
10101
10804
  var init_proxy_attempts = __esm(() => {
@@ -10120,7 +10823,7 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10120
10823
  provider: ctx.providerName,
10121
10824
  sessionId
10122
10825
  };
10123
- const request2 = {
10826
+ const request3 = {
10124
10827
  body,
10125
10828
  ctx,
10126
10829
  mappedModel,
@@ -10131,20 +10834,20 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
10131
10834
  url
10132
10835
  };
10133
10836
  return {
10134
- accounts: selectRequestAccounts(request2, selectionOptions),
10135
- request: request2
10837
+ accounts: selectRequestAccounts(request3, selectionOptions),
10838
+ request: request3
10136
10839
  };
10137
10840
  }
10138
- function onThreadSeat(request2, accounts) {
10139
- const threadAccountId = getThreadBoundAccountId(request2.ctx.messageThreads, request2.thread);
10841
+ function onThreadSeat(request3, accounts) {
10842
+ const threadAccountId = getThreadBoundAccountId(request3.ctx.messageThreads, request3.thread);
10140
10843
  return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
10141
10844
  }
10142
- function selectRequestAccounts(request2, selectionOptions) {
10143
- return onThreadSeat(request2, selectAccountsForRequest(request2.meta, request2.ctx, request2.teamRequest, selectionOptions));
10845
+ function selectRequestAccounts(request3, selectionOptions) {
10846
+ return onThreadSeat(request3, selectAccountsForRequest(request3.meta, request3.ctx, request3.teamRequest, selectionOptions));
10144
10847
  }
10145
- function getRequestRetryAt(request2) {
10146
- const { ctx, teamRequest } = request2;
10147
- return getSoonestQuotaReset(request2.meta, ctx, (fleet) => onThreadSeat(request2, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10848
+ function getRequestRetryAt(request3) {
10849
+ const { ctx, teamRequest } = request3;
10850
+ return getSoonestQuotaReset(request3.meta, ctx, (fleet) => onThreadSeat(request3, ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.teamRouting) ?? fleet));
10148
10851
  }
10149
10852
  var init_proxy_request = __esm(() => {
10150
10853
  init_account_selector();
@@ -10189,10 +10892,10 @@ function preferPinnedProvider(pool, pinnedAccount) {
10189
10892
  const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
10190
10893
  return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
10191
10894
  }
10192
- async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
10895
+ async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
10193
10896
  for (let index = 0;index < accounts.length; index += 1) {
10194
10897
  const account2 = accounts[index];
10195
- const attempt = await attemptAccount(request2, account2, index);
10898
+ const attempt = await attemptAccount(request3, account2, index);
10196
10899
  if (attempt.kind === "response") {
10197
10900
  return { account: account2, kind: "response", response: attempt.response };
10198
10901
  }
@@ -10205,13 +10908,13 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
10205
10908
  if (attempt.kind === "per-minute-rate-limit") {
10206
10909
  return {
10207
10910
  kind: "response",
10208
- response: await resolvePerMinuteRateLimit(request2, account2, index, attempt)
10911
+ response: await resolvePerMinuteRateLimit(request3, account2, index, attempt)
10209
10912
  };
10210
10913
  }
10211
10914
  if (attempt.kind === "request-scoped-rate-limit") {
10212
10915
  return {
10213
10916
  kind: "response",
10214
- response: await resolveRequestScopedRateLimit(request2, accounts, index, attempt)
10917
+ response: await resolveRequestScopedRateLimit(request3, accounts, index, attempt)
10215
10918
  };
10216
10919
  }
10217
10920
  if (attempt.kind === "quota-rate-limit") {
@@ -10224,7 +10927,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
10224
10927
  }
10225
10928
  return {
10226
10929
  kind: "response",
10227
- response: await resolveQuotaRateLimit(request2, accounts, index, attempt)
10930
+ response: await resolveQuotaRateLimit(request3, accounts, index, attempt)
10228
10931
  };
10229
10932
  }
10230
10933
  if (attempt.kind === "upstream-failure") {
@@ -10237,7 +10940,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
10237
10940
  }
10238
10941
  return {
10239
10942
  kind: "response",
10240
- response: await resolveUpstreamFailure(request2, accounts, index, attempt)
10943
+ response: await resolveUpstreamFailure(request3, accounts, index, attempt)
10241
10944
  };
10242
10945
  }
10243
10946
  if (attempt.kind === "transport-failure") {
@@ -10249,7 +10952,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
10249
10952
  }
10250
10953
  return {
10251
10954
  kind: "response",
10252
- response: await resolveTransportFailure(request2, accounts, index)
10955
+ response: await resolveTransportFailure(request3, accounts, index)
10253
10956
  };
10254
10957
  }
10255
10958
  }
@@ -10272,10 +10975,10 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
10272
10975
  let everyCandidateFull = true;
10273
10976
  let emittedIngress = false;
10274
10977
  const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
10275
- const recordUnserved = (request2) => {
10276
- everyCandidateFull &&= isEveryAccountQuotaBlocked(request2.meta, request2.ctx);
10277
- soonestRetry = earliest(soonestRetry, getRequestRetryAt(request2));
10278
- soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request2.meta, request2.ctx));
10978
+ const recordUnserved = (request3) => {
10979
+ everyCandidateFull &&= isEveryAccountQuotaBlocked(request3.meta, request3.ctx);
10980
+ soonestRetry = earliest(soonestRetry, getRequestRetryAt(request3));
10981
+ soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(request3.meta, request3.ctx));
10279
10982
  };
10280
10983
  const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
10281
10984
  for (const [candidateIndex, candidate] of candidates.entries()) {
@@ -10437,9 +11140,9 @@ class SeatAlerts {
10437
11140
  }
10438
11141
  if (!delivery.repliesOk)
10439
11142
  return;
10440
- const reply = await response.json();
10441
- if (reply.ok !== true) {
10442
- const code = typeof reply.error === "string" && SLACK_ERROR_CODE.test(reply.error) ? reply.error : "no reason given";
11143
+ const reply2 = await response.json();
11144
+ if (reply2.ok !== true) {
11145
+ const code = typeof reply2.error === "string" && SLACK_ERROR_CODE.test(reply2.error) ? reply2.error : "no reason given";
10443
11146
  log23.warn(`${delivery.channel} alert was refused (${code})`);
10444
11147
  }
10445
11148
  } catch (error) {
@@ -10905,17 +11608,17 @@ async function handleProxy(req, url, ctx) {
10905
11608
  const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
10906
11609
  const body = buffer ?? null;
10907
11610
  requestMeta.model = readRequestModel(body);
10908
- const { accounts: initiallySelectedAccounts, request: request2 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
11611
+ const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
10909
11612
  let accounts = initiallySelectedAccounts;
10910
11613
  if (accounts.length === 0) {
10911
11614
  const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
10912
11615
  alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
10913
- const retryAt = getRequestRetryAt(request2);
11616
+ const retryAt = getRequestRetryAt(request3);
10914
11617
  if (retryAt !== null) {
10915
11618
  const holdMs = holdSeconds * 1000;
10916
11619
  if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
10917
11620
  await requestContext.quotaHold.waitUntil(retryAt, req.signal);
10918
- const resumedAccounts = selectRequestAccounts(request2);
11621
+ const resumedAccounts = selectRequestAccounts(request3);
10919
11622
  if (resumedAccounts.length > 0) {
10920
11623
  accounts = resumedAccounts;
10921
11624
  }
@@ -10937,7 +11640,7 @@ async function handleProxy(req, url, ctx) {
10937
11640
  });
10938
11641
  log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
10939
11642
  log24.info(`Request: ${req.method} ${url.pathname}`);
10940
- return await proxySelectedAccounts(request2, accounts);
11643
+ return await proxySelectedAccounts(request3, accounts);
10941
11644
  }
10942
11645
  var log24, usageWorkerInstance = null;
10943
11646
  var init_proxy = __esm(() => {
@@ -11000,6 +11703,12 @@ class QuotaHold {
11000
11703
  }
11001
11704
 
11002
11705
  // ../../packages/proxy/src/quota-probe.ts
11706
+ function recordSeatQuota(store, outsideSpend, provider, account2, quota2) {
11707
+ const observed = outsideSpend.observe(account2, quota2, provider);
11708
+ account2.quota_state = observed;
11709
+ store.updateAccountQuotaState(account2.id, observed);
11710
+ }
11711
+
11003
11712
  class QuotaProbe {
11004
11713
  config;
11005
11714
  store;
@@ -11066,9 +11775,7 @@ class QuotaProbe {
11066
11775
  const quota2 = await provider.probeQuota(account2, accessToken);
11067
11776
  if (!quota2)
11068
11777
  return;
11069
- const observed = this.outsideSpend.observe(account2, quota2, provider);
11070
- account2.quota_state = observed;
11071
- this.store.updateAccountQuotaState(account2.id, observed);
11778
+ recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
11072
11779
  } catch {}
11073
11780
  }
11074
11781
  }
@@ -11342,7 +12049,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
11342
12049
  isStream: true,
11343
12050
  providerName: session.providerName,
11344
12051
  retryAttempt: 0,
11345
- failoverAttempts: Math.max(0, session.nextAccountIndex - 1)
12052
+ failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
12053
+ storePayload: session.requestContext.runtime.storeRequestPayloads
11346
12054
  };
11347
12055
  session.activeTurn = {
11348
12056
  requestId,
@@ -11699,6 +12407,106 @@ var init_websocket_proxy = __esm(() => {
11699
12407
  };
11700
12408
  });
11701
12409
 
12410
+ // ../../packages/proxy/src/window-warmup.ts
12411
+ function fiveHourWindowRuns(provider, account2, now) {
12412
+ return Object.entries(account2.quota_state?.windows ?? {}).some(([bucket, window2]) => provider.isFiveHourBucket(bucket) && window2.resetAt !== null && isOpenQuotaWindow(window2, now));
12413
+ }
12414
+
12415
+ class WindowWarmup {
12416
+ runtime;
12417
+ store;
12418
+ outsideSpend;
12419
+ providers;
12420
+ readToken;
12421
+ now;
12422
+ running = false;
12423
+ timer;
12424
+ constructor(runtime, store, outsideSpend, providers2, readToken, now = Date.now) {
12425
+ this.runtime = runtime;
12426
+ this.store = store;
12427
+ this.outsideSpend = outsideSpend;
12428
+ this.providers = providers2;
12429
+ this.readToken = readToken;
12430
+ this.now = now;
12431
+ }
12432
+ start() {
12433
+ this.reschedule();
12434
+ }
12435
+ reschedule() {
12436
+ this.scheduleAfter(this.now());
12437
+ }
12438
+ async run() {
12439
+ const runtime = this.runtime();
12440
+ const routing = runtime.teamRouting;
12441
+ if (this.running || !routing.enabled || !routing.windowWarmup.enabled) {
12442
+ return;
12443
+ }
12444
+ this.running = true;
12445
+ try {
12446
+ const now = this.now();
12447
+ await Promise.all(this.store.getAllAccounts().flatMap((account2) => {
12448
+ const provider = this.providers.getProvider(account2.provider);
12449
+ return provider && this.needsWarmup(provider, account2, runtime, now) ? [this.warm(provider, account2, routing.windowWarmup.model)] : [];
12450
+ }));
12451
+ } finally {
12452
+ this.running = false;
12453
+ }
12454
+ }
12455
+ dispose() {
12456
+ if (this.timer)
12457
+ clearTimeout(this.timer);
12458
+ this.timer = undefined;
12459
+ }
12460
+ scheduleAfter(after) {
12461
+ this.dispose();
12462
+ const dueAt = nextWindowWarmupAt(this.runtime().teamRouting, after);
12463
+ if (dueAt === null)
12464
+ return;
12465
+ this.timer = setTimeout(() => void this.fire(dueAt), Math.max(0, dueAt - this.now()));
12466
+ this.timer.unref?.();
12467
+ }
12468
+ async fire(dueAt) {
12469
+ await this.run();
12470
+ this.scheduleAfter(Math.max(this.now(), dueAt));
12471
+ }
12472
+ needsWarmup(provider, account2, runtime, now) {
12473
+ return provider.startQuotaWindow !== undefined && provider.supportsQuotaProbe(account2) && !fiveHourWindowRuns(provider, account2, now) && isServableSeat(provider, account2, runtime.teamRouting.windowWarmup.model ?? undefined, { runtime, dbOps: this.store }, now);
12474
+ }
12475
+ async warm(provider, account2, model) {
12476
+ try {
12477
+ const accessToken = await this.readToken(account2);
12478
+ if (!accessToken) {
12479
+ log26.warn(`Window warm-up skipped ${account2.name}: no access token`);
12480
+ return;
12481
+ }
12482
+ const quota2 = await this.startWindow(provider, account2, accessToken, model);
12483
+ log26.info(`Window warm-up started ${account2.name}'s five-hour window`);
12484
+ if (quota2) {
12485
+ recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
12486
+ }
12487
+ } catch (error) {
12488
+ log26.warn(`Window warm-up failed for ${account2.name}: ${error instanceof Error ? error.message : "unknown error"}`);
12489
+ }
12490
+ }
12491
+ async startWindow(provider, account2, accessToken, model) {
12492
+ this.outsideSpend.begin(account2.id);
12493
+ try {
12494
+ return await provider.startQuotaWindow?.(account2, accessToken, model) ?? null;
12495
+ } finally {
12496
+ this.outsideSpend.end(account2.id);
12497
+ }
12498
+ }
12499
+ }
12500
+ var log26;
12501
+ var init_window_warmup2 = __esm(() => {
12502
+ init_src4();
12503
+ init_src3();
12504
+ init_src();
12505
+ init_account_selector();
12506
+ init_quota_probe();
12507
+ log26 = new Logger("WindowWarmup");
12508
+ });
12509
+
11702
12510
  // ../../packages/proxy/src/index.ts
11703
12511
  var init_src10 = __esm(() => {
11704
12512
  init_background_tasks();
@@ -11713,6 +12521,7 @@ var init_src10 = __esm(() => {
11713
12521
  init_team_admission();
11714
12522
  init_team_router();
11715
12523
  init_websocket_proxy();
12524
+ init_window_warmup2();
11716
12525
  });
11717
12526
 
11718
12527
  // ../../packages/runtime-server/src/device-keys.ts
@@ -11891,7 +12700,7 @@ function exposureFailure(req, url, server, config) {
11891
12700
  if (!isSameOriginManagementRequest(req, url)) {
11892
12701
  return jsonError(403, "Cross-origin management requests are not allowed");
11893
12702
  }
11894
- if (url.pathname === "/api/drain" || MUTATING_METHODS.has(req.method)) {
12703
+ if (url.pathname === "/api/drain" || /^\/api\/accounts\/[^/]+\/reset-credits(?:\/consume)?$/.test(url.pathname) || MUTATING_METHODS.has(req.method)) {
11895
12704
  if (role !== "admin") {
11896
12705
  return jsonError(401, "An admin key is required for management writes");
11897
12706
  }
@@ -11927,13 +12736,14 @@ function createRuntimeConfig(config, port) {
11927
12736
  },
11928
12737
  sessionDurationMs: config.get("session_duration_ms", TIME_CONSTANTS.SESSION_DURATION_DEFAULT),
11929
12738
  port,
12739
+ storeRequestPayloads: config.storesRequestPayloads(),
11930
12740
  teamRouting: config.getTeamRouting()
11931
12741
  };
11932
12742
  }
11933
- function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe) {
12743
+ function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
11934
12744
  config.on("change", (change) => {
11935
12745
  if (change.key === "lb_strategy") {
11936
- log26.info("Strategy configuration changed");
12746
+ log27.info("Strategy configuration changed");
11937
12747
  const newStrategyName = config.getStrategy();
11938
12748
  if (newStrategyName === "session") {
11939
12749
  const strategy3 = new SessionStrategy;
@@ -11941,13 +12751,38 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
11941
12751
  proxyContext.strategy = strategy3;
11942
12752
  }
11943
12753
  }
12754
+ if (change.key === "data_retention_days") {
12755
+ runtimeConfig2.storeRequestPayloads = config.storesRequestPayloads();
12756
+ }
11944
12757
  if (change.key === "team_routing") {
11945
12758
  runtimeConfig2.teamRouting = config.getTeamRouting();
11946
12759
  quotaProbe.reschedule();
11947
- log26.info("Team routing configuration changed");
12760
+ windowWarmup.reschedule();
12761
+ log27.info("Team routing configuration changed");
11948
12762
  }
11949
12763
  });
11950
12764
  }
12765
+ function startSeatSchedulers(config, proxyContext, outsideSpendTracker) {
12766
+ const { dbOps, providerRegistry, runtime } = proxyContext;
12767
+ const readSeatToken = async (account2) => {
12768
+ const provider = providerRegistry.getProvider(account2.provider);
12769
+ if (!provider)
12770
+ return null;
12771
+ return await getValidAccessToken(account2, {
12772
+ ...proxyContext,
12773
+ provider,
12774
+ providerName: account2.provider,
12775
+ upstreamPath: "/"
12776
+ });
12777
+ };
12778
+ const quotaProbe = new QuotaProbe(() => config.getTeamRouting(), dbOps, outsideSpendTracker, providerRegistry, readSeatToken);
12779
+ const windowWarmup = new WindowWarmup(() => runtime, dbOps, outsideSpendTracker, providerRegistry, readSeatToken);
12780
+ for (const scheduler of [quotaProbe, windowWarmup]) {
12781
+ scheduler.start();
12782
+ registerDisposable(scheduler);
12783
+ }
12784
+ return { quotaProbe, windowWarmup };
12785
+ }
11951
12786
  function bootstrapRuntime(port, serverLog, deploymentDrain) {
11952
12787
  container.registerInstance(SERVICE_KEYS.Config, new Config);
11953
12788
  container.registerInstance(SERVICE_KEYS.Logger, serverLog);
@@ -11958,7 +12793,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
11958
12793
  sessionDurationMs: runtimeConfig2.sessionDurationMs
11959
12794
  });
11960
12795
  const dbOps = DatabaseFactory.getInstance();
11961
- const log26 = container.resolve(SERVICE_KEYS.Logger);
12796
+ const log27 = container.resolve(SERVICE_KEYS.Logger);
11962
12797
  container.registerInstance(SERVICE_KEYS.Database, dbOps);
11963
12798
  const asyncWriter = new AsyncDbWriter;
11964
12799
  container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
@@ -11973,6 +12808,17 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
11973
12808
  dbOps,
11974
12809
  providerRegistry,
11975
12810
  getProviders: () => providerRegistry.listProviders(),
12811
+ getAccountAccessToken: async (account2) => {
12812
+ const provider = providerRegistry.getProvider(account2.provider);
12813
+ if (!provider)
12814
+ throw new Error("Provider unavailable");
12815
+ return getValidAccessToken(account2, {
12816
+ ...proxyContext,
12817
+ provider,
12818
+ providerName: account2.provider,
12819
+ upstreamPath: "/"
12820
+ });
12821
+ },
11976
12822
  getPoolStatus: (provider, model) => getPoolStatus(provider, model, {
11977
12823
  dbOps,
11978
12824
  runtime: runtimeConfig2,
@@ -12011,24 +12857,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12011
12857
  asyncWriter,
12012
12858
  usageWorker: getUsageWorker()
12013
12859
  };
12014
- const quotaProbe = new QuotaProbe(() => config.getTeamRouting(), dbOps, outsideSpendTracker, providerRegistry, async (account2) => {
12015
- const provider = providerRegistry.getProvider(account2.provider);
12016
- if (!provider)
12017
- return null;
12018
- return await getValidAccessToken(account2, {
12019
- ...proxyContext,
12020
- provider,
12021
- providerName: account2.provider,
12022
- upstreamPath: "/"
12023
- });
12024
- });
12025
- quotaProbe.start();
12026
- registerDisposable(quotaProbe);
12027
- wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
12860
+ const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
12861
+ wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
12028
12862
  return {
12029
12863
  config,
12030
12864
  dbOps,
12031
- log: log26,
12865
+ log: log27,
12032
12866
  asyncWriter,
12033
12867
  apiRouter,
12034
12868
  exposureConfig,
@@ -12037,12 +12871,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
12037
12871
  runtimeConfig: runtimeConfig2
12038
12872
  };
12039
12873
  }
12040
- function logInitialAccountStatus(log26, dbOps) {
12874
+ function logInitialAccountStatus(log27, dbOps) {
12041
12875
  const accounts = dbOps.getAllAccounts();
12042
12876
  const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
12043
- log26.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
12877
+ log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
12044
12878
  if (activeAccounts.length === 0) {
12045
- log26.warn("No active accounts available - requests will be refused with a 503 until an account is added");
12879
+ log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
12046
12880
  }
12047
12881
  }
12048
12882
  var init_bootstrap_runtime = __esm(() => {
@@ -12283,6 +13117,44 @@ var init_fetch_handler = __esm(() => {
12283
13117
  init_oauth_token();
12284
13118
  });
12285
13119
 
13120
+ // ../../packages/runtime-server/src/retention-maintenance.ts
13121
+ function removeExpiredRequests(config, dbOps, log27, label) {
13122
+ try {
13123
+ const payloadDays = config.getDataRetentionDays();
13124
+ const requestDays = config.getRequestRetentionDays();
13125
+ const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * DAY_MS2, requestDays * DAY_MS2);
13126
+ log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
13127
+ } catch (err) {
13128
+ log27.error(`${label} cleanup error: ${err}`);
13129
+ }
13130
+ }
13131
+ function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
13132
+ const log27 = new Logger("RetentionMaintenance");
13133
+ removeExpiredRequests(config, dbOps, log27, "Startup");
13134
+ try {
13135
+ const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
13136
+ log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
13137
+ } catch (err) {
13138
+ log27.error(`Database compaction error: ${err}`);
13139
+ }
13140
+ const timer = setInterval(() => {
13141
+ removeExpiredRequests(config, dbOps, log27, "Periodic");
13142
+ try {
13143
+ dbOps.checkpointWal();
13144
+ } catch (err) {
13145
+ log27.error(`WAL checkpoint error: ${err}`);
13146
+ }
13147
+ }, intervalMs);
13148
+ timer.unref?.();
13149
+ return () => clearInterval(timer);
13150
+ }
13151
+ var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
13152
+ var init_retention_maintenance = __esm(() => {
13153
+ init_src3();
13154
+ DAY_MS2 = 24 * 60 * 60 * 1000;
13155
+ RETENTION_CLEANUP_INTERVAL_MS = 60 * 60 * 1000;
13156
+ });
13157
+
12286
13158
  // ../../packages/runtime-server/src/startup-banner.ts
12287
13159
  function createStartupBanner(options) {
12288
13160
  const { version, port, withDashboard, strategy: strategy3, providers: providers2 } = options;
@@ -12313,29 +13185,6 @@ var init_startup_banner = __esm(() => {
12313
13185
  init_src2();
12314
13186
  });
12315
13187
 
12316
- // ../../packages/runtime-server/src/startup-maintenance.ts
12317
- function runStartupMaintenance(config, dbOps) {
12318
- const log26 = new Logger("StartupMaintenance");
12319
- try {
12320
- const payloadDays = config.getDataRetentionDays();
12321
- const requestDays = config.getRequestRetentionDays();
12322
- const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
12323
- log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
12324
- } catch (err) {
12325
- log26.error(`Startup cleanup error: ${err}`);
12326
- }
12327
- try {
12328
- dbOps.compact();
12329
- log26.info("Database compacted at startup");
12330
- } catch (err) {
12331
- log26.error(`Database compaction error: ${err}`);
12332
- }
12333
- return () => {};
12334
- }
12335
- var init_startup_maintenance = __esm(() => {
12336
- init_src3();
12337
- });
12338
-
12339
13188
  // ../../packages/runtime-server/src/index.ts
12340
13189
  import { isAbsolute as isAbsolute4 } from "path";
12341
13190
  var {serve } = globalThis.Bun;
@@ -12451,14 +13300,14 @@ function startServer(options) {
12451
13300
  const {
12452
13301
  config,
12453
13302
  dbOps,
12454
- log: log26,
13303
+ log: log27,
12455
13304
  apiRouter,
12456
13305
  exposureConfig,
12457
13306
  proxyContext,
12458
13307
  providerRegistry,
12459
13308
  runtimeConfig: runtimeConfig2
12460
13309
  } = bootstrapRuntime(port, serverLog, drain.control);
12461
- stopRetentionJob = runStartupMaintenance(config, dbOps);
13310
+ stopRetentionJob = startRetentionMaintenance(config, dbOps);
12462
13311
  const fetchHandler = createServerFetchHandler({
12463
13312
  apiRouter,
12464
13313
  exposureConfig,
@@ -12496,7 +13345,7 @@ function startServer(options) {
12496
13345
  strategy: config.getStrategy(),
12497
13346
  providers: providerRegistry.listProviders()
12498
13347
  }));
12499
- logInitialAccountStatus(log26, dbOps);
13348
+ logInitialAccountStatus(log27, dbOps);
12500
13349
  return {
12501
13350
  port: activePort,
12502
13351
  stop: () => stopServerRuntime(),
@@ -12529,8 +13378,8 @@ var init_src11 = __esm(() => {
12529
13378
  init_dashboard_assets();
12530
13379
  init_deployment_drain();
12531
13380
  init_fetch_handler();
13381
+ init_retention_maintenance();
12532
13382
  init_startup_banner();
12533
- init_startup_maintenance();
12534
13383
  init_fetch_handler();
12535
13384
  init_startup_banner();
12536
13385
  serverLog = new Logger("Server");
@@ -13834,13 +14683,17 @@ function teamRoutingFileConfig(routing) {
13834
14683
  return {
13835
14684
  enabled: routing.enabled,
13836
14685
  distribution_enabled: routing.distributionEnabled,
14686
+ prefer_expiring_quota: routing.preferExpiringQuota,
13837
14687
  allowlisted_account_uuids: routing.allowlistedAccountUuids,
13838
14688
  max_usage: routing.maxUsage,
14689
+ weekly_max_usage: routing.weeklyMaxUsage,
14690
+ weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
13839
14691
  admission_cap: routing.admissionCap,
13840
14692
  admission_queue_limit: routing.admissionQueueLimit,
13841
14693
  admission_wait_ms: routing.admissionWaitMs,
13842
14694
  hold_seconds: routing.holdSeconds,
13843
- quota_probe_seconds: routing.quotaProbeSeconds
14695
+ quota_probe_seconds: routing.quotaProbeSeconds,
14696
+ window_warmup: windowWarmupFileConfig(routing.windowWarmup)
13844
14697
  };
13845
14698
  }
13846
14699
  function quotaWindowLabel(key) {
@@ -13859,6 +14712,9 @@ function formatPoolLimits(quotaState) {
13859
14712
  });
13860
14713
  return windows.length > 0 ? windows.join(" \xB7 ") : "limits not observed yet";
13861
14714
  }
14715
+ var init_local_pool = __esm(() => {
14716
+ init_src4();
14717
+ });
13862
14718
 
13863
14719
  // src/core/accounts.ts
13864
14720
  function getAddAccountProviderOptions() {
@@ -14034,6 +14890,7 @@ var init_accounts2 = __esm(() => {
14034
14890
  init_src12();
14035
14891
  init_cli();
14036
14892
  init_cli();
14893
+ init_local_pool();
14037
14894
  });
14038
14895
 
14039
14896
  // src/core/analytics.ts
@@ -14161,6 +15018,7 @@ import {
14161
15018
  } from "fs";
14162
15019
  import { homedir as homedir2 } from "os";
14163
15020
  import { dirname as dirname4, join as join8 } from "path";
15021
+ import { fileURLToPath } from "url";
14164
15022
  function shellQuote(value) {
14165
15023
  return `'${value.replaceAll("'", `'"'"'`)}'`;
14166
15024
  }
@@ -14201,14 +15059,22 @@ function proxyKeySetup(proxyKeyFile) {
14201
15059
  fi
14202
15060
  export AGENT_SMITH_PROXY_KEY=$(cat ${shellQuote(proxyKeyFile)})`;
14203
15061
  }
14204
- function claudeWrapper(claudePath, baseUrl, proxyKeyFile) {
15062
+ function claudeProxyCredential(keepClaudeLogin) {
15063
+ if (!keepClaudeLogin) {
15064
+ return `export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"`;
15065
+ }
15066
+ return `unset ANTHROPIC_API_KEY
15067
+ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
15068
+ }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
15069
+ }
15070
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
14205
15071
  return `#!/bin/sh
14206
15072
  # Generated by agent-smith. This file delegates to the real Claude Code binary.
14207
15073
  unset AGENT_SMITH_ADMIN_KEY
14208
15074
  unset AGENT_SMITH_PROXY_KEY
14209
15075
  unset ANTHROPIC_AUTH_TOKEN
14210
15076
  ${proxyKeySetup(proxyKeyFile)}
14211
- export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"
15077
+ ${claudeProxyCredential(keepClaudeLogin)}
14212
15078
  unset AGENT_SMITH_PROXY_KEY
14213
15079
  export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
14214
15080
  exec ${shellQuote(claudePath)} "$@"
@@ -14236,6 +15102,26 @@ ${overrides} \\
14236
15102
  `;
14237
15103
  }
14238
15104
  async function installClientWrappers(options) {
15105
+ if (options.clientConfigPath) {
15106
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
15107
+ mkdirSync4(options.binDir, { recursive: true, mode: 448 });
15108
+ for (const [tool, target] of [
15109
+ ["claude", options.claudePath],
15110
+ ["codex", options.codexPath]
15111
+ ]) {
15112
+ if (!target)
15113
+ continue;
15114
+ if (target === join8(options.binDir, tool))
15115
+ throw new Error("A client launcher cannot call itself");
15116
+ const wrapper = join8(options.binDir, tool);
15117
+ writeFileSync2(wrapper, `#!/bin/sh
15118
+ ${CONFIG_CLIENT_MARKER}
15119
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
15120
+ `, { encoding: "utf8", mode: 448 });
15121
+ chmodSync2(wrapper, 448);
15122
+ }
15123
+ return;
15124
+ }
14239
15125
  if (options.baseUrl && !options.proxyKeyFile) {
14240
15126
  throw new Error("A configured Agent Smith server requires a forwarding key file");
14241
15127
  }
@@ -14243,7 +15129,7 @@ async function installClientWrappers(options) {
14243
15129
  const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
14244
15130
  if (options.claudePath) {
14245
15131
  const claude = join8(options.binDir, "claude");
14246
- writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile), {
15132
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
14247
15133
  encoding: "utf8",
14248
15134
  mode: 448
14249
15135
  });
@@ -14304,7 +15190,7 @@ function readSavedClientPaths(statePath) {
14304
15190
  } catch {}
14305
15191
  return null;
14306
15192
  }
14307
- function getLocalRoutingStatus(paths2 = {}) {
15193
+ function installedRoutingStatus(paths2 = {}) {
14308
15194
  const defaults = getLocalRoutingPaths();
14309
15195
  const binDir = paths2.binDir ?? defaults.binDir;
14310
15196
  const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
@@ -14318,6 +15204,58 @@ function getLocalRoutingStatus(paths2 = {}) {
14318
15204
  shellProfile
14319
15205
  };
14320
15206
  }
15207
+ function getLocalRoutingStatus(paths2 = {}) {
15208
+ const status = installedRoutingStatus(paths2);
15209
+ if (!configClientWrappersInstalled(paths2))
15210
+ return status;
15211
+ try {
15212
+ return { ...status, enabled: readClientRouting().enabled };
15213
+ } catch {
15214
+ return { ...status, enabled: false };
15215
+ }
15216
+ }
15217
+ function configClientWrappersInstalled(paths2 = {}) {
15218
+ const binDir = paths2.binDir ?? getLocalRoutingPaths().binDir;
15219
+ const files = ["claude", "codex"].map((name) => join8(binDir, name)).filter(existsSync3);
15220
+ return installedRoutingStatus(paths2).enabled && files.length > 0 && files.every((path) => readFileSync4(path, "utf8").includes(CONFIG_CLIENT_MARKER));
15221
+ }
15222
+ async function launchConfiguredClient(configPath, tool, target, args) {
15223
+ if (tool !== "claude" && tool !== "codex")
15224
+ throw new Error("Unknown Agent Smith client");
15225
+ const client2 = readClientRouting(configPath);
15226
+ const env = { ...process.env };
15227
+ delete env.AGENT_SMITH_ADMIN_KEY;
15228
+ delete env.AGENT_SMITH_PROXY_KEY;
15229
+ let command = [target, ...args];
15230
+ if (client2.enabled) {
15231
+ if (!client2.baseUrl || !client2.proxyKeyFile)
15232
+ throw new Error("client.base_url and client.proxy_key_file are required");
15233
+ const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
15234
+ const wires = Object.keys(new Config(configPath).getProviderPools());
15235
+ const base = proxyBaseUrl(8080, client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
15236
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
15237
+ command = ["/bin/sh", "-c", script, "--", ...args];
15238
+ }
15239
+ const child = Bun.spawn(command, {
15240
+ env,
15241
+ stdin: "inherit",
15242
+ stdout: "inherit",
15243
+ stderr: "inherit"
15244
+ });
15245
+ const forward = {
15246
+ SIGINT: () => child.kill("SIGINT"),
15247
+ SIGTERM: () => child.kill("SIGTERM"),
15248
+ SIGHUP: () => child.kill("SIGHUP")
15249
+ };
15250
+ for (const [signal, listener] of Object.entries(forward))
15251
+ process.on(signal, listener);
15252
+ try {
15253
+ return await child.exited;
15254
+ } finally {
15255
+ for (const [signal, listener] of Object.entries(forward))
15256
+ process.off(signal, listener);
15257
+ }
15258
+ }
14321
15259
  async function enableLocalClientRouting(options) {
14322
15260
  const defaults = getLocalRoutingPaths();
14323
15261
  const binDir = options.binDir ?? defaults.binDir;
@@ -14344,7 +15282,9 @@ async function enableLocalClientRouting(options) {
14344
15282
  port: options.port,
14345
15283
  baseUrl: options.baseUrl,
14346
15284
  proxyKeyFile: options.proxyKeyFile,
14347
- providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
15285
+ keepClaudeLogin: options.keepClaudeLogin,
15286
+ clientConfigPath: options.clientConfigPath,
15287
+ providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
14348
15288
  });
14349
15289
  const existingProfile = existsSync3(shellProfile) ? readFileSync4(shellProfile, "utf8") : "";
14350
15290
  writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
@@ -14395,7 +15335,7 @@ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
14395
15335
  ${ROUTING_END}
14396
15336
  `;
14397
15337
  }
14398
- var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local";
15338
+ 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";
14399
15339
  var init_local_routing = __esm(() => {
14400
15340
  init_src4();
14401
15341
  });
@@ -14596,6 +15536,7 @@ var init_core = __esm(() => {
14596
15536
  init_accounts2();
14597
15537
  init_analytics2();
14598
15538
  init_args();
15539
+ init_local_pool();
14599
15540
  init_local_routing();
14600
15541
  init_logs2();
14601
15542
  init_requests2();
@@ -14603,6 +15544,384 @@ var init_core = __esm(() => {
14603
15544
  init_strategy3();
14604
15545
  });
14605
15546
 
15547
+ // src/core/client-command.ts
15548
+ import { existsSync as existsSync4 } from "fs";
15549
+ import { parseArgs as parseArgs2 } from "util";
15550
+ async function runClientCommand(argv) {
15551
+ const { positionals, values } = parseArgs2({
15552
+ args: argv,
15553
+ options: { raw: { type: "boolean" } },
15554
+ allowPositionals: true,
15555
+ strict: true
15556
+ });
15557
+ const [command] = positionals;
15558
+ if (positionals.length !== 1 || !["on", "off", "status"].includes(command ?? ""))
15559
+ throw new Error("usage: agent-smith client on|off|status [--raw]");
15560
+ const configPath = resolveConfigPath();
15561
+ const client2 = existsSync4(configPath) ? readClientRouting(configPath) : { enabled: false };
15562
+ let installed = configClientWrappersInstalled();
15563
+ if (command !== "status") {
15564
+ const enabled = command === "on";
15565
+ if (enabled) {
15566
+ if (!client2.baseUrl || !client2.proxyKeyFile)
15567
+ throw new Error("Set client.base_url and client.proxy_key_file before enabling the pool");
15568
+ validateProxyKeyFile(client2.proxyKeyFile);
15569
+ }
15570
+ if (!installed && (enabled || getLocalRoutingStatus().enabled)) {
15571
+ await enableLocalClientRouting({
15572
+ port: 8080,
15573
+ clientConfigPath: configPath
15574
+ });
15575
+ installed = true;
15576
+ }
15577
+ new Config(configPath).setClientRoutingEnabled(enabled);
15578
+ client2.enabled = enabled;
15579
+ }
15580
+ const status = {
15581
+ enabled: client2.enabled,
15582
+ installed,
15583
+ ...client2.baseUrl && { baseUrl: client2.baseUrl }
15584
+ };
15585
+ if (values.raw)
15586
+ console.log(JSON.stringify(status));
15587
+ else {
15588
+ console.log(`Shared pool: ${status.enabled ? "on" : "off"}`);
15589
+ console.log(`Launchers: ${installed ? "installed" : "not configured; use client on to set up"}`);
15590
+ if (command !== "status")
15591
+ console.log("Restart existing Claude/Codex sessions to use this setting. After first setup, open a new terminal.");
15592
+ }
15593
+ }
15594
+ var init_client_command = __esm(() => {
15595
+ init_src4();
15596
+ init_local_routing();
15597
+ });
15598
+
15599
+ // src/core/menubar.ts
15600
+ function fullDate(ms) {
15601
+ const part = Object.fromEntries(fullDateParts.formatToParts(ms).map(({ type, value }) => [type, value]));
15602
+ return `${part.weekday} ${part.day} ${part.month}, ${part.hour}:${part.minute}`;
15603
+ }
15604
+ function percentOf(window2, nowMs, windowHours) {
15605
+ if (!window2 || typeof window2.utilization !== "number" || !Number.isFinite(window2.utilization) || window2.utilization < 0)
15606
+ return null;
15607
+ if (window2.resetAt !== null && window2.resetAt <= nowMs)
15608
+ return null;
15609
+ if (nowMs - window2.seenAt > windowHours * HOUR_MS2)
15610
+ return null;
15611
+ return window2.utilization * 100;
15612
+ }
15613
+ function resetLabel(window2, format, nowMs) {
15614
+ return window2?.resetAt && window2.resetAt > nowMs ? format.format(window2.resetAt) : "";
15615
+ }
15616
+ function bar(percent) {
15617
+ if (percent === null)
15618
+ return "\u2591".repeat(10);
15619
+ const filled = Math.round(Math.min(Math.max(percent, 0), 100) / 10);
15620
+ return "\u2588".repeat(filled) + "\u2591".repeat(10 - filled);
15621
+ }
15622
+ function ageText(seconds) {
15623
+ if (seconds === null)
15624
+ return "unknown age";
15625
+ if (seconds < 120)
15626
+ return `${seconds} s old`;
15627
+ if (seconds < 7200)
15628
+ return `${Math.round(seconds / 60)} min old`;
15629
+ if (seconds < 172800)
15630
+ return `${Math.round(seconds / 3600)} h old`;
15631
+ return `${Math.round(seconds / 86400)} days old`;
15632
+ }
15633
+ function stateOf(account3, known, peak, cap) {
15634
+ if (!account3.poolAllowed)
15635
+ return {
15636
+ color: GRAY,
15637
+ label: account3.paused ? "not in pool, paused" : "not in pool"
15638
+ };
15639
+ if (account3.paused)
15640
+ return { color: GRAY, label: "paused" };
15641
+ if (account3.blocked)
15642
+ return { color: RED, label: "unavailable (blocked)" };
15643
+ if (!known)
15644
+ return { color: GRAY, label: "no current reading" };
15645
+ if (peak >= cap)
15646
+ return { color: RED, label: `at the ${cap}% cap` };
15647
+ if (peak >= NEAR_CAP_PERCENT)
15648
+ return { color: ORANGE, label: "free, close to the cap" };
15649
+ return { color: GREEN, label: "free" };
15650
+ }
15651
+ function describe(account3, cap, nowMs) {
15652
+ const fiveHour = percentOf(account3.usage.fiveHour, nowMs, 5);
15653
+ const sevenDay = percentOf(account3.usage.sevenDay, nowMs, 168);
15654
+ const active = account3.poolAllowed && !account3.paused;
15655
+ const known = fiveHour !== null && sevenDay !== null;
15656
+ const peak = Math.max(fiveHour ?? 0, sevenDay ?? 0);
15657
+ const free = active && !account3.blocked && known && peak < cap;
15658
+ return {
15659
+ account: account3,
15660
+ fiveHour,
15661
+ sevenDay,
15662
+ active,
15663
+ free,
15664
+ ...stateOf(account3, known, peak, cap)
15665
+ };
15666
+ }
15667
+ function windowLine(label, window2, percent, nowMs) {
15668
+ const reset2 = window2?.resetAt && window2.resetAt > nowMs ? ` \xB7 resets ${fullDate(window2.resetAt)}` : "";
15669
+ const used = percent === null ? "unknown" : `${Math.round(percent)}%`;
15670
+ return `--${label}: ${used}${reset2} | ${PLAIN}`;
15671
+ }
15672
+ function accountLines(row, nameWidth, nowMs) {
15673
+ const { account: account3, fiveHour, sevenDay } = row;
15674
+ const { usage } = account3;
15675
+ const name = clean(account3.name).padEnd(nameWidth);
15676
+ const fiveReset = resetLabel(usage.fiveHour, hhmm, nowMs).padEnd(5);
15677
+ const sevenReset = resetLabel(usage.sevenDay, dayHhmm, nowMs);
15678
+ const line = `${name} 5h ${pct(fiveHour)} ${bar(fiveHour)} ${fiveReset} 7d ${pct(sevenDay)} ${bar(sevenDay)} ${sevenReset}`;
15679
+ const lines = [
15680
+ `${DOT[row.color]} ${line.trimEnd()} | ${MONO} color=${ROW_TEXT}`,
15681
+ `--${clean(account3.name)}: ${row.label} | ${PLAIN}`,
15682
+ "-----",
15683
+ windowLine("5h", usage.fiveHour, fiveHour, nowMs),
15684
+ windowLine("7d", usage.sevenDay, sevenDay, nowMs)
15685
+ ];
15686
+ for (const [model, window2] of Object.entries(usage.weeklyByModel))
15687
+ lines.push(windowLine(`${clean(model)} 7d`, window2, percentOf(window2, nowMs, 168), nowMs));
15688
+ const age = usage.fiveHour ? Math.max(0, Math.round((nowMs - usage.fiveHour.seenAt) / 1000)) : null;
15689
+ const ageColor = age !== null && age > STALE_READING_SECONDS ? ` color=${ORANGE}` : "";
15690
+ lines.push("-----", `--Reading ${ageText(age)} | ${PLAIN} size=11${ageColor}`, `--Login token: ${clean(account3.tokenStatus) || "unknown"} | ${PLAIN} size=11`);
15691
+ return lines;
15692
+ }
15693
+ function renderMenubar({ cached, error }, nowMs) {
15694
+ if (!cached)
15695
+ return [
15696
+ `| sfimage=person.3 sfcolor=${GRAY}`,
15697
+ "---",
15698
+ `Pool status unavailable | color=${RED}`,
15699
+ `${clean(error)} | size=11 ${PLAIN}`,
15700
+ "---",
15701
+ "Refresh | refresh=true"
15702
+ ];
15703
+ const { fetchedAt, status } = cached;
15704
+ const cap = Number.isFinite(status.maxUsagePercent) ? status.maxUsagePercent : 100;
15705
+ const rows = status.accounts.map((account3) => describe(account3, cap, nowMs)).sort((a, b) => clean(a.account.name).localeCompare(clean(b.account.name)));
15706
+ const active = rows.filter((row) => row.active);
15707
+ const inactive = rows.filter((row) => !row.active);
15708
+ const freeCount = active.filter((row) => row.free).length;
15709
+ const titleColor = freeCount === 0 ? RED : freeCount <= 2 ? ORANGE : GREEN;
15710
+ const nameWidth = Math.max(0, ...rows.map((row) => clean(row.account.name).length));
15711
+ const lines = [
15712
+ `${freeCount}/${active.length}${error ? " \u26A0" : ""} | sfimage=person.3.fill sfcolor=${titleColor} ${PLAIN}`,
15713
+ "---",
15714
+ `Agent Smith pool \xB7 ${freeCount} of ${active.length} accounts free (5h and 7d both under ${cap}%) | ${PLAIN}`,
15715
+ `Routing ${status.routingEnabled ? "on" : "off"} \xB7 updated ${hhmm.format(fetchedAt)} \xB7 refreshes every 5 min | size=11 color=${GRAY} ${PLAIN}`
15716
+ ];
15717
+ if (error)
15718
+ lines.push(`Last refresh failed (${clean(error)}), showing ${hhmm.format(fetchedAt)} data | size=11 color=${ORANGE} ${PLAIN}`);
15719
+ lines.push("---");
15720
+ for (const row of active)
15721
+ lines.push(...accountLines(row, nameWidth, nowMs));
15722
+ if (inactive.length) {
15723
+ lines.push("---", `Not serving | size=11 color=${GRAY}`);
15724
+ for (const row of inactive)
15725
+ lines.push(...accountLines(row, nameWidth, nowMs));
15726
+ }
15727
+ const names = new Set(rows.map((row) => clean(row.account.name)));
15728
+ const notConnected = status.emails.filter((email) => !email.startsWith("*@") && !names.has(clean(email).split("@")[0] ?? ""));
15729
+ lines.push("---", `Allowed, not connected (${notConnected.length}) | ${PLAIN} color=${ROW_TEXT}`, ...notConnected.map((email) => `--${clean(email)} | ${PLAIN}`));
15730
+ if (/^https:\/\//.test(status.enrollmentUrl))
15731
+ lines.push(`Open team sign-in page | href=${clean(status.enrollmentUrl)}`);
15732
+ lines.push("Refresh | refresh=true");
15733
+ return lines;
15734
+ }
15735
+ var HOUR_MS2 = 3600000, STALE_READING_SECONDS, NEAR_CAP_PERCENT = 70, GREEN = "#34C759", ORANGE = "#FF9500", RED = "#FF3B30", GRAY = "#8E8E93", DOT, MONO = "font=Menlo size=12 emojize=false symbolize=false", PLAIN = "emojize=false symbolize=false", ROW_TEXT = "#000000,#FFFFFF", hhmm, dayHhmm, fullDateParts, clean = (value) => String(value ?? "").replace(/[\p{C}|]/gu, " ").replace(/^-+/, "").trim(), pct = (percent) => percent === null ? " ?" : `${Math.round(percent)}%`.padStart(4);
15736
+ var init_menubar = __esm(() => {
15737
+ STALE_READING_SECONDS = 15 * 60;
15738
+ DOT = {
15739
+ [GREEN]: "\uD83D\uDFE2",
15740
+ [ORANGE]: "\uD83D\uDFE0",
15741
+ [RED]: "\uD83D\uDD34",
15742
+ [GRAY]: "\u26AA"
15743
+ };
15744
+ hhmm = new Intl.DateTimeFormat("en-GB", {
15745
+ hour: "2-digit",
15746
+ minute: "2-digit",
15747
+ hourCycle: "h23"
15748
+ });
15749
+ dayHhmm = new Intl.DateTimeFormat("en-GB", {
15750
+ weekday: "short",
15751
+ hour: "2-digit",
15752
+ minute: "2-digit",
15753
+ hourCycle: "h23"
15754
+ });
15755
+ fullDateParts = new Intl.DateTimeFormat("en-GB", {
15756
+ weekday: "short",
15757
+ day: "numeric",
15758
+ month: "short",
15759
+ hour: "2-digit",
15760
+ minute: "2-digit",
15761
+ hourCycle: "h23"
15762
+ });
15763
+ });
15764
+
15765
+ // src/core/menubar-command.ts
15766
+ import {
15767
+ chmodSync as chmodSync3,
15768
+ existsSync as existsSync5,
15769
+ mkdirSync as mkdirSync5,
15770
+ readFileSync as readFileSync5,
15771
+ realpathSync,
15772
+ rmSync as rmSync2,
15773
+ writeFileSync as writeFileSync3
15774
+ } from "fs";
15775
+ import { homedir as homedir3 } from "os";
15776
+ import { dirname as dirname5, join as join9 } from "path";
15777
+ import { fileURLToPath as fileURLToPath2 } from "url";
15778
+ import { parseArgs as parseArgs3 } from "util";
15779
+ function swiftBarPluginDirectory() {
15780
+ if (process.platform !== "darwin")
15781
+ return null;
15782
+ const result = Bun.spawnSync([
15783
+ "defaults",
15784
+ "read",
15785
+ "com.ameba.SwiftBar",
15786
+ "PluginDirectory"
15787
+ ]);
15788
+ const path = result.exitCode === 0 ? result.stdout.toString().trim() : "";
15789
+ if (!path)
15790
+ return null;
15791
+ return path.startsWith("~/") ? join9(homedir3(), path.slice(2)) : path;
15792
+ }
15793
+ async function remoteScript() {
15794
+ const built = new URL("./pool-status.js", import.meta.url);
15795
+ if (existsSync5(built))
15796
+ return readFileSync5(built, "utf8");
15797
+ const output = await Bun.build({
15798
+ entrypoints: [fileURLToPath2(new URL("../pool-status.ts", import.meta.url))],
15799
+ target: "bun"
15800
+ });
15801
+ const [artifact] = output.outputs;
15802
+ if (!output.success || !artifact)
15803
+ throw new Error("Pool status script could not be built");
15804
+ return artifact.text();
15805
+ }
15806
+ async function fetchPoolStatus(host) {
15807
+ const result = Bun.spawnSync(["ssh", ...SSH_OPTIONS, host, "bun", "run", "-"], {
15808
+ stdin: new Blob([await remoteScript()]),
15809
+ env: process.env,
15810
+ timeout: 45000
15811
+ });
15812
+ if (result.exitedDueToTimeout)
15813
+ throw new Error("timed out");
15814
+ if (result.exitCode !== 0)
15815
+ throw new Error(clean(result.stderr.toString().split(`
15816
+ `)[0]) || "ssh failed");
15817
+ return JSON.parse(result.stdout.toString());
15818
+ }
15819
+ function defaultDeps() {
15820
+ return {
15821
+ configPath: resolveConfigPath(),
15822
+ cachePath: join9(homedir3(), "Library", "Caches", "agent-smith", "menubar-status.json"),
15823
+ runtime: process.execPath,
15824
+ entry: () => realpathSync(process.argv[1] ?? ""),
15825
+ pluginDirectory: swiftBarPluginDirectory,
15826
+ fetchStatus: fetchPoolStatus,
15827
+ now: Date.now,
15828
+ log: console.log
15829
+ };
15830
+ }
15831
+ function readCache(path) {
15832
+ try {
15833
+ const cached = JSON.parse(readFileSync5(path, "utf8"));
15834
+ return typeof cached?.fetchedAt === "number" && Array.isArray(cached?.status?.accounts) ? cached : null;
15835
+ } catch {
15836
+ return null;
15837
+ }
15838
+ }
15839
+ async function loadSnapshot(deps) {
15840
+ try {
15841
+ const host = readClientRouting(deps.configPath).poolSshHost;
15842
+ if (!host)
15843
+ throw new Error(`Set client.pool_ssh_host in ${deps.configPath}`);
15844
+ const cached = {
15845
+ fetchedAt: deps.now(),
15846
+ status: await deps.fetchStatus(host)
15847
+ };
15848
+ mkdirSync5(dirname5(deps.cachePath), { recursive: true, mode: 448 });
15849
+ writeFileSync3(deps.cachePath, JSON.stringify(cached), { mode: 384 });
15850
+ return { cached, error: null };
15851
+ } catch (error) {
15852
+ return {
15853
+ cached: readCache(deps.cachePath),
15854
+ error: error instanceof Error ? error.message : String(error)
15855
+ };
15856
+ }
15857
+ }
15858
+ function pluginScript(runtime, entry) {
15859
+ return `#!/bin/sh
15860
+ # <swiftbar.title>Agent Smith pool</swiftbar.title>
15861
+ # <swiftbar.hideAbout>true</swiftbar.hideAbout>
15862
+ # <swiftbar.hideRunInTerminal>true</swiftbar.hideRunInTerminal>
15863
+ # <swiftbar.hideLastUpdated>true</swiftbar.hideLastUpdated>
15864
+ export SSH_AUTH_SOCK="\${SSH_AUTH_SOCK:-$(/bin/launchctl getenv SSH_AUTH_SOCK)}"
15865
+ exec ${shellQuote(runtime)} ${shellQuote(entry)} ${PLUGIN_MARKER}
15866
+ `;
15867
+ }
15868
+ function install(deps) {
15869
+ const directory = deps.pluginDirectory();
15870
+ if (!directory)
15871
+ 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.");
15872
+ if (!readClientRouting(deps.configPath).poolSshHost)
15873
+ throw new Error(`Set client.pool_ssh_host in ${deps.configPath} first`);
15874
+ const path = join9(directory, PLUGIN_FILE);
15875
+ writeFileSync3(path, pluginScript(deps.runtime, deps.entry()));
15876
+ chmodSync3(path, 493);
15877
+ deps.log(`Installed ${path}. SwiftBar shows the pool shortly and refreshes it every 5 minutes.`);
15878
+ }
15879
+ function uninstall(deps) {
15880
+ const directory = deps.pluginDirectory();
15881
+ const path = directory ? join9(directory, PLUGIN_FILE) : null;
15882
+ if (!path || !existsSync5(path) || !readFileSync5(path, "utf8").includes(PLUGIN_MARKER)) {
15883
+ deps.log("No Agent Smith menu bar plugin is installed.");
15884
+ return;
15885
+ }
15886
+ rmSync2(path);
15887
+ deps.log(`Removed ${path}.`);
15888
+ }
15889
+ async function runMenubarCommand(argv, overrides = {}) {
15890
+ const { positionals } = parseArgs3({
15891
+ args: argv,
15892
+ allowPositionals: true,
15893
+ strict: true
15894
+ });
15895
+ const [command] = positionals;
15896
+ if (positionals.length !== 1 || !COMMANDS.some((candidate) => candidate === command))
15897
+ throw new Error(`usage: agent-smith menubar ${COMMANDS.join("|")}`);
15898
+ const deps = { ...defaultDeps(), ...overrides };
15899
+ if (command === "install")
15900
+ return install(deps);
15901
+ if (command === "uninstall")
15902
+ return uninstall(deps);
15903
+ const snapshot = await loadSnapshot(deps);
15904
+ deps.log(renderMenubar(snapshot, deps.now()).join(`
15905
+ `));
15906
+ }
15907
+ var COMMANDS, PLUGIN_FILE = "agent-smith-pool.5m.sh", PLUGIN_MARKER = "menubar render", SSH_OPTIONS;
15908
+ var init_menubar_command = __esm(() => {
15909
+ init_src4();
15910
+ init_local_routing();
15911
+ init_menubar();
15912
+ COMMANDS = ["install", "uninstall", "render"];
15913
+ SSH_OPTIONS = [
15914
+ "-o",
15915
+ "BatchMode=yes",
15916
+ "-o",
15917
+ "ConnectTimeout=15",
15918
+ "-o",
15919
+ "UpdateHostKeys=no",
15920
+ "-o",
15921
+ "LogLevel=ERROR"
15922
+ ];
15923
+ });
15924
+
14606
15925
  // src/poc-notice.ts
14607
15926
  var POC_BANNER = "PROOF OF CONCEPT \xB7 read the README before enabling sign-ins", POC_NOTICE = `\u26A0 PROOF OF CONCEPT, FOR IDEATION ONLY
14608
15927
  agent-smith is an experiment, not a product: no warranty and no support.
@@ -14622,13 +15941,13 @@ __export(exports_theme, {
14622
15941
  NAV_ITEMS: () => NAV_ITEMS,
14623
15942
  C: () => C
14624
15943
  });
14625
- import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
14626
- import { homedir as homedir3 } from "os";
14627
- import { join as join9 } from "path";
15944
+ import { existsSync as existsSync6, mkdirSync as mkdirSync6, readFileSync as readFileSync6, writeFileSync as writeFileSync4 } from "fs";
15945
+ import { homedir as homedir4 } from "os";
15946
+ import { join as join10 } from "path";
14628
15947
  function loadPersistedThemeId() {
14629
15948
  try {
14630
- if (existsSync4(CONFIG_FILE)) {
14631
- const data = JSON.parse(readFileSync5(CONFIG_FILE, "utf-8"));
15949
+ if (existsSync6(CONFIG_FILE)) {
15950
+ const data = JSON.parse(readFileSync6(CONFIG_FILE, "utf-8"));
14632
15951
  if (data?.themeId && getThemeById(data.themeId)) {
14633
15952
  return data.themeId;
14634
15953
  }
@@ -14638,10 +15957,10 @@ function loadPersistedThemeId() {
14638
15957
  }
14639
15958
  function persistThemeId(themeId) {
14640
15959
  try {
14641
- if (!existsSync4(CONFIG_DIR)) {
14642
- mkdirSync5(CONFIG_DIR, { recursive: true });
15960
+ if (!existsSync6(CONFIG_DIR)) {
15961
+ mkdirSync6(CONFIG_DIR, { recursive: true });
14643
15962
  }
14644
- writeFileSync3(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
15963
+ writeFileSync4(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
14645
15964
  } catch {}
14646
15965
  }
14647
15966
  function setTuiTheme(themeId) {
@@ -14666,8 +15985,8 @@ function getAvailableThemes() {
14666
15985
  var CONFIG_DIR, CONFIG_FILE, currentThemeId, currentColors, C, NAV_ITEMS, SCREEN_TITLES;
14667
15986
  var init_theme = __esm(() => {
14668
15987
  init_src12();
14669
- CONFIG_DIR = join9(homedir3(), ".config", "agent-smith");
14670
- CONFIG_FILE = join9(CONFIG_DIR, "theme.json");
15988
+ CONFIG_DIR = join10(homedir4(), ".config", "agent-smith");
15989
+ CONFIG_FILE = join10(CONFIG_DIR, "theme.json");
14671
15990
  currentThemeId = loadPersistedThemeId();
14672
15991
  currentColors = themeToTuiColors(getThemeById(currentThemeId) ?? getDefaultTheme("dark"));
14673
15992
  C = new Proxy({}, {
@@ -15481,22 +16800,22 @@ function createBar(value, maxValue, width, showPercentage = true) {
15481
16800
  const percentage = maxValue > 0 ? value / maxValue : 0;
15482
16801
  const filledWidth = Math.floor(percentage * width);
15483
16802
  const remainingWidth = width - filledWidth;
15484
- let bar = "";
16803
+ let bar2 = "";
15485
16804
  for (let i = 0;i < filledWidth; i++) {
15486
- bar += BAR_CHARS.full;
16805
+ bar2 += BAR_CHARS.full;
15487
16806
  }
15488
16807
  if (remainingWidth > 0) {
15489
16808
  const remainingPercentage = percentage * width - filledWidth;
15490
- bar += getBarChar(remainingPercentage);
16809
+ bar2 += getBarChar(remainingPercentage);
15491
16810
  for (let i = 1;i < remainingWidth; i++) {
15492
- bar += BAR_CHARS.empty;
16811
+ bar2 += BAR_CHARS.empty;
15493
16812
  }
15494
16813
  }
15495
16814
  if (showPercentage) {
15496
16815
  const percentStr = `${Math.round(percentage * 100)}%`;
15497
- return `${bar} ${percentStr}`;
16816
+ return `${bar2} ${percentStr}`;
15498
16817
  }
15499
- return bar;
16818
+ return bar2;
15500
16819
  }
15501
16820
  function createSparkline(data) {
15502
16821
  if (data.length === 0)
@@ -15561,7 +16880,7 @@ function BarChart({
15561
16880
  })
15562
16881
  }),
15563
16882
  data.map((item) => {
15564
- const bar = createBar(item.value, maxValue, width, false);
16883
+ const bar2 = createBar(item.value, maxValue, width, false);
15565
16884
  const color = item.color || C.chart1;
15566
16885
  return /* @__PURE__ */ jsxs2("box", {
15567
16886
  flexDirection: "row",
@@ -15572,7 +16891,7 @@ function BarChart({
15572
16891
  }),
15573
16892
  /* @__PURE__ */ jsx2("text", {
15574
16893
  fg: color,
15575
- children: bar
16894
+ children: bar2
15576
16895
  }),
15577
16896
  showValues && /* @__PURE__ */ jsxs2("text", {
15578
16897
  fg: C.muted,
@@ -16403,13 +17722,13 @@ function reducer(state, action) {
16403
17722
  function LogsScreen({ refreshKey }) {
16404
17723
  const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
16405
17724
  const logKeyCounts = new Map;
16406
- const keyedLogs = state.logs.map((log26) => {
16407
- const baseKey = `${log26.ts}-${log26.level ?? ""}-${log26.msg}`;
17725
+ const keyedLogs = state.logs.map((log27) => {
17726
+ const baseKey = `${log27.ts}-${log27.level ?? ""}-${log27.msg}`;
16408
17727
  const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
16409
17728
  logKeyCounts.set(baseKey, count);
16410
17729
  return {
16411
17730
  key: count === 1 ? baseKey : `${baseKey}-${count}`,
16412
- log: log26
17731
+ log: log27
16413
17732
  };
16414
17733
  });
16415
17734
  useKeyboard3((key) => {
@@ -16433,8 +17752,8 @@ function LogsScreen({ refreshKey }) {
16433
17752
  }, [refreshKey]);
16434
17753
  useEffect3(() => {
16435
17754
  if (!state.paused && !state.loading) {
16436
- const unsubscribe = streamLogs((log26) => {
16437
- dispatch({ type: "new_entry", log: log26 });
17755
+ const unsubscribe = streamLogs((log27) => {
17756
+ dispatch({ type: "new_entry", log: log27 });
16438
17757
  });
16439
17758
  return () => {
16440
17759
  unsubscribe();
@@ -16487,15 +17806,15 @@ function LogsScreen({ refreshKey }) {
16487
17806
  children: "No logs yet..."
16488
17807
  }) : /* @__PURE__ */ jsx7("box", {
16489
17808
  flexDirection: "column",
16490
- children: keyedLogs.map(({ key, log: log26 }) => {
16491
- const sev = getLogSeverityMeta(log26.level);
17809
+ children: keyedLogs.map(({ key, log: log27 }) => {
17810
+ const sev = getLogSeverityMeta(log27.level);
16492
17811
  return /* @__PURE__ */ jsxs7("text", {
16493
17812
  fg: sev.termColor,
16494
17813
  children: [
16495
17814
  "[",
16496
17815
  sev.label,
16497
17816
  "] ",
16498
- log26.msg
17817
+ log27.msg
16499
17818
  ]
16500
17819
  }, key);
16501
17820
  })
@@ -16908,9 +18227,9 @@ function TokenBar({
16908
18227
  total,
16909
18228
  color
16910
18229
  }) {
16911
- const pct = total > 0 ? value / total * 100 : 0;
18230
+ const pct2 = total > 0 ? value / total * 100 : 0;
16912
18231
  const barWidth = 20;
16913
- const filled = Math.round(pct / 100 * barWidth);
18232
+ const filled = Math.round(pct2 / 100 * barWidth);
16914
18233
  return /* @__PURE__ */ jsxs8("box", {
16915
18234
  flexDirection: "row",
16916
18235
  gap: 1,
@@ -16933,7 +18252,7 @@ function TokenBar({
16933
18252
  " ",
16934
18253
  formatNumber(value),
16935
18254
  " (",
16936
- Math.round(pct),
18255
+ Math.round(pct2),
16937
18256
  "%)"
16938
18257
  ]
16939
18258
  })
@@ -18067,6 +19386,14 @@ Accounts:`);
18067
19386
  }
18068
19387
  }
18069
19388
  async function main() {
19389
+ if (process.argv[2] === "client") {
19390
+ await runClientCommand(process.argv.slice(3));
19391
+ return;
19392
+ }
19393
+ if (process.argv[2] === "menubar") {
19394
+ await runMenubarCommand(process.argv.slice(3));
19395
+ return;
19396
+ }
18070
19397
  container.registerInstance(SERVICE_KEYS.Config, new Config);
18071
19398
  container.registerInstance(SERVICE_KEYS.Logger, new Logger("TUI"));
18072
19399
  DatabaseFactory.initialize();
@@ -18083,6 +19410,8 @@ ${POC_NOTICE}
18083
19410
  Usage: agent-smith [options]
18084
19411
  agent-smith run [--port <number>] -- [claude arguments]
18085
19412
  agent-smith install-client
19413
+ agent-smith client on|off|status [--raw]
19414
+ agent-smith menubar install|uninstall|render
18086
19415
 
18087
19416
  Options:
18088
19417
  --serve Start API server with dashboard
@@ -18113,6 +19442,7 @@ Examples:
18113
19442
  agent-smith --analyze # Run performance analysis
18114
19443
  agent-smith --stats # View stats
18115
19444
  agent-smith install-client # Configure Claude Code and Codex for this Agent Smith server
19445
+ agent-smith menubar install # Show the shared pool's usage in the macOS menu bar (SwiftBar)
18116
19446
  `);
18117
19447
  process.exit(0);
18118
19448
  }
@@ -18139,7 +19469,9 @@ Examples:
18139
19469
  await enableLocalClientRouting({
18140
19470
  port: port2,
18141
19471
  baseUrl: client2.baseUrl,
18142
- proxyKeyFile: client2.proxyKeyFile
19472
+ proxyKeyFile: client2.proxyKeyFile,
19473
+ keepClaudeLogin: client2.keepClaudeLogin,
19474
+ clientConfigPath: resolveConfigPath()
18143
19475
  });
18144
19476
  console.log(`Client wrappers configured for ${client2.baseUrl}.`);
18145
19477
  console.log("Open a new shell and launch Claude Code or Codex through these wrappers. Already-running sessions are unchanged; restart or resume them through the wrapper.");
@@ -18163,13 +19495,13 @@ Examples:
18163
19495
  const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
18164
19496
  if (typeof parsed.logs === "number") {
18165
19497
  const history = await getLogHistory(limit);
18166
- for (const log26 of history) {
18167
- console.log(`[${log26.level}] ${log26.msg}`);
19498
+ for (const log27 of history) {
19499
+ console.log(`[${log27.level}] ${log27.msg}`);
18168
19500
  }
18169
19501
  console.log("--- Live logs ---");
18170
19502
  }
18171
- await streamLogs((log26) => {
18172
- console.log(`[${log26.level}] ${log26.msg}`);
19503
+ await streamLogs((log27) => {
19504
+ console.log(`[${log27.level}] ${log27.msg}`);
18173
19505
  });
18174
19506
  return;
18175
19507
  }
@@ -18271,6 +19603,8 @@ var init_main = __esm(() => {
18271
19603
  init_src11();
18272
19604
  init_core();
18273
19605
  init_core();
19606
+ init_client_command();
19607
+ init_menubar_command();
18274
19608
  main().catch(async (error) => {
18275
19609
  console.error("Error:", error.message);
18276
19610
  try {