@certalis/agent-smith 0.1.15 → 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/README.md +13 -1
- package/dist/bin.js +1473 -301
- package/dist/client-launcher.js +197 -19
- package/dist/dashboard/chunk-re8nxxzq.css +1 -0
- package/dist/dashboard/chunk-v15gev12.js +111 -0
- package/dist/dashboard/{chunk-rnbsj0t8.js.map → chunk-v15gev12.js.map} +11 -8
- package/dist/dashboard/index.html +1 -1
- package/dist/dashboard/manifest.json +3 -3
- package/dist/edge.js +12 -1
- package/dist/https.js +13 -2
- package/dist/pool-status.js +170 -0
- package/dist/pool.js +1097 -267
- package/dist/post-processor.worker.js +229 -25
- package/dist/server.js +1097 -267
- package/package.json +1 -1
- package/dist/dashboard/chunk-r6qvhv5e.css +0 -1
- package/dist/dashboard/chunk-rnbsj0t8.js +0 -111
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(
|
|
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) {
|
|
@@ -1439,6 +1571,9 @@ function sanitizeClientRouting(value) {
|
|
|
1439
1571
|
if (typeof value.keep_claude_login === "boolean") {
|
|
1440
1572
|
client.keep_claude_login = value.keep_claude_login;
|
|
1441
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
|
+
}
|
|
1442
1577
|
return Object.keys(client).length > 0 ? client : undefined;
|
|
1443
1578
|
}
|
|
1444
1579
|
function sanitizeProviderModels(value) {
|
|
@@ -1506,12 +1641,25 @@ function sanitizeTeamRouting(value) {
|
|
|
1506
1641
|
if (typeof value.distribution_enabled === "boolean") {
|
|
1507
1642
|
result.distribution_enabled = value.distribution_enabled;
|
|
1508
1643
|
}
|
|
1644
|
+
if (typeof value.prefer_expiring_quota === "boolean") {
|
|
1645
|
+
result.prefer_expiring_quota = value.prefer_expiring_quota;
|
|
1646
|
+
}
|
|
1509
1647
|
if (Array.isArray(value.allowlisted_account_uuids) && value.allowlisted_account_uuids.every((entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 200)) {
|
|
1510
1648
|
result.allowlisted_account_uuids = [...value.allowlisted_account_uuids];
|
|
1511
1649
|
}
|
|
1512
1650
|
if (isFiniteNumber(value.max_usage) && value.max_usage > 0 && value.max_usage <= 0.9) {
|
|
1513
1651
|
result.max_usage = value.max_usage;
|
|
1514
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
|
+
}
|
|
1515
1663
|
if (isNonNegativeFiniteNumber(value.admission_cap)) {
|
|
1516
1664
|
result.admission_cap = Math.floor(value.admission_cap);
|
|
1517
1665
|
}
|
|
@@ -1527,6 +1675,9 @@ function sanitizeTeamRouting(value) {
|
|
|
1527
1675
|
if (isNonNegativeFiniteNumber(value.quota_probe_seconds)) {
|
|
1528
1676
|
result.quota_probe_seconds = Math.min(Math.floor(value.quota_probe_seconds), 7 * 24 * 60 * 60);
|
|
1529
1677
|
}
|
|
1678
|
+
const windowWarmup = sanitizeWindowWarmup(value.window_warmup);
|
|
1679
|
+
if (windowWarmup)
|
|
1680
|
+
result.window_warmup = windowWarmup;
|
|
1530
1681
|
return result;
|
|
1531
1682
|
}
|
|
1532
1683
|
function readClientRouting(configPath = resolveConfigPath()) {
|
|
@@ -1546,17 +1697,20 @@ function clientRouting(client) {
|
|
|
1546
1697
|
enabled: client?.enabled === true,
|
|
1547
1698
|
...client?.base_url && { baseUrl: client.base_url },
|
|
1548
1699
|
...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
|
|
1549
|
-
...client?.keep_claude_login === true && { keepClaudeLogin: true }
|
|
1700
|
+
...client?.keep_claude_login === true && { keepClaudeLogin: true },
|
|
1701
|
+
...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
|
|
1550
1702
|
};
|
|
1551
1703
|
}
|
|
1552
|
-
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;
|
|
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;
|
|
1553
1705
|
var init_src4 = __esm(() => {
|
|
1554
1706
|
init_src2();
|
|
1555
1707
|
init_src3();
|
|
1556
1708
|
init_src();
|
|
1557
1709
|
init_paths();
|
|
1710
|
+
init_window_warmup();
|
|
1558
1711
|
init_paths();
|
|
1559
1712
|
init_paths_common();
|
|
1713
|
+
init_window_warmup();
|
|
1560
1714
|
log2 = new Logger("Config");
|
|
1561
1715
|
PROVIDER_STRATEGIES = [
|
|
1562
1716
|
"anthropic-api",
|
|
@@ -1572,16 +1726,21 @@ var init_src4 = __esm(() => {
|
|
|
1572
1726
|
];
|
|
1573
1727
|
BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
|
|
1574
1728
|
PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
1729
|
+
POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
|
|
1575
1730
|
TEAM_ROUTING_DEFAULTS = {
|
|
1576
1731
|
enabled: false,
|
|
1577
1732
|
distributionEnabled: true,
|
|
1733
|
+
preferExpiringQuota: false,
|
|
1578
1734
|
allowlistedAccountUuids: [],
|
|
1579
1735
|
maxUsage: 0.9,
|
|
1736
|
+
weeklyMaxUsage: 0.95,
|
|
1737
|
+
weeklyMaxUsageByEmail: {},
|
|
1580
1738
|
admissionCap: 5,
|
|
1581
1739
|
admissionQueueLimit: 25,
|
|
1582
1740
|
admissionWaitMs: 30000,
|
|
1583
1741
|
holdSeconds: 0,
|
|
1584
|
-
quotaProbeSeconds: 0
|
|
1742
|
+
quotaProbeSeconds: 0,
|
|
1743
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
1585
1744
|
};
|
|
1586
1745
|
Config = class Config extends EventEmitter3 {
|
|
1587
1746
|
configPath;
|
|
@@ -1687,17 +1846,20 @@ var init_src4 = __esm(() => {
|
|
|
1687
1846
|
if (fromEnv) {
|
|
1688
1847
|
const n = parseInt(fromEnv, 10);
|
|
1689
1848
|
if (!Number.isNaN(n))
|
|
1690
|
-
return this.clamp(n,
|
|
1849
|
+
return this.clamp(n, 0, 365);
|
|
1691
1850
|
}
|
|
1692
1851
|
const fromFile = this.data.data_retention_days;
|
|
1693
1852
|
if (typeof fromFile === "number")
|
|
1694
|
-
return this.clamp(fromFile,
|
|
1853
|
+
return this.clamp(fromFile, 0, 365);
|
|
1695
1854
|
return 7;
|
|
1696
1855
|
}
|
|
1697
1856
|
setDataRetentionDays(days) {
|
|
1698
|
-
const clamped = this.clamp(days,
|
|
1857
|
+
const clamped = this.clamp(days, 0, 365);
|
|
1699
1858
|
this.set("data_retention_days", clamped);
|
|
1700
1859
|
}
|
|
1860
|
+
storesRequestPayloads() {
|
|
1861
|
+
return this.getDataRetentionDays() > 0;
|
|
1862
|
+
}
|
|
1701
1863
|
getRequestRetentionDays() {
|
|
1702
1864
|
const fromEnv = process.env.AGENT_SMITH_REQUEST_RETENTION_DAYS;
|
|
1703
1865
|
if (fromEnv) {
|
|
@@ -1728,15 +1890,19 @@ var init_src4 = __esm(() => {
|
|
|
1728
1890
|
return {
|
|
1729
1891
|
enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
|
|
1730
1892
|
distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
|
|
1893
|
+
preferExpiringQuota: file?.prefer_expiring_quota ?? TEAM_ROUTING_DEFAULTS.preferExpiringQuota,
|
|
1731
1894
|
allowlistedAccountUuids: [
|
|
1732
1895
|
...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
|
|
1733
1896
|
],
|
|
1734
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 },
|
|
1735
1900
|
admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
|
|
1736
1901
|
admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
|
|
1737
1902
|
admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
|
|
1738
1903
|
holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
|
|
1739
|
-
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)
|
|
1740
1906
|
};
|
|
1741
1907
|
}
|
|
1742
1908
|
getAlerts() {
|
|
@@ -1795,13 +1961,17 @@ var init_src4 = __esm(() => {
|
|
|
1795
1961
|
const allowed = new Set([
|
|
1796
1962
|
"enabled",
|
|
1797
1963
|
"distribution_enabled",
|
|
1964
|
+
"prefer_expiring_quota",
|
|
1798
1965
|
"allowlisted_account_uuids",
|
|
1799
1966
|
"max_usage",
|
|
1967
|
+
"weekly_max_usage",
|
|
1968
|
+
"weekly_max_usage_by_email",
|
|
1800
1969
|
"admission_cap",
|
|
1801
1970
|
"admission_queue_limit",
|
|
1802
1971
|
"admission_wait_ms",
|
|
1803
1972
|
"hold_seconds",
|
|
1804
|
-
"quota_probe_seconds"
|
|
1973
|
+
"quota_probe_seconds",
|
|
1974
|
+
"window_warmup"
|
|
1805
1975
|
]);
|
|
1806
1976
|
if (Object.keys(value).some((key) => !allowed.has(key))) {
|
|
1807
1977
|
throw new Error("team routing configuration contains an unknown field");
|
|
@@ -1816,13 +1986,12 @@ var init_src4 = __esm(() => {
|
|
|
1816
1986
|
}
|
|
1817
1987
|
}
|
|
1818
1988
|
const oldValue = this.data.team_routing;
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
});
|
|
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);
|
|
1826
1995
|
}
|
|
1827
1996
|
allowAccountUuid(accountUuid) {
|
|
1828
1997
|
const current = this.getTeamRouting().allowlistedAccountUuids;
|
|
@@ -1845,10 +2014,18 @@ var init_src4 = __esm(() => {
|
|
|
1845
2014
|
getEnrollmentEmails() {
|
|
1846
2015
|
return [...this.data.enrollment_emails ?? []];
|
|
1847
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
|
+
}
|
|
1848
2025
|
setEnrollmentEmails(emails) {
|
|
1849
|
-
const normalized = emails.map(
|
|
2026
|
+
const normalized = emails.map(normalizeEnrollmentRule);
|
|
1850
2027
|
if (normalized.some((email) => email === undefined)) {
|
|
1851
|
-
throw new ValidationError("Invalid enrollment email", "enrollment_emails");
|
|
2028
|
+
throw new ValidationError("Invalid enrollment email or exact-domain rule (use *@example.com)", "enrollment_emails");
|
|
1852
2029
|
}
|
|
1853
2030
|
const unique = [...new Set(normalized)];
|
|
1854
2031
|
if (unique.length > MAX_ENROLLMENT_EMAILS) {
|
|
@@ -1878,6 +2055,7 @@ var init_src4 = __esm(() => {
|
|
|
1878
2055
|
},
|
|
1879
2056
|
sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
|
|
1880
2057
|
port: NETWORK.DEFAULT_PORT,
|
|
2058
|
+
storeRequestPayloads: this.storesRequestPayloads(),
|
|
1881
2059
|
teamRouting: this.getTeamRouting()
|
|
1882
2060
|
};
|
|
1883
2061
|
if (process.env.AGENT_SMITH_CLIENT_ID) {
|
|
@@ -2454,7 +2632,7 @@ function backfillRequestLinkageColumns(db) {
|
|
|
2454
2632
|
FROM requests r
|
|
2455
2633
|
LEFT JOIN request_payloads rp ON rp.id = r.id
|
|
2456
2634
|
ORDER BY r.timestamp ASC
|
|
2457
|
-
`).
|
|
2635
|
+
`).iterate();
|
|
2458
2636
|
const responseToChain = new Map;
|
|
2459
2637
|
let updatedRows = 0;
|
|
2460
2638
|
const updateStmt = db.prepare(`
|
|
@@ -3612,7 +3790,7 @@ var init_request_repository = __esm(() => {
|
|
|
3612
3790
|
}
|
|
3613
3791
|
save(data) {
|
|
3614
3792
|
const { usage, timings } = data;
|
|
3615
|
-
const payloadJson = data.payload === undefined ? undefined : JSON.stringify(data.payload);
|
|
3793
|
+
const payloadJson = data.payload === undefined || data.storePayload === false ? undefined : JSON.stringify(data.payload);
|
|
3616
3794
|
const linkage = requestLinkageFromPayload(data.payload);
|
|
3617
3795
|
const responseChainId = this.resolveResponseChainId(linkage.previousResponseId, linkage.responseId, data.id);
|
|
3618
3796
|
this.db.run("BEGIN");
|
|
@@ -3992,7 +4170,11 @@ var init_request_repository = __esm(() => {
|
|
|
3992
4170
|
return this.runWithChanges(`DELETE FROM request_payloads WHERE id NOT IN (SELECT id FROM requests)`);
|
|
3993
4171
|
}
|
|
3994
4172
|
deletePayloadsOlderThan(cutoffTs) {
|
|
3995
|
-
return this.runWithChanges(`DELETE FROM request_payloads
|
|
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]);
|
|
3996
4178
|
}
|
|
3997
4179
|
};
|
|
3998
4180
|
});
|
|
@@ -4119,11 +4301,16 @@ var init_strategy_repository = __esm(() => {
|
|
|
4119
4301
|
|
|
4120
4302
|
// ../../packages/database/src/database-operations.ts
|
|
4121
4303
|
import { Database } from "bun:sqlite";
|
|
4122
|
-
import { mkdirSync as mkdirSync3 } from "fs";
|
|
4304
|
+
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
4123
4305
|
import { dirname as dirname2 } from "path";
|
|
4306
|
+
function freeDiskBytes(directory) {
|
|
4307
|
+
const { bavail, bsize } = statfsSync(directory);
|
|
4308
|
+
return bavail * bsize;
|
|
4309
|
+
}
|
|
4124
4310
|
|
|
4125
4311
|
class DatabaseOperations {
|
|
4126
4312
|
db;
|
|
4313
|
+
dbPath;
|
|
4127
4314
|
runtime;
|
|
4128
4315
|
closed = false;
|
|
4129
4316
|
accounts;
|
|
@@ -4135,6 +4322,7 @@ class DatabaseOperations {
|
|
|
4135
4322
|
stats;
|
|
4136
4323
|
constructor(dbPath) {
|
|
4137
4324
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
4325
|
+
this.dbPath = resolvedPath;
|
|
4138
4326
|
const dir = dirname2(resolvedPath);
|
|
4139
4327
|
mkdirSync3(dir, { recursive: true });
|
|
4140
4328
|
this.db = new Database(resolvedPath, { create: true });
|
|
@@ -4267,6 +4455,7 @@ class DatabaseOperations {
|
|
|
4267
4455
|
usage,
|
|
4268
4456
|
timestamp: options?.timestamp,
|
|
4269
4457
|
payload: options?.payload,
|
|
4458
|
+
storePayload: options?.storePayload,
|
|
4270
4459
|
timings: options?.timings
|
|
4271
4460
|
});
|
|
4272
4461
|
}
|
|
@@ -4351,7 +4540,7 @@ class DatabaseOperations {
|
|
|
4351
4540
|
return;
|
|
4352
4541
|
}
|
|
4353
4542
|
this.closed = true;
|
|
4354
|
-
this.
|
|
4543
|
+
this.checkpointWal();
|
|
4355
4544
|
this.db.close();
|
|
4356
4545
|
}
|
|
4357
4546
|
dispose() {
|
|
@@ -4361,9 +4550,23 @@ class DatabaseOperations {
|
|
|
4361
4550
|
this.db.exec("PRAGMA optimize");
|
|
4362
4551
|
this.db.exec("PRAGMA wal_checkpoint(PASSIVE)");
|
|
4363
4552
|
}
|
|
4364
|
-
|
|
4553
|
+
checkpointWal() {
|
|
4365
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
|
+
}
|
|
4366
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;
|
|
4367
4570
|
}
|
|
4368
4571
|
getStatsRepository() {
|
|
4369
4572
|
return this.stats;
|
|
@@ -4431,7 +4634,7 @@ var init_src5 = __esm(() => {
|
|
|
4431
4634
|
});
|
|
4432
4635
|
|
|
4433
4636
|
// ../../packages/http/src/errors.ts
|
|
4434
|
-
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;
|
|
4435
4638
|
var init_errors2 = __esm(() => {
|
|
4436
4639
|
ERROR_TYPES = {
|
|
4437
4640
|
NETWORK: "network",
|
|
@@ -5197,7 +5400,7 @@ async function fetchClaudeCodeUsage(accessToken) {
|
|
|
5197
5400
|
var CLAUDE_CODE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage";
|
|
5198
5401
|
|
|
5199
5402
|
// ../../packages/providers/src/providers/claude-code/provider.ts
|
|
5200
|
-
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;
|
|
5201
5404
|
var init_provider2 = __esm(() => {
|
|
5202
5405
|
init_src3();
|
|
5203
5406
|
init_src();
|
|
@@ -5238,6 +5441,27 @@ var init_provider2 = __esm(() => {
|
|
|
5238
5441
|
async probeQuota(_account, accessToken) {
|
|
5239
5442
|
return await fetchClaudeCodeUsage(accessToken);
|
|
5240
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
|
+
}
|
|
5241
5465
|
async refreshToken(account2, clientId) {
|
|
5242
5466
|
return executeTokenRefresh(account2, clientId, CLAUDE_CODE_REFRESH_CONFIG, log7);
|
|
5243
5467
|
}
|
|
@@ -5651,6 +5875,107 @@ var init_oauth3 = __esm(() => {
|
|
|
5651
5875
|
};
|
|
5652
5876
|
});
|
|
5653
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
|
+
|
|
5654
5979
|
// ../../packages/providers/src/providers/codex/provider.ts
|
|
5655
5980
|
function isEnvironmentContext(value) {
|
|
5656
5981
|
return isRecord(value) && value.type === "input_text" && typeof value.text === "string" && /^<environment_context>\r?\n[\s\S]*<\/environment_context>\s*$/.test(value.text);
|
|
@@ -5716,6 +6041,7 @@ var init_provider4 = __esm(() => {
|
|
|
5716
6041
|
init_base();
|
|
5717
6042
|
init_provider3();
|
|
5718
6043
|
init_oauth3();
|
|
6044
|
+
init_reset_credits();
|
|
5719
6045
|
CODEX_USER_AGENT = `codex_cli_rs/${CODEX_CLIENT_VERSION} (Mac OS; arm64)`;
|
|
5720
6046
|
log8 = new Logger("CodexProvider");
|
|
5721
6047
|
DEFAULT_BASE_URL4 = getProviderDefaultBaseUrl(PROVIDER_NAME4);
|
|
@@ -5747,6 +6073,25 @@ var init_provider4 = __esm(() => {
|
|
|
5747
6073
|
name = PROVIDER_NAME4;
|
|
5748
6074
|
defaultBaseUrl = DEFAULT_BASE_URL4;
|
|
5749
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
|
+
}
|
|
5750
6095
|
getClientSessionId(headers2) {
|
|
5751
6096
|
return headers2.get("session-id");
|
|
5752
6097
|
}
|
|
@@ -6313,9 +6658,9 @@ function startCallbackForwarder(provider, providerRegistry) {
|
|
|
6313
6658
|
try {
|
|
6314
6659
|
const server = Bun.serve({
|
|
6315
6660
|
port,
|
|
6316
|
-
fetch(
|
|
6317
|
-
const url = new URL(
|
|
6318
|
-
if (
|
|
6661
|
+
fetch(request3) {
|
|
6662
|
+
const url = new URL(request3.url);
|
|
6663
|
+
if (request3.method !== "GET" || url.pathname !== "/auth/callback") {
|
|
6319
6664
|
return new Response("Not Found", { status: 404 });
|
|
6320
6665
|
}
|
|
6321
6666
|
const target = new URL(`http://localhost:8080${targetPath}`);
|
|
@@ -6527,6 +6872,7 @@ function serializeAccount(account2, providerRegistry, now = Date.now()) {
|
|
|
6527
6872
|
name: account2.name,
|
|
6528
6873
|
provider: account2.provider,
|
|
6529
6874
|
providerDisabled: !providerRegistry.getProvider(account2.provider),
|
|
6875
|
+
resetCreditsSupported: providerRegistry.getProvider(account2.provider)?.supportsResetCredits?.(account2) ?? false,
|
|
6530
6876
|
auth_method: account2.auth_method,
|
|
6531
6877
|
base_url: account2.base_url,
|
|
6532
6878
|
requestCount: account2.request_count,
|
|
@@ -7116,7 +7462,10 @@ function createConfigHandlers(config) {
|
|
|
7116
7462
|
getStrategies: () => {
|
|
7117
7463
|
return jsonResponse(LB_STRATEGIES);
|
|
7118
7464
|
},
|
|
7119
|
-
getTeamRouting: () =>
|
|
7465
|
+
getTeamRouting: () => {
|
|
7466
|
+
const { weeklyMaxUsageByEmail: _privateLimits, ...routing } = config.getTeamRouting();
|
|
7467
|
+
return jsonResponse(routing);
|
|
7468
|
+
},
|
|
7120
7469
|
setTeamRouting: async (req) => {
|
|
7121
7470
|
try {
|
|
7122
7471
|
const body = await parseJsonObject(req);
|
|
@@ -7146,7 +7495,7 @@ function createConfigHandlers(config) {
|
|
|
7146
7495
|
let updated = false;
|
|
7147
7496
|
if (body.payloadDays !== undefined) {
|
|
7148
7497
|
const payloadDays = validateNumber(body.payloadDays, "payloadDays", {
|
|
7149
|
-
min:
|
|
7498
|
+
min: 0,
|
|
7150
7499
|
max: 365,
|
|
7151
7500
|
integer: true
|
|
7152
7501
|
});
|
|
@@ -7212,7 +7561,7 @@ function enrollmentPage() {
|
|
|
7212
7561
|
<section class="card" id="step-email" hidden>
|
|
7213
7562
|
<div class="avatar">${icon("mail")}</div>
|
|
7214
7563
|
<h1 tabindex="-1">Connect your Claude subscription</h1>
|
|
7215
|
-
<p class="lead">
|
|
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>
|
|
7216
7565
|
<form id="request">
|
|
7217
7566
|
<p class="notice err" id="email-error" role="alert" hidden></p>
|
|
7218
7567
|
<label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
|
|
@@ -7225,16 +7574,16 @@ function enrollmentPage() {
|
|
|
7225
7574
|
<h1 tabindex="-1">Sign in with Claude</h1>
|
|
7226
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>
|
|
7227
7576
|
<ul class="facts">
|
|
7228
|
-
<li>Claude opens in a new tab. Sign in
|
|
7577
|
+
<li>Claude opens in a new tab. Sign in with the email shown above.</li>
|
|
7229
7578
|
<li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
|
|
7230
|
-
<li>Claude then
|
|
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>
|
|
7231
7580
|
</ul>
|
|
7232
7581
|
<button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
|
|
7233
7582
|
</section>
|
|
7234
7583
|
<section class="card" id="step-code" hidden>
|
|
7235
7584
|
<div class="avatar">${icon("code")}</div>
|
|
7236
7585
|
<h1 tabindex="-1">Paste the code from Claude</h1>
|
|
7237
|
-
<p class="lead" id="code-lead">
|
|
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>
|
|
7238
7587
|
<form id="verify">
|
|
7239
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>
|
|
7240
7589
|
<button class="button" type="submit">Verify account</button>
|
|
@@ -7244,42 +7593,47 @@ function enrollmentPage() {
|
|
|
7244
7593
|
<section class="card" id="step-confirm" hidden>
|
|
7245
7594
|
<div class="avatar">${icon("person")}</div>
|
|
7246
7595
|
<h1 tabindex="-1">Is this the right account?</h1>
|
|
7247
|
-
<p class="lead">Claude verified
|
|
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>
|
|
7248
7597
|
<form id="confirm">
|
|
7249
7598
|
<div class="account">${icon("check")}<span id="account"></span></div>
|
|
7250
7599
|
<label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
|
|
7251
|
-
<button class="button" type="submit">
|
|
7600
|
+
<button class="button" type="submit">Confirm connection</button>
|
|
7252
7601
|
</form>
|
|
7253
|
-
<p class="aside">Wrong account? Do not confirm
|
|
7602
|
+
<p class="aside">Wrong account? Do not confirm. Use \u201CStart again\u201D below to choose the right one.</p>
|
|
7254
7603
|
</section>
|
|
7255
7604
|
<section class="card" id="step-done" hidden>
|
|
7256
7605
|
<div class="avatar ok">${icon("check")}</div>
|
|
7257
|
-
<h1 tabindex="-1">Subscription connected</h1>
|
|
7258
|
-
<p class="lead"><strong id="connected-account"></strong
|
|
7259
|
-
<div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership.
|
|
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>
|
|
7260
7609
|
</section>
|
|
7261
7610
|
<section class="card" id="step-error" hidden>
|
|
7262
7611
|
<div class="avatar err">${icon("alert")}</div>
|
|
7263
7612
|
<h1 tabindex="-1">This sign-in can't continue</h1>
|
|
7264
7613
|
<p class="lead" id="error-message"></p>
|
|
7265
|
-
<p class="aside">
|
|
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>
|
|
7266
7616
|
</section>
|
|
7267
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>
|
|
7268
7620
|
</main>
|
|
7269
|
-
<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>
|
|
7270
7622
|
<noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
|
|
7271
7623
|
<script nonce="${nonce}">
|
|
7272
7624
|
let token = location.hash.slice(1);
|
|
7273
|
-
history.replaceState(null, '', location.pathname);
|
|
7625
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(token)) { token = ''; history.replaceState(null, '', location.pathname); }
|
|
7274
7626
|
addEventListener('hashchange', () => { if (location.hash) location.reload(); });
|
|
7275
7627
|
const get = id => document.getElementById(id);
|
|
7276
7628
|
const steps = ['email', 'signin', 'code', 'confirm', 'done'];
|
|
7277
7629
|
let current = 'email';
|
|
7630
|
+
let pending = 0;
|
|
7278
7631
|
function show(step) {
|
|
7279
7632
|
const failed = step === 'error';
|
|
7280
7633
|
const index = steps.indexOf(failed ? current : step);
|
|
7281
7634
|
if (!failed) current = step;
|
|
7282
7635
|
for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
|
|
7636
|
+
get('restart').hidden = step === 'email';
|
|
7283
7637
|
document.querySelectorAll('#stepper li').forEach((item, position) => {
|
|
7284
7638
|
item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
|
|
7285
7639
|
item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
|
|
@@ -7289,23 +7643,78 @@ function show(step) {
|
|
|
7289
7643
|
(step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
|
|
7290
7644
|
}
|
|
7291
7645
|
async function send(step, body) {
|
|
7292
|
-
|
|
7293
|
-
|
|
7294
|
-
|
|
7295
|
-
|
|
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);
|
|
7296
7657
|
return data;
|
|
7297
7658
|
}
|
|
7298
|
-
|
|
7299
|
-
|
|
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) {
|
|
7300
7687
|
token = ''; get('code').value = '';
|
|
7301
|
-
get('
|
|
7688
|
+
get('recovery').hidden = true;
|
|
7689
|
+
get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Try resuming.';
|
|
7302
7690
|
show('error');
|
|
7303
7691
|
}
|
|
7304
|
-
|
|
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
|
+
});
|
|
7305
7713
|
get('request').addEventListener('submit', async event => {
|
|
7306
7714
|
event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
|
|
7307
7715
|
try {
|
|
7308
7716
|
const data = await send('request', {email: get('email').value});
|
|
7717
|
+
token = ''; history.replaceState(null, '', location.pathname); get('recovery').hidden = true;
|
|
7309
7718
|
get('signin-email').textContent = data.email; get('signin-for').hidden = false;
|
|
7310
7719
|
show('signin');
|
|
7311
7720
|
} catch (error) {
|
|
@@ -7318,24 +7727,26 @@ get('start').addEventListener('click', async () => {
|
|
|
7318
7727
|
get('start').disabled = true;
|
|
7319
7728
|
try {
|
|
7320
7729
|
const data = await post('start', {});
|
|
7321
|
-
const url =
|
|
7322
|
-
|
|
7323
|
-
|
|
7324
|
-
|
|
7325
|
-
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.';
|
|
7326
7734
|
show('code');
|
|
7327
|
-
} catch (error) { if (tab) tab.close(); fail(error); }
|
|
7735
|
+
} catch (error) { if (tab) tab.close(); await fail(error); }
|
|
7736
|
+
finally { get('start').disabled = false; }
|
|
7328
7737
|
});
|
|
7329
7738
|
get('verify').addEventListener('submit', async event => {
|
|
7330
7739
|
event.preventDefault(); event.submitter.disabled = true;
|
|
7331
7740
|
const code = get('code').value.trim(); get('code').value = '';
|
|
7332
7741
|
try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
|
|
7333
|
-
catch (error) { fail(error); }
|
|
7742
|
+
catch (error) { await fail(error); }
|
|
7743
|
+
finally { event.submitter.disabled = false; }
|
|
7334
7744
|
});
|
|
7335
7745
|
get('confirm').addEventListener('submit', async event => {
|
|
7336
7746
|
event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
|
|
7337
|
-
try { await post('confirm', {consent:true})
|
|
7338
|
-
catch (error) { fail(error); }
|
|
7747
|
+
try { connected(await post('confirm', {consent:true})); }
|
|
7748
|
+
catch (error) { await fail(error); }
|
|
7749
|
+
finally { event.submitter.disabled = false; }
|
|
7339
7750
|
});
|
|
7340
7751
|
get('disconnect').addEventListener('click', async () => {
|
|
7341
7752
|
get('disconnect').disabled = true; get('status').hidden = true;
|
|
@@ -7447,12 +7858,68 @@ class EnrollmentHandlers {
|
|
|
7447
7858
|
if (entry.expiresAt <= this.now())
|
|
7448
7859
|
this.entries.delete(key);
|
|
7449
7860
|
}
|
|
7450
|
-
mint(details, state, duration) {
|
|
7861
|
+
mint(details, state, duration, browserSession) {
|
|
7451
7862
|
const token = randomBytes2(32).toString("base64url");
|
|
7452
7863
|
const expiresAt = this.now() + duration;
|
|
7453
|
-
this.entries.set(hash(token), {
|
|
7864
|
+
this.entries.set(hash(token), {
|
|
7865
|
+
details,
|
|
7866
|
+
state,
|
|
7867
|
+
expiresAt,
|
|
7868
|
+
browserSession
|
|
7869
|
+
});
|
|
7454
7870
|
return { token, expiresAt };
|
|
7455
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
|
+
}
|
|
7456
7923
|
async guarded(action) {
|
|
7457
7924
|
try {
|
|
7458
7925
|
this.prune();
|
|
@@ -7467,14 +7934,14 @@ class EnrollmentHandlers {
|
|
|
7467
7934
|
if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
|
|
7468
7935
|
throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
|
|
7469
7936
|
}
|
|
7470
|
-
reserve(name) {
|
|
7471
|
-
if (this.context.dbOps.getAccountByName(name))
|
|
7937
|
+
reserve(name, reconnect = false) {
|
|
7938
|
+
if (!reconnect && this.context.dbOps.getAccountByName(name))
|
|
7472
7939
|
throw new EnrollmentError(409, "This seat is already in the pool.");
|
|
7473
7940
|
for (const entry of this.entries.values())
|
|
7474
7941
|
if (entry.details.name === name && entry.state.kind === "busy")
|
|
7475
7942
|
throw new EnrollmentError(409, "Sign-in is already in progress");
|
|
7476
7943
|
for (const [key, entry] of this.entries)
|
|
7477
|
-
if (entry.details.name === name)
|
|
7944
|
+
if (entry.details.name === name && entry.state.kind !== "connected")
|
|
7478
7945
|
this.entries.delete(key);
|
|
7479
7946
|
if (this.entries.size >= 100)
|
|
7480
7947
|
throw new EnrollmentError(429, "Too many pending invitations");
|
|
@@ -7484,12 +7951,32 @@ class EnrollmentHandlers {
|
|
|
7484
7951
|
if (Object.keys(body).some((key) => key !== "email"))
|
|
7485
7952
|
throw new EnrollmentError(400, "Unknown request field");
|
|
7486
7953
|
const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
|
7487
|
-
if (!this.context.config.
|
|
7488
|
-
throw new EnrollmentError(403, "This email is not
|
|
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.");
|
|
7489
7956
|
const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
|
|
7490
|
-
this.
|
|
7491
|
-
const
|
|
7492
|
-
|
|
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
|
+
});
|
|
7493
7980
|
}
|
|
7494
7981
|
emails = (req) => this.guarded(async () => {
|
|
7495
7982
|
const body = await readBody(req);
|
|
@@ -7558,9 +8045,20 @@ class EnrollmentHandlers {
|
|
|
7558
8045
|
const body = await readBody(req);
|
|
7559
8046
|
if (url.pathname === "/pool-enroll/request")
|
|
7560
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
|
+
}
|
|
7561
8060
|
const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
|
|
7562
|
-
const key = hash(token);
|
|
7563
|
-
const entry = this.entries.get(key);
|
|
8061
|
+
const [key, entry] = body.token === undefined ? this.browserEntry(req) ?? ["", undefined] : [hash(token), this.entries.get(hash(token))];
|
|
7564
8062
|
const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
|
|
7565
8063
|
if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
|
|
7566
8064
|
throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
|
|
@@ -7570,8 +8068,7 @@ class EnrollmentHandlers {
|
|
|
7570
8068
|
if (state.kind === "invited") {
|
|
7571
8069
|
const flow = await this.oauth.beginClaudeSeat();
|
|
7572
8070
|
this.assertCurrent(key, entry);
|
|
7573
|
-
return
|
|
7574
|
-
...this.mint(entry.details, { kind: "started", flow }, tenMinutes),
|
|
8071
|
+
return this.next(entry, { kind: "started", flow }, tenMinutes, req, {
|
|
7575
8072
|
authUrl: flow.authUrl
|
|
7576
8073
|
});
|
|
7577
8074
|
}
|
|
@@ -7588,9 +8085,8 @@ class EnrollmentHandlers {
|
|
|
7588
8085
|
const { email } = seat.identity;
|
|
7589
8086
|
if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
|
|
7590
8087
|
throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
|
|
7591
|
-
this.
|
|
7592
|
-
return
|
|
7593
|
-
...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
|
|
8088
|
+
this.assertSeat(entry.details, seat);
|
|
8089
|
+
return this.next(entry, { kind: "verified", seat }, tenMinutes, req, {
|
|
7594
8090
|
email
|
|
7595
8091
|
});
|
|
7596
8092
|
}
|
|
@@ -7598,13 +8094,16 @@ class EnrollmentHandlers {
|
|
|
7598
8094
|
if (body.consent !== true)
|
|
7599
8095
|
throw new EnrollmentError(400, "Confirm the displayed account before adding it");
|
|
7600
8096
|
const accountId = this.save(entry.details, state.seat);
|
|
7601
|
-
return
|
|
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, {
|
|
7602
8103
|
connected: true,
|
|
7603
|
-
|
|
7604
|
-
|
|
7605
|
-
|
|
7606
|
-
accountUuid: state.seat.identity.accountUuid
|
|
7607
|
-
}, oneDay)
|
|
8104
|
+
email: state.seat.identity.email,
|
|
8105
|
+
reconnected: !!entry.details.reconnect,
|
|
8106
|
+
...this.connectionStatus(accountId)
|
|
7608
8107
|
});
|
|
7609
8108
|
}
|
|
7610
8109
|
if (state.kind === "connected") {
|
|
@@ -7616,9 +8115,8 @@ class EnrollmentHandlers {
|
|
|
7616
8115
|
entry.state = state;
|
|
7617
8116
|
throw new EnrollmentError(500, "Removal could not be saved. Retry here or ask the operator to check this seat.");
|
|
7618
8117
|
}
|
|
7619
|
-
return
|
|
7620
|
-
disconnected: true
|
|
7621
|
-
...this.mint(entry.details, { kind: "invited" }, oneDay)
|
|
8118
|
+
return this.next({ ...entry, details: { ...entry.details, reconnect: undefined } }, { kind: "invited" }, oneDay, req, {
|
|
8119
|
+
disconnected: true
|
|
7622
8120
|
});
|
|
7623
8121
|
}
|
|
7624
8122
|
throw new EnrollmentError(410, "Link already used");
|
|
@@ -7632,14 +8130,40 @@ class EnrollmentHandlers {
|
|
|
7632
8130
|
if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
|
|
7633
8131
|
throw new EnrollmentError(410, "Sign-in expired. Start again.");
|
|
7634
8132
|
}
|
|
7635
|
-
|
|
7636
|
-
if (
|
|
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))
|
|
7637
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
|
+
};
|
|
7638
8150
|
}
|
|
7639
8151
|
save(details, seat) {
|
|
7640
8152
|
const { dbOps, config } = this.context;
|
|
7641
8153
|
return dbOps.getDatabase().transaction(() => {
|
|
7642
|
-
this.
|
|
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
|
+
}
|
|
7643
8167
|
const account2 = dbOps.createOAuthAccount({
|
|
7644
8168
|
name: details.name,
|
|
7645
8169
|
provider: "claude-code",
|
|
@@ -7708,7 +8232,7 @@ async function readBody(req) {
|
|
|
7708
8232
|
reader.releaseLock();
|
|
7709
8233
|
}
|
|
7710
8234
|
}
|
|
7711
|
-
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;
|
|
7712
8236
|
var init_enrollment = __esm(() => {
|
|
7713
8237
|
init_src2();
|
|
7714
8238
|
init_src8();
|
|
@@ -7720,7 +8244,9 @@ var init_enrollment = __esm(() => {
|
|
|
7720
8244
|
"/pool-enroll/start",
|
|
7721
8245
|
"/pool-enroll/verify",
|
|
7722
8246
|
"/pool-enroll/confirm",
|
|
7723
|
-
"/pool-enroll/disconnect"
|
|
8247
|
+
"/pool-enroll/disconnect",
|
|
8248
|
+
"/pool-enroll/resume",
|
|
8249
|
+
"/pool-enroll/reset"
|
|
7724
8250
|
]);
|
|
7725
8251
|
headers2 = {
|
|
7726
8252
|
"cache-control": "no-store",
|
|
@@ -7873,7 +8399,13 @@ function createCleanupHandler(dbOps, config) {
|
|
|
7873
8399
|
function createCompactHandler(dbOps) {
|
|
7874
8400
|
return () => {
|
|
7875
8401
|
try {
|
|
7876
|
-
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
|
+
}
|
|
7877
8409
|
const result = {
|
|
7878
8410
|
success: true,
|
|
7879
8411
|
message: "Database compacted successfully"
|
|
@@ -7893,10 +8425,10 @@ var init_maintenance = __esm(() => {
|
|
|
7893
8425
|
});
|
|
7894
8426
|
|
|
7895
8427
|
// ../../packages/api/src/serializers/request.ts
|
|
7896
|
-
function serializeRequestResponse(
|
|
8428
|
+
function serializeRequestResponse(request3) {
|
|
7897
8429
|
return {
|
|
7898
|
-
...toRequestSummary(
|
|
7899
|
-
accountName:
|
|
8430
|
+
...toRequestSummary(request3),
|
|
8431
|
+
accountName: request3.accountName ?? null
|
|
7900
8432
|
};
|
|
7901
8433
|
}
|
|
7902
8434
|
function enrichRequestPayload(payload, accountName = null) {
|
|
@@ -8018,6 +8550,94 @@ var init_requests_stream = __esm(() => {
|
|
|
8018
8550
|
init_src();
|
|
8019
8551
|
});
|
|
8020
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
|
+
|
|
8021
8641
|
// ../../packages/api/src/handlers/stats.ts
|
|
8022
8642
|
function createStatsHandler(dbOps) {
|
|
8023
8643
|
return () => {
|
|
@@ -8093,17 +8713,22 @@ function blockedReason(account2, threshold, now) {
|
|
|
8093
8713
|
function createFleetStatusHandler(dbOps, config, providerRegistry) {
|
|
8094
8714
|
return () => {
|
|
8095
8715
|
const now = Date.now();
|
|
8096
|
-
const quotaThreshold = config.getRuntime()
|
|
8716
|
+
const { quotaThreshold, teamRouting } = config.getRuntime();
|
|
8097
8717
|
const accounts = dbOps.getAllAccounts().map((account2) => ({
|
|
8098
8718
|
...serializeAccount(account2, providerRegistry, now),
|
|
8099
8719
|
blockedReason: blockedReason(account2, quotaThreshold, now),
|
|
8100
8720
|
quotaWindows: account2.quota_state?.windows ?? {},
|
|
8101
8721
|
outsideSpend: account2.quota_state?.outsideSpend ?? {}
|
|
8102
8722
|
}));
|
|
8103
|
-
return jsonResponse({
|
|
8723
|
+
return jsonResponse({
|
|
8724
|
+
accounts,
|
|
8725
|
+
quotaThreshold,
|
|
8726
|
+
nextWindowWarmupAt: nextWindowWarmupAt(teamRouting, now)
|
|
8727
|
+
});
|
|
8104
8728
|
};
|
|
8105
8729
|
}
|
|
8106
8730
|
var init_status = __esm(() => {
|
|
8731
|
+
init_src4();
|
|
8107
8732
|
init_src6();
|
|
8108
8733
|
init_src();
|
|
8109
8734
|
init_account();
|
|
@@ -8155,6 +8780,9 @@ class APIRouter {
|
|
|
8155
8780
|
const statsResetHandler = createStatsResetHandler(dbOps);
|
|
8156
8781
|
const fleetStatusHandler = createFleetStatusHandler(dbOps, config, providerRegistry);
|
|
8157
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));
|
|
8158
8786
|
const accountAddHandler = createAccountAddHandler(dbOps, config, providerRegistry);
|
|
8159
8787
|
const requestsSummaryHandler = createRequestsSummaryHandler(dbOps);
|
|
8160
8788
|
const requestsDetailHandler = createRequestsDetailHandler(dbOps);
|
|
@@ -8313,6 +8941,7 @@ var init_router = __esm(() => {
|
|
|
8313
8941
|
init_oauth6();
|
|
8314
8942
|
init_requests();
|
|
8315
8943
|
init_requests_stream();
|
|
8944
|
+
init_reset_credits2();
|
|
8316
8945
|
init_stats2();
|
|
8317
8946
|
init_status();
|
|
8318
8947
|
});
|
|
@@ -8343,6 +8972,14 @@ var init_background_tasks = __esm(() => {
|
|
|
8343
8972
|
});
|
|
8344
8973
|
|
|
8345
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
|
+
}
|
|
8346
8983
|
function liveUtilization(window2, now) {
|
|
8347
8984
|
if (window2.utilization === null)
|
|
8348
8985
|
return 0;
|
|
@@ -8365,11 +9002,11 @@ function soonestWeeklyReset(provider, account2, now) {
|
|
|
8365
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);
|
|
8366
9003
|
return Math.min(...resets, Number.POSITIVE_INFINITY);
|
|
8367
9004
|
}
|
|
8368
|
-
function compareSeatUsage(provider, model, now) {
|
|
9005
|
+
function compareSeatUsage(provider, model, now, preferExpiringQuota = false) {
|
|
8369
9006
|
return (left, right) => {
|
|
8370
9007
|
const a = seatUsage(provider, left, model, now);
|
|
8371
9008
|
const b = seatUsage(provider, right, model, now);
|
|
8372
|
-
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);
|
|
8373
9010
|
};
|
|
8374
9011
|
}
|
|
8375
9012
|
var init_seat_usage = __esm(() => {
|
|
@@ -8381,12 +9018,12 @@ import { createHash as createHash2 } from "crypto";
|
|
|
8381
9018
|
function isRecord5(value) {
|
|
8382
9019
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8383
9020
|
}
|
|
8384
|
-
function openingDigest(
|
|
8385
|
-
if (!
|
|
9021
|
+
function openingDigest(request3, provider) {
|
|
9022
|
+
if (!request3.body || request3.body.byteLength > MAX_OPENING_BYTES || !request3.contentType?.toLowerCase().includes("application/json")) {
|
|
8386
9023
|
return null;
|
|
8387
9024
|
}
|
|
8388
9025
|
try {
|
|
8389
|
-
const parsed = JSON.parse(new TextDecoder().decode(
|
|
9026
|
+
const parsed = JSON.parse(new TextDecoder().decode(request3.body));
|
|
8390
9027
|
if (!isRecord5(parsed))
|
|
8391
9028
|
return null;
|
|
8392
9029
|
const opening = provider.getConversationOpening?.(parsed);
|
|
@@ -8397,14 +9034,14 @@ function openingDigest(request2, provider) {
|
|
|
8397
9034
|
return null;
|
|
8398
9035
|
}
|
|
8399
9036
|
}
|
|
8400
|
-
function pinKey(
|
|
8401
|
-
if (!
|
|
9037
|
+
function pinKey(request3, provider) {
|
|
9038
|
+
if (!request3.sessionId)
|
|
8402
9039
|
return null;
|
|
8403
|
-
const digest = openingDigest(
|
|
9040
|
+
const digest = openingDigest(request3, provider) ?? "no-opening";
|
|
8404
9041
|
return createHash2("sha256").update([
|
|
8405
|
-
|
|
8406
|
-
|
|
8407
|
-
|
|
9042
|
+
request3.pinScope ?? request3.provider,
|
|
9043
|
+
request3.pinBucket ?? provider.weeklyBucketFor(request3.model) ?? "",
|
|
9044
|
+
request3.sessionId,
|
|
8408
9045
|
digest
|
|
8409
9046
|
].join("\x00")).digest("hex");
|
|
8410
9047
|
}
|
|
@@ -8415,15 +9052,15 @@ function isAllowlisted(account2, config) {
|
|
|
8415
9052
|
class TeamRouter {
|
|
8416
9053
|
inFlight = new Map;
|
|
8417
9054
|
pins = new Map;
|
|
8418
|
-
order(accounts,
|
|
8419
|
-
if (!config.enabled || !
|
|
9055
|
+
order(accounts, request3, config, provider, store, now = Date.now()) {
|
|
9056
|
+
if (!config.enabled || !request3)
|
|
8420
9057
|
return accounts;
|
|
8421
9058
|
this.removeExpiredPins(now, store);
|
|
8422
|
-
const eligible = this.eligibleAccounts(accounts,
|
|
9059
|
+
const eligible = this.eligibleAccounts(accounts, request3, config);
|
|
8423
9060
|
if (eligible.length === 0)
|
|
8424
9061
|
return [];
|
|
8425
|
-
const key = pinKey(
|
|
8426
|
-
const pinnedId = this.getPinnedAccountId(
|
|
9062
|
+
const key = pinKey(request3, provider);
|
|
9063
|
+
const pinnedId = this.getPinnedAccountId(request3, config, provider, store, now);
|
|
8427
9064
|
const pinned = pinnedId ? eligible.find((account2) => account2.id === pinnedId) : undefined;
|
|
8428
9065
|
if (pinned && key) {
|
|
8429
9066
|
this.touchPin(key, pinned.id, now, store);
|
|
@@ -8434,27 +9071,27 @@ class TeamRouter {
|
|
|
8434
9071
|
}
|
|
8435
9072
|
if (!config.distributionEnabled || !key)
|
|
8436
9073
|
return eligible;
|
|
8437
|
-
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider,
|
|
9074
|
+
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
8438
9075
|
this.touchPin(key, selected.id, now, store);
|
|
8439
9076
|
return [
|
|
8440
9077
|
selected,
|
|
8441
9078
|
...eligible.filter((account2) => account2.id !== selected.id)
|
|
8442
9079
|
];
|
|
8443
9080
|
}
|
|
8444
|
-
eligibleAccounts(accounts,
|
|
9081
|
+
eligibleAccounts(accounts, request3, config) {
|
|
8445
9082
|
if (!config.enabled)
|
|
8446
9083
|
return accounts;
|
|
8447
9084
|
const eligible = accounts.filter((account2) => isAllowlisted(account2, config));
|
|
8448
|
-
if (!
|
|
9085
|
+
if (!request3?.manualAccountName)
|
|
8449
9086
|
return eligible;
|
|
8450
|
-
return eligible.filter((account2) => account2.name ===
|
|
9087
|
+
return eligible.filter((account2) => account2.name === request3.manualAccountName);
|
|
8451
9088
|
}
|
|
8452
|
-
getPinnedAccountId(
|
|
8453
|
-
if (!config.enabled || !
|
|
9089
|
+
getPinnedAccountId(request3, config, provider, store, now = Date.now()) {
|
|
9090
|
+
if (!config.enabled || !request3?.sessionId || request3.manualAccountName) {
|
|
8454
9091
|
return;
|
|
8455
9092
|
}
|
|
8456
9093
|
this.removeExpiredPins(now, store);
|
|
8457
|
-
const key = pinKey(
|
|
9094
|
+
const key = pinKey(request3, provider);
|
|
8458
9095
|
return key ? (this.pins.get(key) ?? store?.getConversationPin(key))?.accountId : undefined;
|
|
8459
9096
|
}
|
|
8460
9097
|
begin(accountId) {
|
|
@@ -8468,10 +9105,10 @@ class TeamRouter {
|
|
|
8468
9105
|
}
|
|
8469
9106
|
this.inFlight.set(accountId, current - 1);
|
|
8470
9107
|
}
|
|
8471
|
-
rebind(
|
|
8472
|
-
if (!config.enabled ||
|
|
9108
|
+
rebind(request3, accountId, config, provider, store, now = Date.now()) {
|
|
9109
|
+
if (!config.enabled || request3?.manualAccountName)
|
|
8473
9110
|
return;
|
|
8474
|
-
const key =
|
|
9111
|
+
const key = request3 ? pinKey(request3, provider) : null;
|
|
8475
9112
|
if (key)
|
|
8476
9113
|
this.touchPin(key, accountId, now, store);
|
|
8477
9114
|
}
|
|
@@ -8542,18 +9179,32 @@ var init_proxy_types = __esm(() => {
|
|
|
8542
9179
|
});
|
|
8543
9180
|
|
|
8544
9181
|
// ../../packages/proxy/src/handlers/token-manager.ts
|
|
8545
|
-
function refreshBackoffUntil(
|
|
8546
|
-
const failure = refreshFailures.get(
|
|
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
|
+
}
|
|
8547
9188
|
return failure && now - failure.at < TOKEN_REFRESH_BACKOFF_MS ? failure.at + TOKEN_REFRESH_BACKOFF_MS : null;
|
|
8548
9189
|
}
|
|
8549
9190
|
function quarantineAccount(account2, ctx, reason) {
|
|
9191
|
+
const { access_token: accessToken, refresh_token: refreshToken } = account2;
|
|
8550
9192
|
account2.paused = true;
|
|
8551
9193
|
account2.error_reason = reason;
|
|
8552
|
-
ctx.asyncWriter.enqueue(() =>
|
|
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
|
+
});
|
|
8553
9199
|
}
|
|
8554
9200
|
function recordRefreshFailure(account2, ctx, error) {
|
|
8555
9201
|
const refreshError = new TokenRefreshError(account2.id, error);
|
|
8556
|
-
refreshFailures.set(account2.id, {
|
|
9202
|
+
refreshFailures.set(account2.id, {
|
|
9203
|
+
at: Date.now(),
|
|
9204
|
+
error: refreshError,
|
|
9205
|
+
accessToken: account2.access_token,
|
|
9206
|
+
refreshToken: account2.refresh_token
|
|
9207
|
+
});
|
|
8557
9208
|
const status = error?.status;
|
|
8558
9209
|
if (typeof status === "number" && status >= 400 && status < 500 && status !== 408 && status !== 429) {
|
|
8559
9210
|
quarantineAccount(account2, ctx, "OAuth refresh was rejected by the upstream");
|
|
@@ -8563,7 +9214,7 @@ function recordRefreshFailure(account2, ctx, error) {
|
|
|
8563
9214
|
}
|
|
8564
9215
|
async function refreshAccessTokenSafe(account2, ctx) {
|
|
8565
9216
|
const lastFailure = refreshFailures.get(account2.id);
|
|
8566
|
-
if (lastFailure && refreshBackoffUntil(account2
|
|
9217
|
+
if (lastFailure && refreshBackoffUntil(account2) !== null) {
|
|
8567
9218
|
log18.warn(`Account ${account2.name} is in refresh backoff period`);
|
|
8568
9219
|
throw lastFailure.error;
|
|
8569
9220
|
}
|
|
@@ -8571,8 +9222,20 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8571
9222
|
if (!ctx.provider.refreshToken) {
|
|
8572
9223
|
throw new TokenRefreshError(account2.id, new Error(`Provider ${ctx.provider.name} does not support OAuth token refresh`));
|
|
8573
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
|
+
};
|
|
8574
9230
|
const refreshPromise = ctx.provider.refreshToken(account2, ctx.runtime.clientId).then((result) => {
|
|
8575
|
-
|
|
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
|
+
});
|
|
8576
9239
|
account2.access_token = result.accessToken;
|
|
8577
9240
|
account2.expires_at = result.expiresAt;
|
|
8578
9241
|
if (result.refreshToken) {
|
|
@@ -8583,6 +9246,9 @@ async function refreshAccessTokenSafe(account2, ctx) {
|
|
|
8583
9246
|
log18.info(`Successfully refreshed token for account: ${account2.name}`);
|
|
8584
9247
|
return result.accessToken;
|
|
8585
9248
|
}).catch((error) => {
|
|
9249
|
+
const saved = reconnected();
|
|
9250
|
+
if (saved?.access_token)
|
|
9251
|
+
return saved.access_token;
|
|
8586
9252
|
throw recordRefreshFailure(account2, ctx, error);
|
|
8587
9253
|
}).finally(() => {
|
|
8588
9254
|
ctx.refreshInFlight.delete(account2.id);
|
|
@@ -8621,32 +9287,44 @@ function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, no
|
|
|
8621
9287
|
const threshold = Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage ?? Number.POSITIVE_INFINITY);
|
|
8622
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);
|
|
8623
9289
|
}
|
|
8624
|
-
function pooledMaxUsage(account2, ctx) {
|
|
9290
|
+
function pooledMaxUsage(provider, account2, bucket, ctx) {
|
|
8625
9291
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8626
|
-
|
|
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);
|
|
8627
9299
|
}
|
|
8628
9300
|
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx) {
|
|
8629
9301
|
const quota2 = account2.quota_state;
|
|
8630
9302
|
if (!quota2)
|
|
8631
9303
|
return true;
|
|
8632
9304
|
for (const [name, window2] of Object.entries(quota2.windows)) {
|
|
8633
|
-
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))) {
|
|
8634
9306
|
return false;
|
|
8635
9307
|
}
|
|
8636
9308
|
}
|
|
8637
9309
|
return true;
|
|
8638
9310
|
}
|
|
8639
9311
|
function fleetAccounts(provider, ctx) {
|
|
9312
|
+
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
|
|
9313
|
+
}
|
|
9314
|
+
function isFleetSeat(account2, ctx) {
|
|
8640
9315
|
const teamRouting = ctx.runtime.teamRouting;
|
|
8641
|
-
return
|
|
9316
|
+
return !account2.paused && (teamRouting?.enabled !== true || isAllowlisted(account2, teamRouting));
|
|
8642
9317
|
}
|
|
8643
9318
|
function cooldownEnd(account2, now) {
|
|
8644
9319
|
const rateLimitEnd = account2.rate_limited_until !== null && account2.rate_limited_until >= now ? account2.rate_limited_until + 1 : null;
|
|
8645
|
-
const refreshEnd = refreshBackoffUntil(account2
|
|
9320
|
+
const refreshEnd = refreshBackoffUntil(account2, now);
|
|
8646
9321
|
return rateLimitEnd === null ? refreshEnd : Math.max(rateLimitEnd, refreshEnd ?? 0);
|
|
8647
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
|
+
}
|
|
8648
9326
|
function blockingResets(provider, account2, model, ctx, now) {
|
|
8649
|
-
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);
|
|
8650
9328
|
}
|
|
8651
9329
|
function servableAt(provider, account2, model, ctx, now) {
|
|
8652
9330
|
const cooldown = cooldownEnd(account2, now);
|
|
@@ -8673,7 +9351,7 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
8673
9351
|
const config = ctx.runtime.teamRouting;
|
|
8674
9352
|
const now = Date.now();
|
|
8675
9353
|
const accounts = config?.enabled ? fleetAccounts(provider, ctx) : [];
|
|
8676
|
-
const eligibleAccounts = accounts.filter((account2) =>
|
|
9354
|
+
const eligibleAccounts = accounts.filter((account2) => isServableSeat(providerStrategy, account2, model, ctx, now)).length;
|
|
8677
9355
|
return {
|
|
8678
9356
|
version: 1,
|
|
8679
9357
|
provider,
|
|
@@ -8691,14 +9369,14 @@ function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet) {
|
|
|
8691
9369
|
function isEveryAccountQuotaBlocked(meta, ctx, now = Date.now()) {
|
|
8692
9370
|
return !fleetAccounts(ctx.providerName, ctx).some((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8693
9371
|
}
|
|
8694
|
-
function selectRevalidationProbe(accounts, ctx, now) {
|
|
9372
|
+
function selectRevalidationProbe(accounts, ctx, now, model) {
|
|
8695
9373
|
const probes = ctx.quotaProbeAt;
|
|
8696
9374
|
const lastProbeAt = probes?.get(ctx.providerName);
|
|
8697
9375
|
if (lastProbeAt !== undefined && now - lastProbeAt < QUOTA_PROBE_INTERVAL_MS) {
|
|
8698
9376
|
return [];
|
|
8699
9377
|
}
|
|
8700
9378
|
const [probe] = accounts.filter((account2) => {
|
|
8701
|
-
return
|
|
9379
|
+
return ctx.runtime.teamRouting?.enabled !== true || !isAllowlisted(account2, ctx.runtime.teamRouting) || isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, model, ctx);
|
|
8702
9380
|
}).sort((left, right) => soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
|
|
8703
9381
|
if (!probe)
|
|
8704
9382
|
return [];
|
|
@@ -8707,9 +9385,9 @@ function selectRevalidationProbe(accounts, ctx, now) {
|
|
|
8707
9385
|
}
|
|
8708
9386
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
8709
9387
|
const now = Date.now();
|
|
8710
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2
|
|
9388
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
|
|
8711
9389
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx));
|
|
8712
|
-
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);
|
|
8713
9391
|
const prioritized = [...candidates].sort((left, right) => {
|
|
8714
9392
|
const priority = (left.priority ?? 0) - (right.priority ?? 0);
|
|
8715
9393
|
return priority !== 0 ? priority : soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now);
|
|
@@ -9018,13 +9696,17 @@ class TeamAdmission {
|
|
|
9018
9696
|
const account2 = this.account(accountId, {
|
|
9019
9697
|
enabled: true,
|
|
9020
9698
|
distributionEnabled: true,
|
|
9699
|
+
preferExpiringQuota: false,
|
|
9021
9700
|
allowlistedAccountUuids: [],
|
|
9022
9701
|
maxUsage: 0.9,
|
|
9702
|
+
weeklyMaxUsage: 0.95,
|
|
9703
|
+
weeklyMaxUsageByEmail: {},
|
|
9023
9704
|
admissionCap: 1,
|
|
9024
9705
|
admissionQueueLimit: 0,
|
|
9025
9706
|
admissionWaitMs: 0,
|
|
9026
9707
|
holdSeconds: 0,
|
|
9027
|
-
quotaProbeSeconds: 0
|
|
9708
|
+
quotaProbeSeconds: 0,
|
|
9709
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
9028
9710
|
});
|
|
9029
9711
|
if (account2.active > 0 || account2.queue.length > 0)
|
|
9030
9712
|
return;
|
|
@@ -9117,6 +9799,7 @@ class TeamAdmission {
|
|
|
9117
9799
|
}
|
|
9118
9800
|
var RAMP_INTERVAL_MS = 250, RAMP_WINDOW_MS = 30000, TeamAdmissionError;
|
|
9119
9801
|
var init_team_admission = __esm(() => {
|
|
9802
|
+
init_src4();
|
|
9120
9803
|
TeamAdmissionError = class TeamAdmissionError extends Error {
|
|
9121
9804
|
constructor(message) {
|
|
9122
9805
|
super(message);
|
|
@@ -9170,7 +9853,8 @@ async function forwardToClient(options, ctx) {
|
|
|
9170
9853
|
isStream,
|
|
9171
9854
|
providerName: ctx.providerName,
|
|
9172
9855
|
retryAttempt,
|
|
9173
|
-
failoverAttempts
|
|
9856
|
+
failoverAttempts,
|
|
9857
|
+
storePayload: ctx.runtime.storeRequestPayloads
|
|
9174
9858
|
};
|
|
9175
9859
|
ctx.usageWorker.postMessage(startMessage);
|
|
9176
9860
|
requestEvents.emit("event", {
|
|
@@ -9473,8 +10157,8 @@ function retryAfterMs(response) {
|
|
|
9473
10157
|
if (Number.isFinite(seconds)) {
|
|
9474
10158
|
return Math.max(0, seconds) * 1000;
|
|
9475
10159
|
}
|
|
9476
|
-
const
|
|
9477
|
-
return Number.isNaN(
|
|
10160
|
+
const date2 = Date.parse(value);
|
|
10161
|
+
return Number.isNaN(date2) ? undefined : Math.max(0, date2 - Date.now());
|
|
9478
10162
|
}
|
|
9479
10163
|
async function isQuotaRejection(response, provider) {
|
|
9480
10164
|
return await provider.isQuotaRejection?.(response) ?? false;
|
|
@@ -9931,37 +10615,37 @@ function quotaExhaustionResponse(resetAt2) {
|
|
|
9931
10615
|
headers: { "retry-after": String(retryAfterSeconds) }
|
|
9932
10616
|
});
|
|
9933
10617
|
}
|
|
9934
|
-
async function attemptAccount(
|
|
9935
|
-
|
|
9936
|
-
const admission =
|
|
10618
|
+
async function attemptAccount(request3, account2, failoverAttempts) {
|
|
10619
|
+
request3.req.signal.throwIfAborted();
|
|
10620
|
+
const admission = request3.ctx.teamAdmission;
|
|
9937
10621
|
let permit;
|
|
9938
10622
|
try {
|
|
9939
|
-
permit =
|
|
10623
|
+
permit = request3.ctx.runtime.teamRouting.enabled ? await admission?.acquire(account2.id, request3.ctx.runtime.teamRouting, request3.req.signal) : undefined;
|
|
9940
10624
|
} catch (error) {
|
|
9941
10625
|
if (error instanceof TeamAdmissionError) {
|
|
9942
|
-
throw new ServiceUnavailableError(error.message,
|
|
10626
|
+
throw new ServiceUnavailableError(error.message, request3.ctx.providerName, admissionRetrySeconds(request3.req));
|
|
9943
10627
|
}
|
|
9944
10628
|
throw error;
|
|
9945
10629
|
}
|
|
9946
10630
|
if (permit)
|
|
9947
|
-
|
|
9948
|
-
|
|
10631
|
+
request3.ctx.teamRouter?.begin(account2.id);
|
|
10632
|
+
request3.ctx.outsideSpendTracker?.begin(account2.id);
|
|
9949
10633
|
const release = () => {
|
|
9950
10634
|
permit?.release();
|
|
9951
10635
|
if (permit)
|
|
9952
|
-
|
|
9953
|
-
|
|
10636
|
+
request3.ctx.teamRouter?.end(account2.id);
|
|
10637
|
+
request3.ctx.outsideSpendTracker?.end(account2.id);
|
|
9954
10638
|
};
|
|
9955
10639
|
try {
|
|
9956
|
-
const attempt = await proxyWithAccount(
|
|
10640
|
+
const attempt = await proxyWithAccount(request3.req, request3.url, account2, request3.meta, request3.body, (body) => createBodyStream(body), request3.thread, failoverAttempts, request3.mappedModel, request3.ctx);
|
|
9957
10641
|
if (attempt.kind === "response") {
|
|
9958
|
-
const spentExtraUsage =
|
|
10642
|
+
const spentExtraUsage = request3.ctx.provider.spendsExtraUsage?.(attempt.response) ?? false;
|
|
9959
10643
|
return {
|
|
9960
10644
|
...attempt,
|
|
9961
10645
|
response: releaseAfterResponse(attempt.response, () => {
|
|
9962
10646
|
release();
|
|
9963
10647
|
if (spentExtraUsage) {
|
|
9964
|
-
|
|
10648
|
+
request3.ctx.seatAlerts?.extraUsageSpent(account2, request3.ctx.providerName);
|
|
9965
10649
|
}
|
|
9966
10650
|
})
|
|
9967
10651
|
};
|
|
@@ -9973,14 +10657,14 @@ async function attemptAccount(request2, account2, failoverAttempts) {
|
|
|
9973
10657
|
throw error;
|
|
9974
10658
|
}
|
|
9975
10659
|
}
|
|
9976
|
-
async function resolvePerMinuteRateLimit(
|
|
10660
|
+
async function resolvePerMinuteRateLimit(request3, account2, failoverAttempts, attempt) {
|
|
9977
10661
|
if (attempt.retryAfterMs > MAX_INLINE_RATE_LIMIT_RETRY_MS) {
|
|
9978
10662
|
return await attempt.forward();
|
|
9979
10663
|
}
|
|
9980
10664
|
if (attempt.retryAfterMs > 0) {
|
|
9981
10665
|
await Bun.sleep(attempt.retryAfterMs);
|
|
9982
10666
|
}
|
|
9983
|
-
const retryAttempt = await attemptAccount(
|
|
10667
|
+
const retryAttempt = await attemptAccount(request3, account2, failoverAttempts);
|
|
9984
10668
|
if (retryAttempt.kind === "response") {
|
|
9985
10669
|
return retryAttempt.response;
|
|
9986
10670
|
}
|
|
@@ -9989,26 +10673,26 @@ async function resolvePerMinuteRateLimit(request2, account2, failoverAttempts, a
|
|
|
9989
10673
|
}
|
|
9990
10674
|
return await attempt.forward();
|
|
9991
10675
|
}
|
|
9992
|
-
async function resolveRequestScopedRateLimit(
|
|
10676
|
+
async function resolveRequestScopedRateLimit(request3, accounts, index, attempt) {
|
|
9993
10677
|
const sibling = accounts[index + 1];
|
|
9994
10678
|
if (!sibling) {
|
|
9995
10679
|
return await attempt.forward();
|
|
9996
10680
|
}
|
|
9997
|
-
|
|
9998
|
-
const siblingAttempt = await attemptAccount(
|
|
10681
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10682
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
9999
10683
|
if (siblingAttempt.kind === "response") {
|
|
10000
10684
|
return siblingAttempt.response;
|
|
10001
10685
|
}
|
|
10002
10686
|
if (siblingAttempt.kind === "per-minute-rate-limit") {
|
|
10003
|
-
return await resolvePerMinuteRateLimit(
|
|
10687
|
+
return await resolvePerMinuteRateLimit(request3, sibling, index + 1, siblingAttempt);
|
|
10004
10688
|
}
|
|
10005
10689
|
if (siblingAttempt.kind !== "request-scoped-rate-limit") {
|
|
10006
10690
|
return await attempt.forward();
|
|
10007
10691
|
}
|
|
10008
|
-
if (
|
|
10009
|
-
await Bun.sleep(
|
|
10692
|
+
if (request3.ctx.runtime.requestScopedRetryDelayMs > 0) {
|
|
10693
|
+
await Bun.sleep(request3.ctx.runtime.requestScopedRetryDelayMs);
|
|
10010
10694
|
}
|
|
10011
|
-
const retryAttempt = await attemptAccount(
|
|
10695
|
+
const retryAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10012
10696
|
if (retryAttempt.kind === "response") {
|
|
10013
10697
|
return retryAttempt.response;
|
|
10014
10698
|
}
|
|
@@ -10017,14 +10701,14 @@ async function resolveRequestScopedRateLimit(request2, accounts, index, attempt)
|
|
|
10017
10701
|
}
|
|
10018
10702
|
return await attempt.forward();
|
|
10019
10703
|
}
|
|
10020
|
-
async function resolveQuotaRateLimit(
|
|
10704
|
+
async function resolveQuotaRateLimit(request3, accounts, index, attempt) {
|
|
10021
10705
|
const sibling = accounts[index + 1];
|
|
10022
10706
|
if (!sibling)
|
|
10023
10707
|
return await attempt.forward();
|
|
10024
|
-
|
|
10025
|
-
const siblingAttempt = await attemptAccount(
|
|
10708
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10709
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10026
10710
|
if (siblingAttempt.kind === "response") {
|
|
10027
|
-
|
|
10711
|
+
request3.ctx.teamRouter?.rebind(request3.teamRequest, sibling.id, request3.ctx.runtime.teamRouting, request3.ctx.provider, request3.ctx.dbOps);
|
|
10028
10712
|
return siblingAttempt.response;
|
|
10029
10713
|
}
|
|
10030
10714
|
if (siblingAttempt.kind === "authentication-failure") {
|
|
@@ -10040,13 +10724,13 @@ async function resolveQuotaRateLimit(request2, accounts, index, attempt) {
|
|
|
10040
10724
|
return await attempt.forward();
|
|
10041
10725
|
}
|
|
10042
10726
|
}
|
|
10043
|
-
async function resolveUpstreamFailure(
|
|
10727
|
+
async function resolveUpstreamFailure(request3, accounts, index, attempt) {
|
|
10044
10728
|
const sibling = accounts[index + 1];
|
|
10045
10729
|
if (!sibling) {
|
|
10046
10730
|
return await attempt.forward();
|
|
10047
10731
|
}
|
|
10048
|
-
|
|
10049
|
-
const siblingAttempt = await attemptAccount(
|
|
10732
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10733
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10050
10734
|
if (siblingAttempt.kind === "response") {
|
|
10051
10735
|
await discardAttempt(attempt);
|
|
10052
10736
|
return siblingAttempt.response;
|
|
@@ -10073,12 +10757,12 @@ async function discardAttempt(attempt) {
|
|
|
10073
10757
|
log21.warn(`Could not close a discarded upstream stream: ${error instanceof Error ? error.message : String(error)}`);
|
|
10074
10758
|
}
|
|
10075
10759
|
}
|
|
10076
|
-
async function resolveTransportFailure(
|
|
10760
|
+
async function resolveTransportFailure(request3, accounts, index) {
|
|
10077
10761
|
const sibling = accounts[index + 1];
|
|
10078
10762
|
if (!sibling)
|
|
10079
10763
|
return new Response("Bad Gateway", { status: 502 });
|
|
10080
|
-
|
|
10081
|
-
const siblingAttempt = await attemptAccount(
|
|
10764
|
+
request3.ctx.teamAdmission?.armSwitch(sibling.id);
|
|
10765
|
+
const siblingAttempt = await attemptAccount(request3, sibling, index + 1);
|
|
10082
10766
|
if (siblingAttempt.kind === "response")
|
|
10083
10767
|
return siblingAttempt.response;
|
|
10084
10768
|
switch (siblingAttempt.kind) {
|
|
@@ -10090,31 +10774,31 @@ async function resolveTransportFailure(request2, accounts, index) {
|
|
|
10090
10774
|
return new Response("Bad Gateway", { status: 502 });
|
|
10091
10775
|
}
|
|
10092
10776
|
}
|
|
10093
|
-
async function proxySelectedAccounts(
|
|
10777
|
+
async function proxySelectedAccounts(request3, accounts) {
|
|
10094
10778
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10095
|
-
const attempt = await attemptAccount(
|
|
10779
|
+
const attempt = await attemptAccount(request3, accounts[index], index);
|
|
10096
10780
|
if (attempt.kind === "response")
|
|
10097
10781
|
return attempt.response;
|
|
10098
10782
|
if (attempt.kind === "authentication-failure") {
|
|
10099
10783
|
return new Response("Bad Gateway", { status: 502 });
|
|
10100
10784
|
}
|
|
10101
10785
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10102
|
-
return await resolvePerMinuteRateLimit(
|
|
10786
|
+
return await resolvePerMinuteRateLimit(request3, accounts[index], index, attempt);
|
|
10103
10787
|
}
|
|
10104
10788
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10105
|
-
return await resolveRequestScopedRateLimit(
|
|
10789
|
+
return await resolveRequestScopedRateLimit(request3, accounts, index, attempt);
|
|
10106
10790
|
}
|
|
10107
10791
|
if (attempt.kind === "quota-rate-limit") {
|
|
10108
|
-
return await resolveQuotaRateLimit(
|
|
10792
|
+
return await resolveQuotaRateLimit(request3, accounts, index, attempt);
|
|
10109
10793
|
}
|
|
10110
10794
|
if (attempt.kind === "upstream-failure") {
|
|
10111
|
-
return await resolveUpstreamFailure(
|
|
10795
|
+
return await resolveUpstreamFailure(request3, accounts, index, attempt);
|
|
10112
10796
|
}
|
|
10113
10797
|
if (attempt.kind === "transport-failure") {
|
|
10114
|
-
return await resolveTransportFailure(
|
|
10798
|
+
return await resolveTransportFailure(request3, accounts, index);
|
|
10115
10799
|
}
|
|
10116
10800
|
}
|
|
10117
|
-
throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`,
|
|
10801
|
+
throw new ServiceUnavailableError(`${ERROR_MESSAGES.ALL_ACCOUNTS_FAILED} (${accounts.length} attempted)`, request3.ctx.providerName);
|
|
10118
10802
|
}
|
|
10119
10803
|
var log21;
|
|
10120
10804
|
var init_proxy_attempts = __esm(() => {
|
|
@@ -10139,7 +10823,7 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10139
10823
|
provider: ctx.providerName,
|
|
10140
10824
|
sessionId
|
|
10141
10825
|
};
|
|
10142
|
-
const
|
|
10826
|
+
const request3 = {
|
|
10143
10827
|
body,
|
|
10144
10828
|
ctx,
|
|
10145
10829
|
mappedModel,
|
|
@@ -10150,20 +10834,20 @@ function prepareProxyRequest(req, url, ctx, meta, body, manualAccountName, teamR
|
|
|
10150
10834
|
url
|
|
10151
10835
|
};
|
|
10152
10836
|
return {
|
|
10153
|
-
accounts: selectRequestAccounts(
|
|
10154
|
-
request:
|
|
10837
|
+
accounts: selectRequestAccounts(request3, selectionOptions),
|
|
10838
|
+
request: request3
|
|
10155
10839
|
};
|
|
10156
10840
|
}
|
|
10157
|
-
function onThreadSeat(
|
|
10158
|
-
const threadAccountId = getThreadBoundAccountId(
|
|
10841
|
+
function onThreadSeat(request3, accounts) {
|
|
10842
|
+
const threadAccountId = getThreadBoundAccountId(request3.ctx.messageThreads, request3.thread);
|
|
10159
10843
|
return threadAccountId ? accounts.filter((account2) => account2.id === threadAccountId) : accounts;
|
|
10160
10844
|
}
|
|
10161
|
-
function selectRequestAccounts(
|
|
10162
|
-
return onThreadSeat(
|
|
10845
|
+
function selectRequestAccounts(request3, selectionOptions) {
|
|
10846
|
+
return onThreadSeat(request3, selectAccountsForRequest(request3.meta, request3.ctx, request3.teamRequest, selectionOptions));
|
|
10163
10847
|
}
|
|
10164
|
-
function getRequestRetryAt(
|
|
10165
|
-
const { ctx, teamRequest } =
|
|
10166
|
-
return getSoonestQuotaReset(
|
|
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));
|
|
10167
10851
|
}
|
|
10168
10852
|
var init_proxy_request = __esm(() => {
|
|
10169
10853
|
init_account_selector();
|
|
@@ -10208,10 +10892,10 @@ function preferPinnedProvider(pool, pinnedAccount) {
|
|
|
10208
10892
|
const pinned = pool.providers.find((candidate) => candidate.provider.name === pinnedAccount.provider);
|
|
10209
10893
|
return pinned ? [pinned, ...pool.providers.filter((candidate) => candidate !== pinned)] : pool.providers;
|
|
10210
10894
|
}
|
|
10211
|
-
async function proxyPoolCandidate(
|
|
10895
|
+
async function proxyPoolCandidate(request3, accounts, allowNextProvider) {
|
|
10212
10896
|
for (let index = 0;index < accounts.length; index += 1) {
|
|
10213
10897
|
const account2 = accounts[index];
|
|
10214
|
-
const attempt = await attemptAccount(
|
|
10898
|
+
const attempt = await attemptAccount(request3, account2, index);
|
|
10215
10899
|
if (attempt.kind === "response") {
|
|
10216
10900
|
return { account: account2, kind: "response", response: attempt.response };
|
|
10217
10901
|
}
|
|
@@ -10224,13 +10908,13 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10224
10908
|
if (attempt.kind === "per-minute-rate-limit") {
|
|
10225
10909
|
return {
|
|
10226
10910
|
kind: "response",
|
|
10227
|
-
response: await resolvePerMinuteRateLimit(
|
|
10911
|
+
response: await resolvePerMinuteRateLimit(request3, account2, index, attempt)
|
|
10228
10912
|
};
|
|
10229
10913
|
}
|
|
10230
10914
|
if (attempt.kind === "request-scoped-rate-limit") {
|
|
10231
10915
|
return {
|
|
10232
10916
|
kind: "response",
|
|
10233
|
-
response: await resolveRequestScopedRateLimit(
|
|
10917
|
+
response: await resolveRequestScopedRateLimit(request3, accounts, index, attempt)
|
|
10234
10918
|
};
|
|
10235
10919
|
}
|
|
10236
10920
|
if (attempt.kind === "quota-rate-limit") {
|
|
@@ -10243,7 +10927,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10243
10927
|
}
|
|
10244
10928
|
return {
|
|
10245
10929
|
kind: "response",
|
|
10246
|
-
response: await resolveQuotaRateLimit(
|
|
10930
|
+
response: await resolveQuotaRateLimit(request3, accounts, index, attempt)
|
|
10247
10931
|
};
|
|
10248
10932
|
}
|
|
10249
10933
|
if (attempt.kind === "upstream-failure") {
|
|
@@ -10256,7 +10940,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10256
10940
|
}
|
|
10257
10941
|
return {
|
|
10258
10942
|
kind: "response",
|
|
10259
|
-
response: await resolveUpstreamFailure(
|
|
10943
|
+
response: await resolveUpstreamFailure(request3, accounts, index, attempt)
|
|
10260
10944
|
};
|
|
10261
10945
|
}
|
|
10262
10946
|
if (attempt.kind === "transport-failure") {
|
|
@@ -10268,7 +10952,7 @@ async function proxyPoolCandidate(request2, accounts, allowNextProvider) {
|
|
|
10268
10952
|
}
|
|
10269
10953
|
return {
|
|
10270
10954
|
kind: "response",
|
|
10271
|
-
response: await resolveTransportFailure(
|
|
10955
|
+
response: await resolveTransportFailure(request3, accounts, index)
|
|
10272
10956
|
};
|
|
10273
10957
|
}
|
|
10274
10958
|
}
|
|
@@ -10291,10 +10975,10 @@ async function proxyProviderPool(req, url, ctx, meta, body, pool, manualAccountN
|
|
|
10291
10975
|
let everyCandidateFull = true;
|
|
10292
10976
|
let emittedIngress = false;
|
|
10293
10977
|
const earliest = (current, next) => next !== null && (current === null || next < current) ? next : current;
|
|
10294
|
-
const recordUnserved = (
|
|
10295
|
-
everyCandidateFull &&= isEveryAccountQuotaBlocked(
|
|
10296
|
-
soonestRetry = earliest(soonestRetry, getRequestRetryAt(
|
|
10297
|
-
soonestFleetReset = earliest(soonestFleetReset, getSoonestQuotaReset(
|
|
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));
|
|
10298
10982
|
};
|
|
10299
10983
|
const candidates = preferPinnedProvider(pool, pinnedAccount).slice(0, 2);
|
|
10300
10984
|
for (const [candidateIndex, candidate] of candidates.entries()) {
|
|
@@ -10456,9 +11140,9 @@ class SeatAlerts {
|
|
|
10456
11140
|
}
|
|
10457
11141
|
if (!delivery.repliesOk)
|
|
10458
11142
|
return;
|
|
10459
|
-
const
|
|
10460
|
-
if (
|
|
10461
|
-
const code = typeof
|
|
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";
|
|
10462
11146
|
log23.warn(`${delivery.channel} alert was refused (${code})`);
|
|
10463
11147
|
}
|
|
10464
11148
|
} catch (error) {
|
|
@@ -10924,17 +11608,17 @@ async function handleProxy(req, url, ctx) {
|
|
|
10924
11608
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
10925
11609
|
const body = buffer ?? null;
|
|
10926
11610
|
requestMeta.model = readRequestModel(body);
|
|
10927
|
-
const { accounts: initiallySelectedAccounts, request:
|
|
11611
|
+
const { accounts: initiallySelectedAccounts, request: request3 } = prepareProxyRequest(req, upstreamUrl, requestContext, requestMeta, body, manualPin?.accountName);
|
|
10928
11612
|
let accounts = initiallySelectedAccounts;
|
|
10929
11613
|
if (accounts.length === 0) {
|
|
10930
11614
|
const holdSeconds = requestContext.runtime.teamRouting.enabled && requestContext.quotaHold ? requestContext.runtime.teamRouting.holdSeconds : 0;
|
|
10931
11615
|
alertWhenFleetFull(requestMeta, requestContext, holdSeconds);
|
|
10932
|
-
const retryAt = getRequestRetryAt(
|
|
11616
|
+
const retryAt = getRequestRetryAt(request3);
|
|
10933
11617
|
if (retryAt !== null) {
|
|
10934
11618
|
const holdMs = holdSeconds * 1000;
|
|
10935
11619
|
if (holdMs > 0 && retryAt - Date.now() <= holdMs && requestContext.quotaHold) {
|
|
10936
11620
|
await requestContext.quotaHold.waitUntil(retryAt, req.signal);
|
|
10937
|
-
const resumedAccounts = selectRequestAccounts(
|
|
11621
|
+
const resumedAccounts = selectRequestAccounts(request3);
|
|
10938
11622
|
if (resumedAccounts.length > 0) {
|
|
10939
11623
|
accounts = resumedAccounts;
|
|
10940
11624
|
}
|
|
@@ -10956,7 +11640,7 @@ async function handleProxy(req, url, ctx) {
|
|
|
10956
11640
|
});
|
|
10957
11641
|
log24.info(`Selected ${accounts.length} accounts: ${accounts.map((a) => a.name).join(", ")}`);
|
|
10958
11642
|
log24.info(`Request: ${req.method} ${url.pathname}`);
|
|
10959
|
-
return await proxySelectedAccounts(
|
|
11643
|
+
return await proxySelectedAccounts(request3, accounts);
|
|
10960
11644
|
}
|
|
10961
11645
|
var log24, usageWorkerInstance = null;
|
|
10962
11646
|
var init_proxy = __esm(() => {
|
|
@@ -11019,6 +11703,12 @@ class QuotaHold {
|
|
|
11019
11703
|
}
|
|
11020
11704
|
|
|
11021
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
|
+
|
|
11022
11712
|
class QuotaProbe {
|
|
11023
11713
|
config;
|
|
11024
11714
|
store;
|
|
@@ -11085,9 +11775,7 @@ class QuotaProbe {
|
|
|
11085
11775
|
const quota2 = await provider.probeQuota(account2, accessToken);
|
|
11086
11776
|
if (!quota2)
|
|
11087
11777
|
return;
|
|
11088
|
-
|
|
11089
|
-
account2.quota_state = observed;
|
|
11090
|
-
this.store.updateAccountQuotaState(account2.id, observed);
|
|
11778
|
+
recordSeatQuota(this.store, this.outsideSpend, provider, account2, quota2);
|
|
11091
11779
|
} catch {}
|
|
11092
11780
|
}
|
|
11093
11781
|
}
|
|
@@ -11361,7 +12049,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
11361
12049
|
isStream: true,
|
|
11362
12050
|
providerName: session.providerName,
|
|
11363
12051
|
retryAttempt: 0,
|
|
11364
|
-
failoverAttempts: Math.max(0, session.nextAccountIndex - 1)
|
|
12052
|
+
failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
|
|
12053
|
+
storePayload: session.requestContext.runtime.storeRequestPayloads
|
|
11365
12054
|
};
|
|
11366
12055
|
session.activeTurn = {
|
|
11367
12056
|
requestId,
|
|
@@ -11718,6 +12407,106 @@ var init_websocket_proxy = __esm(() => {
|
|
|
11718
12407
|
};
|
|
11719
12408
|
});
|
|
11720
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
|
+
|
|
11721
12510
|
// ../../packages/proxy/src/index.ts
|
|
11722
12511
|
var init_src10 = __esm(() => {
|
|
11723
12512
|
init_background_tasks();
|
|
@@ -11732,6 +12521,7 @@ var init_src10 = __esm(() => {
|
|
|
11732
12521
|
init_team_admission();
|
|
11733
12522
|
init_team_router();
|
|
11734
12523
|
init_websocket_proxy();
|
|
12524
|
+
init_window_warmup2();
|
|
11735
12525
|
});
|
|
11736
12526
|
|
|
11737
12527
|
// ../../packages/runtime-server/src/device-keys.ts
|
|
@@ -11910,7 +12700,7 @@ function exposureFailure(req, url, server, config) {
|
|
|
11910
12700
|
if (!isSameOriginManagementRequest(req, url)) {
|
|
11911
12701
|
return jsonError(403, "Cross-origin management requests are not allowed");
|
|
11912
12702
|
}
|
|
11913
|
-
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)) {
|
|
11914
12704
|
if (role !== "admin") {
|
|
11915
12705
|
return jsonError(401, "An admin key is required for management writes");
|
|
11916
12706
|
}
|
|
@@ -11946,13 +12736,14 @@ function createRuntimeConfig(config, port) {
|
|
|
11946
12736
|
},
|
|
11947
12737
|
sessionDurationMs: config.get("session_duration_ms", TIME_CONSTANTS.SESSION_DURATION_DEFAULT),
|
|
11948
12738
|
port,
|
|
12739
|
+
storeRequestPayloads: config.storesRequestPayloads(),
|
|
11949
12740
|
teamRouting: config.getTeamRouting()
|
|
11950
12741
|
};
|
|
11951
12742
|
}
|
|
11952
|
-
function wireStrategyHotReload(config,
|
|
12743
|
+
function wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup) {
|
|
11953
12744
|
config.on("change", (change) => {
|
|
11954
12745
|
if (change.key === "lb_strategy") {
|
|
11955
|
-
|
|
12746
|
+
log27.info("Strategy configuration changed");
|
|
11956
12747
|
const newStrategyName = config.getStrategy();
|
|
11957
12748
|
if (newStrategyName === "session") {
|
|
11958
12749
|
const strategy3 = new SessionStrategy;
|
|
@@ -11960,13 +12751,38 @@ function wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig
|
|
|
11960
12751
|
proxyContext.strategy = strategy3;
|
|
11961
12752
|
}
|
|
11962
12753
|
}
|
|
12754
|
+
if (change.key === "data_retention_days") {
|
|
12755
|
+
runtimeConfig2.storeRequestPayloads = config.storesRequestPayloads();
|
|
12756
|
+
}
|
|
11963
12757
|
if (change.key === "team_routing") {
|
|
11964
12758
|
runtimeConfig2.teamRouting = config.getTeamRouting();
|
|
11965
12759
|
quotaProbe.reschedule();
|
|
11966
|
-
|
|
12760
|
+
windowWarmup.reschedule();
|
|
12761
|
+
log27.info("Team routing configuration changed");
|
|
11967
12762
|
}
|
|
11968
12763
|
});
|
|
11969
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
|
+
}
|
|
11970
12786
|
function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
11971
12787
|
container.registerInstance(SERVICE_KEYS.Config, new Config);
|
|
11972
12788
|
container.registerInstance(SERVICE_KEYS.Logger, serverLog);
|
|
@@ -11977,7 +12793,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11977
12793
|
sessionDurationMs: runtimeConfig2.sessionDurationMs
|
|
11978
12794
|
});
|
|
11979
12795
|
const dbOps = DatabaseFactory.getInstance();
|
|
11980
|
-
const
|
|
12796
|
+
const log27 = container.resolve(SERVICE_KEYS.Logger);
|
|
11981
12797
|
container.registerInstance(SERVICE_KEYS.Database, dbOps);
|
|
11982
12798
|
const asyncWriter = new AsyncDbWriter;
|
|
11983
12799
|
container.registerInstance(SERVICE_KEYS.AsyncWriter, asyncWriter);
|
|
@@ -11992,6 +12808,17 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
11992
12808
|
dbOps,
|
|
11993
12809
|
providerRegistry,
|
|
11994
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
|
+
},
|
|
11995
12822
|
getPoolStatus: (provider, model) => getPoolStatus(provider, model, {
|
|
11996
12823
|
dbOps,
|
|
11997
12824
|
runtime: runtimeConfig2,
|
|
@@ -12030,24 +12857,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12030
12857
|
asyncWriter,
|
|
12031
12858
|
usageWorker: getUsageWorker()
|
|
12032
12859
|
};
|
|
12033
|
-
const quotaProbe =
|
|
12034
|
-
|
|
12035
|
-
if (!provider)
|
|
12036
|
-
return null;
|
|
12037
|
-
return await getValidAccessToken(account2, {
|
|
12038
|
-
...proxyContext,
|
|
12039
|
-
provider,
|
|
12040
|
-
providerName: account2.provider,
|
|
12041
|
-
upstreamPath: "/"
|
|
12042
|
-
});
|
|
12043
|
-
});
|
|
12044
|
-
quotaProbe.start();
|
|
12045
|
-
registerDisposable(quotaProbe);
|
|
12046
|
-
wireStrategyHotReload(config, log26, dbOps, proxyContext, runtimeConfig2, quotaProbe);
|
|
12860
|
+
const { quotaProbe, windowWarmup } = startSeatSchedulers(config, proxyContext, outsideSpendTracker);
|
|
12861
|
+
wireStrategyHotReload(config, log27, dbOps, proxyContext, runtimeConfig2, quotaProbe, windowWarmup);
|
|
12047
12862
|
return {
|
|
12048
12863
|
config,
|
|
12049
12864
|
dbOps,
|
|
12050
|
-
log:
|
|
12865
|
+
log: log27,
|
|
12051
12866
|
asyncWriter,
|
|
12052
12867
|
apiRouter,
|
|
12053
12868
|
exposureConfig,
|
|
@@ -12056,12 +12871,12 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
12056
12871
|
runtimeConfig: runtimeConfig2
|
|
12057
12872
|
};
|
|
12058
12873
|
}
|
|
12059
|
-
function logInitialAccountStatus(
|
|
12874
|
+
function logInitialAccountStatus(log27, dbOps) {
|
|
12060
12875
|
const accounts = dbOps.getAllAccounts();
|
|
12061
12876
|
const activeAccounts = accounts.filter((account2) => !account2.paused && (!account2.expires_at || account2.expires_at > Date.now()));
|
|
12062
|
-
|
|
12877
|
+
log27.info(`Loaded ${accounts.length} accounts (${activeAccounts.length} active)`);
|
|
12063
12878
|
if (activeAccounts.length === 0) {
|
|
12064
|
-
|
|
12879
|
+
log27.warn("No active accounts available - requests will be refused with a 503 until an account is added");
|
|
12065
12880
|
}
|
|
12066
12881
|
}
|
|
12067
12882
|
var init_bootstrap_runtime = __esm(() => {
|
|
@@ -12302,6 +13117,44 @@ var init_fetch_handler = __esm(() => {
|
|
|
12302
13117
|
init_oauth_token();
|
|
12303
13118
|
});
|
|
12304
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
|
+
|
|
12305
13158
|
// ../../packages/runtime-server/src/startup-banner.ts
|
|
12306
13159
|
function createStartupBanner(options) {
|
|
12307
13160
|
const { version, port, withDashboard, strategy: strategy3, providers: providers2 } = options;
|
|
@@ -12332,29 +13185,6 @@ var init_startup_banner = __esm(() => {
|
|
|
12332
13185
|
init_src2();
|
|
12333
13186
|
});
|
|
12334
13187
|
|
|
12335
|
-
// ../../packages/runtime-server/src/startup-maintenance.ts
|
|
12336
|
-
function runStartupMaintenance(config, dbOps) {
|
|
12337
|
-
const log26 = new Logger("StartupMaintenance");
|
|
12338
|
-
try {
|
|
12339
|
-
const payloadDays = config.getDataRetentionDays();
|
|
12340
|
-
const requestDays = config.getRequestRetentionDays();
|
|
12341
|
-
const { removedRequests, removedPayloads } = dbOps.cleanupOldRequests(payloadDays * 24 * 60 * 60 * 1000, requestDays * 24 * 60 * 60 * 1000);
|
|
12342
|
-
log26.info(`Startup cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (payload=${payloadDays}d, requests=${requestDays}d)`);
|
|
12343
|
-
} catch (err) {
|
|
12344
|
-
log26.error(`Startup cleanup error: ${err}`);
|
|
12345
|
-
}
|
|
12346
|
-
try {
|
|
12347
|
-
dbOps.compact();
|
|
12348
|
-
log26.info("Database compacted at startup");
|
|
12349
|
-
} catch (err) {
|
|
12350
|
-
log26.error(`Database compaction error: ${err}`);
|
|
12351
|
-
}
|
|
12352
|
-
return () => {};
|
|
12353
|
-
}
|
|
12354
|
-
var init_startup_maintenance = __esm(() => {
|
|
12355
|
-
init_src3();
|
|
12356
|
-
});
|
|
12357
|
-
|
|
12358
13188
|
// ../../packages/runtime-server/src/index.ts
|
|
12359
13189
|
import { isAbsolute as isAbsolute4 } from "path";
|
|
12360
13190
|
var {serve } = globalThis.Bun;
|
|
@@ -12470,14 +13300,14 @@ function startServer(options) {
|
|
|
12470
13300
|
const {
|
|
12471
13301
|
config,
|
|
12472
13302
|
dbOps,
|
|
12473
|
-
log:
|
|
13303
|
+
log: log27,
|
|
12474
13304
|
apiRouter,
|
|
12475
13305
|
exposureConfig,
|
|
12476
13306
|
proxyContext,
|
|
12477
13307
|
providerRegistry,
|
|
12478
13308
|
runtimeConfig: runtimeConfig2
|
|
12479
13309
|
} = bootstrapRuntime(port, serverLog, drain.control);
|
|
12480
|
-
stopRetentionJob =
|
|
13310
|
+
stopRetentionJob = startRetentionMaintenance(config, dbOps);
|
|
12481
13311
|
const fetchHandler = createServerFetchHandler({
|
|
12482
13312
|
apiRouter,
|
|
12483
13313
|
exposureConfig,
|
|
@@ -12515,7 +13345,7 @@ function startServer(options) {
|
|
|
12515
13345
|
strategy: config.getStrategy(),
|
|
12516
13346
|
providers: providerRegistry.listProviders()
|
|
12517
13347
|
}));
|
|
12518
|
-
logInitialAccountStatus(
|
|
13348
|
+
logInitialAccountStatus(log27, dbOps);
|
|
12519
13349
|
return {
|
|
12520
13350
|
port: activePort,
|
|
12521
13351
|
stop: () => stopServerRuntime(),
|
|
@@ -12548,8 +13378,8 @@ var init_src11 = __esm(() => {
|
|
|
12548
13378
|
init_dashboard_assets();
|
|
12549
13379
|
init_deployment_drain();
|
|
12550
13380
|
init_fetch_handler();
|
|
13381
|
+
init_retention_maintenance();
|
|
12551
13382
|
init_startup_banner();
|
|
12552
|
-
init_startup_maintenance();
|
|
12553
13383
|
init_fetch_handler();
|
|
12554
13384
|
init_startup_banner();
|
|
12555
13385
|
serverLog = new Logger("Server");
|
|
@@ -13853,13 +14683,17 @@ function teamRoutingFileConfig(routing) {
|
|
|
13853
14683
|
return {
|
|
13854
14684
|
enabled: routing.enabled,
|
|
13855
14685
|
distribution_enabled: routing.distributionEnabled,
|
|
14686
|
+
prefer_expiring_quota: routing.preferExpiringQuota,
|
|
13856
14687
|
allowlisted_account_uuids: routing.allowlistedAccountUuids,
|
|
13857
14688
|
max_usage: routing.maxUsage,
|
|
14689
|
+
weekly_max_usage: routing.weeklyMaxUsage,
|
|
14690
|
+
weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
|
|
13858
14691
|
admission_cap: routing.admissionCap,
|
|
13859
14692
|
admission_queue_limit: routing.admissionQueueLimit,
|
|
13860
14693
|
admission_wait_ms: routing.admissionWaitMs,
|
|
13861
14694
|
hold_seconds: routing.holdSeconds,
|
|
13862
|
-
quota_probe_seconds: routing.quotaProbeSeconds
|
|
14695
|
+
quota_probe_seconds: routing.quotaProbeSeconds,
|
|
14696
|
+
window_warmup: windowWarmupFileConfig(routing.windowWarmup)
|
|
13863
14697
|
};
|
|
13864
14698
|
}
|
|
13865
14699
|
function quotaWindowLabel(key) {
|
|
@@ -13878,6 +14712,9 @@ function formatPoolLimits(quotaState) {
|
|
|
13878
14712
|
});
|
|
13879
14713
|
return windows.length > 0 ? windows.join(" \xB7 ") : "limits not observed yet";
|
|
13880
14714
|
}
|
|
14715
|
+
var init_local_pool = __esm(() => {
|
|
14716
|
+
init_src4();
|
|
14717
|
+
});
|
|
13881
14718
|
|
|
13882
14719
|
// src/core/accounts.ts
|
|
13883
14720
|
function getAddAccountProviderOptions() {
|
|
@@ -14053,6 +14890,7 @@ var init_accounts2 = __esm(() => {
|
|
|
14053
14890
|
init_src12();
|
|
14054
14891
|
init_cli();
|
|
14055
14892
|
init_cli();
|
|
14893
|
+
init_local_pool();
|
|
14056
14894
|
});
|
|
14057
14895
|
|
|
14058
14896
|
// src/core/analytics.ts
|
|
@@ -14698,6 +15536,7 @@ var init_core = __esm(() => {
|
|
|
14698
15536
|
init_accounts2();
|
|
14699
15537
|
init_analytics2();
|
|
14700
15538
|
init_args();
|
|
15539
|
+
init_local_pool();
|
|
14701
15540
|
init_local_routing();
|
|
14702
15541
|
init_logs2();
|
|
14703
15542
|
init_requests2();
|
|
@@ -14757,6 +15596,332 @@ var init_client_command = __esm(() => {
|
|
|
14757
15596
|
init_local_routing();
|
|
14758
15597
|
});
|
|
14759
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
|
+
|
|
14760
15925
|
// src/poc-notice.ts
|
|
14761
15926
|
var POC_BANNER = "PROOF OF CONCEPT \xB7 read the README before enabling sign-ins", POC_NOTICE = `\u26A0 PROOF OF CONCEPT, FOR IDEATION ONLY
|
|
14762
15927
|
agent-smith is an experiment, not a product: no warranty and no support.
|
|
@@ -14776,13 +15941,13 @@ __export(exports_theme, {
|
|
|
14776
15941
|
NAV_ITEMS: () => NAV_ITEMS,
|
|
14777
15942
|
C: () => C
|
|
14778
15943
|
});
|
|
14779
|
-
import { existsSync as
|
|
14780
|
-
import { homedir as
|
|
14781
|
-
import { join as
|
|
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";
|
|
14782
15947
|
function loadPersistedThemeId() {
|
|
14783
15948
|
try {
|
|
14784
|
-
if (
|
|
14785
|
-
const data = JSON.parse(
|
|
15949
|
+
if (existsSync6(CONFIG_FILE)) {
|
|
15950
|
+
const data = JSON.parse(readFileSync6(CONFIG_FILE, "utf-8"));
|
|
14786
15951
|
if (data?.themeId && getThemeById(data.themeId)) {
|
|
14787
15952
|
return data.themeId;
|
|
14788
15953
|
}
|
|
@@ -14792,10 +15957,10 @@ function loadPersistedThemeId() {
|
|
|
14792
15957
|
}
|
|
14793
15958
|
function persistThemeId(themeId) {
|
|
14794
15959
|
try {
|
|
14795
|
-
if (!
|
|
14796
|
-
|
|
15960
|
+
if (!existsSync6(CONFIG_DIR)) {
|
|
15961
|
+
mkdirSync6(CONFIG_DIR, { recursive: true });
|
|
14797
15962
|
}
|
|
14798
|
-
|
|
15963
|
+
writeFileSync4(CONFIG_FILE, JSON.stringify({ themeId }), "utf-8");
|
|
14799
15964
|
} catch {}
|
|
14800
15965
|
}
|
|
14801
15966
|
function setTuiTheme(themeId) {
|
|
@@ -14820,8 +15985,8 @@ function getAvailableThemes() {
|
|
|
14820
15985
|
var CONFIG_DIR, CONFIG_FILE, currentThemeId, currentColors, C, NAV_ITEMS, SCREEN_TITLES;
|
|
14821
15986
|
var init_theme = __esm(() => {
|
|
14822
15987
|
init_src12();
|
|
14823
|
-
CONFIG_DIR =
|
|
14824
|
-
CONFIG_FILE =
|
|
15988
|
+
CONFIG_DIR = join10(homedir4(), ".config", "agent-smith");
|
|
15989
|
+
CONFIG_FILE = join10(CONFIG_DIR, "theme.json");
|
|
14825
15990
|
currentThemeId = loadPersistedThemeId();
|
|
14826
15991
|
currentColors = themeToTuiColors(getThemeById(currentThemeId) ?? getDefaultTheme("dark"));
|
|
14827
15992
|
C = new Proxy({}, {
|
|
@@ -15635,22 +16800,22 @@ function createBar(value, maxValue, width, showPercentage = true) {
|
|
|
15635
16800
|
const percentage = maxValue > 0 ? value / maxValue : 0;
|
|
15636
16801
|
const filledWidth = Math.floor(percentage * width);
|
|
15637
16802
|
const remainingWidth = width - filledWidth;
|
|
15638
|
-
let
|
|
16803
|
+
let bar2 = "";
|
|
15639
16804
|
for (let i = 0;i < filledWidth; i++) {
|
|
15640
|
-
|
|
16805
|
+
bar2 += BAR_CHARS.full;
|
|
15641
16806
|
}
|
|
15642
16807
|
if (remainingWidth > 0) {
|
|
15643
16808
|
const remainingPercentage = percentage * width - filledWidth;
|
|
15644
|
-
|
|
16809
|
+
bar2 += getBarChar(remainingPercentage);
|
|
15645
16810
|
for (let i = 1;i < remainingWidth; i++) {
|
|
15646
|
-
|
|
16811
|
+
bar2 += BAR_CHARS.empty;
|
|
15647
16812
|
}
|
|
15648
16813
|
}
|
|
15649
16814
|
if (showPercentage) {
|
|
15650
16815
|
const percentStr = `${Math.round(percentage * 100)}%`;
|
|
15651
|
-
return `${
|
|
16816
|
+
return `${bar2} ${percentStr}`;
|
|
15652
16817
|
}
|
|
15653
|
-
return
|
|
16818
|
+
return bar2;
|
|
15654
16819
|
}
|
|
15655
16820
|
function createSparkline(data) {
|
|
15656
16821
|
if (data.length === 0)
|
|
@@ -15715,7 +16880,7 @@ function BarChart({
|
|
|
15715
16880
|
})
|
|
15716
16881
|
}),
|
|
15717
16882
|
data.map((item) => {
|
|
15718
|
-
const
|
|
16883
|
+
const bar2 = createBar(item.value, maxValue, width, false);
|
|
15719
16884
|
const color = item.color || C.chart1;
|
|
15720
16885
|
return /* @__PURE__ */ jsxs2("box", {
|
|
15721
16886
|
flexDirection: "row",
|
|
@@ -15726,7 +16891,7 @@ function BarChart({
|
|
|
15726
16891
|
}),
|
|
15727
16892
|
/* @__PURE__ */ jsx2("text", {
|
|
15728
16893
|
fg: color,
|
|
15729
|
-
children:
|
|
16894
|
+
children: bar2
|
|
15730
16895
|
}),
|
|
15731
16896
|
showValues && /* @__PURE__ */ jsxs2("text", {
|
|
15732
16897
|
fg: C.muted,
|
|
@@ -16557,13 +17722,13 @@ function reducer(state, action) {
|
|
|
16557
17722
|
function LogsScreen({ refreshKey }) {
|
|
16558
17723
|
const [state, dispatch] = useReducer(reducer, undefined, createLogFeedInitialState);
|
|
16559
17724
|
const logKeyCounts = new Map;
|
|
16560
|
-
const keyedLogs = state.logs.map((
|
|
16561
|
-
const baseKey = `${
|
|
17725
|
+
const keyedLogs = state.logs.map((log27) => {
|
|
17726
|
+
const baseKey = `${log27.ts}-${log27.level ?? ""}-${log27.msg}`;
|
|
16562
17727
|
const count = (logKeyCounts.get(baseKey) ?? 0) + 1;
|
|
16563
17728
|
logKeyCounts.set(baseKey, count);
|
|
16564
17729
|
return {
|
|
16565
17730
|
key: count === 1 ? baseKey : `${baseKey}-${count}`,
|
|
16566
|
-
log:
|
|
17731
|
+
log: log27
|
|
16567
17732
|
};
|
|
16568
17733
|
});
|
|
16569
17734
|
useKeyboard3((key) => {
|
|
@@ -16587,8 +17752,8 @@ function LogsScreen({ refreshKey }) {
|
|
|
16587
17752
|
}, [refreshKey]);
|
|
16588
17753
|
useEffect3(() => {
|
|
16589
17754
|
if (!state.paused && !state.loading) {
|
|
16590
|
-
const unsubscribe = streamLogs((
|
|
16591
|
-
dispatch({ type: "new_entry", log:
|
|
17755
|
+
const unsubscribe = streamLogs((log27) => {
|
|
17756
|
+
dispatch({ type: "new_entry", log: log27 });
|
|
16592
17757
|
});
|
|
16593
17758
|
return () => {
|
|
16594
17759
|
unsubscribe();
|
|
@@ -16641,15 +17806,15 @@ function LogsScreen({ refreshKey }) {
|
|
|
16641
17806
|
children: "No logs yet..."
|
|
16642
17807
|
}) : /* @__PURE__ */ jsx7("box", {
|
|
16643
17808
|
flexDirection: "column",
|
|
16644
|
-
children: keyedLogs.map(({ key, log:
|
|
16645
|
-
const sev = getLogSeverityMeta(
|
|
17809
|
+
children: keyedLogs.map(({ key, log: log27 }) => {
|
|
17810
|
+
const sev = getLogSeverityMeta(log27.level);
|
|
16646
17811
|
return /* @__PURE__ */ jsxs7("text", {
|
|
16647
17812
|
fg: sev.termColor,
|
|
16648
17813
|
children: [
|
|
16649
17814
|
"[",
|
|
16650
17815
|
sev.label,
|
|
16651
17816
|
"] ",
|
|
16652
|
-
|
|
17817
|
+
log27.msg
|
|
16653
17818
|
]
|
|
16654
17819
|
}, key);
|
|
16655
17820
|
})
|
|
@@ -17062,9 +18227,9 @@ function TokenBar({
|
|
|
17062
18227
|
total,
|
|
17063
18228
|
color
|
|
17064
18229
|
}) {
|
|
17065
|
-
const
|
|
18230
|
+
const pct2 = total > 0 ? value / total * 100 : 0;
|
|
17066
18231
|
const barWidth = 20;
|
|
17067
|
-
const filled = Math.round(
|
|
18232
|
+
const filled = Math.round(pct2 / 100 * barWidth);
|
|
17068
18233
|
return /* @__PURE__ */ jsxs8("box", {
|
|
17069
18234
|
flexDirection: "row",
|
|
17070
18235
|
gap: 1,
|
|
@@ -17087,7 +18252,7 @@ function TokenBar({
|
|
|
17087
18252
|
" ",
|
|
17088
18253
|
formatNumber(value),
|
|
17089
18254
|
" (",
|
|
17090
|
-
Math.round(
|
|
18255
|
+
Math.round(pct2),
|
|
17091
18256
|
"%)"
|
|
17092
18257
|
]
|
|
17093
18258
|
})
|
|
@@ -18225,6 +19390,10 @@ async function main() {
|
|
|
18225
19390
|
await runClientCommand(process.argv.slice(3));
|
|
18226
19391
|
return;
|
|
18227
19392
|
}
|
|
19393
|
+
if (process.argv[2] === "menubar") {
|
|
19394
|
+
await runMenubarCommand(process.argv.slice(3));
|
|
19395
|
+
return;
|
|
19396
|
+
}
|
|
18228
19397
|
container.registerInstance(SERVICE_KEYS.Config, new Config);
|
|
18229
19398
|
container.registerInstance(SERVICE_KEYS.Logger, new Logger("TUI"));
|
|
18230
19399
|
DatabaseFactory.initialize();
|
|
@@ -18242,6 +19411,7 @@ Usage: agent-smith [options]
|
|
|
18242
19411
|
agent-smith run [--port <number>] -- [claude arguments]
|
|
18243
19412
|
agent-smith install-client
|
|
18244
19413
|
agent-smith client on|off|status [--raw]
|
|
19414
|
+
agent-smith menubar install|uninstall|render
|
|
18245
19415
|
|
|
18246
19416
|
Options:
|
|
18247
19417
|
--serve Start API server with dashboard
|
|
@@ -18272,6 +19442,7 @@ Examples:
|
|
|
18272
19442
|
agent-smith --analyze # Run performance analysis
|
|
18273
19443
|
agent-smith --stats # View stats
|
|
18274
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)
|
|
18275
19446
|
`);
|
|
18276
19447
|
process.exit(0);
|
|
18277
19448
|
}
|
|
@@ -18324,13 +19495,13 @@ Examples:
|
|
|
18324
19495
|
const limit = typeof parsed.logs === "number" ? parsed.logs : 100;
|
|
18325
19496
|
if (typeof parsed.logs === "number") {
|
|
18326
19497
|
const history = await getLogHistory(limit);
|
|
18327
|
-
for (const
|
|
18328
|
-
console.log(`[${
|
|
19498
|
+
for (const log27 of history) {
|
|
19499
|
+
console.log(`[${log27.level}] ${log27.msg}`);
|
|
18329
19500
|
}
|
|
18330
19501
|
console.log("--- Live logs ---");
|
|
18331
19502
|
}
|
|
18332
|
-
await streamLogs((
|
|
18333
|
-
console.log(`[${
|
|
19503
|
+
await streamLogs((log27) => {
|
|
19504
|
+
console.log(`[${log27.level}] ${log27.msg}`);
|
|
18334
19505
|
});
|
|
18335
19506
|
return;
|
|
18336
19507
|
}
|
|
@@ -18433,6 +19604,7 @@ var init_main = __esm(() => {
|
|
|
18433
19604
|
init_core();
|
|
18434
19605
|
init_core();
|
|
18435
19606
|
init_client_command();
|
|
19607
|
+
init_menubar_command();
|
|
18436
19608
|
main().catch(async (error) => {
|
|
18437
19609
|
console.error("Error:", error.message);
|
|
18438
19610
|
try {
|