@certalis/agent-smith 0.1.19 → 0.3.0
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 +74 -26
- package/dist/bin.js +5421 -3514
- package/dist/claude-companion/hooks/register.js +4 -1
- package/dist/client-launcher.js +787 -207
- package/dist/dashboard/{chunk-v15gev12.js → chunk-wzenqdk1.js} +4 -4
- package/dist/dashboard/{chunk-v15gev12.js.map → chunk-wzenqdk1.js.map} +5 -5
- package/dist/dashboard/index.html +1 -1
- package/dist/dashboard/manifest.json +2 -2
- package/dist/pool-status.js +3 -3
- package/dist/pool.js +5383 -3497
- package/dist/post-processor.worker.js +791 -170
- package/dist/server.js +5383 -3497
- package/package.json +1 -1
package/dist/client-launcher.js
CHANGED
|
@@ -667,6 +667,14 @@ var init_provider_metadata = __esm(() => {
|
|
|
667
667
|
defaultBaseUrl: "https://api.openai.com/v1",
|
|
668
668
|
specialRequirements: []
|
|
669
669
|
},
|
|
670
|
+
gemini: {
|
|
671
|
+
displayLabel: "Google Gemini",
|
|
672
|
+
authMethod: "api_key",
|
|
673
|
+
supportsOAuth: false,
|
|
674
|
+
supportsWebSocket: false,
|
|
675
|
+
defaultBaseUrl: "https://generativelanguage.googleapis.com",
|
|
676
|
+
specialRequirements: []
|
|
677
|
+
},
|
|
670
678
|
"claude-code": {
|
|
671
679
|
displayLabel: "Claude Code",
|
|
672
680
|
authMethod: "oauth",
|
|
@@ -1230,6 +1238,209 @@ var init_src3 = __esm(() => {
|
|
|
1230
1238
|
log = new Logger;
|
|
1231
1239
|
});
|
|
1232
1240
|
|
|
1241
|
+
// ../../packages/config/src/builtin-providers.ts
|
|
1242
|
+
var BUILTIN_PROVIDER_CONFIGS;
|
|
1243
|
+
var init_builtin_providers = __esm(() => {
|
|
1244
|
+
BUILTIN_PROVIDER_CONFIGS = [
|
|
1245
|
+
{ name: "anthropic", enabled: true, strategy: "anthropic-api" },
|
|
1246
|
+
{ name: "openai", enabled: true, strategy: "openai-api" },
|
|
1247
|
+
{ name: "claude-code", enabled: false, strategy: "claude-code" },
|
|
1248
|
+
{ name: "codex", enabled: false, strategy: "codex" }
|
|
1249
|
+
];
|
|
1250
|
+
});
|
|
1251
|
+
|
|
1252
|
+
// ../../packages/config/src/zoned-time.ts
|
|
1253
|
+
function isTimeZone(value) {
|
|
1254
|
+
if (typeof value !== "string" || value.length === 0 || value.length > 64) {
|
|
1255
|
+
return false;
|
|
1256
|
+
}
|
|
1257
|
+
try {
|
|
1258
|
+
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
1259
|
+
return true;
|
|
1260
|
+
} catch {
|
|
1261
|
+
return false;
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
function localTimeOfDayMs(time) {
|
|
1265
|
+
const [hour = 0, minute = 0] = time.split(":").map(Number);
|
|
1266
|
+
return hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE;
|
|
1267
|
+
}
|
|
1268
|
+
function wallClockFormat(timeZone) {
|
|
1269
|
+
let format = wallClockFormats.get(timeZone);
|
|
1270
|
+
if (!format) {
|
|
1271
|
+
format = new Intl.DateTimeFormat("en-US", {
|
|
1272
|
+
timeZone,
|
|
1273
|
+
hourCycle: "h23",
|
|
1274
|
+
year: "numeric",
|
|
1275
|
+
month: "numeric",
|
|
1276
|
+
day: "numeric",
|
|
1277
|
+
hour: "numeric",
|
|
1278
|
+
minute: "numeric",
|
|
1279
|
+
second: "numeric"
|
|
1280
|
+
});
|
|
1281
|
+
wallClockFormats.set(timeZone, format);
|
|
1282
|
+
}
|
|
1283
|
+
return format;
|
|
1284
|
+
}
|
|
1285
|
+
function wallClock(at, timeZone) {
|
|
1286
|
+
const parts = wallClockFormat(timeZone).formatToParts(at);
|
|
1287
|
+
const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
|
|
1288
|
+
return {
|
|
1289
|
+
year: part("year"),
|
|
1290
|
+
month: part("month"),
|
|
1291
|
+
day: part("day"),
|
|
1292
|
+
hour: part("hour") % 24,
|
|
1293
|
+
minute: part("minute"),
|
|
1294
|
+
second: part("second")
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
function zoneOffsetMs(at, timeZone) {
|
|
1298
|
+
const wall = wallClock(at, timeZone);
|
|
1299
|
+
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
|
|
1300
|
+
}
|
|
1301
|
+
function zonedInstant(wall, timeZone) {
|
|
1302
|
+
return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
|
|
1303
|
+
}
|
|
1304
|
+
var LOCAL_TIME, wallClockFormats;
|
|
1305
|
+
var init_zoned_time = __esm(() => {
|
|
1306
|
+
init_src2();
|
|
1307
|
+
LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
1308
|
+
wallClockFormats = new Map;
|
|
1309
|
+
});
|
|
1310
|
+
|
|
1311
|
+
// ../../packages/config/src/night-pacing.ts
|
|
1312
|
+
function localHours(value) {
|
|
1313
|
+
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) {
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
return { start: value.start, end: value.end };
|
|
1317
|
+
}
|
|
1318
|
+
function isWorkingDays(value) {
|
|
1319
|
+
return Array.isArray(value) && value.length > 0 && new Set(value).size === value.length && value.every((day) => typeof day === "string" && WEEKDAYS.includes(day));
|
|
1320
|
+
}
|
|
1321
|
+
function sanitizeNightPacing(value) {
|
|
1322
|
+
if (!isRecord(value) || Object.keys(value).some((key) => !NIGHT_PACING_FIELDS.has(key))) {
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
const result = {};
|
|
1326
|
+
if (value.time_zone !== undefined) {
|
|
1327
|
+
if (!isTimeZone(value.time_zone))
|
|
1328
|
+
return;
|
|
1329
|
+
result.time_zone = value.time_zone;
|
|
1330
|
+
}
|
|
1331
|
+
if (value.working_days !== undefined) {
|
|
1332
|
+
if (!isWorkingDays(value.working_days))
|
|
1333
|
+
return;
|
|
1334
|
+
result.working_days = [...value.working_days];
|
|
1335
|
+
}
|
|
1336
|
+
if (value.working_hours !== undefined) {
|
|
1337
|
+
const hours = localHours(value.working_hours);
|
|
1338
|
+
if (!hours || hours.start > hours.end)
|
|
1339
|
+
return;
|
|
1340
|
+
result.working_hours = hours;
|
|
1341
|
+
}
|
|
1342
|
+
if (value.night_hours !== undefined) {
|
|
1343
|
+
const hours = localHours(value.night_hours);
|
|
1344
|
+
if (!hours)
|
|
1345
|
+
return;
|
|
1346
|
+
result.night_hours = hours;
|
|
1347
|
+
}
|
|
1348
|
+
if (value.margin_working_days !== undefined) {
|
|
1349
|
+
if (!isFiniteNumber(value.margin_working_days) || value.margin_working_days < 0 || value.margin_working_days > 7) {
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
result.margin_working_days = value.margin_working_days;
|
|
1353
|
+
}
|
|
1354
|
+
if (value.use_up_before !== undefined) {
|
|
1355
|
+
if (typeof value.use_up_before !== "string" || !LOCAL_TIME.test(value.use_up_before)) {
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
result.use_up_before = value.use_up_before;
|
|
1359
|
+
}
|
|
1360
|
+
return result;
|
|
1361
|
+
}
|
|
1362
|
+
function nightPacingSettings(file) {
|
|
1363
|
+
return {
|
|
1364
|
+
timeZone: file.time_zone ?? NIGHT_PACING_DEFAULTS.timeZone,
|
|
1365
|
+
workingDays: [...file.working_days ?? NIGHT_PACING_DEFAULTS.workingDays],
|
|
1366
|
+
workingHours: {
|
|
1367
|
+
...file.working_hours ?? NIGHT_PACING_DEFAULTS.workingHours
|
|
1368
|
+
},
|
|
1369
|
+
nightHours: { ...file.night_hours ?? NIGHT_PACING_DEFAULTS.nightHours },
|
|
1370
|
+
marginWorkingDays: file.margin_working_days ?? NIGHT_PACING_DEFAULTS.marginWorkingDays,
|
|
1371
|
+
useUpBefore: file.use_up_before ?? NIGHT_PACING_DEFAULTS.useUpBefore
|
|
1372
|
+
};
|
|
1373
|
+
}
|
|
1374
|
+
function localDay(at, timeZone) {
|
|
1375
|
+
const wall = wallClock(at, timeZone);
|
|
1376
|
+
return {
|
|
1377
|
+
day: Date.UTC(wall.year, wall.month - 1, wall.day),
|
|
1378
|
+
timeOfDay: wall.hour * TIME_CONSTANTS.HOUR + wall.minute * TIME_CONSTANTS.MINUTE + wall.second * 1000
|
|
1379
|
+
};
|
|
1380
|
+
}
|
|
1381
|
+
function nightEndAt(pacing, now) {
|
|
1382
|
+
const { day, timeOfDay } = localDay(now, pacing.timeZone);
|
|
1383
|
+
const start = localTimeOfDayMs(pacing.nightHours.start);
|
|
1384
|
+
const end = localTimeOfDayMs(pacing.nightHours.end);
|
|
1385
|
+
const wraps = start > end;
|
|
1386
|
+
const night = wraps ? timeOfDay >= start || timeOfDay < end : timeOfDay >= start && timeOfDay < end;
|
|
1387
|
+
if (!night)
|
|
1388
|
+
return null;
|
|
1389
|
+
const endDay = wraps && timeOfDay >= start ? day + TIME_CONSTANTS.DAY : day;
|
|
1390
|
+
return zonedInstant(endDay + end, pacing.timeZone);
|
|
1391
|
+
}
|
|
1392
|
+
function workingMsBetween(pacing, from, to) {
|
|
1393
|
+
const start = localTimeOfDayMs(pacing.workingHours.start);
|
|
1394
|
+
const end = localTimeOfDayMs(pacing.workingHours.end);
|
|
1395
|
+
let total = 0;
|
|
1396
|
+
for (let day = localDay(from, pacing.timeZone).day - TIME_CONSTANTS.DAY;zonedInstant(day + start, pacing.timeZone) < to; day += TIME_CONSTANTS.DAY) {
|
|
1397
|
+
if (!pacing.workingDays.includes(WEEKDAYS[new Date(day).getUTCDay()] ?? ""))
|
|
1398
|
+
continue;
|
|
1399
|
+
const opens = zonedInstant(day + start, pacing.timeZone);
|
|
1400
|
+
const closes = zonedInstant(day + end, pacing.timeZone);
|
|
1401
|
+
total += Math.max(0, Math.min(closes, to) - Math.max(opens, from));
|
|
1402
|
+
}
|
|
1403
|
+
return total;
|
|
1404
|
+
}
|
|
1405
|
+
function expiresBeforeUseUpTime(pacing, resetAt, now) {
|
|
1406
|
+
const endAt = nightEndAt(pacing, now);
|
|
1407
|
+
if (endAt === null || resetAt <= now)
|
|
1408
|
+
return false;
|
|
1409
|
+
return resetAt <= zonedInstant(localDay(endAt, pacing.timeZone).day + localTimeOfDayMs(pacing.useUpBefore), pacing.timeZone);
|
|
1410
|
+
}
|
|
1411
|
+
function nightWeeklyTarget(pacing, resetAt, now) {
|
|
1412
|
+
if (expiresBeforeUseUpTime(pacing, resetAt, now))
|
|
1413
|
+
return 1;
|
|
1414
|
+
const windowStart = resetAt - WEEKLY_WINDOW_MS;
|
|
1415
|
+
const workingDayMs = localTimeOfDayMs(pacing.workingHours.end) - localTimeOfDayMs(pacing.workingHours.start);
|
|
1416
|
+
const elapsed = workingMsBetween(pacing, windowStart, Math.min(now, resetAt));
|
|
1417
|
+
return (elapsed - pacing.marginWorkingDays * workingDayMs) / workingMsBetween(pacing, windowStart, resetAt);
|
|
1418
|
+
}
|
|
1419
|
+
var WEEKDAYS, WEEKLY_WINDOW_MS, NIGHT_PACING_DEFAULTS, NIGHT_PACING_FIELDS;
|
|
1420
|
+
var init_night_pacing = __esm(() => {
|
|
1421
|
+
init_src2();
|
|
1422
|
+
init_src();
|
|
1423
|
+
init_zoned_time();
|
|
1424
|
+
WEEKDAYS = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
|
|
1425
|
+
WEEKLY_WINDOW_MS = 7 * TIME_CONSTANTS.DAY;
|
|
1426
|
+
NIGHT_PACING_DEFAULTS = {
|
|
1427
|
+
timeZone: "Europe/Paris",
|
|
1428
|
+
workingDays: ["mon", "tue", "wed", "thu", "fri"],
|
|
1429
|
+
workingHours: { start: "07:00", end: "21:00" },
|
|
1430
|
+
nightHours: { start: "21:00", end: "07:00" },
|
|
1431
|
+
marginWorkingDays: 1,
|
|
1432
|
+
useUpBefore: "10:00"
|
|
1433
|
+
};
|
|
1434
|
+
NIGHT_PACING_FIELDS = new Set([
|
|
1435
|
+
"time_zone",
|
|
1436
|
+
"working_days",
|
|
1437
|
+
"working_hours",
|
|
1438
|
+
"night_hours",
|
|
1439
|
+
"margin_working_days",
|
|
1440
|
+
"use_up_before"
|
|
1441
|
+
]);
|
|
1442
|
+
});
|
|
1443
|
+
|
|
1233
1444
|
// ../../packages/config/src/paths-common.ts
|
|
1234
1445
|
import { homedir } from "os";
|
|
1235
1446
|
import { join as join3 } from "path";
|
|
@@ -1260,21 +1471,246 @@ var init_paths = __esm(() => {
|
|
|
1260
1471
|
init_paths_common();
|
|
1261
1472
|
});
|
|
1262
1473
|
|
|
1263
|
-
// ../../packages/config/src/
|
|
1264
|
-
function
|
|
1265
|
-
|
|
1474
|
+
// ../../packages/config/src/rewrite-config.ts
|
|
1475
|
+
function rewriteLegacyConfig(value) {
|
|
1476
|
+
if (!isRecord2(value))
|
|
1477
|
+
throw new Error("Configuration must be a JSON object");
|
|
1478
|
+
const output = structuredClone(value);
|
|
1479
|
+
const hasTeam = Object.hasOwn(output, "team_routing");
|
|
1480
|
+
const hasRoutes = Object.hasOwn(output, "provider_pools");
|
|
1481
|
+
const hasBlockPolicy = Object.hasOwn(output, "block_when_all_full");
|
|
1482
|
+
if (!hasTeam && !hasRoutes && !hasBlockPolicy)
|
|
1483
|
+
return output;
|
|
1484
|
+
if (Object.hasOwn(output, "routing"))
|
|
1485
|
+
throw new Error("Cannot rewrite a config containing both legacy keys and routing");
|
|
1486
|
+
const team = hasTeam ? output.team_routing : {};
|
|
1487
|
+
const routes = hasRoutes ? output.provider_pools : {};
|
|
1488
|
+
if (!isRecord2(team) || !isRecord2(routes))
|
|
1489
|
+
throw new Error("Legacy team_routing and provider_pools must be objects");
|
|
1490
|
+
if (output.providers !== undefined && !isRecord2(output.providers))
|
|
1491
|
+
throw new Error("Legacy providers must be an object");
|
|
1492
|
+
const providers = structuredClone(output.providers ?? {});
|
|
1493
|
+
if (Object.values(providers).some((provider) => !isRecord2(provider) || Object.hasOwn(provider, "pool")))
|
|
1494
|
+
throw new Error("Cannot rewrite invalid providers or existing provider pools");
|
|
1495
|
+
const knownTeamFields = new Set([
|
|
1496
|
+
"enabled",
|
|
1497
|
+
"allowlisted_account_uuids",
|
|
1498
|
+
"distribution_enabled",
|
|
1499
|
+
"prefer_expiring_quota",
|
|
1500
|
+
"max_usage",
|
|
1501
|
+
"weekly_max_usage",
|
|
1502
|
+
"weekly_max_usage_by_email",
|
|
1503
|
+
"caller_weekly_max_usage",
|
|
1504
|
+
"caller_provider_fallback",
|
|
1505
|
+
"admission_cap",
|
|
1506
|
+
"admission_queue_limit",
|
|
1507
|
+
"admission_wait_ms",
|
|
1508
|
+
"hold_seconds",
|
|
1509
|
+
"quota_probe_seconds",
|
|
1510
|
+
"window_warmup"
|
|
1511
|
+
]);
|
|
1512
|
+
if (Object.keys(team).some((field) => !knownTeamFields.has(field)))
|
|
1513
|
+
throw new Error("Cannot safely rewrite unknown team_routing fields");
|
|
1514
|
+
if (team.enabled !== undefined && typeof team.enabled !== "boolean")
|
|
1515
|
+
throw new Error("Invalid team_routing.enabled");
|
|
1516
|
+
if (hasBlockPolicy && typeof output.block_when_all_full !== "boolean")
|
|
1517
|
+
throw new Error("Invalid block_when_all_full");
|
|
1518
|
+
if (team.caller_provider_fallback !== undefined && (!isRecord2(team.caller_provider_fallback) || Object.values(team.caller_provider_fallback).some((policy) => policy !== "ordered")))
|
|
1519
|
+
throw new Error("Invalid caller_provider_fallback");
|
|
1520
|
+
const enabled = team.enabled === true;
|
|
1521
|
+
const dormantFields = [
|
|
1522
|
+
"allowlisted_account_uuids",
|
|
1523
|
+
"distribution_enabled",
|
|
1524
|
+
"prefer_expiring_quota",
|
|
1525
|
+
"max_usage",
|
|
1526
|
+
"weekly_max_usage",
|
|
1527
|
+
"weekly_max_usage_by_email",
|
|
1528
|
+
"caller_weekly_max_usage",
|
|
1529
|
+
"admission_cap",
|
|
1530
|
+
"admission_queue_limit",
|
|
1531
|
+
"admission_wait_ms",
|
|
1532
|
+
"quota_probe_seconds",
|
|
1533
|
+
"window_warmup"
|
|
1534
|
+
];
|
|
1535
|
+
const keepPool = enabled || hasBlockPolicy || dormantFields.some((field) => Object.hasOwn(team, field));
|
|
1536
|
+
const callers = {};
|
|
1537
|
+
if (enabled && isRecord2(team.caller_provider_fallback)) {
|
|
1538
|
+
for (const [caller, policy] of Object.entries(team.caller_provider_fallback))
|
|
1539
|
+
if (policy === "ordered")
|
|
1540
|
+
callers[caller] = { allow_fallbacks: true };
|
|
1541
|
+
}
|
|
1542
|
+
const routing = {
|
|
1543
|
+
routes: structuredClone(routes),
|
|
1544
|
+
api_key_accounts: enabled ? "chooser_or_fallback" : "everyone",
|
|
1545
|
+
callers,
|
|
1546
|
+
hold_seconds: typeof team.hold_seconds === "number" ? team.hold_seconds : 0
|
|
1547
|
+
};
|
|
1548
|
+
if (keepPool) {
|
|
1549
|
+
const pool = {
|
|
1550
|
+
...!enabled && { enabled: false },
|
|
1551
|
+
members: structuredClone(team.allowlisted_account_uuids ?? [])
|
|
1552
|
+
};
|
|
1553
|
+
for (const field of [
|
|
1554
|
+
"distribution_enabled",
|
|
1555
|
+
"prefer_expiring_quota",
|
|
1556
|
+
"max_usage",
|
|
1557
|
+
"weekly_max_usage",
|
|
1558
|
+
"weekly_max_usage_by_email",
|
|
1559
|
+
"caller_weekly_max_usage",
|
|
1560
|
+
"quota_probe_seconds",
|
|
1561
|
+
"window_warmup"
|
|
1562
|
+
])
|
|
1563
|
+
if (Object.hasOwn(team, field))
|
|
1564
|
+
pool[field] = structuredClone(team[field]);
|
|
1565
|
+
const admission = {};
|
|
1566
|
+
for (const [oldKey, newKey] of [
|
|
1567
|
+
["admission_cap", "cap"],
|
|
1568
|
+
["admission_queue_limit", "queue_limit"],
|
|
1569
|
+
["admission_wait_ms", "wait_ms"]
|
|
1570
|
+
])
|
|
1571
|
+
if (Object.hasOwn(team, oldKey))
|
|
1572
|
+
admission[newKey] = team[oldKey];
|
|
1573
|
+
if (Object.keys(admission).length)
|
|
1574
|
+
pool.admission = admission;
|
|
1575
|
+
if (hasBlockPolicy)
|
|
1576
|
+
pool.block_when_all_full = output.block_when_all_full;
|
|
1577
|
+
for (const { name } of BUILTIN_PROVIDER_CONFIGS)
|
|
1578
|
+
if (!Object.hasOwn(providers, name))
|
|
1579
|
+
providers[name] = {};
|
|
1580
|
+
for (const [name, entry] of Object.entries(providers)) {
|
|
1581
|
+
if (!isRecord2(entry))
|
|
1582
|
+
throw new Error(`Invalid provider: ${name}`);
|
|
1583
|
+
providers[name] = { ...entry, pool: structuredClone(pool) };
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
delete output.team_routing;
|
|
1587
|
+
delete output.provider_pools;
|
|
1588
|
+
delete output.block_when_all_full;
|
|
1589
|
+
output.providers = providers;
|
|
1590
|
+
output.routing = routing;
|
|
1591
|
+
return output;
|
|
1592
|
+
}
|
|
1593
|
+
function isRecord2(value) {
|
|
1594
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1266
1595
|
}
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1596
|
+
var init_rewrite_config = __esm(() => {
|
|
1597
|
+
init_builtin_providers();
|
|
1598
|
+
});
|
|
1599
|
+
|
|
1600
|
+
// ../../packages/config/src/rewrite-file.ts
|
|
1601
|
+
import { randomUUID } from "crypto";
|
|
1602
|
+
import {
|
|
1603
|
+
accessSync,
|
|
1604
|
+
constants,
|
|
1605
|
+
linkSync,
|
|
1606
|
+
lstatSync,
|
|
1607
|
+
readFileSync,
|
|
1608
|
+
realpathSync,
|
|
1609
|
+
renameSync,
|
|
1610
|
+
statSync as statSync2,
|
|
1611
|
+
unlinkSync as unlinkSync2,
|
|
1612
|
+
writeFileSync
|
|
1613
|
+
} from "fs";
|
|
1614
|
+
import { basename, dirname, join as join5, resolve } from "path";
|
|
1615
|
+
function hasLegacyConfig(value) {
|
|
1616
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) && ["team_routing", "provider_pools", "block_when_all_full"].some((key) => Object.hasOwn(value, key));
|
|
1617
|
+
}
|
|
1618
|
+
function isFileError(error, code) {
|
|
1619
|
+
return error instanceof Error && "code" in error && error.code === code;
|
|
1620
|
+
}
|
|
1621
|
+
function matchesPrivateBackup(path, expected) {
|
|
1271
1622
|
try {
|
|
1272
|
-
|
|
1273
|
-
return
|
|
1623
|
+
const file = lstatSync(path);
|
|
1624
|
+
return file.isFile() && (file.mode & 63) === 0 && (typeof process.getuid !== "function" || file.uid === process.getuid()) && readFileSync(path, "utf8") === expected;
|
|
1274
1625
|
} catch {
|
|
1275
1626
|
return false;
|
|
1276
1627
|
}
|
|
1277
1628
|
}
|
|
1629
|
+
function rewriteConfigFile(input, output) {
|
|
1630
|
+
if (output !== undefined && resolve(input) === resolve(output))
|
|
1631
|
+
throw new Error("Input and output must be different files");
|
|
1632
|
+
const destination = realpathSync(input);
|
|
1633
|
+
const initial = statSync2(destination);
|
|
1634
|
+
const original = readFileSync(input, "utf8");
|
|
1635
|
+
const data = JSON.parse(original);
|
|
1636
|
+
const rewritten = rewriteLegacyConfig(data);
|
|
1637
|
+
const result = `${JSON.stringify(rewritten, null, 2)}
|
|
1638
|
+
`;
|
|
1639
|
+
if (output !== undefined) {
|
|
1640
|
+
writeFileSync(output, result, {
|
|
1641
|
+
encoding: "utf8",
|
|
1642
|
+
mode: 384,
|
|
1643
|
+
flag: "wx"
|
|
1644
|
+
});
|
|
1645
|
+
return { changed: true };
|
|
1646
|
+
}
|
|
1647
|
+
if (!hasLegacyConfig(data))
|
|
1648
|
+
return { changed: false };
|
|
1649
|
+
if ((initial.mode & 146) === 0)
|
|
1650
|
+
throw new Error("Config file is read-only");
|
|
1651
|
+
accessSync(destination, constants.W_OK);
|
|
1652
|
+
const token = randomUUID();
|
|
1653
|
+
const backupTemp = join5(dirname(destination), `.${basename(destination)}.${token}.backup.tmp`);
|
|
1654
|
+
const temporary = join5(dirname(destination), `.${basename(destination)}.${token}.tmp`);
|
|
1655
|
+
const state = () => {
|
|
1656
|
+
if (realpathSync(input) !== destination)
|
|
1657
|
+
throw new Error("Config path changed while rewriting");
|
|
1658
|
+
const current = readFileSync(destination, "utf8");
|
|
1659
|
+
if (current === original)
|
|
1660
|
+
return "original";
|
|
1661
|
+
const parsed = JSON.parse(current);
|
|
1662
|
+
if (!hasLegacyConfig(parsed))
|
|
1663
|
+
return "new";
|
|
1664
|
+
throw new Error("Config changed while it was being rewritten");
|
|
1665
|
+
};
|
|
1666
|
+
try {
|
|
1667
|
+
if (state() === "new")
|
|
1668
|
+
return { changed: false };
|
|
1669
|
+
writeFileSync(backupTemp, original, {
|
|
1670
|
+
encoding: "utf8",
|
|
1671
|
+
mode: 384,
|
|
1672
|
+
flag: "wx"
|
|
1673
|
+
});
|
|
1674
|
+
const base = `${destination}.backup`;
|
|
1675
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
1676
|
+
let backup = base;
|
|
1677
|
+
for (let attempt = 0;; attempt++) {
|
|
1678
|
+
try {
|
|
1679
|
+
linkSync(backupTemp, backup);
|
|
1680
|
+
break;
|
|
1681
|
+
} catch (error) {
|
|
1682
|
+
if (!isFileError(error, "EEXIST"))
|
|
1683
|
+
throw error;
|
|
1684
|
+
if (matchesPrivateBackup(backup, original))
|
|
1685
|
+
break;
|
|
1686
|
+
backup = `${base}-${stamp}${attempt === 0 ? "" : `-${attempt}`}`;
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
writeFileSync(temporary, result, {
|
|
1690
|
+
encoding: "utf8",
|
|
1691
|
+
mode: 384,
|
|
1692
|
+
flag: "wx"
|
|
1693
|
+
});
|
|
1694
|
+
if (state() === "new")
|
|
1695
|
+
return { changed: false };
|
|
1696
|
+
renameSync(temporary, destination);
|
|
1697
|
+
return { changed: true, backup };
|
|
1698
|
+
} finally {
|
|
1699
|
+
for (const path of [backupTemp, temporary]) {
|
|
1700
|
+
try {
|
|
1701
|
+
unlinkSync2(path);
|
|
1702
|
+
} catch {}
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
var init_rewrite_file = __esm(() => {
|
|
1707
|
+
init_rewrite_config();
|
|
1708
|
+
});
|
|
1709
|
+
|
|
1710
|
+
// ../../packages/config/src/window-warmup.ts
|
|
1711
|
+
function isLocalTimes(value) {
|
|
1712
|
+
return Array.isArray(value) && value.length > 0 && value.length <= MAX_TIMES && value.every((time) => typeof time === "string" && LOCAL_TIME.test(time));
|
|
1713
|
+
}
|
|
1278
1714
|
function sanitizeWindowWarmup(value) {
|
|
1279
1715
|
if (!isRecord(value))
|
|
1280
1716
|
return;
|
|
@@ -1311,42 +1747,6 @@ function windowWarmupFileConfig(config) {
|
|
|
1311
1747
|
...config.model && { model: config.model }
|
|
1312
1748
|
};
|
|
1313
1749
|
}
|
|
1314
|
-
function wallClockFormat(timeZone) {
|
|
1315
|
-
let format = wallClockFormats.get(timeZone);
|
|
1316
|
-
if (!format) {
|
|
1317
|
-
format = new Intl.DateTimeFormat("en-US", {
|
|
1318
|
-
timeZone,
|
|
1319
|
-
hourCycle: "h23",
|
|
1320
|
-
year: "numeric",
|
|
1321
|
-
month: "numeric",
|
|
1322
|
-
day: "numeric",
|
|
1323
|
-
hour: "numeric",
|
|
1324
|
-
minute: "numeric",
|
|
1325
|
-
second: "numeric"
|
|
1326
|
-
});
|
|
1327
|
-
wallClockFormats.set(timeZone, format);
|
|
1328
|
-
}
|
|
1329
|
-
return format;
|
|
1330
|
-
}
|
|
1331
|
-
function wallClock(at, timeZone) {
|
|
1332
|
-
const parts = wallClockFormat(timeZone).formatToParts(at);
|
|
1333
|
-
const part = (type) => Number(parts.find((entry) => entry.type === type)?.value);
|
|
1334
|
-
return {
|
|
1335
|
-
year: part("year"),
|
|
1336
|
-
month: part("month"),
|
|
1337
|
-
day: part("day"),
|
|
1338
|
-
hour: part("hour") % 24,
|
|
1339
|
-
minute: part("minute"),
|
|
1340
|
-
second: part("second")
|
|
1341
|
-
};
|
|
1342
|
-
}
|
|
1343
|
-
function zoneOffsetMs(at, timeZone) {
|
|
1344
|
-
const wall = wallClock(at, timeZone);
|
|
1345
|
-
return Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute, wall.second) - Math.floor(at / 1000) * 1000;
|
|
1346
|
-
}
|
|
1347
|
-
function zonedInstant(wall, timeZone) {
|
|
1348
|
-
return wall - zoneOffsetMs(wall - zoneOffsetMs(wall, timeZone), timeZone);
|
|
1349
|
-
}
|
|
1350
1750
|
function nextWindowWarmupAt(routing, after) {
|
|
1351
1751
|
const warmup = routing.windowWarmup;
|
|
1352
1752
|
if (!routing.enabled || !warmup.enabled)
|
|
@@ -1358,19 +1758,16 @@ function nextWindowWarmupAt(routing, after) {
|
|
|
1358
1758
|
if (warmup.weekdaysOnly && (weekday === SATURDAY || weekday === SUNDAY)) {
|
|
1359
1759
|
continue;
|
|
1360
1760
|
}
|
|
1361
|
-
const instants = warmup.times.map((time) =>
|
|
1362
|
-
const [hour = 0, minute = 0] = time.split(":").map(Number);
|
|
1363
|
-
return zonedInstant(day + hour * TIME_CONSTANTS.HOUR + minute * TIME_CONSTANTS.MINUTE, warmup.timeZone);
|
|
1364
|
-
}).filter((at) => at > after);
|
|
1761
|
+
const instants = warmup.times.map((time) => zonedInstant(day + localTimeOfDayMs(time), warmup.timeZone)).filter((at) => at > after);
|
|
1365
1762
|
if (instants.length > 0)
|
|
1366
1763
|
return Math.min(...instants);
|
|
1367
1764
|
}
|
|
1368
1765
|
return null;
|
|
1369
1766
|
}
|
|
1370
|
-
var WINDOW_WARMUP_DEFAULTS,
|
|
1767
|
+
var WINDOW_WARMUP_DEFAULTS, MODEL_NAME, MAX_TIMES = 24, SATURDAY = 6, SUNDAY = 0;
|
|
1371
1768
|
var init_window_warmup = __esm(() => {
|
|
1372
|
-
init_src2();
|
|
1373
1769
|
init_src();
|
|
1770
|
+
init_zoned_time();
|
|
1374
1771
|
WINDOW_WARMUP_DEFAULTS = {
|
|
1375
1772
|
enabled: false,
|
|
1376
1773
|
times: ["06:00"],
|
|
@@ -1378,9 +1775,7 @@ var init_window_warmup = __esm(() => {
|
|
|
1378
1775
|
weekdaysOnly: true,
|
|
1379
1776
|
model: null
|
|
1380
1777
|
};
|
|
1381
|
-
LOCAL_TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
1382
1778
|
MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/;
|
|
1383
|
-
wallClockFormats = new Map;
|
|
1384
1779
|
});
|
|
1385
1780
|
|
|
1386
1781
|
// ../../packages/config/src/index.ts
|
|
@@ -1389,13 +1784,19 @@ import {
|
|
|
1389
1784
|
chmodSync,
|
|
1390
1785
|
existsSync as existsSync2,
|
|
1391
1786
|
mkdirSync as mkdirSync2,
|
|
1392
|
-
readFileSync,
|
|
1393
|
-
renameSync,
|
|
1787
|
+
readFileSync as readFileSync2,
|
|
1788
|
+
renameSync as renameSync2,
|
|
1394
1789
|
rmSync,
|
|
1395
|
-
statSync as
|
|
1396
|
-
writeFileSync
|
|
1790
|
+
statSync as statSync3,
|
|
1791
|
+
writeFileSync as writeFileSync2
|
|
1397
1792
|
} from "fs";
|
|
1398
|
-
import { dirname } from "path";
|
|
1793
|
+
import { dirname as dirname2 } from "path";
|
|
1794
|
+
function runtimeForProvider(runtime, provider) {
|
|
1795
|
+
return {
|
|
1796
|
+
...runtime,
|
|
1797
|
+
pool: runtime.providerPools[provider] ?? { ...POOL_DEFAULTS }
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1399
1800
|
function parseNumber(value) {
|
|
1400
1801
|
if (value === undefined) {
|
|
1401
1802
|
return;
|
|
@@ -1455,6 +1856,12 @@ function sanitizeConfigData(value) {
|
|
|
1455
1856
|
sanitized.provider_pools = providerPools;
|
|
1456
1857
|
continue;
|
|
1457
1858
|
}
|
|
1859
|
+
if (key === "routing") {
|
|
1860
|
+
const routing = sanitizeRouting(entry);
|
|
1861
|
+
if (routing)
|
|
1862
|
+
sanitized.routing = routing;
|
|
1863
|
+
continue;
|
|
1864
|
+
}
|
|
1458
1865
|
if (key === "client") {
|
|
1459
1866
|
const client = sanitizeClientRouting(entry);
|
|
1460
1867
|
if (client)
|
|
@@ -1608,6 +2015,9 @@ function sanitizeProviderConfigs(value) {
|
|
|
1608
2015
|
const models = sanitizeProviderModels(entry.models);
|
|
1609
2016
|
if (models)
|
|
1610
2017
|
provider.models = models;
|
|
2018
|
+
const pool = sanitizeProviderPool(entry.pool);
|
|
2019
|
+
if (pool)
|
|
2020
|
+
provider.pool = pool;
|
|
1611
2021
|
providers[name] = provider;
|
|
1612
2022
|
}
|
|
1613
2023
|
return providers;
|
|
@@ -1626,11 +2036,34 @@ function sanitizeProviderPools(value) {
|
|
|
1626
2036
|
return pools;
|
|
1627
2037
|
}
|
|
1628
2038
|
function wireForStrategy(strategy3) {
|
|
1629
|
-
return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
|
|
2039
|
+
return strategy3 === "anthropic-api" || strategy3 === "model-studio-anthropic-api" || strategy3 === "kimi-code-anthropic-api" || strategy3 === "google-gemini-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
|
|
1630
2040
|
}
|
|
1631
2041
|
function isNonNegativeFiniteNumber(value) {
|
|
1632
2042
|
return isFiniteNumber(value) && value >= 0;
|
|
1633
2043
|
}
|
|
2044
|
+
function sanitizeCapsByEmail(value, maximum) {
|
|
2045
|
+
if (!isRecord(value))
|
|
2046
|
+
return;
|
|
2047
|
+
const entries = Object.entries(value);
|
|
2048
|
+
const normalized = entries.map(([email, cap]) => [normalizeEnrollmentEmail(email), cap]);
|
|
2049
|
+
const isValid = normalized.every(([email, cap]) => email !== undefined && isFiniteNumber(cap) && cap > 0 && cap <= maximum) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
2050
|
+
if (!isValid)
|
|
2051
|
+
return;
|
|
2052
|
+
return Object.fromEntries(normalized);
|
|
2053
|
+
}
|
|
2054
|
+
function isDeviceList(value) {
|
|
2055
|
+
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;
|
|
2056
|
+
}
|
|
2057
|
+
function sanitizeOwnerDevicesByEmail(value) {
|
|
2058
|
+
if (!isRecord(value))
|
|
2059
|
+
return;
|
|
2060
|
+
const entries = Object.entries(value);
|
|
2061
|
+
const normalized = entries.map(([email, devices]) => [normalizeEnrollmentEmail(email), devices]);
|
|
2062
|
+
const isValid = normalized.every(([email, devices]) => email !== undefined && isDeviceList(devices)) && new Set(normalized.map(([email]) => email)).size === entries.length;
|
|
2063
|
+
if (!isValid)
|
|
2064
|
+
return;
|
|
2065
|
+
return Object.fromEntries(normalized.map(([email, devices]) => [email, [...devices]]));
|
|
2066
|
+
}
|
|
1634
2067
|
function sanitizeTeamRouting(value) {
|
|
1635
2068
|
if (!isRecord(value))
|
|
1636
2069
|
return;
|
|
@@ -1652,19 +2085,21 @@ function sanitizeTeamRouting(value) {
|
|
|
1652
2085
|
if (isFiniteNumber(value.weekly_max_usage) && value.weekly_max_usage > 0 && value.weekly_max_usage <= 0.95) {
|
|
1653
2086
|
result.weekly_max_usage = value.weekly_max_usage;
|
|
1654
2087
|
}
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
}
|
|
2088
|
+
const maxUsageByEmail = sanitizeCapsByEmail(value.max_usage_by_email, 0.9);
|
|
2089
|
+
if (maxUsageByEmail)
|
|
2090
|
+
result.max_usage_by_email = maxUsageByEmail;
|
|
2091
|
+
const weeklyMaxUsageByEmail = sanitizeCapsByEmail(value.weekly_max_usage_by_email, 1);
|
|
2092
|
+
if (weeklyMaxUsageByEmail)
|
|
2093
|
+
result.weekly_max_usage_by_email = weeklyMaxUsageByEmail;
|
|
1662
2094
|
if (isRecord(value.caller_weekly_max_usage)) {
|
|
1663
2095
|
const entries = Object.entries(value.caller_weekly_max_usage);
|
|
1664
2096
|
if (entries.length <= MAX_CALLERS && entries.every(([caller, cap]) => CALLER_ID_PATTERN.test(caller) && isFiniteNumber(cap) && cap > 0 && cap <= 0.95)) {
|
|
1665
2097
|
result.caller_weekly_max_usage = Object.fromEntries(entries);
|
|
1666
2098
|
}
|
|
1667
2099
|
}
|
|
2100
|
+
const ownerDevicesByEmail = sanitizeOwnerDevicesByEmail(value.owner_devices_by_email);
|
|
2101
|
+
if (ownerDevicesByEmail)
|
|
2102
|
+
result.owner_devices_by_email = ownerDevicesByEmail;
|
|
1668
2103
|
if (isRecord(value.caller_provider_fallback)) {
|
|
1669
2104
|
const entries = Object.entries(value.caller_provider_fallback);
|
|
1670
2105
|
if (entries.length <= MAX_CALLERS && entries.every(([caller, fallback]) => CALLER_ID_PATTERN.test(caller) && fallback === "ordered")) {
|
|
@@ -1691,13 +2126,116 @@ function sanitizeTeamRouting(value) {
|
|
|
1691
2126
|
result.window_warmup = windowWarmup;
|
|
1692
2127
|
return result;
|
|
1693
2128
|
}
|
|
2129
|
+
function sanitizeProviderPool(value) {
|
|
2130
|
+
if (!isRecord(value))
|
|
2131
|
+
return;
|
|
2132
|
+
const legacy = {
|
|
2133
|
+
...value,
|
|
2134
|
+
allowlisted_account_uuids: value.members
|
|
2135
|
+
};
|
|
2136
|
+
if (isRecord(value.admission)) {
|
|
2137
|
+
legacy.admission_cap = value.admission.cap;
|
|
2138
|
+
legacy.admission_queue_limit = value.admission.queue_limit;
|
|
2139
|
+
legacy.admission_wait_ms = value.admission.wait_ms;
|
|
2140
|
+
}
|
|
2141
|
+
const sanitized = sanitizeTeamRouting(legacy);
|
|
2142
|
+
if (!sanitized)
|
|
2143
|
+
return;
|
|
2144
|
+
const pool = {};
|
|
2145
|
+
if (typeof value.enabled === "boolean")
|
|
2146
|
+
pool.enabled = value.enabled;
|
|
2147
|
+
if (sanitized.allowlisted_account_uuids)
|
|
2148
|
+
pool.members = sanitized.allowlisted_account_uuids;
|
|
2149
|
+
for (const field of [
|
|
2150
|
+
"distribution_enabled",
|
|
2151
|
+
"prefer_expiring_quota",
|
|
2152
|
+
"max_usage",
|
|
2153
|
+
"max_usage_by_email",
|
|
2154
|
+
"weekly_max_usage",
|
|
2155
|
+
"weekly_max_usage_by_email",
|
|
2156
|
+
"caller_weekly_max_usage",
|
|
2157
|
+
"owner_devices_by_email",
|
|
2158
|
+
"quota_probe_seconds",
|
|
2159
|
+
"window_warmup"
|
|
2160
|
+
]) {
|
|
2161
|
+
if (sanitized[field] !== undefined)
|
|
2162
|
+
Object.assign(pool, { [field]: sanitized[field] });
|
|
2163
|
+
}
|
|
2164
|
+
if (isRecord(value.admission)) {
|
|
2165
|
+
pool.admission = {
|
|
2166
|
+
...sanitized.admission_cap !== undefined && {
|
|
2167
|
+
cap: sanitized.admission_cap
|
|
2168
|
+
},
|
|
2169
|
+
...sanitized.admission_queue_limit !== undefined && {
|
|
2170
|
+
queue_limit: sanitized.admission_queue_limit
|
|
2171
|
+
},
|
|
2172
|
+
...sanitized.admission_wait_ms !== undefined && {
|
|
2173
|
+
wait_ms: sanitized.admission_wait_ms
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
2176
|
+
}
|
|
2177
|
+
if (typeof value.block_when_all_full === "boolean")
|
|
2178
|
+
pool.block_when_all_full = value.block_when_all_full;
|
|
2179
|
+
const nightPacing = sanitizeCallerNightPacing(value.caller_night_pacing);
|
|
2180
|
+
if (nightPacing)
|
|
2181
|
+
pool.caller_night_pacing = nightPacing;
|
|
2182
|
+
return pool;
|
|
2183
|
+
}
|
|
2184
|
+
function sanitizeCallerNightPacing(value) {
|
|
2185
|
+
if (!isRecord(value))
|
|
2186
|
+
return;
|
|
2187
|
+
const entries = Object.entries(value).map(([caller, pacing]) => [caller, sanitizeNightPacing(pacing)]);
|
|
2188
|
+
return entries.length <= MAX_CALLERS && entries.every(([caller, pacing]) => CALLER_ID_PATTERN.test(caller) && pacing) ? Object.fromEntries(entries) : undefined;
|
|
2189
|
+
}
|
|
2190
|
+
function sanitizeRouting(value) {
|
|
2191
|
+
if (!isRecord(value))
|
|
2192
|
+
return;
|
|
2193
|
+
const routing = {};
|
|
2194
|
+
const routes = sanitizeProviderPools(value.routes);
|
|
2195
|
+
if (routes)
|
|
2196
|
+
routing.routes = routes;
|
|
2197
|
+
if (value.api_key_accounts === "everyone" || value.api_key_accounts === "chooser_or_fallback")
|
|
2198
|
+
routing.api_key_accounts = value.api_key_accounts;
|
|
2199
|
+
if (isNonNegativeFiniteNumber(value.hold_seconds))
|
|
2200
|
+
routing.hold_seconds = Math.floor(value.hold_seconds);
|
|
2201
|
+
if (isRecord(value.callers)) {
|
|
2202
|
+
const entries = Object.entries(value.callers);
|
|
2203
|
+
if (entries.length <= MAX_CALLERS && entries.every(([caller, policy]) => CALLER_ID_PATTERN.test(caller) && isRecord(policy) && typeof policy.allow_fallbacks === "boolean")) {
|
|
2204
|
+
routing.callers = Object.fromEntries(entries.map(([caller, policy]) => [
|
|
2205
|
+
caller,
|
|
2206
|
+
{
|
|
2207
|
+
allow_fallbacks: policy.allow_fallbacks
|
|
2208
|
+
}
|
|
2209
|
+
]));
|
|
2210
|
+
}
|
|
2211
|
+
}
|
|
2212
|
+
return routing;
|
|
2213
|
+
}
|
|
2214
|
+
function migrateLegacyConfig(path, parsed) {
|
|
2215
|
+
let current = parsed;
|
|
2216
|
+
for (let attempt = 0;attempt < 3 && hasLegacyConfig(current); attempt++) {
|
|
2217
|
+
try {
|
|
2218
|
+
const result = rewriteConfigFile(path);
|
|
2219
|
+
if (result.changed)
|
|
2220
|
+
log2.info(`Rewrote config ${path}; backup: ${result.backup}`);
|
|
2221
|
+
current = JSON.parse(readFileSync2(path, "utf8"));
|
|
2222
|
+
} catch (error) {
|
|
2223
|
+
const reason = error instanceof SyntaxError ? "invalid JSON" : error instanceof Error ? error.message : String(error);
|
|
2224
|
+
throw new Error(`Could not rewrite legacy config ${path}: ${reason}. Run: agent-smith config rewrite`);
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
if (hasLegacyConfig(current))
|
|
2228
|
+
throw new Error(`Config ${path} kept changing while rewriting. Run: agent-smith config rewrite`);
|
|
2229
|
+
return current;
|
|
2230
|
+
}
|
|
1694
2231
|
function readClientRouting(configPath = resolveConfigPath()) {
|
|
1695
2232
|
let data;
|
|
1696
2233
|
try {
|
|
1697
|
-
data = JSON.parse(
|
|
2234
|
+
data = JSON.parse(readFileSync2(configPath, "utf8"));
|
|
1698
2235
|
} catch {
|
|
1699
2236
|
throw new Error("Agent Smith client config could not be read");
|
|
1700
2237
|
}
|
|
2238
|
+
data = migrateLegacyConfig(configPath, data);
|
|
1701
2239
|
if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
|
|
1702
2240
|
throw new Error("Agent Smith client config is invalid");
|
|
1703
2241
|
}
|
|
@@ -1712,50 +2250,54 @@ function clientRouting(client) {
|
|
|
1712
2250
|
...client?.pool_ssh_host && { poolSshHost: client.pool_ssh_host }
|
|
1713
2251
|
};
|
|
1714
2252
|
}
|
|
1715
|
-
var log2, PROVIDER_STRATEGIES,
|
|
2253
|
+
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;
|
|
1716
2254
|
var init_src4 = __esm(() => {
|
|
1717
2255
|
init_src2();
|
|
1718
2256
|
init_src3();
|
|
1719
2257
|
init_src();
|
|
2258
|
+
init_builtin_providers();
|
|
2259
|
+
init_night_pacing();
|
|
1720
2260
|
init_paths();
|
|
2261
|
+
init_rewrite_file();
|
|
1721
2262
|
init_window_warmup();
|
|
2263
|
+
init_night_pacing();
|
|
1722
2264
|
init_paths();
|
|
1723
2265
|
init_paths_common();
|
|
2266
|
+
init_rewrite_config();
|
|
2267
|
+
init_rewrite_file();
|
|
1724
2268
|
init_window_warmup();
|
|
1725
2269
|
log2 = new Logger("Config");
|
|
1726
2270
|
PROVIDER_STRATEGIES = [
|
|
1727
2271
|
"anthropic-api",
|
|
1728
2272
|
"model-studio-anthropic-api",
|
|
2273
|
+
"kimi-code-anthropic-api",
|
|
2274
|
+
"google-gemini-api",
|
|
1729
2275
|
"openai-api",
|
|
1730
2276
|
"claude-code",
|
|
1731
2277
|
"codex"
|
|
1732
2278
|
];
|
|
1733
|
-
BUILTIN_PROVIDER_CONFIGS = [
|
|
1734
|
-
{ name: "anthropic", enabled: true, strategy: "anthropic-api" },
|
|
1735
|
-
{ name: "openai", enabled: true, strategy: "openai-api" },
|
|
1736
|
-
{ name: "claude-code", enabled: false, strategy: "claude-code" },
|
|
1737
|
-
{ name: "codex", enabled: false, strategy: "codex" }
|
|
1738
|
-
];
|
|
1739
2279
|
BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
|
|
1740
2280
|
PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
|
|
1741
2281
|
POOL_SSH_HOST_PATTERN = /^\w[\w.-]{0,127}(@\w[\w.-]{0,127})?$/;
|
|
1742
2282
|
CALLER_ID_PATTERN = /^[-a-zA-Z0-9_]{1,64}$/;
|
|
1743
|
-
|
|
2283
|
+
POOL_DEFAULTS = {
|
|
1744
2284
|
enabled: false,
|
|
1745
2285
|
distributionEnabled: true,
|
|
1746
2286
|
preferExpiringQuota: false,
|
|
1747
2287
|
allowlistedAccountUuids: [],
|
|
1748
2288
|
maxUsage: 0.9,
|
|
2289
|
+
maxUsageByEmail: {},
|
|
1749
2290
|
weeklyMaxUsage: 0.95,
|
|
1750
2291
|
weeklyMaxUsageByEmail: {},
|
|
1751
2292
|
callerWeeklyMaxUsage: {},
|
|
1752
|
-
|
|
2293
|
+
callerNightPacing: {},
|
|
2294
|
+
ownerDevicesByEmail: {},
|
|
1753
2295
|
admissionCap: 5,
|
|
1754
2296
|
admissionQueueLimit: 25,
|
|
1755
2297
|
admissionWaitMs: 30000,
|
|
1756
|
-
holdSeconds: 0,
|
|
1757
2298
|
quotaProbeSeconds: 0,
|
|
1758
|
-
windowWarmup: WINDOW_WARMUP_DEFAULTS
|
|
2299
|
+
windowWarmup: WINDOW_WARMUP_DEFAULTS,
|
|
2300
|
+
blockWhenAllFull: true
|
|
1759
2301
|
};
|
|
1760
2302
|
Config = class Config extends EventEmitter3 {
|
|
1761
2303
|
configPath;
|
|
@@ -1767,20 +2309,23 @@ var init_src4 = __esm(() => {
|
|
|
1767
2309
|
}
|
|
1768
2310
|
loadConfig() {
|
|
1769
2311
|
if (existsSync2(this.configPath)) {
|
|
2312
|
+
let parsed;
|
|
1770
2313
|
try {
|
|
1771
|
-
const content =
|
|
1772
|
-
|
|
2314
|
+
const content = readFileSync2(this.configPath, "utf8");
|
|
2315
|
+
parsed = JSON.parse(content);
|
|
1773
2316
|
} catch (error) {
|
|
1774
2317
|
log2.error(`Failed to parse config file: ${error}`);
|
|
1775
2318
|
this.data = {};
|
|
1776
2319
|
return;
|
|
1777
2320
|
}
|
|
2321
|
+
parsed = migrateLegacyConfig(this.configPath, parsed);
|
|
2322
|
+
this.data = sanitizeConfigData(parsed);
|
|
1778
2323
|
try {
|
|
1779
2324
|
chmodSync(this.configPath, 384);
|
|
1780
2325
|
} catch {
|
|
1781
2326
|
let ownerOnly = false;
|
|
1782
2327
|
try {
|
|
1783
|
-
ownerOnly = (
|
|
2328
|
+
ownerOnly = (statSync3(this.configPath).mode & 63) === 0;
|
|
1784
2329
|
} catch {}
|
|
1785
2330
|
if (!ownerOnly) {
|
|
1786
2331
|
throw new Error("Config file must be owner-only");
|
|
@@ -1791,7 +2336,7 @@ var init_src4 = __esm(() => {
|
|
|
1791
2336
|
this.saveConfig();
|
|
1792
2337
|
}
|
|
1793
2338
|
} else {
|
|
1794
|
-
const dir =
|
|
2339
|
+
const dir = dirname2(this.configPath);
|
|
1795
2340
|
mkdirSync2(dir, { recursive: true, mode: 448 });
|
|
1796
2341
|
chmodSync(dir, 448);
|
|
1797
2342
|
this.data = {
|
|
@@ -1810,11 +2355,11 @@ var init_src4 = __esm(() => {
|
|
|
1810
2355
|
writePrivately(data) {
|
|
1811
2356
|
const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
|
|
1812
2357
|
try {
|
|
1813
|
-
|
|
2358
|
+
writeFileSync2(temporary, JSON.stringify(data, null, 2), {
|
|
1814
2359
|
mode: 384,
|
|
1815
2360
|
flag: "wx"
|
|
1816
2361
|
});
|
|
1817
|
-
|
|
2362
|
+
renameSync2(temporary, this.configPath);
|
|
1818
2363
|
} finally {
|
|
1819
2364
|
rmSync(temporary, { force: true });
|
|
1820
2365
|
}
|
|
@@ -1900,26 +2445,38 @@ var init_src4 = __esm(() => {
|
|
|
1900
2445
|
request_retention_days: this.getRequestRetentionDays()
|
|
1901
2446
|
};
|
|
1902
2447
|
}
|
|
1903
|
-
|
|
1904
|
-
const
|
|
2448
|
+
getRouting() {
|
|
2449
|
+
const routing = this.data.routing;
|
|
1905
2450
|
return {
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
],
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
2451
|
+
routes: structuredClone(routing?.routes ?? {}),
|
|
2452
|
+
apiKeyAccounts: routing?.api_key_accounts ?? "everyone",
|
|
2453
|
+
callers: Object.fromEntries(Object.entries(routing?.callers ?? {}).map(([name, policy]) => [
|
|
2454
|
+
name,
|
|
2455
|
+
{ allowFallbacks: policy.allow_fallbacks }
|
|
2456
|
+
])),
|
|
2457
|
+
holdSeconds: routing?.hold_seconds ?? 0
|
|
2458
|
+
};
|
|
2459
|
+
}
|
|
2460
|
+
getTeamRouting(providerName) {
|
|
2461
|
+
const pool = this.data.providers?.[providerName]?.pool;
|
|
2462
|
+
return {
|
|
2463
|
+
enabled: pool !== undefined && pool.enabled !== false,
|
|
2464
|
+
distributionEnabled: pool?.distribution_enabled ?? POOL_DEFAULTS.distributionEnabled,
|
|
2465
|
+
preferExpiringQuota: pool?.prefer_expiring_quota ?? POOL_DEFAULTS.preferExpiringQuota,
|
|
2466
|
+
allowlistedAccountUuids: [...pool?.members ?? []],
|
|
2467
|
+
maxUsage: pool?.max_usage ?? POOL_DEFAULTS.maxUsage,
|
|
2468
|
+
maxUsageByEmail: { ...pool?.max_usage_by_email },
|
|
2469
|
+
weeklyMaxUsage: pool?.weekly_max_usage ?? POOL_DEFAULTS.weeklyMaxUsage,
|
|
2470
|
+
weeklyMaxUsageByEmail: { ...pool?.weekly_max_usage_by_email },
|
|
2471
|
+
callerWeeklyMaxUsage: { ...pool?.caller_weekly_max_usage },
|
|
2472
|
+
callerNightPacing: Object.fromEntries(Object.entries(pool?.caller_night_pacing ?? {}).map(([caller, pacing]) => [caller, nightPacingSettings(pacing)])),
|
|
2473
|
+
ownerDevicesByEmail: structuredClone(pool?.owner_devices_by_email ?? {}),
|
|
2474
|
+
admissionCap: pool?.admission?.cap ?? POOL_DEFAULTS.admissionCap,
|
|
2475
|
+
admissionQueueLimit: pool?.admission?.queue_limit ?? POOL_DEFAULTS.admissionQueueLimit,
|
|
2476
|
+
admissionWaitMs: pool?.admission?.wait_ms ?? POOL_DEFAULTS.admissionWaitMs,
|
|
2477
|
+
quotaProbeSeconds: pool?.quota_probe_seconds ?? POOL_DEFAULTS.quotaProbeSeconds,
|
|
2478
|
+
windowWarmup: windowWarmupConfig(pool?.window_warmup),
|
|
2479
|
+
blockWhenAllFull: pool?.block_when_all_full !== false
|
|
1923
2480
|
};
|
|
1924
2481
|
}
|
|
1925
2482
|
getAlerts() {
|
|
@@ -1939,9 +2496,6 @@ var init_src4 = __esm(() => {
|
|
|
1939
2496
|
setClientRoutingEnabled(enabled) {
|
|
1940
2497
|
this.persistStrictly("client", { ...this.data.client, enabled });
|
|
1941
2498
|
}
|
|
1942
|
-
getBlockWhenAllFull() {
|
|
1943
|
-
return this.data.block_when_all_full !== false;
|
|
1944
|
-
}
|
|
1945
2499
|
getProviderConfig(name) {
|
|
1946
2500
|
const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
|
|
1947
2501
|
const configured = this.data.providers?.[name];
|
|
@@ -1952,11 +2506,12 @@ var init_src4 = __esm(() => {
|
|
|
1952
2506
|
enabled: configured?.enabled ?? builtin?.enabled ?? true,
|
|
1953
2507
|
strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
|
|
1954
2508
|
...configured?.base_url && { baseUrl: configured.base_url },
|
|
1955
|
-
...configured?.models && { models: { ...configured.models } }
|
|
2509
|
+
...configured?.models && { models: { ...configured.models } },
|
|
2510
|
+
...configured?.pool && { pool: structuredClone(configured.pool) }
|
|
1956
2511
|
};
|
|
1957
2512
|
}
|
|
1958
2513
|
getProviderPool(wire) {
|
|
1959
|
-
return (this.data.
|
|
2514
|
+
return (this.data.routing?.routes?.[wire] ?? []).filter((name) => {
|
|
1960
2515
|
const provider = this.getProviderConfig(name);
|
|
1961
2516
|
return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
|
|
1962
2517
|
});
|
|
@@ -1971,74 +2526,99 @@ var init_src4 = __esm(() => {
|
|
|
1971
2526
|
}
|
|
1972
2527
|
return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
|
|
1973
2528
|
}
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2529
|
+
getProviderPoolSettings() {
|
|
2530
|
+
return Object.fromEntries(this.getProviderConfigs().map((provider) => [
|
|
2531
|
+
provider.name,
|
|
2532
|
+
this.getTeamRouting(provider.name)
|
|
2533
|
+
]));
|
|
2534
|
+
}
|
|
2535
|
+
getProviderPoolConfig(name) {
|
|
2536
|
+
const pool = this.data.providers?.[name]?.pool;
|
|
2537
|
+
return pool ? structuredClone(pool) : undefined;
|
|
2538
|
+
}
|
|
2539
|
+
setProviderPool(name, value) {
|
|
2540
|
+
if (!this.getProviderConfig(name))
|
|
2541
|
+
throw new Error("Unknown provider");
|
|
2542
|
+
if (!isRecord(value))
|
|
2543
|
+
throw new Error("Provider pool configuration must be an object");
|
|
1978
2544
|
const allowed = new Set([
|
|
1979
2545
|
"enabled",
|
|
2546
|
+
"members",
|
|
1980
2547
|
"distribution_enabled",
|
|
1981
2548
|
"prefer_expiring_quota",
|
|
1982
|
-
"allowlisted_account_uuids",
|
|
1983
2549
|
"max_usage",
|
|
2550
|
+
"max_usage_by_email",
|
|
1984
2551
|
"weekly_max_usage",
|
|
1985
2552
|
"weekly_max_usage_by_email",
|
|
1986
2553
|
"caller_weekly_max_usage",
|
|
1987
|
-
"
|
|
1988
|
-
"
|
|
1989
|
-
"
|
|
1990
|
-
"admission_wait_ms",
|
|
1991
|
-
"hold_seconds",
|
|
2554
|
+
"caller_night_pacing",
|
|
2555
|
+
"owner_devices_by_email",
|
|
2556
|
+
"admission",
|
|
1992
2557
|
"quota_probe_seconds",
|
|
1993
|
-
"window_warmup"
|
|
2558
|
+
"window_warmup",
|
|
2559
|
+
"block_when_all_full"
|
|
1994
2560
|
]);
|
|
1995
|
-
if (Object.keys(value).some((key) => !allowed.has(key)))
|
|
1996
|
-
throw new Error("
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2561
|
+
if (Object.keys(value).some((key) => !allowed.has(key)))
|
|
2562
|
+
throw new Error("Provider pool contains an unknown field");
|
|
2563
|
+
const sanitized = sanitizeProviderPool(value);
|
|
2564
|
+
if (!sanitized)
|
|
2565
|
+
throw new Error("Invalid provider pool");
|
|
2566
|
+
for (const key of Object.keys(value))
|
|
2567
|
+
if (!(key in sanitized))
|
|
2568
|
+
throw new Error(`Invalid provider pool field: ${key}`);
|
|
2569
|
+
if (isRecord(value.admission) && Object.keys(value.admission).some((key) => !["cap", "queue_limit", "wait_ms"].includes(key) || !(key in (sanitized.admission ?? {}))))
|
|
2570
|
+
throw new Error("Invalid admission field");
|
|
2571
|
+
const old = this.getProviderPoolConfig(name) ?? { enabled: false };
|
|
2572
|
+
this.persistStrictly("providers", {
|
|
2573
|
+
...this.data.providers,
|
|
2574
|
+
[name]: {
|
|
2575
|
+
...this.data.providers?.[name],
|
|
2576
|
+
pool: { ...old, ...sanitized }
|
|
2005
2577
|
}
|
|
2006
|
-
}
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
}
|
|
2013
|
-
|
|
2014
|
-
sanitized.caller_weekly_max_usage = {
|
|
2015
|
-
...oldValue.caller_weekly_max_usage
|
|
2016
|
-
};
|
|
2017
|
-
}
|
|
2018
|
-
if (!("caller_provider_fallback" in value) && oldValue?.caller_provider_fallback) {
|
|
2019
|
-
sanitized.caller_provider_fallback = {
|
|
2020
|
-
...oldValue.caller_provider_fallback
|
|
2021
|
-
};
|
|
2022
|
-
}
|
|
2023
|
-
this.persistStrictly("team_routing", sanitized);
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
removeProviderPool(name) {
|
|
2581
|
+
const provider = this.data.providers?.[name];
|
|
2582
|
+
if (!provider?.pool)
|
|
2583
|
+
return;
|
|
2584
|
+
const { pool: _pool, ...rest } = provider;
|
|
2585
|
+
this.persistStrictly("providers", { ...this.data.providers, [name]: rest });
|
|
2024
2586
|
}
|
|
2025
|
-
|
|
2026
|
-
|
|
2587
|
+
setRouting(value) {
|
|
2588
|
+
if (!isRecord(value))
|
|
2589
|
+
throw new Error("Routing configuration must be an object");
|
|
2590
|
+
const allowed = new Set([
|
|
2591
|
+
"routes",
|
|
2592
|
+
"api_key_accounts",
|
|
2593
|
+
"callers",
|
|
2594
|
+
"hold_seconds"
|
|
2595
|
+
]);
|
|
2596
|
+
if (Object.keys(value).some((key) => !allowed.has(key)))
|
|
2597
|
+
throw new Error("Routing contains an unknown field");
|
|
2598
|
+
const sanitized = sanitizeRouting(value);
|
|
2599
|
+
if (!sanitized)
|
|
2600
|
+
throw new Error("Invalid routing configuration");
|
|
2601
|
+
for (const key of Object.keys(value))
|
|
2602
|
+
if (!(key in sanitized))
|
|
2603
|
+
throw new Error(`Invalid routing field: ${key}`);
|
|
2604
|
+
if ("routes" in value && (!isRecord(value.routes) || Object.entries(value.routes).some(([wire, providers]) => !isProviderWire(wire) || !Array.isArray(providers) || providers.some((provider) => typeof provider !== "string" || !PROVIDER_NAME_PATTERN.test(provider)))))
|
|
2605
|
+
throw new Error("Invalid routing field: routes");
|
|
2606
|
+
this.persistStrictly("routing", { ...this.data.routing, ...sanitized });
|
|
2607
|
+
}
|
|
2608
|
+
allowAccountUuid(provider, accountUuid) {
|
|
2609
|
+
const current = this.getTeamRouting(provider).allowlistedAccountUuids;
|
|
2027
2610
|
if (current.includes(accountUuid))
|
|
2028
2611
|
return;
|
|
2029
|
-
this.persistAccountAllowlist([...current, accountUuid]);
|
|
2612
|
+
this.persistAccountAllowlist(provider, [...current, accountUuid]);
|
|
2030
2613
|
}
|
|
2031
|
-
removeAccountUuid(accountUuid) {
|
|
2032
|
-
const current = this.getTeamRouting().allowlistedAccountUuids;
|
|
2614
|
+
removeAccountUuid(provider, accountUuid) {
|
|
2615
|
+
const current = this.getTeamRouting(provider).allowlistedAccountUuids;
|
|
2033
2616
|
if (!current.includes(accountUuid))
|
|
2034
2617
|
return;
|
|
2035
|
-
this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
|
|
2618
|
+
this.persistAccountAllowlist(provider, current.filter((uuid) => uuid !== accountUuid));
|
|
2036
2619
|
}
|
|
2037
|
-
persistAccountAllowlist(accountUuids) {
|
|
2038
|
-
this.
|
|
2039
|
-
...this.data.team_routing,
|
|
2040
|
-
allowlisted_account_uuids: accountUuids
|
|
2041
|
-
});
|
|
2620
|
+
persistAccountAllowlist(provider, accountUuids) {
|
|
2621
|
+
this.setProviderPool(provider, { members: accountUuids });
|
|
2042
2622
|
}
|
|
2043
2623
|
getEnrollmentEmails() {
|
|
2044
2624
|
return [...this.data.enrollment_emails ?? []];
|
|
@@ -2072,7 +2652,6 @@ var init_src4 = __esm(() => {
|
|
|
2072
2652
|
}
|
|
2073
2653
|
getRuntime() {
|
|
2074
2654
|
const defaults = {
|
|
2075
|
-
blockWhenAllFull: this.getBlockWhenAllFull(),
|
|
2076
2655
|
clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
|
|
2077
2656
|
maxBodyBytes: 64 * 1024 * 1024,
|
|
2078
2657
|
quotaThreshold: 0.98,
|
|
@@ -2085,7 +2664,8 @@ var init_src4 = __esm(() => {
|
|
|
2085
2664
|
sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
|
|
2086
2665
|
port: NETWORK.DEFAULT_PORT,
|
|
2087
2666
|
storeRequestPayloads: this.storesRequestPayloads(),
|
|
2088
|
-
|
|
2667
|
+
routing: this.getRouting(),
|
|
2668
|
+
providerPools: this.getProviderPoolSettings()
|
|
2089
2669
|
};
|
|
2090
2670
|
if (process.env.AGENT_SMITH_CLIENT_ID) {
|
|
2091
2671
|
defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
|
|
@@ -2156,20 +2736,20 @@ var init_src4 = __esm(() => {
|
|
|
2156
2736
|
|
|
2157
2737
|
// src/core/local-routing.ts
|
|
2158
2738
|
import {
|
|
2159
|
-
accessSync,
|
|
2739
|
+
accessSync as accessSync2,
|
|
2160
2740
|
chmodSync as chmodSync2,
|
|
2161
|
-
constants,
|
|
2741
|
+
constants as constants2,
|
|
2162
2742
|
copyFileSync,
|
|
2163
2743
|
existsSync as existsSync3,
|
|
2164
2744
|
mkdirSync as mkdirSync3,
|
|
2165
|
-
readFileSync as
|
|
2745
|
+
readFileSync as readFileSync3,
|
|
2166
2746
|
rmSync as rmSync2,
|
|
2167
|
-
statSync as
|
|
2168
|
-
unlinkSync as
|
|
2169
|
-
writeFileSync as
|
|
2747
|
+
statSync as statSync4,
|
|
2748
|
+
unlinkSync as unlinkSync3,
|
|
2749
|
+
writeFileSync as writeFileSync3
|
|
2170
2750
|
} from "fs";
|
|
2171
2751
|
import { homedir as homedir2 } from "os";
|
|
2172
|
-
import { dirname as
|
|
2752
|
+
import { dirname as dirname3, join as join6 } from "path";
|
|
2173
2753
|
import { fileURLToPath } from "url";
|
|
2174
2754
|
function shellQuote(value) {
|
|
2175
2755
|
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
@@ -2182,10 +2762,10 @@ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoo
|
|
|
2182
2762
|
return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
|
|
2183
2763
|
}
|
|
2184
2764
|
function validateProxyKeyFile(proxyKeyFile) {
|
|
2185
|
-
const resolvedPath = proxyKeyFile.startsWith("~/") ?
|
|
2765
|
+
const resolvedPath = proxyKeyFile.startsWith("~/") ? join6(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
|
|
2186
2766
|
let metadata;
|
|
2187
2767
|
try {
|
|
2188
|
-
metadata =
|
|
2768
|
+
metadata = statSync4(resolvedPath);
|
|
2189
2769
|
} catch {
|
|
2190
2770
|
throw new Error("Agent Smith forwarding-key file is not readable");
|
|
2191
2771
|
}
|
|
@@ -2195,7 +2775,7 @@ function validateProxyKeyFile(proxyKeyFile) {
|
|
|
2195
2775
|
if ((metadata.mode & 63) !== 0) {
|
|
2196
2776
|
throw new Error("Agent Smith forwarding-key file must be owner-only");
|
|
2197
2777
|
}
|
|
2198
|
-
const key =
|
|
2778
|
+
const key = readFileSync3(resolvedPath, "utf8").trim();
|
|
2199
2779
|
if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
|
|
2200
2780
|
throw new Error("Agent Smith forwarding-key file is invalid");
|
|
2201
2781
|
}
|
|
@@ -2220,30 +2800,30 @@ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_
|
|
|
2220
2800
|
}x-api-key: $AGENT_SMITH_PROXY_KEY"`;
|
|
2221
2801
|
}
|
|
2222
2802
|
function claudeCompanionSourceDir() {
|
|
2223
|
-
const bundled =
|
|
2224
|
-
if (existsSync3(
|
|
2803
|
+
const bundled = join6(import.meta.dir, "claude-companion");
|
|
2804
|
+
if (existsSync3(join6(bundled, ".claude-plugin", "plugin.json"))) {
|
|
2225
2805
|
return bundled;
|
|
2226
2806
|
}
|
|
2227
|
-
const source =
|
|
2228
|
-
if (existsSync3(
|
|
2807
|
+
const source = join6(import.meta.dir, "..", "claude-companion");
|
|
2808
|
+
if (existsSync3(join6(source, ".claude-plugin", "plugin.json"))) {
|
|
2229
2809
|
return source;
|
|
2230
2810
|
}
|
|
2231
2811
|
throw new Error("Agent-smith Claude companion files are missing");
|
|
2232
2812
|
}
|
|
2233
2813
|
function installClaudeCompanion(binDir) {
|
|
2234
2814
|
const sourceDir = claudeCompanionSourceDir();
|
|
2235
|
-
const targetDir =
|
|
2815
|
+
const targetDir = join6(binDir, CLAUDE_COMPANION_DIRNAME);
|
|
2236
2816
|
rmSync2(targetDir, { force: true, recursive: true });
|
|
2237
2817
|
for (const relativePath of CLAUDE_COMPANION_FILES) {
|
|
2238
|
-
const target =
|
|
2239
|
-
mkdirSync3(
|
|
2240
|
-
copyFileSync(
|
|
2818
|
+
const target = join6(targetDir, relativePath);
|
|
2819
|
+
mkdirSync3(dirname3(target), { recursive: true, mode: 448 });
|
|
2820
|
+
copyFileSync(join6(sourceDir, relativePath), target, constants2.COPYFILE_FICLONE);
|
|
2241
2821
|
chmodSync2(target, 384);
|
|
2242
2822
|
}
|
|
2243
2823
|
for (const directory of [
|
|
2244
2824
|
targetDir,
|
|
2245
|
-
|
|
2246
|
-
|
|
2825
|
+
join6(targetDir, ".claude-plugin"),
|
|
2826
|
+
join6(targetDir, "hooks")
|
|
2247
2827
|
]) {
|
|
2248
2828
|
chmodSync2(directory, 448);
|
|
2249
2829
|
}
|
|
@@ -2293,11 +2873,11 @@ async function installClientWrappers(options) {
|
|
|
2293
2873
|
]) {
|
|
2294
2874
|
if (!target)
|
|
2295
2875
|
continue;
|
|
2296
|
-
if (target ===
|
|
2876
|
+
if (target === join6(options.binDir, tool))
|
|
2297
2877
|
throw new Error("A client launcher cannot call itself");
|
|
2298
|
-
const wrapper =
|
|
2878
|
+
const wrapper = join6(options.binDir, tool);
|
|
2299
2879
|
const companionDir = tool === "claude" ? installClaudeCompanion(options.binDir) : "";
|
|
2300
|
-
|
|
2880
|
+
writeFileSync3(wrapper, `#!/bin/sh
|
|
2301
2881
|
${CONFIG_CLIENT_MARKER}
|
|
2302
2882
|
exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, companionDir].map(shellQuote).join(" ")} "$@"
|
|
2303
2883
|
`, { encoding: "utf8", mode: 448 });
|
|
@@ -2311,17 +2891,17 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, comp
|
|
|
2311
2891
|
mkdirSync3(options.binDir, { recursive: true, mode: 448 });
|
|
2312
2892
|
const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
|
|
2313
2893
|
if (options.claudePath) {
|
|
2314
|
-
const claude =
|
|
2894
|
+
const claude = join6(options.binDir, "claude");
|
|
2315
2895
|
const companionDir = installClaudeCompanion(options.binDir);
|
|
2316
|
-
|
|
2896
|
+
writeFileSync3(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true, companionDir), {
|
|
2317
2897
|
encoding: "utf8",
|
|
2318
2898
|
mode: 448
|
|
2319
2899
|
});
|
|
2320
2900
|
chmodSync2(claude, 448);
|
|
2321
2901
|
}
|
|
2322
2902
|
if (options.codexPath) {
|
|
2323
|
-
const codex =
|
|
2324
|
-
|
|
2903
|
+
const codex = join6(options.binDir, "codex");
|
|
2904
|
+
writeFileSync3(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
|
|
2325
2905
|
encoding: "utf8",
|
|
2326
2906
|
mode: 448
|
|
2327
2907
|
});
|
|
@@ -2330,19 +2910,19 @@ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target, comp
|
|
|
2330
2910
|
}
|
|
2331
2911
|
function defaultShellProfile() {
|
|
2332
2912
|
const shell = process.env.SHELL?.split("/").pop();
|
|
2333
|
-
return
|
|
2913
|
+
return join6(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
|
|
2334
2914
|
}
|
|
2335
2915
|
function getLocalRoutingPaths() {
|
|
2336
|
-
const configDir =
|
|
2916
|
+
const configDir = dirname3(resolveConfigPath());
|
|
2337
2917
|
return {
|
|
2338
|
-
binDir:
|
|
2918
|
+
binDir: join6(configDir, "client-bin"),
|
|
2339
2919
|
shellProfile: defaultShellProfile(),
|
|
2340
|
-
statePath:
|
|
2920
|
+
statePath: join6(configDir, "client-routing.json")
|
|
2341
2921
|
};
|
|
2342
2922
|
}
|
|
2343
2923
|
function isExecutable(path) {
|
|
2344
2924
|
try {
|
|
2345
|
-
|
|
2925
|
+
accessSync2(path, constants2.X_OK);
|
|
2346
2926
|
return true;
|
|
2347
2927
|
} catch {
|
|
2348
2928
|
return false;
|
|
@@ -2352,7 +2932,7 @@ function findClientExecutable(name, binDir, path) {
|
|
|
2352
2932
|
for (const directory of path.split(":")) {
|
|
2353
2933
|
if (!directory || directory === binDir)
|
|
2354
2934
|
continue;
|
|
2355
|
-
const candidate =
|
|
2935
|
+
const candidate = join6(directory, name);
|
|
2356
2936
|
if (isExecutable(candidate))
|
|
2357
2937
|
return candidate;
|
|
2358
2938
|
}
|
|
@@ -2362,7 +2942,7 @@ function readSavedClientPaths(statePath) {
|
|
|
2362
2942
|
if (!existsSync3(statePath))
|
|
2363
2943
|
return null;
|
|
2364
2944
|
try {
|
|
2365
|
-
const saved = JSON.parse(
|
|
2945
|
+
const saved = JSON.parse(readFileSync3(statePath, "utf8"));
|
|
2366
2946
|
if (typeof saved === "object" && saved !== null) {
|
|
2367
2947
|
const { claudePath, codexPath } = saved;
|
|
2368
2948
|
const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
|
|
@@ -2380,10 +2960,10 @@ function installedRoutingStatus(paths = {}) {
|
|
|
2380
2960
|
const shellProfile = paths.shellProfile ?? defaults.shellProfile;
|
|
2381
2961
|
let shellProfileHasRouting = false;
|
|
2382
2962
|
try {
|
|
2383
|
-
shellProfileHasRouting = existsSync3(shellProfile) &&
|
|
2963
|
+
shellProfileHasRouting = existsSync3(shellProfile) && readFileSync3(shellProfile, "utf8").includes(ROUTING_BEGIN);
|
|
2384
2964
|
} catch {}
|
|
2385
2965
|
return {
|
|
2386
|
-
enabled: shellProfileHasRouting && (existsSync3(
|
|
2966
|
+
enabled: shellProfileHasRouting && (existsSync3(join6(binDir, "claude")) || existsSync3(join6(binDir, "codex"))),
|
|
2387
2967
|
binDir,
|
|
2388
2968
|
shellProfile
|
|
2389
2969
|
};
|
|
@@ -2400,8 +2980,8 @@ function getLocalRoutingStatus(paths = {}) {
|
|
|
2400
2980
|
}
|
|
2401
2981
|
function configClientWrappersInstalled(paths = {}) {
|
|
2402
2982
|
const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
|
|
2403
|
-
const files = ["claude", "codex"].map((name) =>
|
|
2404
|
-
return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) =>
|
|
2983
|
+
const files = ["claude", "codex"].map((name) => join6(binDir, name)).filter(existsSync3);
|
|
2984
|
+
return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync3(path, "utf8").includes(CONFIG_CLIENT_MARKER));
|
|
2405
2985
|
}
|
|
2406
2986
|
async function launchConfiguredClient(configPath, tool, target, claudeCompanionDir, args) {
|
|
2407
2987
|
if (tool !== "claude" && tool !== "codex")
|
|
@@ -2470,10 +3050,10 @@ async function enableLocalClientRouting(options) {
|
|
|
2470
3050
|
clientConfigPath: options.clientConfigPath,
|
|
2471
3051
|
providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
|
|
2472
3052
|
});
|
|
2473
|
-
const existingProfile = existsSync3(shellProfile) ?
|
|
2474
|
-
|
|
2475
|
-
mkdirSync3(
|
|
2476
|
-
|
|
3053
|
+
const existingProfile = existsSync3(shellProfile) ? readFileSync3(shellProfile, "utf8") : "";
|
|
3054
|
+
writeFileSync3(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
|
|
3055
|
+
mkdirSync3(dirname3(statePath), { recursive: true, mode: 448 });
|
|
3056
|
+
writeFileSync3(statePath, JSON.stringify({ claudePath, codexPath }), {
|
|
2477
3057
|
encoding: "utf8",
|
|
2478
3058
|
mode: 384
|
|
2479
3059
|
});
|
|
@@ -2486,19 +3066,19 @@ function disableLocalClientRouting(paths = {}) {
|
|
|
2486
3066
|
const shellProfile = paths.shellProfile ?? defaults.shellProfile;
|
|
2487
3067
|
const statePath = paths.statePath ?? defaults.statePath;
|
|
2488
3068
|
if (existsSync3(shellProfile)) {
|
|
2489
|
-
|
|
3069
|
+
writeFileSync3(shellProfile, removeRoutingFromShellProfile(readFileSync3(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
|
|
2490
3070
|
}
|
|
2491
3071
|
for (const name of ["claude", "codex"]) {
|
|
2492
|
-
const wrapper =
|
|
3072
|
+
const wrapper = join6(binDir, name);
|
|
2493
3073
|
if (existsSync3(wrapper))
|
|
2494
|
-
|
|
3074
|
+
unlinkSync3(wrapper);
|
|
2495
3075
|
}
|
|
2496
|
-
rmSync2(
|
|
3076
|
+
rmSync2(join6(binDir, CLAUDE_COMPANION_DIRNAME), {
|
|
2497
3077
|
force: true,
|
|
2498
3078
|
recursive: true
|
|
2499
3079
|
});
|
|
2500
3080
|
if (existsSync3(statePath))
|
|
2501
|
-
|
|
3081
|
+
unlinkSync3(statePath);
|
|
2502
3082
|
return getLocalRoutingStatus({ binDir, shellProfile, statePath });
|
|
2503
3083
|
}
|
|
2504
3084
|
function removeRoutingFromShellProfile(profile) {
|