@certalis/agent-smith 0.2.0 → 0.3.2
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 +5 -3
- package/dist/bin.js +786 -191
- package/dist/client-launcher.js +463 -71
- package/dist/dashboard/chunk-wzenqdk1.js.map +1 -1
- package/dist/edge.js +15 -3
- package/dist/https.js +17 -4
- package/dist/pool.js +697 -184
- package/dist/post-processor.worker.js +378 -104
- package/dist/server.js +697 -184
- package/package.json +2 -1
package/dist/bin.js
CHANGED
|
@@ -1250,6 +1250,198 @@ var init_builtin_providers = __esm(() => {
|
|
|
1250
1250
|
];
|
|
1251
1251
|
});
|
|
1252
1252
|
|
|
1253
|
+
// ../../packages/config/src/zoned-time.ts
|
|
1254
|
+
function isTimeZone(value) {
|
|
1255
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 64) {
|
|
1256
|
+
return false;
|
|
1257
|
+
}
|
|
1258
|
+
try {
|
|
1259
|
+
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
1260
|
+
return true;
|
|
1261
|
+
} catch {
|
|
1262
|
+
return false;
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
function localTimeOfDayMs(time) {
|
|
1266
|
+
const [hour = 0, minute = 0] = time.split(":").map(Number);
|
|
1267
|
+
return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
|
|
1268
|
+
}
|
|
1269
|
+
function wallClockFormat(timeZone) {
|
|
1270
|
+
let format = wallClockFormats.get(timeZone);
|
|
1271
|
+
if (!format) {
|
|
1272
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
1273
|
+
timeZone,
|
|
1274
|
+
hourCycle: "h23",
|
|
1275
|
+
year: "numeric",
|
|
1276
|
+
month: "numeric",
|
|
1277
|
+
day: "numeric",
|
|
1278
|
+
hour: "numeric",
|
|
1279
|
+
minute: "numeric",
|
|
1280
|
+
second: "numeric"
|
|
1281
|
+
});
|
|
1282
|
+
wallClockFormats.set(timeZone, format);
|
|
1283
|
+
}
|
|
1284
|
+
return format;
|
|
1285
|
+
}
|
|
1286
|
+
function wallClock(at, timeZone) {
|
|
1287
|
+
const parts = wallClockFormat(timeZone).formatToParts(at);
|
|
1288
|
+
const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
|
|
1289
|
+
return {
|
|
1290
|
+
year: part("year"),
|
|
1291
|
+
month: part("month"),
|
|
1292
|
+
day: part("day"),
|
|
1293
|
+
hour: part("hour") % 24,
|
|
1294
|
+
minute: part("minute"),
|
|
1295
|
+
second: part("second")
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
function zoneOffsetMs(at, timeZone) {
|
|
1299
|
+
const wall = wallClock(at, timeZone);
|
|
1300
|
+
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
|
|
1301
|
+
}
|
|
1302
|
+
function zonedInstant(wall, timeZone) {
|
|
1303
|
+
return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
|
|
1304
|
+
}
|
|
1305
|
+
var LOCAL_TIME, wallClockFormats;
|
|
1306
|
+
var init_zoned_time = __esm(() => {
|
|
1307
|
+
init_src2();
|
|
1308
|
+
LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
1309
|
+
wallClockFormats = new Map;
|
|
1310
|
+
});
|
|
1311
|
+
|
|
1312
|
+
// ../../packages/config/src/night-pacing.ts
|
|
1313
|
+
function localHours(value) {
|
|
1314
|
+
if (!isRecord(value) || Object.keys(value).length !== 2 || typeof value.start !== "string" || typeof value.end !== "string" || !LOCAL_TIME.test(value.start) || !LOCAL_TIME.test(value.end) || value.start === value.end) {
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
return { start: value.start, end: value.end };
|
|
1318
|
+
}
|
|
1319
|
+
function isWorkingDays(value) {
|
|
1320
|
+
return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
|
|
1321
|
+
}
|
|
1322
|
+
function sanitizeNightPacing(value) {
|
|
1323
|
+
if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
const result = {};
|
|
1327
|
+
if (value.time_zone !== undefined) {
|
|
1328
|
+
if (!isTimeZone(value.time_zone))
|
|
1329
|
+
return;
|
|
1330
|
+
result.time_zone = value.time_zone;
|
|
1331
|
+
}
|
|
1332
|
+
if (value.working_days !== undefined) {
|
|
1333
|
+
if (!isWorkingDays(value.working_days))
|
|
1334
|
+
return;
|
|
1335
|
+
result.working_days = [...value.working_days];
|
|
1336
|
+
}
|
|
1337
|
+
if (value.working_hours !== undefined) {
|
|
1338
|
+
const hours = localHours(value.working_hours);
|
|
1339
|
+
if (!hours || hours.start > hours.end)
|
|
1340
|
+
return;
|
|
1341
|
+
result.working_hours = hours;
|
|
1342
|
+
}
|
|
1343
|
+
if (value.night_hours !== undefined) {
|
|
1344
|
+
const hours = localHours(value.night_hours);
|
|
1345
|
+
if (!hours)
|
|
1346
|
+
return;
|
|
1347
|
+
result.night_hours = hours;
|
|
1348
|
+
}
|
|
1349
|
+
if (value.margin_working_days !== undefined) {
|
|
1350
|
+
if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
result.margin_working_days = value.margin_working_days;
|
|
1354
|
+
}
|
|
1355
|
+
if (value.use_up_before !== undefined) {
|
|
1356
|
+
if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
result.use_up_before = value.use_up_before;
|
|
1360
|
+
}
|
|
1361
|
+
return result;
|
|
1362
|
+
}
|
|
1363
|
+
function nightPacingSettings(file) {
|
|
1364
|
+
return {
|
|
1365
|
+
timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
|
|
1366
|
+
workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
|
|
1367
|
+
workingHours: {
|
|
1368
|
+
...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
|
|
1369
|
+
},
|
|
1370
|
+
nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
|
|
1371
|
+
marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
|
|
1372
|
+
useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
function localDay(at, timeZone) {
|
|
1376
|
+
const wall = wallClock(at, timeZone);
|
|
1377
|
+
return {
|
|
1378
|
+
day: Date.UTC(wall.year, wall.month - 1, wall.day),
|
|
1379
|
+
timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
|
|
1380
|
+
};
|
|
1381
|
+
}
|
|
1382
|
+
function nightEndAt(pacing, now) {
|
|
1383
|
+
const { day, timeOfDay } = localDay(now, pacing.timeZone);
|
|
1384
|
+
const start = localTimeOfDayMs(pacing.nightHours.start);
|
|
1385
|
+
const end = localTimeOfDayMs(pacing.nightHours.end);
|
|
1386
|
+
const wraps = start > end;
|
|
1387
|
+
const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
|
|
1388
|
+
if (!night)
|
|
1389
|
+
return null;
|
|
1390
|
+
const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
|
|
1391
|
+
return zonedInstant(endDay + end, pacing.timeZone);
|
|
1392
|
+
}
|
|
1393
|
+
function workingMsBetween(pacing, from, to) {
|
|
1394
|
+
const start = localTimeOfDayMs(pacing.workingHours.start);
|
|
1395
|
+
const end = localTimeOfDayMs(pacing.workingHours.end);
|
|
1396
|
+
let total = 0;
|
|
1397
|
+
for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
|
|
1398
|
+
if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
|
|
1399
|
+
continue;
|
|
1400
|
+
const opens = zonedInstant(day + start, pacing.timeZone);
|
|
1401
|
+
const closes = zonedInstant(day + end, pacing.timeZone);
|
|
1402
|
+
total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
|
|
1403
|
+
}
|
|
1404
|
+
return total;
|
|
1405
|
+
}
|
|
1406
|
+
function expiresBeforeUseUpTime(pacing, resetAt, now) {
|
|
1407
|
+
const endAt = nightEndAt(pacing, now);
|
|
1408
|
+
if (endAt === null || resetAt <= now)
|
|
1409
|
+
return false;
|
|
1410
|
+
return resetAt <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
|
|
1411
|
+
}
|
|
1412
|
+
function nightWeeklyTarget(pacing, resetAt, now) {
|
|
1413
|
+
if (expiresBeforeUseUpTime(pacing, resetAt, now))
|
|
1414
|
+
return 1;
|
|
1415
|
+
const windowStart = resetAt - WEEKLY_WINDOW_MS;
|
|
1416
|
+
const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
|
|
1417
|
+
const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt));
|
|
1418
|
+
return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt);
|
|
1419
|
+
}
|
|
1420
|
+
var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
|
|
1421
|
+
var init_night_pacing = __esm(() => {
|
|
1422
|
+
init_src2();
|
|
1423
|
+
init_src();
|
|
1424
|
+
init_zoned_time();
|
|
1425
|
+
WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
1426
|
+
WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
|
|
1427
|
+
NIGHT_PACING_DEFAULTS = {
|
|
1428
|
+
timeZone: "Europe/Paris",
|
|
1429
|
+
workingDays: ["mon", "tue", "wed", "thu", "fri"],
|
|
1430
|
+
workingHours: { start: "07:00", end: "21:00" },
|
|
1431
|
+
nightHours: { start: "21:00", end: "07:00" },
|
|
1432
|
+
marginWorkingDays: 1,
|
|
1433
|
+
useUpBefore: "10:00"
|
|
1434
|
+
};
|
|
1435
|
+
NIGHT_PACING_FIELDS = new Set([
|
|
1436
|
+
"time_zone",
|
|
1437
|
+
"working_days",
|
|
1438
|
+
"working_hours",
|
|
1439
|
+
"night_hours",
|
|
1440
|
+
"margin_working_days",
|
|
1441
|
+
"use_up_before"
|
|
1442
|
+
]);
|
|
1443
|
+
});
|
|
1444
|
+
|
|
1253
1445
|
// ../../packages/config/src/paths-common.ts
|
|
1254
1446
|
import { homedir } from "os";
|
|
1255
1447
|
import { join as join4 } from "path";
|
|
@@ -1520,17 +1712,6 @@ var init_rewrite_file = __esm(() => {
|
|
|
1520
1712
|
function isLocalTimes(value) {
|
|
1521
1713
|
return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
|
|
1522
1714
|
}
|
|
1523
|
-
function isTimeZone(value) {
|
|
1524
|
-
if (typeof value !== "string" || value.length === 0 || value.length > 64) {
|
|
1525
|
-
return false;
|
|
1526
|
-
}
|
|
1527
|
-
try {
|
|
1528
|
-
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
1529
|
-
return true;
|
|
1530
|
-
} catch {
|
|
1531
|
-
return false;
|
|
1532
|
-
}
|
|
1533
|
-
}
|
|
1534
1715
|
function sanitizeWindowWarmup(value) {
|
|
1535
1716
|
if (!isRecord(value))
|
|
1536
1717
|
return;
|
|
@@ -1567,42 +1748,6 @@ function windowWarmupFileConfig(config) {
|
|
|
1567
1748
|
...config.model && { model: config.model }
|
|
1568
1749
|
};
|
|
1569
1750
|
}
|
|
1570
|
-
function wallClockFormat(timeZone) {
|
|
1571
|
-
let format = wallClockFormats.get(timeZone);
|
|
1572
|
-
if (!format) {
|
|
1573
|
-
format = new Intl.DateTimeFormat("en-US", {
|
|
1574
|
-
timeZone,
|
|
1575
|
-
hourCycle: "h23",
|
|
1576
|
-
year: "numeric",
|
|
1577
|
-
month: "numeric",
|
|
1578
|
-
day: "numeric",
|
|
1579
|
-
hour: "numeric",
|
|
1580
|
-
minute: "numeric",
|
|
1581
|
-
second: "numeric"
|
|
1582
|
-
});
|
|
1583
|
-
wallClockFormats.set(timeZone, format);
|
|
1584
|
-
}
|
|
1585
|
-
return format;
|
|
1586
|
-
}
|
|
1587
|
-
function wallClock(at, timeZone) {
|
|
1588
|
-
const parts = wallClockFormat(timeZone).formatToParts(at);
|
|
1589
|
-
const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
|
|
1590
|
-
return {
|
|
1591
|
-
year: part("year"),
|
|
1592
|
-
month: part("month"),
|
|
1593
|
-
day: part("day"),
|
|
1594
|
-
hour: part("hour") % 24,
|
|
1595
|
-
minute: part("minute"),
|
|
1596
|
-
second: part("second")
|
|
1597
|
-
};
|
|
1598
|
-
}
|
|
1599
|
-
function zoneOffsetMs(at, timeZone) {
|
|
1600
|
-
const wall = wallClock(at, timeZone);
|
|
1601
|
-
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
|
|
1602
|
-
}
|
|
1603
|
-
function zonedInstant(wall, timeZone) {
|
|
1604
|
-
return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
|
|
1605
|
-
}
|
|
1606
1751
|
function nextWindowWarmupAt(routing, after) {
|
|
1607
1752
|
const warmup = routing.windowWarmup;
|
|
1608
1753
|
if (!routing.enabled || !warmup.enabled)
|
|
@@ -1614,19 +1759,16 @@ function nextWindowWarmupAt(routing, after) {
|
|
|
1614
1759
|
if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
|
|
1615
1760
|
continue;
|
|
1616
1761
|
}
|
|
1617
|
-
const instants = warmup.times.map((time) =>
|
|
1618
|
-
const [hour = 0, minute = 0] = time.split(":").map(Number);
|
|
1619
|
-
return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
|
|
1620
|
-
}).filter((at) => at > after);
|
|
1762
|
+
const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
|
|
1621
1763
|
if (instants.length > 0)
|
|
1622
1764
|
return Math.min(...instants);
|
|
1623
1765
|
}
|
|
1624
1766
|
return null;
|
|
1625
1767
|
}
|
|
1626
|
-
var WINDOW_WARMUP_DEFAULTS,
|
|
1768
|
+
var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
|
|
1627
1769
|
var init_window_warmup = __esm(() => {
|
|
1628
|
-
init_src2();
|
|
1629
1770
|
init_src();
|
|
1771
|
+
init_zoned_time();
|
|
1630
1772
|
WINDOW_WARMUP_DEFAULTS = {
|
|
1631
1773
|
enabled: false,
|
|
1632
1774
|
times: ["06:00"],
|
|
@@ -1634,9 +1776,7 @@ var init_window_warmup = __esm(() => {
|
|
|
1634
1776
|
weekdaysOnly: true,
|
|
1635
1777
|
model: null
|
|
1636
1778
|
};
|
|
1637
|
-
LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
1638
1779
|
MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
|
|
1639
|
-
wallClockFormats = new Map;
|
|
1640
1780
|
});
|
|
1641
1781
|
|
|
1642
1782
|
// ../../packages/config/src/index.ts
|
|
@@ -1652,6 +1792,13 @@ import {
|
|
|
1652
1792
|
writeFileSync as writeFileSync2
|
|
1653
1793
|
} from "fs";
|
|
1654
1794
|
import { dirname as dirname2 } from "path";
|
|
1795
|
+
function callerWeeklyCap(caps, callerId) {
|
|
1796
|
+
if (!Object.hasOwn(caps, callerId))
|
|
1797
|
+
return;
|
|
1798
|
+
const cap = caps[callerId];
|
|
1799
|
+
const shared = typeof cap === "string" && Object.hasOwn(caps, cap) ? caps[cap] : cap;
|
|
1800
|
+
return typeof shared === "number" ? shared : undefined;
|
|
1801
|
+
}
|
|
1655
1802
|
function runtimeForProvider(runtime, provider) {
|
|
1656
1803
|
return {
|
|
1657
1804
|
...runtime,
|
|
@@ -1902,6 +2049,29 @@ function wireForStrategy(strategy3) {
|
|
|
1902
2049
|
function isNonNegativeFiniteNumber(value) {
|
|
1903
2050
|
return isFiniteNumber(value) && value >= 0;
|
|
1904
2051
|
}
|
|
2052
|
+
function sanitizeCapsByEmail(value, maximum) {
|
|
2053
|
+
if (!isRecord(value))
|
|
2054
|
+
return;
|
|
2055
|
+
const entries = Object.entries(value);
|
|
2056
|
+
const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
|
|
2057
|
+
const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
2058
|
+
if (!isValid)
|
|
2059
|
+
return;
|
|
2060
|
+
return Object.fromEntries(normalized);
|
|
2061
|
+
}
|
|
2062
|
+
function isDeviceList(value) {
|
|
2063
|
+
return Array.isArray(value) && value.length > 0 && value.length <= MAX_CALLERS && value.every((device) => typeof device === "string" && CALLER_ID_PATTERN.test(device)) && new Set(value).size === value.length;
|
|
2064
|
+
}
|
|
2065
|
+
function sanitizeOwnerDevicesByEmail(value) {
|
|
2066
|
+
if (!isRecord(value))
|
|
2067
|
+
return;
|
|
2068
|
+
const entries = Object.entries(value);
|
|
2069
|
+
const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
|
|
2070
|
+
const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
2071
|
+
if (!isValid)
|
|
2072
|
+
return;
|
|
2073
|
+
return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
|
|
2074
|
+
}
|
|
1905
2075
|
function sanitizeTeamRouting(value) {
|
|
1906
2076
|
if (!isRecord(value))
|
|
1907
2077
|
return;
|
|
@@ -1923,19 +2093,22 @@ function sanitizeTeamRouting(value) {
|
|
|
1923
2093
|
if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
|
|
1924
2094
|
result.weekly_max_usage = value.weekly_max_usage;
|
|
1925
2095
|
}
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
}
|
|
2096
|
+
const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
|
|
2097
|
+
if (maxUsageByEmail)
|
|
2098
|
+
result.max_usage_by_email = maxUsageByEmail;
|
|
2099
|
+
const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
|
|
2100
|
+
if (weeklyMaxUsageByEmail)
|
|
2101
|
+
result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
|
|
1933
2102
|
if (isRecord(value.caller_weekly_max_usage)) {
|
|
1934
|
-
const
|
|
1935
|
-
|
|
2103
|
+
const caps = value.caller_weekly_max_usage;
|
|
2104
|
+
const entries = Object.entries(caps);
|
|
2105
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && (isCallerWeeklyCap(cap) || sharesACallerCap(caps, cap)))) {
|
|
1936
2106
|
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
1937
2107
|
}
|
|
1938
2108
|
}
|
|
2109
|
+
const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
|
|
2110
|
+
if (ownerDevicesByEmail)
|
|
2111
|
+
result.owner_devices_by_email = ownerDevicesByEmail;
|
|
1939
2112
|
if (isRecord(value.caller_provider_fallback)) {
|
|
1940
2113
|
const entries = Object.entries(value.caller_provider_fallback);
|
|
1941
2114
|
if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
|
|
@@ -1986,9 +2159,11 @@ function sanitizeProviderPool(value) {
|
|
|
1986
2159
|
"distribution_enabled",
|
|
1987
2160
|
"prefer_expiring_quota",
|
|
1988
2161
|
"max_usage",
|
|
2162
|
+
"max_usage_by_email",
|
|
1989
2163
|
"weekly_max_usage",
|
|
1990
2164
|
"weekly_max_usage_by_email",
|
|
1991
2165
|
"caller_weekly_max_usage",
|
|
2166
|
+
"owner_devices_by_email",
|
|
1992
2167
|
"quota_probe_seconds",
|
|
1993
2168
|
"window_warmup"
|
|
1994
2169
|
]) {
|
|
@@ -2010,8 +2185,17 @@ function sanitizeProviderPool(value) {
|
|
|
2010
2185
|
}
|
|
2011
2186
|
if (typeof value.block_when_all_full === "boolean")
|
|
2012
2187
|
pool.block_when_all_full = value.block_when_all_full;
|
|
2188
|
+
const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
|
|
2189
|
+
if (nightPacing)
|
|
2190
|
+
pool.caller_night_pacing = nightPacing;
|
|
2013
2191
|
return pool;
|
|
2014
2192
|
}
|
|
2193
|
+
function sanitizeCallerNightPacing(value) {
|
|
2194
|
+
if (!isRecord(value))
|
|
2195
|
+
return;
|
|
2196
|
+
const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
|
|
2197
|
+
return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
|
|
2198
|
+
}
|
|
2015
2199
|
function sanitizeRouting(value) {
|
|
2016
2200
|
if (!isRecord(value))
|
|
2017
2201
|
return;
|
|
@@ -2075,15 +2259,17 @@ function clientRouting(client) {
|
|
|
2075
2259
|
...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
|
|
2076
2260
|
};
|
|
2077
2261
|
}
|
|
2078
|
-
var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
2262
|
+
var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, POOL_SSH_HOST_PATTERN, CALLER_ID_PATTERN, MAX_CALLERS = 128, isCallerWeeklyCap = (cap) => isFiniteNumber(cap) && cap > 0 && cap <= 0.95, sharesACallerCap = (caps, cap) => typeof cap === "string" && Object.hasOwn(caps, cap) && isCallerWeeklyCap(caps[cap]), POOL_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
|
|
2079
2263
|
var init_src4 = __esm(() => {
|
|
2080
2264
|
init_src2();
|
|
2081
2265
|
init_src3();
|
|
2082
2266
|
init_src();
|
|
2083
2267
|
init_builtin_providers();
|
|
2268
|
+
init_night_pacing();
|
|
2084
2269
|
init_paths();
|
|
2085
2270
|
init_rewrite_file();
|
|
2086
2271
|
init_window_warmup();
|
|
2272
|
+
init_night_pacing();
|
|
2087
2273
|
init_paths();
|
|
2088
2274
|
init_paths_common();
|
|
2089
2275
|
init_rewrite_config();
|
|
@@ -2109,9 +2295,12 @@ var init_src4 = __esm(() => {
|
|
|
2109
2295
|
preferExpiringQuota: false,
|
|
2110
2296
|
allowlistedAccountUuids: [],
|
|
2111
2297
|
maxUsage: 0.9,
|
|
2298
|
+
maxUsageByEmail: {},
|
|
2112
2299
|
weeklyMaxUsage: 0.95,
|
|
2113
2300
|
weeklyMaxUsageByEmail: {},
|
|
2114
2301
|
callerWeeklyMaxUsage: {},
|
|
2302
|
+
callerNightPacing: {},
|
|
2303
|
+
ownerDevicesByEmail: {},
|
|
2115
2304
|
admissionCap: 5,
|
|
2116
2305
|
admissionQueueLimit: 25,
|
|
2117
2306
|
admissionWaitMs: 30000,
|
|
@@ -2285,9 +2474,12 @@ var init_src4 = __esm(() => {
|
|
|
2285
2474
|
preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
|
|
2286
2475
|
allowlistedAccountUuids: [...pool?.members ?? []],
|
|
2287
2476
|
maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
|
|
2477
|
+
maxUsageByEmail: { ...pool?.max_usage_by_email },
|
|
2288
2478
|
weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
|
|
2289
2479
|
weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
|
|
2290
2480
|
callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
|
|
2481
|
+
callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
|
|
2482
|
+
ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
|
|
2291
2483
|
admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
|
|
2292
2484
|
admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
|
|
2293
2485
|
admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
|
|
@@ -2364,9 +2556,12 @@ var init_src4 = __esm(() => {
|
|
|
2364
2556
|
"distribution_enabled",
|
|
2365
2557
|
"prefer_expiring_quota",
|
|
2366
2558
|
"max_usage",
|
|
2559
|
+
"max_usage_by_email",
|
|
2367
2560
|
"weekly_max_usage",
|
|
2368
2561
|
"weekly_max_usage_by_email",
|
|
2369
2562
|
"caller_weekly_max_usage",
|
|
2563
|
+
"caller_night_pacing",
|
|
2564
|
+
"owner_devices_by_email",
|
|
2370
2565
|
"admission",
|
|
2371
2566
|
"quota_probe_seconds",
|
|
2372
2567
|
"window_warmup",
|
|
@@ -2641,10 +2836,11 @@ function addPerformanceIndexes(db) {
|
|
|
2641
2836
|
`);
|
|
2642
2837
|
log3.info("Added index: idx_accounts_paused");
|
|
2643
2838
|
db.run(`
|
|
2644
|
-
CREATE INDEX IF NOT EXISTS
|
|
2645
|
-
ON requests(account_used, timestamp DESC)
|
|
2839
|
+
CREATE INDEX IF NOT EXISTS idx_requests_account_timestamp_cost
|
|
2840
|
+
ON requests(account_used, timestamp DESC, cost_usd)
|
|
2646
2841
|
`);
|
|
2647
|
-
|
|
2842
|
+
db.run("DROP INDEX IF EXISTS idx_requests_account_timestamp");
|
|
2843
|
+
log3.info("Added index: idx_requests_account_timestamp_cost");
|
|
2648
2844
|
db.run(`
|
|
2649
2845
|
CREATE INDEX IF NOT EXISTS idx_requests_cost_model
|
|
2650
2846
|
ON requests(cost_usd, model, timestamp DESC)
|
|
@@ -3010,7 +3206,8 @@ function ensureRequestLinkageColumns(db) {
|
|
|
3010
3206
|
["ttft_ms", "INTEGER"],
|
|
3011
3207
|
["proxy_overhead_ms", "INTEGER"],
|
|
3012
3208
|
["upstream_ttfb_ms", "INTEGER"],
|
|
3013
|
-
["streaming_duration_ms", "INTEGER"]
|
|
3209
|
+
["streaming_duration_ms", "INTEGER"],
|
|
3210
|
+
["caller", "TEXT"]
|
|
3014
3211
|
];
|
|
3015
3212
|
for (const [columnName, columnType] of requestColumns) {
|
|
3016
3213
|
if (!hasColumn(columns, columnName)) {
|
|
@@ -3034,6 +3231,13 @@ function ensureAccountExtensionColumns(db) {
|
|
|
3034
3231
|
}
|
|
3035
3232
|
}
|
|
3036
3233
|
}
|
|
3234
|
+
function backfillRequestLinkageColumnsOnce(db) {
|
|
3235
|
+
const { user_version } = db.query("PRAGMA user_version").get();
|
|
3236
|
+
if (user_version >= LINKAGE_BACKFILLED_VERSION)
|
|
3237
|
+
return;
|
|
3238
|
+
backfillRequestLinkageColumns(db);
|
|
3239
|
+
db.run(`PRAGMA user_version = ${LINKAGE_BACKFILLED_VERSION}`);
|
|
3240
|
+
}
|
|
3037
3241
|
function backfillRequestLinkageColumns(db) {
|
|
3038
3242
|
const missingCount = db.query(`
|
|
3039
3243
|
SELECT COUNT(*) AS count
|
|
@@ -3428,7 +3632,8 @@ function ensureSchema(db) {
|
|
|
3428
3632
|
ttft_ms INTEGER,
|
|
3429
3633
|
proxy_overhead_ms INTEGER,
|
|
3430
3634
|
upstream_ttfb_ms INTEGER,
|
|
3431
|
-
streaming_duration_ms INTEGER
|
|
3635
|
+
streaming_duration_ms INTEGER,
|
|
3636
|
+
caller TEXT
|
|
3432
3637
|
)
|
|
3433
3638
|
`);
|
|
3434
3639
|
db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
|
|
@@ -3456,7 +3661,7 @@ function runMigrations(db) {
|
|
|
3456
3661
|
migrateRequestsTable(db, requestsInfo);
|
|
3457
3662
|
}
|
|
3458
3663
|
ensureRequestLinkageColumns(db);
|
|
3459
|
-
|
|
3664
|
+
backfillRequestLinkageColumnsOnce(db);
|
|
3460
3665
|
db.run("DROP TABLE IF EXISTS agent_preferences");
|
|
3461
3666
|
db.run("DROP TABLE IF EXISTS oauth_sessions");
|
|
3462
3667
|
db.run("DROP INDEX IF EXISTS idx_oauth_sessions_expires");
|
|
@@ -3472,7 +3677,7 @@ function runMigrations(db) {
|
|
|
3472
3677
|
db.run(`CREATE INDEX IF NOT EXISTS idx_requests_timestamp ON requests(timestamp DESC)`);
|
|
3473
3678
|
addPerformanceIndexes(db);
|
|
3474
3679
|
}
|
|
3475
|
-
var log5;
|
|
3680
|
+
var log5, LINKAGE_BACKFILLED_VERSION = 1;
|
|
3476
3681
|
var init_migrations = __esm(() => {
|
|
3477
3682
|
init_src3();
|
|
3478
3683
|
init_src();
|
|
@@ -3882,6 +4087,30 @@ var init_analytics_repository = __esm(() => {
|
|
|
3882
4087
|
totalTokens: row.total_tokens ?? 0,
|
|
3883
4088
|
totalCostUsd: row.total_cost_usd ?? 0
|
|
3884
4089
|
}));
|
|
4090
|
+
const callerBreakdown = this.query(`
|
|
4091
|
+
SELECT
|
|
4092
|
+
r.caller as caller,
|
|
4093
|
+
COUNT(*) as requests,
|
|
4094
|
+
SUM(COALESCE(r.input_tokens, 0)) as input_tokens,
|
|
4095
|
+
SUM(COALESCE(r.cache_read_input_tokens, 0)) as cache_read_input_tokens,
|
|
4096
|
+
SUM(COALESCE(r.cache_creation_input_tokens, 0)) as cache_creation_input_tokens,
|
|
4097
|
+
SUM(COALESCE(r.output_tokens, 0)) as output_tokens,
|
|
4098
|
+
SUM(COALESCE(r.cost_usd, 0)) as total_cost_usd
|
|
4099
|
+
FROM requests r
|
|
4100
|
+
WHERE ${whereClause}
|
|
4101
|
+
GROUP BY r.caller
|
|
4102
|
+
ORDER BY total_cost_usd DESC, requests DESC
|
|
4103
|
+
`, queryParams).map((row) => ({
|
|
4104
|
+
caller: row.caller,
|
|
4105
|
+
requests: row.requests,
|
|
4106
|
+
tokenBreakdown: {
|
|
4107
|
+
inputTokens: row.input_tokens ?? 0,
|
|
4108
|
+
cacheReadInputTokens: row.cache_read_input_tokens ?? 0,
|
|
4109
|
+
cacheCreationInputTokens: row.cache_creation_input_tokens ?? 0,
|
|
4110
|
+
outputTokens: row.output_tokens ?? 0
|
|
4111
|
+
},
|
|
4112
|
+
totalCostUsd: row.total_cost_usd ?? 0
|
|
4113
|
+
}));
|
|
3885
4114
|
const modelPerformance = this.query(`
|
|
3886
4115
|
WITH model_stats AS (
|
|
3887
4116
|
SELECT
|
|
@@ -3978,6 +4207,7 @@ var init_analytics_repository = __esm(() => {
|
|
|
3978
4207
|
successRate: account2.success_rate ?? 0
|
|
3979
4208
|
})),
|
|
3980
4209
|
providerBreakdown,
|
|
4210
|
+
callerBreakdown,
|
|
3981
4211
|
costByModel,
|
|
3982
4212
|
modelPerformance
|
|
3983
4213
|
};
|
|
@@ -4294,7 +4524,7 @@ function requestLinkageFromPayload(payload) {
|
|
|
4294
4524
|
clientSessionId: typeof trace.clientSessionId === "string" ? trace.clientSessionId : fromBodies.clientSessionId
|
|
4295
4525
|
};
|
|
4296
4526
|
}
|
|
4297
|
-
var log6, RequestRepository;
|
|
4527
|
+
var log6, ACCOUNT_COST_SINCE_SQL = "SELECT SUM(cost_usd) AS cost FROM requests WHERE account_used = ? AND timestamp >= ?", RequestRepository;
|
|
4298
4528
|
var init_request_repository = __esm(() => {
|
|
4299
4529
|
init_src3();
|
|
4300
4530
|
init_src();
|
|
@@ -4372,7 +4602,8 @@ var init_request_repository = __esm(() => {
|
|
|
4372
4602
|
response_id = ?,
|
|
4373
4603
|
previous_response_id = ?,
|
|
4374
4604
|
response_chain_id = ?,
|
|
4375
|
-
client_session_id =
|
|
4605
|
+
client_session_id = ?,
|
|
4606
|
+
caller = ?
|
|
4376
4607
|
WHERE id = ?
|
|
4377
4608
|
`, [
|
|
4378
4609
|
data.method,
|
|
@@ -4404,6 +4635,7 @@ var init_request_repository = __esm(() => {
|
|
|
4404
4635
|
linkage.previousResponseId,
|
|
4405
4636
|
responseChainId,
|
|
4406
4637
|
linkage.clientSessionId,
|
|
4638
|
+
data.caller ?? null,
|
|
4407
4639
|
data.id
|
|
4408
4640
|
]);
|
|
4409
4641
|
if (payloadJson !== undefined) {
|
|
@@ -4666,6 +4898,12 @@ var init_request_repository = __esm(() => {
|
|
|
4666
4898
|
`, [limit]);
|
|
4667
4899
|
return errors.map((e) => e.error_message);
|
|
4668
4900
|
}
|
|
4901
|
+
sumAccountCostSince(accountId, since) {
|
|
4902
|
+
return this.get(ACCOUNT_COST_SINCE_SQL, [
|
|
4903
|
+
accountId,
|
|
4904
|
+
since
|
|
4905
|
+
])?.cost ?? 0;
|
|
4906
|
+
}
|
|
4669
4907
|
getRequestsByAccount(since) {
|
|
4670
4908
|
const whereClause = since ? "WHERE r.timestamp > ?" : "";
|
|
4671
4909
|
const params = since ? [since] : [];
|
|
@@ -4688,23 +4926,26 @@ var init_request_repository = __esm(() => {
|
|
|
4688
4926
|
successRate: row.success_rate
|
|
4689
4927
|
}));
|
|
4690
4928
|
}
|
|
4691
|
-
deleteOlderThan(cutoffTs) {
|
|
4692
|
-
return this.runWithChanges(`DELETE FROM requests WHERE
|
|
4693
|
-
|
|
4694
|
-
|
|
4929
|
+
deleteOlderThan(cutoffTs, limit) {
|
|
4930
|
+
return this.runWithChanges(`DELETE FROM requests WHERE rowid IN (
|
|
4931
|
+
SELECT rowid FROM requests WHERE timestamp < ? LIMIT ?
|
|
4932
|
+
)`, [cutoffTs, limit]);
|
|
4695
4933
|
}
|
|
4696
4934
|
clear() {
|
|
4697
4935
|
return this.runWithChanges(`DELETE FROM requests`);
|
|
4698
4936
|
}
|
|
4699
|
-
|
|
4700
|
-
|
|
4701
|
-
|
|
4702
|
-
|
|
4703
|
-
|
|
4704
|
-
|
|
4705
|
-
|
|
4706
|
-
|
|
4707
|
-
|
|
4937
|
+
deleteOldestExpiredPayloads(cutoffTs, limit) {
|
|
4938
|
+
const oldest = this.query(`SELECT rp.rowid AS rowid, r.timestamp AS timestamp
|
|
4939
|
+
FROM request_payloads rp
|
|
4940
|
+
LEFT JOIN requests r ON r.id = rp.id
|
|
4941
|
+
ORDER BY rp.rowid
|
|
4942
|
+
LIMIT ?`, [limit]);
|
|
4943
|
+
const firstLive = oldest.findIndex(({ timestamp }) => timestamp !== null && timestamp >= cutoffTs);
|
|
4944
|
+
const expiredCount = firstLive === -1 ? oldest.length : firstLive;
|
|
4945
|
+
const lastExpired = oldest[expiredCount - 1];
|
|
4946
|
+
if (!lastExpired)
|
|
4947
|
+
return 0;
|
|
4948
|
+
return this.runWithChanges(`DELETE FROM request_payloads WHERE rowid <= ?`, [lastExpired.rowid]);
|
|
4708
4949
|
}
|
|
4709
4950
|
};
|
|
4710
4951
|
});
|
|
@@ -4833,6 +5074,7 @@ var init_strategy_repository = __esm(() => {
|
|
|
4833
5074
|
import { Database } from "bun:sqlite";
|
|
4834
5075
|
import { mkdirSync as mkdirSync3, statfsSync } from "fs";
|
|
4835
5076
|
import { dirname as dirname3 } from "path";
|
|
5077
|
+
import { setImmediate as yieldToEventLoop } from "timers/promises";
|
|
4836
5078
|
function freeDiskBytes(directory) {
|
|
4837
5079
|
const { bavail, bsize } = statfsSync(directory);
|
|
4838
5080
|
return bavail * bsize;
|
|
@@ -4852,7 +5094,7 @@ class DatabaseOperations {
|
|
|
4852
5094
|
conversationProviderPreferences;
|
|
4853
5095
|
strategy;
|
|
4854
5096
|
stats;
|
|
4855
|
-
constructor(dbPath) {
|
|
5097
|
+
constructor(dbPath, { migrate = true } = {}) {
|
|
4856
5098
|
const resolvedPath = dbPath ?? resolveDbPath();
|
|
4857
5099
|
this.dbPath = resolvedPath;
|
|
4858
5100
|
const dir = dirname3(resolvedPath);
|
|
@@ -4862,8 +5104,11 @@ class DatabaseOperations {
|
|
|
4862
5104
|
this.db.exec("PRAGMA journal_mode = WAL");
|
|
4863
5105
|
this.db.exec("PRAGMA busy_timeout = 5000");
|
|
4864
5106
|
this.db.exec("PRAGMA synchronous = NORMAL");
|
|
4865
|
-
|
|
4866
|
-
|
|
5107
|
+
this.db.exec(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES}`);
|
|
5108
|
+
if (migrate) {
|
|
5109
|
+
ensureSchema(this.db);
|
|
5110
|
+
runMigrations(this.db);
|
|
5111
|
+
}
|
|
4867
5112
|
this.accounts = new AccountRepository(this.db);
|
|
4868
5113
|
this.analytics = new AnalyticsRepository(this.db);
|
|
4869
5114
|
this.requests = new RequestRepository(this.db);
|
|
@@ -5009,9 +5254,13 @@ class DatabaseOperations {
|
|
|
5009
5254
|
timestamp: options?.timestamp,
|
|
5010
5255
|
payload: options?.payload,
|
|
5011
5256
|
storePayload: options?.storePayload,
|
|
5012
|
-
timings: options?.timings
|
|
5257
|
+
timings: options?.timings,
|
|
5258
|
+
caller: options?.callerId ?? null
|
|
5013
5259
|
});
|
|
5014
5260
|
}
|
|
5261
|
+
getAccountCostSince(accountId, since) {
|
|
5262
|
+
return this.requests.sumAccountCostSince(accountId, since);
|
|
5263
|
+
}
|
|
5015
5264
|
updateRequestUsage(requestId, usage) {
|
|
5016
5265
|
this.requests.updateUsage(requestId, usage);
|
|
5017
5266
|
}
|
|
@@ -5075,18 +5324,40 @@ class DatabaseOperations {
|
|
|
5075
5324
|
getAnalytics(options) {
|
|
5076
5325
|
return this.analytics.getAnalytics(options);
|
|
5077
5326
|
}
|
|
5078
|
-
cleanupOldRequests(payloadRetentionMs, requestRetentionMs) {
|
|
5079
|
-
const
|
|
5080
|
-
const
|
|
5081
|
-
|
|
5082
|
-
|
|
5083
|
-
|
|
5084
|
-
|
|
5327
|
+
cleanupOldRequests(payloadRetentionMs, requestRetentionMs, batchRows = CLEANUP_BATCH_ROWS) {
|
|
5328
|
+
const total = { removedRequests: 0, removedPayloads: 0 };
|
|
5329
|
+
for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
|
|
5330
|
+
total.removedRequests += batch.removedRequests;
|
|
5331
|
+
total.removedPayloads += batch.removedPayloads;
|
|
5332
|
+
}
|
|
5333
|
+
return total;
|
|
5334
|
+
}
|
|
5335
|
+
async cleanupOldRequestsInBatches(payloadRetentionMs, requestRetentionMs, {
|
|
5336
|
+
batchRows = CLEANUP_BATCH_ROWS,
|
|
5337
|
+
signal
|
|
5338
|
+
} = {}) {
|
|
5339
|
+
const total = { removedRequests: 0, removedPayloads: 0 };
|
|
5340
|
+
for (const batch of this.cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows)) {
|
|
5341
|
+
total.removedRequests += batch.removedRequests;
|
|
5342
|
+
total.removedPayloads += batch.removedPayloads;
|
|
5343
|
+
await yieldToEventLoop();
|
|
5344
|
+
if (signal?.aborted)
|
|
5345
|
+
break;
|
|
5346
|
+
}
|
|
5347
|
+
return total;
|
|
5348
|
+
}
|
|
5349
|
+
*cleanupBatches(payloadRetentionMs, requestRetentionMs, batchRows) {
|
|
5350
|
+
for (;; ) {
|
|
5351
|
+
const now = Date.now();
|
|
5352
|
+
let removedRequests = 0;
|
|
5353
|
+
if (typeof requestRetentionMs === "number" && Number.isFinite(requestRetentionMs)) {
|
|
5354
|
+
removedRequests = this.requests.deleteOlderThan(now - requestRetentionMs, batchRows);
|
|
5355
|
+
}
|
|
5356
|
+
const removedPayloads = this.requests.deleteOldestExpiredPayloads(now - payloadRetentionMs, batchRows);
|
|
5357
|
+
yield { removedRequests, removedPayloads };
|
|
5358
|
+
if (removedRequests < batchRows && removedPayloads < batchRows)
|
|
5359
|
+
return;
|
|
5085
5360
|
}
|
|
5086
|
-
const removedPayloadsByAge = this.requests.deletePayloadsOlderThan(payloadCutoff);
|
|
5087
|
-
const removedOrphans = this.requests.deleteOrphanedPayloads();
|
|
5088
|
-
const removedPayloads = removedPayloadsByAge + removedOrphans;
|
|
5089
|
-
return { removedRequests, removedPayloads };
|
|
5090
5361
|
}
|
|
5091
5362
|
close() {
|
|
5092
5363
|
if (this.closed) {
|
|
@@ -5125,6 +5396,7 @@ class DatabaseOperations {
|
|
|
5125
5396
|
return this.stats;
|
|
5126
5397
|
}
|
|
5127
5398
|
}
|
|
5399
|
+
var CLEANUP_BATCH_ROWS = 50, WAL_SIZE_LIMIT_BYTES;
|
|
5128
5400
|
var init_database_operations = __esm(() => {
|
|
5129
5401
|
init_migrations();
|
|
5130
5402
|
init_paths2();
|
|
@@ -5137,6 +5409,7 @@ var init_database_operations = __esm(() => {
|
|
|
5137
5409
|
init_request_repository();
|
|
5138
5410
|
init_stats_repository();
|
|
5139
5411
|
init_strategy_repository();
|
|
5412
|
+
WAL_SIZE_LIMIT_BYTES = 64 * 1024 * 1024;
|
|
5140
5413
|
});
|
|
5141
5414
|
|
|
5142
5415
|
// ../../packages/database/src/factory.ts
|
|
@@ -8692,8 +8965,11 @@ var init_analytics = __esm(() => {
|
|
|
8692
8965
|
// ../../packages/api/src/handlers/config.ts
|
|
8693
8966
|
function publicProviderPool(config, name) {
|
|
8694
8967
|
const {
|
|
8968
|
+
maxUsageByEmail: _fiveHour,
|
|
8695
8969
|
weeklyMaxUsageByEmail: _weekly,
|
|
8696
8970
|
callerWeeklyMaxUsage: _caller,
|
|
8971
|
+
callerNightPacing: _nightPacing,
|
|
8972
|
+
ownerDevicesByEmail: _owners,
|
|
8697
8973
|
...pool
|
|
8698
8974
|
} = config.getTeamRouting(name);
|
|
8699
8975
|
return pool;
|
|
@@ -9660,13 +9936,13 @@ var init_logs_history = __esm(() => {
|
|
|
9660
9936
|
|
|
9661
9937
|
// ../../packages/api/src/handlers/maintenance.ts
|
|
9662
9938
|
function createCleanupHandler(dbOps, config) {
|
|
9663
|
-
return () => {
|
|
9939
|
+
return async () => {
|
|
9664
9940
|
try {
|
|
9665
9941
|
const payloadDays = config.getDataRetentionDays();
|
|
9666
9942
|
const requestDays = config.getRequestRetentionDays();
|
|
9667
9943
|
const payloadMs = payloadDays * 24 * 60 * 60 * 1000;
|
|
9668
9944
|
const requestMs = requestDays * 24 * 60 * 60 * 1000;
|
|
9669
|
-
const { removedRequests, removedPayloads } = dbOps.
|
|
9945
|
+
const { removedRequests, removedPayloads } = await dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs);
|
|
9670
9946
|
const cutoffIso = new Date(Date.now() - Math.min(payloadMs, requestMs)).toISOString();
|
|
9671
9947
|
const cleanupData = {
|
|
9672
9948
|
removedRequests,
|
|
@@ -10185,7 +10461,7 @@ class APIRouter {
|
|
|
10185
10461
|
error: `A registered device key is required in ${DEVICE_KEY_HEADER}`
|
|
10186
10462
|
}, { status: 401 });
|
|
10187
10463
|
}
|
|
10188
|
-
const status = await getCallerPoolStatus(pool, model, callerId);
|
|
10464
|
+
const status = await getCallerPoolStatus(pool, model, callerId, url.searchParams.get("nightBudget") === "1");
|
|
10189
10465
|
if (!status) {
|
|
10190
10466
|
return Response.json({ error: "No provider in this pool serves the model" }, { status: 400 });
|
|
10191
10467
|
}
|
|
@@ -10555,9 +10831,12 @@ class TeamAdmission {
|
|
|
10555
10831
|
preferExpiringQuota: false,
|
|
10556
10832
|
allowlistedAccountUuids: [],
|
|
10557
10833
|
maxUsage: 0.9,
|
|
10834
|
+
maxUsageByEmail: {},
|
|
10558
10835
|
weeklyMaxUsage: 0.95,
|
|
10559
10836
|
weeklyMaxUsageByEmail: {},
|
|
10560
10837
|
callerWeeklyMaxUsage: {},
|
|
10838
|
+
callerNightPacing: {},
|
|
10839
|
+
ownerDevicesByEmail: {},
|
|
10561
10840
|
admissionCap: 1,
|
|
10562
10841
|
admissionQueueLimit: 0,
|
|
10563
10842
|
admissionWaitMs: 0,
|
|
@@ -10979,13 +11258,17 @@ function pinKey(request3, provider) {
|
|
|
10979
11258
|
function isAllowlisted(account2, config) {
|
|
10980
11259
|
return account2.auth_method === "oauth" && account2.account_uuid !== null && account2.account_uuid !== undefined && config.allowlistedAccountUuids.includes(account2.account_uuid);
|
|
10981
11260
|
}
|
|
11261
|
+
function soonestToUseUp(accounts, useUpResetAt) {
|
|
11262
|
+
const soonest = Math.min(...accounts.map(useUpResetAt));
|
|
11263
|
+
return soonest === Number.POSITIVE_INFINITY ? accounts : accounts.filter((account2) => useUpResetAt(account2) === soonest);
|
|
11264
|
+
}
|
|
10982
11265
|
|
|
10983
11266
|
class TeamRouter {
|
|
10984
11267
|
inFlight = new Map;
|
|
10985
11268
|
pins = new Map;
|
|
10986
11269
|
pinLookups = new WeakMap;
|
|
10987
11270
|
cleanedLookups = new WeakSet;
|
|
10988
|
-
order(accounts, request3, config, provider, store, now = Date.now()) {
|
|
11271
|
+
order(accounts, request3, config, provider, store, now = Date.now(), useUpResetAt = () => Number.POSITIVE_INFINITY) {
|
|
10989
11272
|
if (!config.enabled || !request3)
|
|
10990
11273
|
return accounts;
|
|
10991
11274
|
this.removeExpiredPinsOnce(request3, now, store);
|
|
@@ -11004,7 +11287,7 @@ class TeamRouter {
|
|
|
11004
11287
|
}
|
|
11005
11288
|
if (!config.distributionEnabled || !key)
|
|
11006
11289
|
return eligible;
|
|
11007
|
-
const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
11290
|
+
const selected = this.leastUsedPriorityAccount(soonestToUseUp(eligible, useUpResetAt), compareSeatUsage(provider, request3.model, now, config.preferExpiringQuota), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
|
|
11008
11291
|
this.touchPin(key, selected.id, now, store);
|
|
11009
11292
|
return [
|
|
11010
11293
|
selected,
|
|
@@ -11092,37 +11375,144 @@ var init_seat_router = __esm(() => {
|
|
|
11092
11375
|
PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
|
11093
11376
|
});
|
|
11094
11377
|
|
|
11378
|
+
// ../../packages/pool/src/night-pacing.ts
|
|
11379
|
+
function callerNightPacing(pool, callerId) {
|
|
11380
|
+
return callerId && pool.enabled && Object.hasOwn(pool.callerNightPacing, callerId) ? pool.callerNightPacing[callerId] ?? null : null;
|
|
11381
|
+
}
|
|
11382
|
+
function pacedNight(pool, account2, now, callerId) {
|
|
11383
|
+
const pacing = callerNightPacing(pool, callerId);
|
|
11384
|
+
if (!pacing || !isAllowlisted(account2, pool))
|
|
11385
|
+
return null;
|
|
11386
|
+
const endAt = nightEndAt(pacing, now);
|
|
11387
|
+
return endAt === null ? null : { pacing, endAt };
|
|
11388
|
+
}
|
|
11389
|
+
function startsWindowIntoMorning(provider, account2, night, now) {
|
|
11390
|
+
return now >= night.endAt - FIVE_HOUR_WINDOW_MS && !Object.entries(account2.quota_state?.windows ?? {}).some(([bucket, window2]) => provider.isFiveHourBucket(bucket) && window2.resetAt !== null && window2.resetAt > now && window2.resetAt <= night.endAt);
|
|
11391
|
+
}
|
|
11392
|
+
function weeklyWindows(provider, account2, model, now) {
|
|
11393
|
+
return Object.entries(account2.quota_state?.windows ?? {}).flatMap(([bucket, window2]) => {
|
|
11394
|
+
if (window2.resetAt === null || !provider.isWeeklyBucket(bucket) || !(provider.quotaBucketsFor(model)?.includes(bucket) ?? true)) {
|
|
11395
|
+
return [];
|
|
11396
|
+
}
|
|
11397
|
+
const rolled = window2.resetAt <= now;
|
|
11398
|
+
const resetAt2 = rolled ? window2.resetAt + (Math.floor((now - window2.resetAt) / WEEKLY_WINDOW_MS) + 1) * WEEKLY_WINDOW_MS : window2.resetAt;
|
|
11399
|
+
return [
|
|
11400
|
+
{
|
|
11401
|
+
bucket,
|
|
11402
|
+
resetAt: resetAt2,
|
|
11403
|
+
used: rolled ? 0 : window2.status === "rejected" ? 1 : window2.utilization ?? 0
|
|
11404
|
+
}
|
|
11405
|
+
];
|
|
11406
|
+
});
|
|
11407
|
+
}
|
|
11408
|
+
function nightWeeklyWindows(provider, account2, model, pacing, now) {
|
|
11409
|
+
return weeklyWindows(provider, account2, model, now).map((window2) => ({
|
|
11410
|
+
...window2,
|
|
11411
|
+
target: nightWeeklyTarget(pacing, window2.resetAt, now)
|
|
11412
|
+
}));
|
|
11413
|
+
}
|
|
11414
|
+
function useUpResetAt(provider, account2, model, pool, now, callerId) {
|
|
11415
|
+
const night = pacedNight(pool, account2, now, callerId);
|
|
11416
|
+
if (!night)
|
|
11417
|
+
return Number.POSITIVE_INFINITY;
|
|
11418
|
+
return Math.min(...weeklyWindows(provider, account2, model, now).flatMap(({ resetAt: resetAt2 }) => expiresBeforeUseUpTime(night.pacing, resetAt2, now) ? [resetAt2] : []), Number.POSITIVE_INFINITY);
|
|
11419
|
+
}
|
|
11420
|
+
function nightPacingBlock(provider, account2, model, pool, now, callerId) {
|
|
11421
|
+
const night = pacedNight(pool, account2, now, callerId);
|
|
11422
|
+
if (!night)
|
|
11423
|
+
return null;
|
|
11424
|
+
if (startsWindowIntoMorning(provider, account2, night, now)) {
|
|
11425
|
+
return { category: "five-hour-limit", retryAt: night.endAt };
|
|
11426
|
+
}
|
|
11427
|
+
return nightWeeklyWindows(provider, account2, model, night.pacing, now).some((window2) => window2.used >= Math.max(0, window2.target)) ? { category: "weekly-limit", retryAt: night.endAt } : null;
|
|
11428
|
+
}
|
|
11429
|
+
function median(values) {
|
|
11430
|
+
if (values.length === 0)
|
|
11431
|
+
return 0;
|
|
11432
|
+
const sorted = [...values].sort((left, right) => left - right);
|
|
11433
|
+
const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
|
|
11434
|
+
const lower = sorted[Math.ceil(sorted.length / 2) - 1] ?? 0;
|
|
11435
|
+
return (lower + upper) / 2;
|
|
11436
|
+
}
|
|
11437
|
+
function seatsNightCostEq(provider, seats, model, pacing, now, costSince, weeklyCap) {
|
|
11438
|
+
const endAt = nightEndAt(pacing, now);
|
|
11439
|
+
const headrooms = seats.flatMap((account2) => {
|
|
11440
|
+
if (endAt !== null && startsWindowIntoMorning(provider, account2, { pacing, endAt }, now)) {
|
|
11441
|
+
return [];
|
|
11442
|
+
}
|
|
11443
|
+
const [binding] = nightWeeklyWindows(provider, account2, model, pacing, now).map((window2) => ({
|
|
11444
|
+
...window2,
|
|
11445
|
+
ceiling: Math.min(window2.target, weeklyCap(account2, window2.bucket))
|
|
11446
|
+
})).sort((left, right) => left.ceiling - left.used - (right.ceiling - right.used));
|
|
11447
|
+
if (!binding)
|
|
11448
|
+
return [];
|
|
11449
|
+
const usedPoints = binding.used * 100;
|
|
11450
|
+
return [
|
|
11451
|
+
{
|
|
11452
|
+
points: Math.max(0, binding.ceiling - binding.used) * 100,
|
|
11453
|
+
costPerPoint: usedPoints >= MIN_OWN_RATE_POINTS ? costSince(account2.id, binding.resetAt - WEEKLY_WINDOW_MS) / usedPoints : null
|
|
11454
|
+
}
|
|
11455
|
+
];
|
|
11456
|
+
});
|
|
11457
|
+
const fallbackRate = median(headrooms.flatMap(({ costPerPoint }) => costPerPoint === null ? [] : [costPerPoint]));
|
|
11458
|
+
return headrooms.reduce((sum, { points, costPerPoint }) => sum + points * (costPerPoint ?? fallbackRate), 0);
|
|
11459
|
+
}
|
|
11460
|
+
var FIVE_HOUR_WINDOW_MS, MIN_OWN_RATE_POINTS = 5;
|
|
11461
|
+
var init_night_pacing2 = __esm(() => {
|
|
11462
|
+
init_src4();
|
|
11463
|
+
init_seat_router();
|
|
11464
|
+
FIVE_HOUR_WINDOW_MS = 5 * 60 * 60000;
|
|
11465
|
+
});
|
|
11466
|
+
|
|
11095
11467
|
// ../../packages/pool/src/handlers/account-selector.ts
|
|
11096
|
-
function
|
|
11468
|
+
function quotaCeiling(account2, bucket, fleetThreshold, maxUsage) {
|
|
11097
11469
|
const accountThreshold = account2.switch_threshold === null || account2.switch_threshold === undefined ? undefined : quotaThresholdFor(account2, bucket, fleetThreshold);
|
|
11098
|
-
|
|
11470
|
+
return maxUsage?.overridesFleetThreshold === true ? Math.min(maxUsage.limit, accountThreshold ?? Number.POSITIVE_INFINITY) : Math.min(quotaThresholdFor(account2, bucket, fleetThreshold), maxUsage?.limit ?? Number.POSITIVE_INFINITY);
|
|
11471
|
+
}
|
|
11472
|
+
function isQuotaBlocking(provider, account2, bucket, window2, fleetThreshold, now, model, maxUsage) {
|
|
11473
|
+
const threshold = quotaCeiling(account2, bucket, fleetThreshold, maxUsage);
|
|
11099
11474
|
return (provider.quotaBucketsFor(model)?.includes(bucket) ?? true) && (maxUsage === undefined ? isCurrentQuotaWindow(window2, now) : isOpenQuotaWindow(window2, now)) && (window2.status === "rejected" || window2.utilization !== null && window2.utilization >= threshold);
|
|
11100
11475
|
}
|
|
11101
|
-
function
|
|
11476
|
+
function capForAccountEmail(capsByEmail, account2, ctx) {
|
|
11477
|
+
if (Object.keys(capsByEmail).length === 0)
|
|
11478
|
+
return;
|
|
11479
|
+
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
11480
|
+
return email ? capsByEmail[email] : undefined;
|
|
11481
|
+
}
|
|
11482
|
+
function pooledMaxUsage(provider, account2, bucket, ctx, now, callerId) {
|
|
11102
11483
|
const teamRouting = ctx.runtime.pool;
|
|
11103
11484
|
if (teamRouting?.enabled !== true || !isAllowlisted(account2, teamRouting))
|
|
11104
11485
|
return;
|
|
11105
11486
|
if (!provider.isWeeklyBucket(bucket)) {
|
|
11106
|
-
|
|
11487
|
+
const accountCap = capForAccountEmail(teamRouting.maxUsageByEmail, account2, ctx);
|
|
11488
|
+
return {
|
|
11489
|
+
limit: Math.min(teamRouting.maxUsage, accountCap ?? Number.POSITIVE_INFINITY),
|
|
11490
|
+
overridesFleetThreshold: false
|
|
11491
|
+
};
|
|
11107
11492
|
}
|
|
11108
|
-
const
|
|
11109
|
-
const
|
|
11110
|
-
const callerOverride = callerId && Object.hasOwn(teamRouting.callerWeeklyMaxUsage, callerId) ? teamRouting.callerWeeklyMaxUsage[callerId] : undefined;
|
|
11493
|
+
const accountOverride = capForAccountEmail(teamRouting.weeklyMaxUsageByEmail, account2, ctx);
|
|
11494
|
+
const callerOverride = callerId && !pacedNight(teamRouting, account2, now, callerId) ? callerWeeklyCap(teamRouting.callerWeeklyMaxUsage, callerId) : undefined;
|
|
11111
11495
|
return {
|
|
11112
11496
|
limit: Math.min(accountOverride ?? teamRouting.weeklyMaxUsage, callerOverride ?? Number.POSITIVE_INFINITY),
|
|
11113
11497
|
overridesFleetThreshold: accountOverride !== undefined
|
|
11114
11498
|
};
|
|
11115
11499
|
}
|
|
11116
|
-
function
|
|
11117
|
-
const
|
|
11118
|
-
if (!
|
|
11500
|
+
function servesCaller(account2, ctx, callerId) {
|
|
11501
|
+
const ownerDevices = ctx.runtime.pool?.ownerDevicesByEmail;
|
|
11502
|
+
if (!ownerDevices || Object.keys(ownerDevices).length === 0)
|
|
11503
|
+
return true;
|
|
11504
|
+
const email = ctx.dbOps.getEnrollmentContact(account2.id)?.email?.trim().toLowerCase();
|
|
11505
|
+
if (!email || !Object.hasOwn(ownerDevices, email))
|
|
11119
11506
|
return true;
|
|
11120
|
-
|
|
11121
|
-
|
|
11507
|
+
return callerId !== undefined && !!ownerDevices[email]?.includes(callerId);
|
|
11508
|
+
}
|
|
11509
|
+
function isQuotaEligible(provider, account2, fleetThreshold, now, model, ctx, callerId) {
|
|
11510
|
+
for (const [name, window2] of Object.entries(account2.quota_state?.windows ?? {})) {
|
|
11511
|
+
if (isQuotaBlocking(provider, account2, name, window2, fleetThreshold, now, model, pooledMaxUsage(provider, account2, name, ctx, now, callerId))) {
|
|
11122
11512
|
return false;
|
|
11123
11513
|
}
|
|
11124
11514
|
}
|
|
11125
|
-
return
|
|
11515
|
+
return nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId) === null;
|
|
11126
11516
|
}
|
|
11127
11517
|
function fleetAccounts(provider, ctx) {
|
|
11128
11518
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx));
|
|
@@ -11146,19 +11536,23 @@ function callerPoolAccounts(provider, ctx, orderedFallback) {
|
|
|
11146
11536
|
return ctx.dbOps.getAccountsByProvider(provider).filter((account2) => isFleetSeat(account2, ctx) || orderedFallback && !account2.paused && account2.auth_method === "api_key");
|
|
11147
11537
|
}
|
|
11148
11538
|
function blockingResets(provider, account2, model, ctx, now, callerId) {
|
|
11149
|
-
|
|
11539
|
+
const nightEnd = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId)?.retryAt;
|
|
11540
|
+
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, now, callerId))).map(([, window2]) => window2.resetAt).concat(nightEnd === undefined ? [] : [nightEnd]);
|
|
11150
11541
|
}
|
|
11151
11542
|
function quotaBlockForAccount(provider, account2, model, ctx, now, callerId) {
|
|
11152
|
-
const
|
|
11543
|
+
const night = nightPacingBlock(provider, account2, model, ctx.runtime.pool, now, callerId);
|
|
11544
|
+
const blocking = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket2, window3]) => isQuotaBlocking(provider, account2, bucket2, window3, ctx.runtime.quotaThreshold, now, model, pooledMaxUsage(provider, account2, bucket2, ctx, now, callerId)));
|
|
11153
11545
|
if (blocking.length === 0)
|
|
11154
|
-
return
|
|
11546
|
+
return night;
|
|
11155
11547
|
const [bucket, window2] = [...blocking].sort(([, left], [, right]) => {
|
|
11156
11548
|
const leftReset = left.resetAt ?? Number.POSITIVE_INFINITY;
|
|
11157
11549
|
const rightReset = right.resetAt ?? Number.POSITIVE_INFINITY;
|
|
11158
11550
|
return rightReset - leftReset;
|
|
11159
11551
|
})[0];
|
|
11160
11552
|
const category = provider.isFiveHourBucket(bucket) ? "five-hour-limit" : provider.isWeeklyBucket(bucket) ? "weekly-limit" : "unknown";
|
|
11161
|
-
|
|
11553
|
+
if (window2.resetAt === null)
|
|
11554
|
+
return { category };
|
|
11555
|
+
return night?.retryAt !== undefined && night.retryAt > window2.resetAt ? night : { category, retryAt: window2.resetAt };
|
|
11162
11556
|
}
|
|
11163
11557
|
function getQuotaCapacityBlock(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
11164
11558
|
const now = Date.now();
|
|
@@ -11200,19 +11594,30 @@ function getPoolStatus(provider, model, ctx) {
|
|
|
11200
11594
|
admissionWaitMs: config?.admissionWaitMs ?? 0
|
|
11201
11595
|
};
|
|
11202
11596
|
}
|
|
11203
|
-
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts) {
|
|
11597
|
+
function getProviderCallerStatus(provider, model, callerId, ctx, apiKeyAccounts, readNightBudget) {
|
|
11204
11598
|
const strategy3 = ctx.providerRegistry.getProvider(provider);
|
|
11205
11599
|
if (!strategy3)
|
|
11206
11600
|
throw new Error(`Unknown provider '${provider}'`);
|
|
11207
11601
|
const config = ctx.runtime.pool;
|
|
11208
11602
|
const now = Date.now();
|
|
11209
|
-
const accounts = config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"));
|
|
11603
|
+
const accounts = (config.enabled ? callerPoolAccounts(provider, ctx, apiKeyAccounts) : ctx.dbOps.getAccountsByProvider(provider).filter((account2) => !account2.paused && (apiKeyAccounts || account2.auth_method !== "api_key"))).filter((account2) => servesCaller(account2, ctx, callerId));
|
|
11210
11604
|
const servableSeats = accounts.filter((account2) => isServableNow(strategy3, account2, model, ctx, now, callerId)).length;
|
|
11605
|
+
const nightBudget = readNightBudget ? callerNightBudget(strategy3, accounts, model, callerId, ctx, now) : null;
|
|
11211
11606
|
return {
|
|
11212
11607
|
poolEnabled: config.enabled,
|
|
11213
11608
|
servableSeats,
|
|
11214
11609
|
retryAt: servableSeats === 0 ? soonestServableAt(strategy3, accounts, accounts, model, ctx, now, callerId) : null,
|
|
11215
|
-
admissionWaitMs: config.admissionWaitMs
|
|
11610
|
+
admissionWaitMs: config.admissionWaitMs,
|
|
11611
|
+
...nightBudget && { nightBudget }
|
|
11612
|
+
};
|
|
11613
|
+
}
|
|
11614
|
+
function callerNightBudget(provider, accounts, model, callerId, ctx, now) {
|
|
11615
|
+
const pacing = callerNightPacing(ctx.runtime.pool, callerId);
|
|
11616
|
+
if (!pacing)
|
|
11617
|
+
return null;
|
|
11618
|
+
return {
|
|
11619
|
+
night: nightEndAt(pacing, now) !== null,
|
|
11620
|
+
seatsCostEq: seatsNightCostEq(provider, accounts.filter((account2) => isFleetSeat(account2, ctx)), model, pacing, now, (accountId, since) => ctx.dbOps.getAccountCostSince(accountId, since), (account2, bucket) => quotaCeiling(account2, bucket, ctx.runtime.quotaThreshold, pooledMaxUsage(provider, account2, bucket, ctx, now)))
|
|
11216
11621
|
};
|
|
11217
11622
|
}
|
|
11218
11623
|
function getSoonestQuotaReset(meta, ctx, seatsFor = (fleet) => fleet, callerId) {
|
|
@@ -11240,19 +11645,23 @@ function selectRevalidationProbe(accounts, ctx, now, model, callerId) {
|
|
|
11240
11645
|
function getOrderedAccounts(meta, ctx, teamRequest, options = {}) {
|
|
11241
11646
|
const now = Date.now();
|
|
11242
11647
|
const callerId = teamRequest?.callerId;
|
|
11243
|
-
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null);
|
|
11648
|
+
const providerAccounts = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).filter((account2) => refreshBackoffUntil(account2, now) === null && servesCaller(account2, ctx, callerId));
|
|
11244
11649
|
const eligible = providerAccounts.filter((account2) => isQuotaEligible(ctx.provider, account2, ctx.runtime.quotaThreshold, now, meta.model, ctx, callerId));
|
|
11245
11650
|
const candidates = eligible.length > 0 ? eligible : options.allowRevalidationProbe === false || ctx.runtime.pool.blockWhenAllFull ? [] : selectRevalidationProbe(providerAccounts, ctx, now, meta.model, callerId);
|
|
11246
|
-
const
|
|
11247
|
-
|
|
11248
|
-
|
|
11249
|
-
|
|
11651
|
+
const useUpResets = new Map(candidates.map((account2) => [
|
|
11652
|
+
account2.id,
|
|
11653
|
+
useUpResetAt(ctx.provider, account2, meta.model, ctx.runtime.pool, now, callerId)
|
|
11654
|
+
]));
|
|
11655
|
+
const useUpAt = (account2) => useUpResets.get(account2.id) ?? Number.POSITIVE_INFINITY;
|
|
11656
|
+
const prioritized = [...candidates].sort((left, right) => useUpAt(left) - useUpAt(right) || (left.priority ?? 0) - (right.priority ?? 0) || soonestWeeklyReset(ctx.provider, left, now) - soonestWeeklyReset(ctx.provider, right, now));
|
|
11250
11657
|
const ordered = ctx.strategy.select(prioritized, meta);
|
|
11251
|
-
return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps)) ?? ordered;
|
|
11658
|
+
return (options.applyTeamRouting === false ? undefined : ctx.teamRouter?.order(ordered, teamRequest, ctx.runtime.pool, ctx.provider, ctx.dbOps, now, useUpAt)) ?? ordered;
|
|
11252
11659
|
}
|
|
11253
11660
|
var QUOTA_PROBE_INTERVAL_MS = 60000;
|
|
11254
11661
|
var init_account_selector = __esm(() => {
|
|
11662
|
+
init_src4();
|
|
11255
11663
|
init_src();
|
|
11664
|
+
init_night_pacing2();
|
|
11256
11665
|
init_seat_router();
|
|
11257
11666
|
init_seat_usage();
|
|
11258
11667
|
init_token_manager();
|
|
@@ -11502,7 +11911,7 @@ class ProviderSupply {
|
|
|
11502
11911
|
return threadAccount;
|
|
11503
11912
|
};
|
|
11504
11913
|
const seatsFor = (fleet) => {
|
|
11505
|
-
const eligible = ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet;
|
|
11914
|
+
const eligible = (ctx.teamRouter?.eligibleAccounts(fleet, teamRequest, ctx.runtime.pool) ?? fleet).filter((account2) => servesCaller(account2, ctx, route.callerId));
|
|
11506
11915
|
const id = getThreadAccount();
|
|
11507
11916
|
return id ? eligible.filter((account2) => account2.id === id) : eligible;
|
|
11508
11917
|
};
|
|
@@ -11589,7 +11998,7 @@ class ProviderSupply {
|
|
|
11589
11998
|
const teamEnabled = ctx.runtime.pool.enabled;
|
|
11590
11999
|
const pooled = account2.auth_method !== "api_key" && (!teamEnabled || isAllowlisted(account2, ctx.runtime.pool) && (!route.seatHint || account2.name === route.seatHint));
|
|
11591
12000
|
const keyReached = route.apiKeyAccounts && account2.auth_method === "api_key";
|
|
11592
|
-
return (pooled || keyReached) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
|
|
12001
|
+
return (pooled || keyReached) && servesCaller(account2, ctx, route.callerId) && isServableNow(this.provider, account2, model, ctx, Date.now(), route.callerId);
|
|
11593
12002
|
});
|
|
11594
12003
|
if (hasAvailableAccount)
|
|
11595
12004
|
return {
|
|
@@ -11625,7 +12034,7 @@ class ProviderSupply {
|
|
|
11625
12034
|
admissionWaitMs: context2.runtime.pool.admissionWaitMs
|
|
11626
12035
|
};
|
|
11627
12036
|
if (route.scope.kind === "pool-route" && route.callerId) {
|
|
11628
|
-
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts);
|
|
12037
|
+
return getProviderCallerStatus(this.name, mapped, route.callerId, context2, route.apiKeyAccounts, route.readNightBudget === true);
|
|
11629
12038
|
}
|
|
11630
12039
|
return getPoolStatus(this.name, mapped, context2);
|
|
11631
12040
|
}
|
|
@@ -12526,7 +12935,26 @@ async function getCallerPoolStatus(input) {
|
|
|
12526
12935
|
eligibleAccounts,
|
|
12527
12936
|
retryAtMs: eligibleAccounts === 0 && retryTimes.length ? Math.min(...retryTimes) : null,
|
|
12528
12937
|
holdSeconds: input.holdSeconds,
|
|
12529
|
-
admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0
|
|
12938
|
+
admissionWaitMs: statuses[0]?.admissionWaitMs ?? 0,
|
|
12939
|
+
...input.route.readNightBudget && {
|
|
12940
|
+
nightBudget: callerNightBudget2(statuses, Date.now())
|
|
12941
|
+
}
|
|
12942
|
+
};
|
|
12943
|
+
}
|
|
12944
|
+
function toCents(value) {
|
|
12945
|
+
return Math.round(value * 100) / 100;
|
|
12946
|
+
}
|
|
12947
|
+
function callerNightBudget2(statuses, now) {
|
|
12948
|
+
const budgets = statuses.flatMap((status) => status.nightBudget ? [status.nightBudget] : []);
|
|
12949
|
+
if (budgets.length === 0)
|
|
12950
|
+
return null;
|
|
12951
|
+
const seatsCostEq = toCents(budgets.reduce((sum, budget) => sum + budget.seatsCostEq, 0));
|
|
12952
|
+
return {
|
|
12953
|
+
costEq: seatsCostEq,
|
|
12954
|
+
creditsCostEq: 0,
|
|
12955
|
+
seatsCostEq,
|
|
12956
|
+
night: budgets.some((budget) => budget.night),
|
|
12957
|
+
computedAtMs: now
|
|
12530
12958
|
};
|
|
12531
12959
|
}
|
|
12532
12960
|
var init_router2 = () => {};
|
|
@@ -12597,12 +13025,13 @@ function normalizeMaxBodyBytes(maxBodyBytes) {
|
|
|
12597
13025
|
function bodyTooLargeError(maxBodyBytes) {
|
|
12598
13026
|
return new HttpError(413, `Request body too large (maximum ${maxBodyBytes} bytes)`);
|
|
12599
13027
|
}
|
|
12600
|
-
function createRequestMetadata(req, url) {
|
|
13028
|
+
function createRequestMetadata(req, url, callerId) {
|
|
12601
13029
|
return {
|
|
12602
13030
|
id: crypto2.randomUUID(),
|
|
12603
13031
|
method: isHttpMethod(req.method) ? req.method : "GET",
|
|
12604
13032
|
path: url.pathname,
|
|
12605
|
-
timestamp: Date.now()
|
|
13033
|
+
timestamp: Date.now(),
|
|
13034
|
+
...callerId !== undefined && { callerId }
|
|
12606
13035
|
};
|
|
12607
13036
|
}
|
|
12608
13037
|
function readRequestModel(body) {
|
|
@@ -12697,7 +13126,8 @@ async function forwardToClient(options, ctx) {
|
|
|
12697
13126
|
responseHeadersReceivedAt,
|
|
12698
13127
|
retryAttempt,
|
|
12699
13128
|
failoverAttempts,
|
|
12700
|
-
preExtractedModel
|
|
13129
|
+
preExtractedModel,
|
|
13130
|
+
callerId
|
|
12701
13131
|
} = options;
|
|
12702
13132
|
const responseProcessed = ctx.provider.processResponse ? await ctx.provider.processResponse(responseRaw, account2, {
|
|
12703
13133
|
messageId: `msg_${requestId.replaceAll("-", "")}`,
|
|
@@ -12726,7 +13156,8 @@ async function forwardToClient(options, ctx) {
|
|
|
12726
13156
|
providerName: ctx.providerName,
|
|
12727
13157
|
retryAttempt,
|
|
12728
13158
|
failoverAttempts,
|
|
12729
|
-
storePayload: ctx.runtime.storeRequestPayloads
|
|
13159
|
+
storePayload: ctx.runtime.storeRequestPayloads,
|
|
13160
|
+
callerId
|
|
12730
13161
|
};
|
|
12731
13162
|
ctx.usageWorker.postMessage(startMessage);
|
|
12732
13163
|
requestEvents.emit("event", {
|
|
@@ -13303,7 +13734,8 @@ function createForwarder(input, upstream, state) {
|
|
|
13303
13734
|
responseHeadersReceivedAt: upstream.responseHeadersReceivedAt,
|
|
13304
13735
|
retryAttempt: 0,
|
|
13305
13736
|
failoverAttempts: input.failoverAttempts,
|
|
13306
|
-
preExtractedModel: input.mappedModel ?? input.requestMeta.model
|
|
13737
|
+
preExtractedModel: input.mappedModel ?? input.requestMeta.model,
|
|
13738
|
+
callerId: input.requestMeta.callerId
|
|
13307
13739
|
}, input.ctx);
|
|
13308
13740
|
}
|
|
13309
13741
|
function discardUpstreamResponse(state) {
|
|
@@ -13786,7 +14218,8 @@ function startActiveTurn(session, messageType, messageData, parsed) {
|
|
|
13786
14218
|
providerName: session.providerName,
|
|
13787
14219
|
retryAttempt: 0,
|
|
13788
14220
|
failoverAttempts: Math.max(0, session.nextAccountIndex - 1),
|
|
13789
|
-
storePayload: session.requestContext.runtime.storeRequestPayloads
|
|
14221
|
+
storePayload: session.requestContext.runtime.storeRequestPayloads,
|
|
14222
|
+
callerId: session.callerId
|
|
13790
14223
|
};
|
|
13791
14224
|
session.activeTurn = {
|
|
13792
14225
|
requestId,
|
|
@@ -14052,7 +14485,7 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
|
|
|
14052
14485
|
status: 400
|
|
14053
14486
|
});
|
|
14054
14487
|
}
|
|
14055
|
-
const requestMeta = createRequestMetadata(req, url);
|
|
14488
|
+
const requestMeta = createRequestMetadata(req, url, callerId);
|
|
14056
14489
|
const teamRequest = {
|
|
14057
14490
|
body: null,
|
|
14058
14491
|
contentType: null,
|
|
@@ -14106,7 +14539,8 @@ async function handleWebSocketUpgradeRequest(req, url, ctx, server, callerId) {
|
|
|
14106
14539
|
activeTurn: null,
|
|
14107
14540
|
connectedAccount: null,
|
|
14108
14541
|
pendingRequestBody: null,
|
|
14109
|
-
pendingRequestTimestamp: null
|
|
14542
|
+
pendingRequestTimestamp: null,
|
|
14543
|
+
callerId
|
|
14110
14544
|
};
|
|
14111
14545
|
websocketSessions.set(sessionId, session);
|
|
14112
14546
|
const upgraded = server.upgrade(req, {
|
|
@@ -14333,6 +14767,18 @@ var init_router_bridge = __esm(() => {
|
|
|
14333
14767
|
// ../../packages/proxy/src/usage-worker.ts
|
|
14334
14768
|
import { isAbsolute, resolve as resolve2 } from "path";
|
|
14335
14769
|
import { pathToFileURL } from "url";
|
|
14770
|
+
function heldBytesOf(message) {
|
|
14771
|
+
switch (message.type) {
|
|
14772
|
+
case "start":
|
|
14773
|
+
return MESSAGE_OVERHEAD_BYTES + (message.requestBody?.length ?? 0);
|
|
14774
|
+
case "chunk":
|
|
14775
|
+
return MESSAGE_OVERHEAD_BYTES + message.data.byteLength;
|
|
14776
|
+
case "end":
|
|
14777
|
+
return MESSAGE_OVERHEAD_BYTES + (message.responseBody?.length ?? 0);
|
|
14778
|
+
default:
|
|
14779
|
+
return MESSAGE_OVERHEAD_BYTES;
|
|
14780
|
+
}
|
|
14781
|
+
}
|
|
14336
14782
|
function noop() {}
|
|
14337
14783
|
function createDefaultLogger() {
|
|
14338
14784
|
return {
|
|
@@ -14386,6 +14832,7 @@ class UsageWorkerController {
|
|
|
14386
14832
|
readyTimeoutMs;
|
|
14387
14833
|
ackTimeoutMs;
|
|
14388
14834
|
shutdownDelayMs;
|
|
14835
|
+
maxHeldBytes;
|
|
14389
14836
|
logger;
|
|
14390
14837
|
worker = null;
|
|
14391
14838
|
ready = false;
|
|
@@ -14395,6 +14842,9 @@ class UsageWorkerController {
|
|
|
14395
14842
|
shutdownTimer = null;
|
|
14396
14843
|
queuedMessages = [];
|
|
14397
14844
|
pendingAcks = new Map;
|
|
14845
|
+
heldBytes = 0;
|
|
14846
|
+
droppedRequestIds = new Set;
|
|
14847
|
+
droppedRequests = 0;
|
|
14398
14848
|
shutdownPromise = null;
|
|
14399
14849
|
resolveShutdown = null;
|
|
14400
14850
|
rejectShutdown = null;
|
|
@@ -14405,6 +14855,7 @@ class UsageWorkerController {
|
|
|
14405
14855
|
this.readyTimeoutMs = options.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS;
|
|
14406
14856
|
this.ackTimeoutMs = options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS;
|
|
14407
14857
|
this.shutdownDelayMs = options.shutdownDelayMs ?? DEFAULT_SHUTDOWN_DELAY_MS;
|
|
14858
|
+
this.maxHeldBytes = options.maxHeldBytes ?? DEFAULT_MAX_HELD_BYTES;
|
|
14408
14859
|
this.logger = options.logger ?? createDefaultLogger();
|
|
14409
14860
|
this.startWorker();
|
|
14410
14861
|
}
|
|
@@ -14413,16 +14864,65 @@ class UsageWorkerController {
|
|
|
14413
14864
|
this.logger.warn("Dropping usage worker message because the worker is shutting down");
|
|
14414
14865
|
return;
|
|
14415
14866
|
}
|
|
14867
|
+
if (!this.admit(message)) {
|
|
14868
|
+
return;
|
|
14869
|
+
}
|
|
14416
14870
|
const decoratedMessage = {
|
|
14417
14871
|
...message,
|
|
14418
14872
|
messageId: crypto.randomUUID()
|
|
14419
14873
|
};
|
|
14420
14874
|
if (!this.ready || !this.worker) {
|
|
14421
|
-
this.
|
|
14875
|
+
this.queue(decoratedMessage);
|
|
14422
14876
|
return;
|
|
14423
14877
|
}
|
|
14424
14878
|
this.sendMessage(decoratedMessage);
|
|
14425
14879
|
}
|
|
14880
|
+
admit(message) {
|
|
14881
|
+
if (message.type === "shutdown") {
|
|
14882
|
+
return true;
|
|
14883
|
+
}
|
|
14884
|
+
if (this.droppedRequestIds.has(message.requestId)) {
|
|
14885
|
+
if (message.type === "end") {
|
|
14886
|
+
this.droppedRequestIds.delete(message.requestId);
|
|
14887
|
+
}
|
|
14888
|
+
return false;
|
|
14889
|
+
}
|
|
14890
|
+
if (message.type !== "start") {
|
|
14891
|
+
return true;
|
|
14892
|
+
}
|
|
14893
|
+
if (this.heldBytes + heldBytesOf(message) > this.maxHeldBytes) {
|
|
14894
|
+
if (this.droppedRequests === 0) {
|
|
14895
|
+
this.logger.warn(`Usage worker messages hold ${this.heldBytes} bytes, over the ${this.maxHeldBytes}-byte cap; dropping new requests' usage until the worker catches up`);
|
|
14896
|
+
}
|
|
14897
|
+
this.droppedRequests += 1;
|
|
14898
|
+
this.droppedRequestIds.add(message.requestId);
|
|
14899
|
+
return false;
|
|
14900
|
+
}
|
|
14901
|
+
if (this.droppedRequests > 0) {
|
|
14902
|
+
this.logger.warn(`Dropped the usage of ${this.droppedRequests} requests while usage worker messages were over their byte cap`);
|
|
14903
|
+
this.droppedRequests = 0;
|
|
14904
|
+
}
|
|
14905
|
+
return true;
|
|
14906
|
+
}
|
|
14907
|
+
queue(message) {
|
|
14908
|
+
this.queuedMessages.push(message);
|
|
14909
|
+
this.heldBytes += heldBytesOf(message);
|
|
14910
|
+
}
|
|
14911
|
+
forgetQueuedMessages() {
|
|
14912
|
+
for (const message of this.queuedMessages) {
|
|
14913
|
+
this.heldBytes -= heldBytesOf(message);
|
|
14914
|
+
}
|
|
14915
|
+
this.queuedMessages.length = 0;
|
|
14916
|
+
}
|
|
14917
|
+
forgetPendingAck(messageId) {
|
|
14918
|
+
const pending = this.pendingAcks.get(messageId);
|
|
14919
|
+
if (!pending) {
|
|
14920
|
+
return;
|
|
14921
|
+
}
|
|
14922
|
+
clearTimeout(pending.timer);
|
|
14923
|
+
this.heldBytes -= heldBytesOf(pending.message);
|
|
14924
|
+
this.pendingAcks.delete(messageId);
|
|
14925
|
+
}
|
|
14426
14926
|
isShuttingDown() {
|
|
14427
14927
|
return this.shuttingDown;
|
|
14428
14928
|
}
|
|
@@ -14443,7 +14943,7 @@ class UsageWorkerController {
|
|
|
14443
14943
|
this.ready = false;
|
|
14444
14944
|
this.clearReadyTimer();
|
|
14445
14945
|
this.clearPendingAcks();
|
|
14446
|
-
this.
|
|
14946
|
+
this.forgetQueuedMessages();
|
|
14447
14947
|
const worker = this.worker;
|
|
14448
14948
|
if (!worker) {
|
|
14449
14949
|
this.shuttingDown = false;
|
|
@@ -14479,7 +14979,7 @@ class UsageWorkerController {
|
|
|
14479
14979
|
this.ready = false;
|
|
14480
14980
|
this.clearReadyTimer();
|
|
14481
14981
|
this.clearPendingAcks();
|
|
14482
|
-
this.
|
|
14982
|
+
this.forgetQueuedMessages();
|
|
14483
14983
|
if (this.shutdownTimer) {
|
|
14484
14984
|
clearTimeout(this.shutdownTimer);
|
|
14485
14985
|
this.shutdownTimer = null;
|
|
@@ -14550,10 +15050,9 @@ class UsageWorkerController {
|
|
|
14550
15050
|
this.readyTimer = null;
|
|
14551
15051
|
}
|
|
14552
15052
|
clearPendingAcks() {
|
|
14553
|
-
for (const
|
|
14554
|
-
|
|
15053
|
+
for (const messageId of Array.from(this.pendingAcks.keys())) {
|
|
15054
|
+
this.forgetPendingAck(messageId);
|
|
14555
15055
|
}
|
|
14556
|
-
this.pendingAcks.clear();
|
|
14557
15056
|
}
|
|
14558
15057
|
handleWorkerMessage(message) {
|
|
14559
15058
|
if (isShutdownCompleteMessage(message)) {
|
|
@@ -14576,12 +15075,7 @@ class UsageWorkerController {
|
|
|
14576
15075
|
return;
|
|
14577
15076
|
}
|
|
14578
15077
|
if (isAckMessage(message)) {
|
|
14579
|
-
|
|
14580
|
-
if (!pendingAck) {
|
|
14581
|
-
return;
|
|
14582
|
-
}
|
|
14583
|
-
clearTimeout(pendingAck.timer);
|
|
14584
|
-
this.pendingAcks.delete(message.messageId);
|
|
15078
|
+
this.forgetPendingAck(message.messageId);
|
|
14585
15079
|
return;
|
|
14586
15080
|
}
|
|
14587
15081
|
this.onWorkerMessage?.(message);
|
|
@@ -14590,14 +15084,15 @@ class UsageWorkerController {
|
|
|
14590
15084
|
if (!this.worker || !this.ready || this.queuedMessages.length === 0) {
|
|
14591
15085
|
return;
|
|
14592
15086
|
}
|
|
14593
|
-
const queuedMessages = this.queuedMessages.
|
|
15087
|
+
const queuedMessages = this.queuedMessages.slice();
|
|
15088
|
+
this.forgetQueuedMessages();
|
|
14594
15089
|
for (const message of queuedMessages) {
|
|
14595
15090
|
this.sendMessage(message);
|
|
14596
15091
|
}
|
|
14597
15092
|
}
|
|
14598
15093
|
sendMessage(message) {
|
|
14599
15094
|
if (!this.worker) {
|
|
14600
|
-
this.
|
|
15095
|
+
this.queue(message);
|
|
14601
15096
|
return;
|
|
14602
15097
|
}
|
|
14603
15098
|
try {
|
|
@@ -14611,11 +15106,10 @@ class UsageWorkerController {
|
|
|
14611
15106
|
return;
|
|
14612
15107
|
}
|
|
14613
15108
|
const timer = setTimeout(() => {
|
|
14614
|
-
|
|
14615
|
-
if (!pendingAck) {
|
|
15109
|
+
if (!this.pendingAcks.has(message.messageId)) {
|
|
14616
15110
|
return;
|
|
14617
15111
|
}
|
|
14618
|
-
this.
|
|
15112
|
+
this.forgetPendingAck(message.messageId);
|
|
14619
15113
|
this.logger.warn("Usage worker became unresponsive while waiting for an acknowledgement; restarting it");
|
|
14620
15114
|
this.restartWorker();
|
|
14621
15115
|
}, this.ackTimeoutMs);
|
|
@@ -14624,6 +15118,7 @@ class UsageWorkerController {
|
|
|
14624
15118
|
message,
|
|
14625
15119
|
timer
|
|
14626
15120
|
});
|
|
15121
|
+
this.heldBytes += heldBytesOf(message);
|
|
14627
15122
|
}
|
|
14628
15123
|
restartWorker() {
|
|
14629
15124
|
if (this.shuttingDown) {
|
|
@@ -14677,12 +15172,13 @@ class UsageWorkerController {
|
|
|
14677
15172
|
resolveShutdown?.();
|
|
14678
15173
|
}
|
|
14679
15174
|
}
|
|
14680
|
-
var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100;
|
|
15175
|
+
var DEFAULT_READY_TIMEOUT_MS, DEFAULT_ACK_TIMEOUT_MS, DEFAULT_SHUTDOWN_DELAY_MS = 100, DEFAULT_MAX_HELD_BYTES, MESSAGE_OVERHEAD_BYTES = 1024;
|
|
14681
15176
|
var init_usage_worker = __esm(() => {
|
|
14682
15177
|
init_src2();
|
|
14683
15178
|
init_src();
|
|
14684
15179
|
DEFAULT_READY_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_READY_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
|
|
14685
15180
|
DEFAULT_ACK_TIMEOUT_MS = Number(process.env.AGENT_SMITH_USAGE_WORKER_ACK_TIMEOUT_MS || TIME_CONSTANTS.RETRY_DELAY_DEFAULT * 5);
|
|
15181
|
+
DEFAULT_MAX_HELD_BYTES = Number(process.env.AGENT_SMITH_USAGE_WORKER_MAX_HELD_MB || 256) * 1024 * 1024;
|
|
14686
15182
|
});
|
|
14687
15183
|
|
|
14688
15184
|
// ../../packages/proxy/src/proxy.ts
|
|
@@ -14763,7 +15259,7 @@ async function handleProxy(req, url, ctx, callerId) {
|
|
|
14763
15259
|
if (!upstreamUrl.pathname.startsWith("/v1/pool/")) {
|
|
14764
15260
|
return new Response("Not Found", { status: 404 });
|
|
14765
15261
|
}
|
|
14766
|
-
const requestMeta2 = createRequestMetadata(req, upstreamUrl);
|
|
15262
|
+
const requestMeta2 = createRequestMetadata(req, upstreamUrl, callerId);
|
|
14767
15263
|
const { buffer: buffer2 } = await prepareRequestBody(req, ctx.runtime.maxBodyBytes);
|
|
14768
15264
|
const body2 = buffer2 ?? null;
|
|
14769
15265
|
requestMeta2.model = readRequestModel(body2);
|
|
@@ -14775,7 +15271,7 @@ async function handleProxy(req, url, ctx, callerId) {
|
|
|
14775
15271
|
}
|
|
14776
15272
|
return await routePoolRequest(req, upstreamUrl, ctx, requestMeta2, body2, pool, manualPin?.accountName, callerId);
|
|
14777
15273
|
}
|
|
14778
|
-
const requestMeta = createRequestMetadata(req, upstreamUrl);
|
|
15274
|
+
const requestMeta = createRequestMetadata(req, upstreamUrl, callerId);
|
|
14779
15275
|
const { buffer } = await prepareRequestBody(req, requestContext.runtime.maxBodyBytes);
|
|
14780
15276
|
const body = buffer ?? null;
|
|
14781
15277
|
requestMeta.model = readRequestModel(body);
|
|
@@ -15196,7 +15692,7 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15196
15692
|
admissionWaitMs: status.admissionWaitMs
|
|
15197
15693
|
};
|
|
15198
15694
|
},
|
|
15199
|
-
getCallerPoolStatus: async (pool, model, callerId) => {
|
|
15695
|
+
getCallerPoolStatus: async (pool, model, callerId, readNightBudget) => {
|
|
15200
15696
|
const members = providerRegistry.poolCapacityMembers(pool, model);
|
|
15201
15697
|
const url = new URL(`http://localhost/v1/pool/${pool}/`);
|
|
15202
15698
|
const providers2 = members.map(({ provider }) => {
|
|
@@ -15206,7 +15702,10 @@ function bootstrapRuntime(port, serverLog, deploymentDrain) {
|
|
|
15206
15702
|
return supply;
|
|
15207
15703
|
});
|
|
15208
15704
|
return getCallerPoolStatus({
|
|
15209
|
-
route:
|
|
15705
|
+
route: {
|
|
15706
|
+
...createStatusRequest({ kind: "pool-route", wire: pool }, url, model, callerId),
|
|
15707
|
+
readNightBudget
|
|
15708
|
+
},
|
|
15210
15709
|
providers: providers2,
|
|
15211
15710
|
orderedFallback: hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
15212
15711
|
apiKeyAccounts: runtimeConfig2.routing.apiKeyAccounts === "everyone" || hasOrderedProviderFallback(runtimeConfig2.routing, callerId),
|
|
@@ -15524,35 +16023,49 @@ var init_fetch_handler = __esm(() => {
|
|
|
15524
16023
|
});
|
|
15525
16024
|
|
|
15526
16025
|
// ../../packages/runtime-server/src/retention-maintenance.ts
|
|
15527
|
-
function
|
|
15528
|
-
|
|
15529
|
-
|
|
15530
|
-
|
|
15531
|
-
|
|
15532
|
-
|
|
15533
|
-
|
|
15534
|
-
|
|
15535
|
-
|
|
16026
|
+
function retentionWindows(config) {
|
|
16027
|
+
const payloadDays = config.getDataRetentionDays();
|
|
16028
|
+
const requestDays = config.getRequestRetentionDays();
|
|
16029
|
+
return {
|
|
16030
|
+
payloadMs: payloadDays * DAY_MS2,
|
|
16031
|
+
requestMs: requestDays * DAY_MS2,
|
|
16032
|
+
description: `payload=${payloadDays}d, requests=${requestDays}d`
|
|
16033
|
+
};
|
|
16034
|
+
}
|
|
16035
|
+
function logRemoved(log27, label, { removedRequests, removedPayloads }, description) {
|
|
16036
|
+
log27.info(`${label} cleanup removed ${removedRequests} requests and ${removedPayloads} payloads (${description})`);
|
|
15536
16037
|
}
|
|
15537
16038
|
function startRetentionMaintenance(config, dbOps, intervalMs = RETENTION_CLEANUP_INTERVAL_MS) {
|
|
15538
16039
|
const log27 = new Logger("RetentionMaintenance");
|
|
15539
|
-
|
|
16040
|
+
try {
|
|
16041
|
+
const { payloadMs, requestMs, description } = retentionWindows(config);
|
|
16042
|
+
logRemoved(log27, "Startup", dbOps.cleanupOldRequests(payloadMs, requestMs), description);
|
|
16043
|
+
} catch (err) {
|
|
16044
|
+
log27.error(`Startup cleanup error: ${err}`);
|
|
16045
|
+
}
|
|
15540
16046
|
try {
|
|
15541
16047
|
const { vacuumed, freeBytes, requiredBytes } = dbOps.compact();
|
|
15542
16048
|
log27.info(vacuumed ? "Database compacted at startup" : `Startup VACUUM skipped: ${freeBytes} bytes free, ${requiredBytes} needed`);
|
|
15543
16049
|
} catch (err) {
|
|
15544
16050
|
log27.error(`Database compaction error: ${err}`);
|
|
15545
16051
|
}
|
|
16052
|
+
const stopped = new AbortController;
|
|
16053
|
+
let running;
|
|
15546
16054
|
const timer = setInterval(() => {
|
|
15547
|
-
|
|
15548
|
-
|
|
15549
|
-
|
|
15550
|
-
|
|
15551
|
-
|
|
15552
|
-
}
|
|
16055
|
+
if (running)
|
|
16056
|
+
return;
|
|
16057
|
+
const { payloadMs, requestMs, description } = retentionWindows(config);
|
|
16058
|
+
running = dbOps.cleanupOldRequestsInBatches(payloadMs, requestMs, {
|
|
16059
|
+
signal: stopped.signal
|
|
16060
|
+
}).then((removed) => logRemoved(log27, "Periodic", removed, description), (err) => log27.error(`Periodic cleanup error: ${err}`)).finally(() => {
|
|
16061
|
+
running = undefined;
|
|
16062
|
+
});
|
|
15553
16063
|
}, intervalMs);
|
|
15554
16064
|
timer.unref?.();
|
|
15555
|
-
return () =>
|
|
16065
|
+
return () => {
|
|
16066
|
+
clearInterval(timer);
|
|
16067
|
+
stopped.abort();
|
|
16068
|
+
};
|
|
15556
16069
|
}
|
|
15557
16070
|
var DAY_MS2, RETENTION_CLEANUP_INTERVAL_MS;
|
|
15558
16071
|
var init_retention_maintenance = __esm(() => {
|
|
@@ -17094,9 +17607,11 @@ function providerPoolFileConfig(routing) {
|
|
|
17094
17607
|
prefer_expiring_quota: routing.preferExpiringQuota,
|
|
17095
17608
|
members: routing.allowlistedAccountUuids,
|
|
17096
17609
|
max_usage: routing.maxUsage,
|
|
17610
|
+
max_usage_by_email: routing.maxUsageByEmail,
|
|
17097
17611
|
weekly_max_usage: routing.weeklyMaxUsage,
|
|
17098
17612
|
weekly_max_usage_by_email: routing.weeklyMaxUsageByEmail,
|
|
17099
17613
|
caller_weekly_max_usage: routing.callerWeeklyMaxUsage,
|
|
17614
|
+
owner_devices_by_email: routing.ownerDevicesByEmail,
|
|
17100
17615
|
admission: {
|
|
17101
17616
|
cap: routing.admissionCap,
|
|
17102
17617
|
queue_limit: routing.admissionQueueLimit,
|
|
@@ -17414,6 +17929,71 @@ function parseArgs(args) {
|
|
|
17414
17929
|
}
|
|
17415
17930
|
var init_args = () => {};
|
|
17416
17931
|
|
|
17932
|
+
// src/core/client-relay.ts
|
|
17933
|
+
function forwardedHeaders(original) {
|
|
17934
|
+
const headers3 = new Headers(original);
|
|
17935
|
+
for (const name of UNFORWARDED_REQUEST_HEADERS)
|
|
17936
|
+
headers3.delete(name);
|
|
17937
|
+
return headers3;
|
|
17938
|
+
}
|
|
17939
|
+
async function compressedBody(req, headers3) {
|
|
17940
|
+
const body = new Uint8Array(await req.arrayBuffer());
|
|
17941
|
+
if (body.length === 0)
|
|
17942
|
+
return;
|
|
17943
|
+
if (headers3.has("content-encoding"))
|
|
17944
|
+
return body;
|
|
17945
|
+
headers3.set("content-encoding", "gzip");
|
|
17946
|
+
return Bun.gzipSync(body);
|
|
17947
|
+
}
|
|
17948
|
+
function startClientRelay(remoteBaseUrl) {
|
|
17949
|
+
const remote = remoteBaseUrl.replace(/\/+$/, "");
|
|
17950
|
+
const server = Bun.serve({
|
|
17951
|
+
hostname: "127.0.0.1",
|
|
17952
|
+
port: 0,
|
|
17953
|
+
idleTimeout: 0,
|
|
17954
|
+
async fetch(req) {
|
|
17955
|
+
const url = new URL(req.url);
|
|
17956
|
+
const headers3 = forwardedHeaders(req.headers);
|
|
17957
|
+
const body = await compressedBody(req, headers3);
|
|
17958
|
+
try {
|
|
17959
|
+
const upstream = await fetch(`${remote}${url.pathname}${url.search}`, {
|
|
17960
|
+
method: req.method,
|
|
17961
|
+
headers: headers3,
|
|
17962
|
+
body,
|
|
17963
|
+
signal: req.signal,
|
|
17964
|
+
redirect: "manual"
|
|
17965
|
+
});
|
|
17966
|
+
return withSanitizedProxyHeaders(upstream);
|
|
17967
|
+
} catch (error) {
|
|
17968
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
17969
|
+
return Response.json({
|
|
17970
|
+
type: "error",
|
|
17971
|
+
error: {
|
|
17972
|
+
type: "api_error",
|
|
17973
|
+
message: `Agent Smith relay could not reach the pool: ${reason}`
|
|
17974
|
+
}
|
|
17975
|
+
}, { status: 502 });
|
|
17976
|
+
}
|
|
17977
|
+
}
|
|
17978
|
+
});
|
|
17979
|
+
return {
|
|
17980
|
+
url: `http://127.0.0.1:${server.port}`,
|
|
17981
|
+
stop: () => server.stop(true)
|
|
17982
|
+
};
|
|
17983
|
+
}
|
|
17984
|
+
var UNFORWARDED_REQUEST_HEADERS;
|
|
17985
|
+
var init_client_relay = __esm(() => {
|
|
17986
|
+
init_src6();
|
|
17987
|
+
UNFORWARDED_REQUEST_HEADERS = [
|
|
17988
|
+
"accept-encoding",
|
|
17989
|
+
"connection",
|
|
17990
|
+
"content-length",
|
|
17991
|
+
"host",
|
|
17992
|
+
"keep-alive",
|
|
17993
|
+
"transfer-encoding"
|
|
17994
|
+
];
|
|
17995
|
+
});
|
|
17996
|
+
|
|
17417
17997
|
// src/core/local-routing.ts
|
|
17418
17998
|
import {
|
|
17419
17999
|
accessSync as accessSync2,
|
|
@@ -17671,12 +18251,15 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
|
|
|
17671
18251
|
delete env.AGENT_SMITH_ADMIN_KEY;
|
|
17672
18252
|
delete env.AGENT_SMITH_PROXY_KEY;
|
|
17673
18253
|
let command = [target, ...args];
|
|
18254
|
+
let relay;
|
|
17674
18255
|
if (client2.enabled) {
|
|
17675
18256
|
if (!client2.baseUrl || !client2.proxyKeyFile)
|
|
17676
18257
|
throw new Error("client.base_url and client.proxy_key_file are required");
|
|
17677
18258
|
const keyFile = validateProxyKeyFile(client2.proxyKeyFile);
|
|
17678
18259
|
const wires = Object.keys(new Config(configPath).getProviderPools());
|
|
17679
|
-
|
|
18260
|
+
if (client2.baseUrl.startsWith("https://"))
|
|
18261
|
+
relay = startClientRelay(client2.baseUrl);
|
|
18262
|
+
const base = proxyBaseUrl(8080, relay?.url ?? client2.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
|
|
17680
18263
|
const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client2.keepClaudeLogin === true, claudeCompanionDir) : codexWrapper(target, base, keyFile);
|
|
17681
18264
|
command = ["/bin/sh", "-c", script, "--", ...args];
|
|
17682
18265
|
}
|
|
@@ -17698,6 +18281,7 @@ async function launchConfiguredClient(configPath, tool, target, claudeCompanionD
|
|
|
17698
18281
|
} finally {
|
|
17699
18282
|
for (const [signal, listener] of Object.entries(forward))
|
|
17700
18283
|
process.off(signal, listener);
|
|
18284
|
+
relay?.stop();
|
|
17701
18285
|
}
|
|
17702
18286
|
}
|
|
17703
18287
|
async function enableLocalClientRouting(options) {
|
|
@@ -17786,6 +18370,7 @@ ${ROUTING_END}
|
|
|
17786
18370
|
var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CLAUDE_COMPANION_DIRNAME = "agent-smith-claude-companion", CLAUDE_COMPANION_FILES, CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
|
|
17787
18371
|
var init_local_routing = __esm(() => {
|
|
17788
18372
|
init_src4();
|
|
18373
|
+
init_client_relay();
|
|
17789
18374
|
CLAUDE_COMPANION_FILES = [
|
|
17790
18375
|
".claude-plugin/plugin.json",
|
|
17791
18376
|
"hooks/hooks.json",
|
|
@@ -18222,7 +18807,6 @@ import {
|
|
|
18222
18807
|
existsSync as existsSync5,
|
|
18223
18808
|
mkdirSync as mkdirSync5,
|
|
18224
18809
|
readFileSync as readFileSync6,
|
|
18225
|
-
realpathSync as realpathSync2,
|
|
18226
18810
|
rmSync as rmSync3,
|
|
18227
18811
|
writeFileSync as writeFileSync4
|
|
18228
18812
|
} from "fs";
|
|
@@ -18270,12 +18854,22 @@ async function fetchPoolStatus(host) {
|
|
|
18270
18854
|
`)[0]) || "ssh failed");
|
|
18271
18855
|
return JSON.parse(result.stdout.toString());
|
|
18272
18856
|
}
|
|
18857
|
+
function cliBinDirectories() {
|
|
18858
|
+
const found = [Bun.which("agent-smith"), Bun.which("bun")].flatMap((path) => path ? [dirname6(path)] : []);
|
|
18859
|
+
return [
|
|
18860
|
+
...new Set([
|
|
18861
|
+
...found,
|
|
18862
|
+
join10(homedir3(), ".bun", "bin"),
|
|
18863
|
+
"/opt/homebrew/bin",
|
|
18864
|
+
"/usr/local/bin"
|
|
18865
|
+
])
|
|
18866
|
+
];
|
|
18867
|
+
}
|
|
18273
18868
|
function defaultDeps() {
|
|
18274
18869
|
return {
|
|
18275
18870
|
configPath: resolveConfigPath(),
|
|
18276
18871
|
cachePath: join10(homedir3(), "Library", "Caches", "agent-smith", "menubar-status.json"),
|
|
18277
|
-
|
|
18278
|
-
entry: () => realpathSync2(process.argv[1] ?? ""),
|
|
18872
|
+
binDirectories: cliBinDirectories,
|
|
18279
18873
|
pluginDirectory: swiftBarPluginDirectory,
|
|
18280
18874
|
fetchStatus: fetchPoolStatus,
|
|
18281
18875
|
now: Date.now,
|
|
@@ -18309,14 +18903,15 @@ async function loadSnapshot(deps) {
|
|
|
18309
18903
|
};
|
|
18310
18904
|
}
|
|
18311
18905
|
}
|
|
18312
|
-
function pluginScript(
|
|
18906
|
+
function pluginScript(binDirectories) {
|
|
18313
18907
|
return `#!/bin/sh
|
|
18314
18908
|
# <swiftbar.title>Agent Smith pool</swiftbar.title>
|
|
18315
18909
|
# <swiftbar.hideAbout>true</swiftbar.hideAbout>
|
|
18316
18910
|
# <swiftbar.hideRunInTerminal>true</swiftbar.hideRunInTerminal>
|
|
18317
18911
|
# <swiftbar.hideLastUpdated>true</swiftbar.hideLastUpdated>
|
|
18318
18912
|
export SSH_AUTH_SOCK="\${SSH_AUTH_SOCK:-$(/bin/launchctl getenv SSH_AUTH_SOCK)}"
|
|
18319
|
-
|
|
18913
|
+
export PATH=${shellQuote(binDirectories.join(":"))}:"$PATH"
|
|
18914
|
+
exec agent-smith ${PLUGIN_MARKER}
|
|
18320
18915
|
`;
|
|
18321
18916
|
}
|
|
18322
18917
|
function install(deps) {
|
|
@@ -18326,7 +18921,7 @@ function install(deps) {
|
|
|
18326
18921
|
if (!readClientRouting(deps.configPath).poolSshHost)
|
|
18327
18922
|
throw new Error(`Set client.pool_ssh_host in ${deps.configPath} first`);
|
|
18328
18923
|
const path = join10(directory, PLUGIN_FILE);
|
|
18329
|
-
writeFileSync4(path, pluginScript(deps.
|
|
18924
|
+
writeFileSync4(path, pluginScript(deps.binDirectories()));
|
|
18330
18925
|
chmodSync3(path, 493);
|
|
18331
18926
|
deps.log(`Installed ${path}. SwiftBar shows the pool shortly and refreshes it every 5 minutes.`);
|
|
18332
18927
|
}
|