@certalis/agent-smith 0.1.13 → 0.1.15

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.
@@ -0,0 +1,2295 @@
1
+ // @bun
2
+ var __defProp = Object.defineProperty;
3
+ var __export = (target, all) => {
4
+ for (var name in all)
5
+ __defProp(target, name, {
6
+ get: all[name],
7
+ enumerable: true,
8
+ configurable: true,
9
+ set: (newValue) => all[name] = () => newValue
10
+ });
11
+ };
12
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
13
+ var __require = import.meta.require;
14
+
15
+ // ../../packages/core/src/constants.ts
16
+ var TIME_CONSTANTS, BUFFER_SIZES, NETWORK, CACHE, LIMITS, HTTP_STATUS;
17
+ var init_constants = __esm(() => {
18
+ TIME_CONSTANTS = {
19
+ SECOND: 1000,
20
+ MINUTE: 60 * 1000,
21
+ HOUR: 60 * 60 * 1000,
22
+ DAY: 24 * 60 * 60 * 1000,
23
+ SESSION_DURATION_DEFAULT: 5 * 60 * 60 * 1000,
24
+ SESSION_DURATION_FALLBACK: 3600000,
25
+ STREAM_TIMEOUT_DEFAULT: 1000 * 60 * 1,
26
+ OAUTH_STATE_TTL: 10,
27
+ RETRY_DELAY_DEFAULT: 1000,
28
+ CACHE_YEAR: 31536000
29
+ };
30
+ BUFFER_SIZES = {
31
+ STREAM_USAGE_BUFFER_KB: 256,
32
+ STREAM_USAGE_BUFFER_BYTES: 256 * 1024,
33
+ STREAM_BODY_MAX_KB: 256,
34
+ STREAM_BODY_MAX_BYTES: 256 * 1024,
35
+ ANTHROPIC_STREAM_CAP_BYTES: 32768,
36
+ STREAM_TEE_MAX_BYTES: 1024 * 1024,
37
+ LOG_FILE_MAX_SIZE: 10 * 1024 * 1024
38
+ };
39
+ NETWORK = {
40
+ DEFAULT_PORT: 8080,
41
+ IDLE_TIMEOUT_MAX: 255
42
+ };
43
+ CACHE = {
44
+ STATIC_ASSETS_MAX_AGE: 31536000,
45
+ CACHE_CONTROL_IMMUTABLE: "public, max-age=31536000, immutable",
46
+ CACHE_CONTROL_STATIC: "public, max-age=31536000",
47
+ CACHE_CONTROL_NO_CACHE: "no-cache, no-store, must-revalidate"
48
+ };
49
+ LIMITS = {
50
+ REQUEST_HISTORY_DEFAULT: 50,
51
+ REQUEST_DETAILS_DEFAULT: 100,
52
+ REQUEST_HISTORY_MAX: 1000,
53
+ LOG_READ_DEFAULT: 1000,
54
+ ACCOUNT_NAME_MIN_LENGTH: 1,
55
+ ACCOUNT_NAME_MAX_LENGTH: 100,
56
+ CONSOLE_SEPARATOR_LENGTH: 100,
57
+ CONSOLE_COLUMN_PADDING: {
58
+ NAME: 20,
59
+ TYPE: 10,
60
+ TIER: 6,
61
+ REQUESTS: 12,
62
+ TOKEN: 10,
63
+ STATUS: 20
64
+ }
65
+ };
66
+ HTTP_STATUS = {
67
+ OK: 200,
68
+ NOT_FOUND: 404,
69
+ TOO_MANY_REQUESTS: 429,
70
+ INTERNAL_SERVER_ERROR: 500,
71
+ SERVICE_UNAVAILABLE: 503
72
+ };
73
+ });
74
+
75
+ // ../../packages/core/src/container.ts
76
+ class Container {
77
+ services = new Map;
78
+ factories = new Map;
79
+ register(key, factory) {
80
+ this.factories.set(key, factory);
81
+ }
82
+ registerInstance(key, instance) {
83
+ this.services.set(key, instance);
84
+ }
85
+ resolve(key) {
86
+ if (this.services.has(key)) {
87
+ return this.services.get(key);
88
+ }
89
+ const factory = this.factories.get(key);
90
+ if (!factory) {
91
+ throw new Error(`Service '${String(key)}' not registered`);
92
+ }
93
+ const instance = factory();
94
+ this.services.set(key, instance);
95
+ return instance;
96
+ }
97
+ has(key) {
98
+ return this.factories.has(key) || this.services.has(key);
99
+ }
100
+ clear() {
101
+ this.services.clear();
102
+ this.factories.clear();
103
+ }
104
+ }
105
+ var container;
106
+ var init_container = __esm(() => {
107
+ container = new Container;
108
+ });
109
+
110
+ // ../../packages/core/src/di.ts
111
+ var SERVICE_KEYS;
112
+ var init_di = __esm(() => {
113
+ init_container();
114
+ SERVICE_KEYS = {
115
+ Logger: Symbol("Logger"),
116
+ Config: Symbol("Config"),
117
+ Database: Symbol("Database"),
118
+ PricingLogger: Symbol("PricingLogger"),
119
+ AsyncWriter: Symbol("AsyncWriter")
120
+ };
121
+ });
122
+
123
+ // ../../packages/core/src/errors.ts
124
+ function isAppError(error) {
125
+ return error instanceof AppError;
126
+ }
127
+ function logError(error, logger) {
128
+ if (isAppError(error)) {
129
+ const sanitizedContext = error.context ? sanitizeErrorContext(error.context) : undefined;
130
+ logger.error(`${error.name}: ${error.message}`, {
131
+ code: error.code,
132
+ statusCode: error.statusCode,
133
+ context: sanitizedContext
134
+ });
135
+ } else if (error instanceof Error) {
136
+ logger.error(`Error: ${error.message}`, {
137
+ name: error.name,
138
+ stack: error.stack
139
+ });
140
+ } else {
141
+ logger.error("Unknown error", error);
142
+ }
143
+ }
144
+ function sanitizeErrorContext(context) {
145
+ const sanitized = {};
146
+ const sensitiveKeys = ["token", "password", "secret", "key", "authorization"];
147
+ for (const [key, value] of Object.entries(context)) {
148
+ const lowerKey = key.toLowerCase();
149
+ if (sensitiveKeys.some((sensitive) => lowerKey.includes(sensitive))) {
150
+ sanitized[key] = "[REDACTED]";
151
+ } else if (typeof value === "object" && value !== null) {
152
+ sanitized[key] = sanitizeErrorContext(value);
153
+ } else {
154
+ sanitized[key] = value;
155
+ }
156
+ }
157
+ return sanitized;
158
+ }
159
+ var AppError, AuthError, TokenRefreshError, RateLimitError, ValidationError, ProviderError, OAuthError, ServiceUnavailableError;
160
+ var init_errors = __esm(() => {
161
+ AppError = class AppError extends Error {
162
+ code;
163
+ statusCode;
164
+ timestamp;
165
+ context;
166
+ constructor(message, code, statusCode, context) {
167
+ super(message);
168
+ this.code = code;
169
+ this.statusCode = statusCode;
170
+ this.name = this.constructor.name;
171
+ this.timestamp = new Date;
172
+ this.context = context;
173
+ Error.captureStackTrace(this, this.constructor);
174
+ }
175
+ toJSON() {
176
+ return {
177
+ name: this.name,
178
+ message: this.message,
179
+ code: this.code,
180
+ statusCode: this.statusCode,
181
+ timestamp: this.timestamp,
182
+ context: this.context
183
+ };
184
+ }
185
+ };
186
+ AuthError = class AuthError extends AppError {
187
+ constructor(message, context) {
188
+ super(message, "AUTH_ERROR", 401, context);
189
+ }
190
+ };
191
+ TokenRefreshError = class TokenRefreshError extends AuthError {
192
+ originalError;
193
+ constructor(accountId, originalError) {
194
+ super("Failed to refresh access token", {
195
+ accountId,
196
+ originalError: originalError?.message
197
+ });
198
+ this.originalError = originalError;
199
+ }
200
+ };
201
+ RateLimitError = class RateLimitError extends AppError {
202
+ accountId;
203
+ resetTime;
204
+ remaining;
205
+ constructor(accountId, resetTime, remaining) {
206
+ super("Rate limit exceeded", "RATE_LIMIT_ERROR", 429, {
207
+ accountId,
208
+ resetTime,
209
+ remaining
210
+ });
211
+ this.accountId = accountId;
212
+ this.resetTime = resetTime;
213
+ this.remaining = remaining;
214
+ }
215
+ };
216
+ ValidationError = class ValidationError extends AppError {
217
+ field;
218
+ value;
219
+ constructor(message, field, value) {
220
+ super(message, "VALIDATION_ERROR", 400, { field, value });
221
+ this.field = field;
222
+ this.value = value;
223
+ }
224
+ };
225
+ ProviderError = class ProviderError extends AppError {
226
+ provider;
227
+ constructor(message, provider, statusCode = 502, context) {
228
+ super(message, "PROVIDER_ERROR", statusCode, { provider, ...context });
229
+ this.provider = provider;
230
+ }
231
+ };
232
+ OAuthError = class OAuthError extends ProviderError {
233
+ oauthCode;
234
+ constructor(message, provider, oauthCode) {
235
+ super(message, provider, 400, { oauthCode });
236
+ this.oauthCode = oauthCode;
237
+ }
238
+ };
239
+ ServiceUnavailableError = class ServiceUnavailableError extends AppError {
240
+ service;
241
+ retryAfterSeconds;
242
+ constructor(message, service, retryAfterSeconds) {
243
+ super(message, "SERVICE_UNAVAILABLE", 503, { service });
244
+ this.service = service;
245
+ this.retryAfterSeconds = retryAfterSeconds;
246
+ }
247
+ };
248
+ });
249
+
250
+ // ../../packages/core/src/formatters.ts
251
+ function formatCost(cost) {
252
+ if (!cost || cost === 0)
253
+ return "$0.0000";
254
+ return `$${cost.toFixed(4)}`;
255
+ }
256
+
257
+ // ../../packages/core/src/lifecycle.ts
258
+ class LifecycleManager {
259
+ disposables = new Set;
260
+ isShuttingDown = false;
261
+ register(disposable) {
262
+ this.disposables.add(disposable);
263
+ }
264
+ unregister(disposable) {
265
+ this.disposables.delete(disposable);
266
+ }
267
+ async shutdown() {
268
+ if (this.isShuttingDown) {
269
+ return;
270
+ }
271
+ this.isShuttingDown = true;
272
+ const errors = [];
273
+ const disposableArray = Array.from(this.disposables).reverse();
274
+ for (const disposable of disposableArray) {
275
+ try {
276
+ await disposable.dispose();
277
+ } catch (error) {
278
+ errors.push(error instanceof Error ? error : new Error(`Disposal error: ${String(error)}`));
279
+ }
280
+ }
281
+ this.disposables.clear();
282
+ this.isShuttingDown = false;
283
+ if (errors.length > 0) {
284
+ throw new AggregateError(errors, "Errors occurred during shutdown");
285
+ }
286
+ }
287
+ }
288
+ function registerDisposable(disposable) {
289
+ lifecycleManager.register(disposable);
290
+ }
291
+ function unregisterDisposable(disposable) {
292
+ lifecycleManager.unregister(disposable);
293
+ }
294
+ async function shutdown() {
295
+ await lifecycleManager.shutdown();
296
+ }
297
+ var lifecycleManager;
298
+ var init_lifecycle = __esm(() => {
299
+ lifecycleManager = new LifecycleManager;
300
+ });
301
+
302
+ // ../../packages/core/src/models.ts
303
+ function normalizeModelId(modelId) {
304
+ return modelId.trim().replace(PROVIDER_PREFIX_RE, "").replace(LATEST_SUFFIX_RE, "").replace(DATE_SUFFIX_RE, "");
305
+ }
306
+ function getModelShortName(modelId) {
307
+ const normalized = normalizeModelId(modelId);
308
+ return normalized || modelId;
309
+ }
310
+ var PROVIDER_PREFIX_RE, DATE_SUFFIX_RE, LATEST_SUFFIX_RE;
311
+ var init_models = __esm(() => {
312
+ PROVIDER_PREFIX_RE = /^(anthropic|openai|codex|claude-code|google|xai|zai)\//;
313
+ DATE_SUFFIX_RE = /-\d{8}$/;
314
+ LATEST_SUFFIX_RE = /-latest$/;
315
+ });
316
+
317
+ // ../../packages/core/src/pricing.ts
318
+ import { promises as fs } from "fs";
319
+ import { tmpdir } from "os";
320
+ import { join } from "path";
321
+
322
+ class PriceCatalogue {
323
+ static instance;
324
+ priceData = null;
325
+ lastFetch = 0;
326
+ warnedModels = new Set;
327
+ logger = null;
328
+ constructor() {}
329
+ setLogger(logger) {
330
+ this.logger = logger;
331
+ }
332
+ static get() {
333
+ if (!PriceCatalogue.instance) {
334
+ PriceCatalogue.instance = new PriceCatalogue;
335
+ }
336
+ return PriceCatalogue.instance;
337
+ }
338
+ getCacheDir() {
339
+ return join(tmpdir(), "agent-smith");
340
+ }
341
+ getCachePath() {
342
+ return join(this.getCacheDir(), "models.dev.json");
343
+ }
344
+ getCacheDurationMs() {
345
+ const hours = Number(process.env.AGENT_SMITH_PRICING_REFRESH_HOURS) || 24;
346
+ return hours * TIME_CONSTANTS.HOUR;
347
+ }
348
+ async ensureCacheDir() {
349
+ try {
350
+ await fs.mkdir(this.getCacheDir(), { recursive: true });
351
+ } catch (error) {
352
+ this.logger?.warn("Failed to create cache directory: %s", error);
353
+ }
354
+ }
355
+ async loadFromCache() {
356
+ try {
357
+ const cachePath = this.getCachePath();
358
+ const stats = await fs.stat(cachePath);
359
+ const age = Date.now() - stats.mtime.getTime();
360
+ if (age < this.getCacheDurationMs()) {
361
+ const content = await fs.readFile(cachePath, "utf-8");
362
+ return JSON.parse(content);
363
+ }
364
+ } catch {}
365
+ return null;
366
+ }
367
+ async saveToCache(data) {
368
+ try {
369
+ await this.ensureCacheDir();
370
+ const cachePath = this.getCachePath();
371
+ await fs.writeFile(cachePath, JSON.stringify(data, null, 2));
372
+ } catch (error) {
373
+ this.logger?.warn("Failed to save pricing cache: %s", error);
374
+ }
375
+ }
376
+ async fetchRemote() {
377
+ try {
378
+ const response = await fetch("https://models.dev/api.json");
379
+ if (!response.ok) {
380
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
381
+ }
382
+ const data = await response.json();
383
+ await this.saveToCache(data);
384
+ return data;
385
+ } catch (error) {
386
+ this.logger?.warn("Failed to fetch pricing data: %s", error);
387
+ return null;
388
+ }
389
+ }
390
+ async getPricing() {
391
+ if (this.priceData && Date.now() - this.lastFetch < this.getCacheDurationMs()) {
392
+ return this.priceData;
393
+ }
394
+ let data = await this.fetchRemote();
395
+ if (!data) {
396
+ data = await this.loadFromCache();
397
+ }
398
+ if (!data) {
399
+ data = {};
400
+ }
401
+ this.priceData = data;
402
+ this.lastFetch = Date.now();
403
+ return data;
404
+ }
405
+ warnOnce(modelId) {
406
+ if (!this.warnedModels.has(modelId)) {
407
+ this.warnedModels.add(modelId);
408
+ this.logger?.warn("Price for model %s not found - cost set to 0", modelId);
409
+ }
410
+ }
411
+ }
412
+ function setPricingLogger(logger) {
413
+ PriceCatalogue.get().setLogger(logger);
414
+ }
415
+ function findModelCost(pricing, modelId) {
416
+ for (const provider of Object.values(pricing)) {
417
+ const model = provider.models?.[modelId];
418
+ if (model?.cost) {
419
+ return model.cost;
420
+ }
421
+ }
422
+ return null;
423
+ }
424
+ async function estimateCostUSD(modelId, tokens) {
425
+ const catalogue = PriceCatalogue.get();
426
+ try {
427
+ const pricing = await catalogue.getPricing();
428
+ const normalizedModelId = modelId.trim();
429
+ if (!normalizedModelId) {
430
+ throw new Error("Model id is empty");
431
+ }
432
+ const cost = findModelCost(pricing, normalizedModelId);
433
+ if (!cost) {
434
+ throw new Error(`Model ${normalizedModelId} not found in pricing catalogue`);
435
+ }
436
+ let totalCost = 0;
437
+ if (tokens.inputTokens && cost.input !== undefined) {
438
+ totalCost += tokens.inputTokens * (cost.input / 1e6);
439
+ }
440
+ if (tokens.outputTokens && cost.output !== undefined) {
441
+ totalCost += tokens.outputTokens * (cost.output / 1e6);
442
+ }
443
+ if (tokens.cacheReadInputTokens && cost.cache_read !== undefined) {
444
+ totalCost += tokens.cacheReadInputTokens * (cost.cache_read / 1e6);
445
+ }
446
+ if (tokens.cacheCreationInputTokens && cost.cache_write !== undefined) {
447
+ totalCost += tokens.cacheCreationInputTokens * (cost.cache_write / 1e6);
448
+ }
449
+ return totalCost;
450
+ } catch (_error) {
451
+ catalogue.warnOnce(modelId);
452
+ return 0;
453
+ }
454
+ }
455
+ var init_pricing = __esm(() => {
456
+ init_constants();
457
+ });
458
+
459
+ // ../../packages/core/src/request-events.ts
460
+ import { EventEmitter } from "events";
461
+ var RequestEventBus, requestEvents;
462
+ var init_request_events = __esm(() => {
463
+ RequestEventBus = class RequestEventBus extends EventEmitter {
464
+ };
465
+ requestEvents = new RequestEventBus;
466
+ });
467
+
468
+ // ../../packages/types/src/account.ts
469
+ function normalizeRateLimitCode(account, now) {
470
+ if (account.paused) {
471
+ return "paused";
472
+ }
473
+ if (account.rate_limit_status) {
474
+ return account.rate_limit_status;
475
+ }
476
+ if (account.rate_limited_until && account.rate_limited_until > now) {
477
+ return "rate_limited";
478
+ }
479
+ return "ok";
480
+ }
481
+ function getAccountRateLimitInfo(account, now = Date.now()) {
482
+ const limitedUntil = account.rate_limited_until && account.rate_limited_until > now ? account.rate_limited_until : null;
483
+ return {
484
+ code: normalizeRateLimitCode(account, now),
485
+ isLimited: account.paused ? false : limitedUntil !== null,
486
+ until: limitedUntil,
487
+ resetAt: account.rate_limit_reset ?? null,
488
+ remaining: account.rate_limit_remaining ?? null
489
+ };
490
+ }
491
+ function getAccountSessionInfo(account) {
492
+ return {
493
+ active: account.session_start !== null,
494
+ startedAt: account.session_start ?? null,
495
+ requestCount: account.session_request_count
496
+ };
497
+ }
498
+ function getAccountTokenStatus(account, now = Date.now()) {
499
+ if (account.expires_at !== null) {
500
+ return account.expires_at > now ? "valid" : "expired";
501
+ }
502
+ return account.access_token ? "valid" : "expired";
503
+ }
504
+ // ../../packages/types/src/conversation.ts
505
+ var init_conversation = () => {};
506
+
507
+ // ../../packages/types/src/guards.ts
508
+ function isRecord(value) {
509
+ return typeof value === "object" && value !== null && !Array.isArray(value);
510
+ }
511
+ function isFiniteNumber(value) {
512
+ return typeof value === "number" && Number.isFinite(value);
513
+ }
514
+
515
+ // ../../packages/types/src/conversation-links.ts
516
+ function decodeBase64Utf8(value) {
517
+ if (!value || value === "[streamed]") {
518
+ return null;
519
+ }
520
+ try {
521
+ if (typeof Buffer !== "undefined") {
522
+ return Buffer.from(value, "base64").toString("utf8");
523
+ }
524
+ if (typeof atob === "function") {
525
+ const binary = atob(value);
526
+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
527
+ return new TextDecoder("utf-8").decode(bytes);
528
+ }
529
+ } catch {}
530
+ return null;
531
+ }
532
+ function extractResponseIdFromRecord(record) {
533
+ if (typeof record.id === "string") {
534
+ return record.id;
535
+ }
536
+ if (isRecord(record.response) && typeof record.response.id === "string") {
537
+ return record.response.id;
538
+ }
539
+ return null;
540
+ }
541
+ function extractPreviousResponseId(requestBody) {
542
+ if (!requestBody) {
543
+ return null;
544
+ }
545
+ try {
546
+ const parsed = JSON.parse(requestBody);
547
+ if (!isRecord(parsed)) {
548
+ return null;
549
+ }
550
+ return typeof parsed.previous_response_id === "string" ? parsed.previous_response_id : null;
551
+ } catch {
552
+ return null;
553
+ }
554
+ }
555
+ function extractResponseId(responseBody) {
556
+ if (!responseBody) {
557
+ return null;
558
+ }
559
+ try {
560
+ const parsed = JSON.parse(responseBody);
561
+ if (isRecord(parsed)) {
562
+ return extractResponseIdFromRecord(parsed);
563
+ }
564
+ } catch {}
565
+ for (const line of responseBody.split(`
566
+ `)) {
567
+ if (!line.startsWith("data:")) {
568
+ continue;
569
+ }
570
+ const dataStr = line.slice(5).trim();
571
+ if (!dataStr || dataStr === "[DONE]") {
572
+ continue;
573
+ }
574
+ try {
575
+ const parsed = JSON.parse(dataStr);
576
+ if (isRecord(parsed)) {
577
+ const responseId = extractResponseIdFromRecord(parsed);
578
+ if (responseId) {
579
+ return responseId;
580
+ }
581
+ }
582
+ } catch {}
583
+ }
584
+ return null;
585
+ }
586
+ function extractClientSessionIdFromHeaders(headers) {
587
+ if (!headers) {
588
+ return null;
589
+ }
590
+ const value = headers[CLAUDE_CODE_SESSION_ID_HEADER];
591
+ return typeof value === "string" ? value : null;
592
+ }
593
+ function extractRequestLinkageFromPayload(payload) {
594
+ if (!isRecord(payload)) {
595
+ return {
596
+ previousResponseId: null,
597
+ responseId: null,
598
+ clientSessionId: null
599
+ };
600
+ }
601
+ const requestBody = isRecord(payload.request) ? decodeBase64Utf8(typeof payload.request.body === "string" ? payload.request.body : null) : null;
602
+ const responseBody = isRecord(payload.response) ? decodeBase64Utf8(typeof payload.response.body === "string" ? payload.response.body : null) : null;
603
+ const requestHeaders = isRecord(payload.request) && isRecord(payload.request.headers) ? payload.request.headers : null;
604
+ return {
605
+ previousResponseId: extractPreviousResponseId(requestBody),
606
+ responseId: extractResponseId(responseBody),
607
+ clientSessionId: extractClientSessionIdFromHeaders(requestHeaders)
608
+ };
609
+ }
610
+ var CLAUDE_CODE_SESSION_ID_HEADER = "x-claude-code-session-id";
611
+ var init_conversation_links = () => {};
612
+
613
+ // ../../packages/types/src/logging.ts
614
+ function isLogLevel(value) {
615
+ return LOG_LEVELS.includes(value);
616
+ }
617
+ function isLogEvent(value) {
618
+ return isRecord(value) && isFiniteNumber(value.ts) && typeof value.level === "string" && isLogLevel(value.level) && typeof value.msg === "string";
619
+ }
620
+ var LOG_LEVELS;
621
+ var init_logging = __esm(() => {
622
+ LOG_LEVELS = ["DEBUG", "INFO", "WARN", "ERROR"];
623
+ });
624
+
625
+ // ../../packages/types/src/provider-metadata.ts
626
+ function isAccountProvider(value) {
627
+ return Object.hasOwn(PROVIDER_METADATA_MAP, value);
628
+ }
629
+ function isAuthMethod(value) {
630
+ return AUTH_METHODS.includes(value);
631
+ }
632
+ function isProviderWire(value) {
633
+ return PROVIDER_WIRES.includes(value);
634
+ }
635
+ function isApiKeyProvider(value) {
636
+ return isAccountProvider(value) && PROVIDER_METADATA_MAP[value].authMethod === "api_key";
637
+ }
638
+ function isOAuthProvider(value) {
639
+ return isAccountProvider(value) && PROVIDER_METADATA_MAP[value].authMethod === "oauth";
640
+ }
641
+ function getProviderDisplayLabel(provider) {
642
+ return isAccountProvider(provider) ? PROVIDER_METADATA_MAP[provider].displayLabel : provider;
643
+ }
644
+ function getProviderDefaultBaseUrl(provider) {
645
+ return PROVIDER_METADATA_MAP[provider].defaultBaseUrl;
646
+ }
647
+ var PROVIDER_WIRES, PROVIDER_METADATA_MAP, providerNames, authMethods, providerOptions, ACCOUNT_PROVIDERS, AUTH_METHODS, API_KEY_PROVIDERS, OAUTH_PROVIDERS;
648
+ var init_provider_metadata = __esm(() => {
649
+ PROVIDER_WIRES = [
650
+ "anthropic-messages",
651
+ "openai-responses"
652
+ ];
653
+ PROVIDER_METADATA_MAP = {
654
+ anthropic: {
655
+ displayLabel: "Anthropic",
656
+ authMethod: "api_key",
657
+ supportsOAuth: false,
658
+ supportsWebSocket: false,
659
+ defaultBaseUrl: "https://api.anthropic.com",
660
+ specialRequirements: []
661
+ },
662
+ openai: {
663
+ displayLabel: "OpenAI",
664
+ authMethod: "api_key",
665
+ supportsOAuth: false,
666
+ supportsWebSocket: false,
667
+ defaultBaseUrl: "https://api.openai.com/v1",
668
+ specialRequirements: []
669
+ },
670
+ "claude-code": {
671
+ displayLabel: "Claude Code",
672
+ authMethod: "oauth",
673
+ supportsOAuth: true,
674
+ supportsWebSocket: false,
675
+ defaultBaseUrl: "https://api.anthropic.com",
676
+ specialRequirements: ["Requires Claude Code OAuth authentication"]
677
+ },
678
+ codex: {
679
+ displayLabel: "Codex",
680
+ authMethod: "oauth",
681
+ supportsOAuth: true,
682
+ supportsWebSocket: true,
683
+ defaultBaseUrl: "https://chatgpt.com/backend-api/codex",
684
+ specialRequirements: ["Requires Codex OAuth authentication"]
685
+ }
686
+ };
687
+ providerNames = Object.freeze(Object.keys(PROVIDER_METADATA_MAP));
688
+ authMethods = Object.freeze(Array.from(new Set(providerNames.map((provider) => PROVIDER_METADATA_MAP[provider].authMethod))));
689
+ providerOptions = Object.freeze(providerNames.map((provider) => ({
690
+ value: provider,
691
+ label: PROVIDER_METADATA_MAP[provider].displayLabel
692
+ })));
693
+ ACCOUNT_PROVIDERS = providerNames;
694
+ AUTH_METHODS = authMethods;
695
+ API_KEY_PROVIDERS = Object.freeze(ACCOUNT_PROVIDERS.filter((provider) => isApiKeyProvider(provider)));
696
+ OAUTH_PROVIDERS = Object.freeze(ACCOUNT_PROVIDERS.filter((provider) => isOAuthProvider(provider)));
697
+ });
698
+
699
+ // ../../packages/types/src/quota.ts
700
+ function quotaThresholdFor(account, bucket, fleetThreshold) {
701
+ const threshold = account.switch_threshold;
702
+ if (typeof threshold === "number")
703
+ return threshold;
704
+ return threshold?.[bucket] ?? threshold?.default ?? fleetThreshold;
705
+ }
706
+ function isCurrentQuotaWindow(window, now) {
707
+ return (window.resetAt === null || window.resetAt > now) && now - window.seenAt <= QUOTA_STALE_MS;
708
+ }
709
+ function isOpenQuotaWindow(window, now) {
710
+ return window.resetAt === null ? isCurrentQuotaWindow(window, now) : window.resetAt > now;
711
+ }
712
+ var QUOTA_STALE_MS;
713
+ var init_quota = __esm(() => {
714
+ QUOTA_STALE_MS = 30 * 60000;
715
+ });
716
+
717
+ // ../../packages/types/src/request.ts
718
+ function isOptionalNullableNumber(value) {
719
+ return value === undefined || value === null || isFiniteNumber(value);
720
+ }
721
+ function isNullableNumber(value) {
722
+ return value === null || isFiniteNumber(value);
723
+ }
724
+ function isOptionalString(value) {
725
+ return value === undefined || typeof value === "string";
726
+ }
727
+ function isOptionalNullableString(value) {
728
+ return value === undefined || value === null || typeof value === "string";
729
+ }
730
+ function isNullableString(value) {
731
+ return value === null || typeof value === "string";
732
+ }
733
+ function isNullableBoolean(value) {
734
+ return value === null || typeof value === "boolean";
735
+ }
736
+ function isStringRecord(value) {
737
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
738
+ }
739
+ function isTokenCurveSampleArray(value) {
740
+ return Array.isArray(value) && value.every((sample) => isRecord(sample) && isFiniteNumber(sample.chunkIndex) && isFiniteNumber(sample.tokenDelta) && isFiniteNumber(sample.timestamp));
741
+ }
742
+ function isHttpMethod(value) {
743
+ return HTTP_METHODS.includes(value);
744
+ }
745
+ function toRequestSummary(request) {
746
+ return {
747
+ id: request.id,
748
+ timestamp: new Date(request.timestamp).toISOString(),
749
+ method: request.method,
750
+ path: request.path,
751
+ provider: request.provider,
752
+ upstreamPath: request.upstreamPath,
753
+ accountUsed: request.accountUsed,
754
+ accountName: null,
755
+ statusCode: request.statusCode,
756
+ success: request.success,
757
+ errorMessage: request.errorMessage,
758
+ responseTimeMs: request.responseTimeMs,
759
+ failoverAttempts: request.failoverAttempts,
760
+ model: request.model ?? null,
761
+ promptTokens: request.promptTokens ?? null,
762
+ completionTokens: request.completionTokens ?? null,
763
+ totalTokens: request.totalTokens ?? null,
764
+ inputTokens: request.inputTokens ?? null,
765
+ cacheReadInputTokens: request.cacheReadInputTokens ?? null,
766
+ cacheCreationInputTokens: request.cacheCreationInputTokens ?? null,
767
+ outputTokens: request.outputTokens ?? null,
768
+ reasoningTokens: request.reasoningTokens ?? null,
769
+ costUsd: request.costUsd ?? null,
770
+ tokensPerSecond: request.tokensPerSecond ?? null,
771
+ ttftMs: request.ttftMs ?? null,
772
+ proxyOverheadMs: request.proxyOverheadMs ?? null,
773
+ upstreamTtfbMs: request.upstreamTtfbMs ?? null,
774
+ streamingDurationMs: request.streamingDurationMs ?? null,
775
+ responseId: request.responseId ?? null,
776
+ previousResponseId: request.previousResponseId ?? null,
777
+ responseChainId: request.responseChainId ?? null,
778
+ clientSessionId: request.clientSessionId ?? null
779
+ };
780
+ }
781
+ function isRequestSummary(value) {
782
+ if (!isRecord(value)) {
783
+ return false;
784
+ }
785
+ return typeof value.id === "string" && typeof value.timestamp === "string" && typeof value.method === "string" && isHttpMethod(value.method) && typeof value.path === "string" && typeof value.provider === "string" && value.provider.length > 0 && typeof value.upstreamPath === "string" && (value.accountUsed === null || typeof value.accountUsed === "string") && (value.accountName === null || typeof value.accountName === "string") && isOptionalNullableNumber(value.statusCode) && isNullableBoolean(value.success) && isOptionalNullableString(value.errorMessage) && isOptionalNullableNumber(value.responseTimeMs) && isFiniteNumber(value.failoverAttempts) && isNullableString(value.model) && isNullableNumber(value.promptTokens) && isNullableNumber(value.completionTokens) && isNullableNumber(value.totalTokens) && isNullableNumber(value.inputTokens) && isNullableNumber(value.cacheReadInputTokens) && isNullableNumber(value.cacheCreationInputTokens) && isNullableNumber(value.outputTokens) && isNullableNumber(value.reasoningTokens) && isNullableNumber(value.costUsd) && isNullableNumber(value.tokensPerSecond) && isNullableNumber(value.ttftMs) && isNullableNumber(value.proxyOverheadMs) && isNullableNumber(value.upstreamTtfbMs) && isNullableNumber(value.streamingDurationMs) && isNullableString(value.responseId) && isNullableString(value.previousResponseId) && isNullableString(value.responseChainId) && isNullableString(value.clientSessionId);
786
+ }
787
+ function isRequestPayload(value) {
788
+ if (!isRecord(value) || !isRecord(value.request) || !isRecord(value.meta) || !isRecord(value.meta.trace) || !isRecord(value.meta.account) || !isRecord(value.meta.transport)) {
789
+ return false;
790
+ }
791
+ const { request, response, meta } = value;
792
+ const trace = meta.trace;
793
+ const account = meta.account;
794
+ const transport = meta.transport;
795
+ if (!isStringRecord(request.headers) || isOptionalNullableString(request.body) === false) {
796
+ return false;
797
+ }
798
+ if (response !== null && (!isRecord(response) || !isFiniteNumber(response.status) || !isStringRecord(response.headers) || isOptionalNullableString(response.body) === false)) {
799
+ return false;
800
+ }
801
+ return typeof value.id === "string" && isOptionalString(value.error) && isFiniteNumber(trace.timestamp) && (trace.provider === undefined || typeof trace.provider === "string" && trace.provider.length > 0) && (trace.upstreamPath === undefined || typeof trace.upstreamPath === "string") && (trace.path === undefined || typeof trace.path === "string") && (trace.method === undefined || typeof trace.method === "string" && isHttpMethod(trace.method)) && isOptionalNullableString(trace.responseId) && isOptionalNullableString(trace.previousResponseId) && isOptionalNullableString(trace.responseChainId) && isOptionalNullableString(trace.clientSessionId) && (account.id === null || typeof account.id === "string") && (account.name === undefined || account.name === null || typeof account.name === "string") && (transport.success === undefined || typeof transport.success === "boolean") && (transport.rateLimited === undefined || typeof transport.rateLimited === "boolean") && (transport.accountsAttempted === undefined || isFiniteNumber(transport.accountsAttempted)) && (transport.pending === undefined || typeof transport.pending === "boolean") && (transport.retry === undefined || isFiniteNumber(transport.retry)) && (transport.isStream === undefined || typeof transport.isStream === "boolean") && isOptionalNullableNumber(transport.ttftMs) && isOptionalNullableNumber(transport.proxyOverheadMs) && isOptionalNullableNumber(transport.upstreamTtfbMs) && isOptionalNullableNumber(transport.streamingDurationMs) && (transport.tokenCurve === undefined || transport.tokenCurve === null || isTokenCurveSampleArray(transport.tokenCurve));
802
+ }
803
+ function parseRequestPayload(value) {
804
+ if (isRequestPayload(value)) {
805
+ return value;
806
+ }
807
+ return null;
808
+ }
809
+ var HTTP_METHODS, NO_ACCOUNT_ID = "no_account";
810
+ var init_request = __esm(() => {
811
+ HTTP_METHODS = Object.freeze([
812
+ "GET",
813
+ "POST",
814
+ "PUT",
815
+ "PATCH",
816
+ "DELETE",
817
+ "OPTIONS",
818
+ "HEAD",
819
+ "WS"
820
+ ]);
821
+ });
822
+
823
+ // ../../packages/types/src/request-events.ts
824
+ function isRequestStreamEvent(value) {
825
+ if (!isRecord(value) || typeof value.type !== "string") {
826
+ return false;
827
+ }
828
+ switch (value.type) {
829
+ case "ingress":
830
+ return typeof value.id === "string" && isFiniteNumber(value.timestamp) && typeof value.method === "string" && isHttpMethod(value.method) && typeof value.path === "string";
831
+ case "start":
832
+ return typeof value.id === "string" && isFiniteNumber(value.timestamp) && typeof value.method === "string" && isHttpMethod(value.method) && typeof value.path === "string" && (value.accountId === null || typeof value.accountId === "string") && isFiniteNumber(value.statusCode);
833
+ case "summary":
834
+ return isRequestSummary(value.payload);
835
+ case "payload":
836
+ return isRequestPayload(value.payload);
837
+ default:
838
+ return false;
839
+ }
840
+ }
841
+ var init_request_events2 = __esm(() => {
842
+ init_request();
843
+ });
844
+
845
+ // ../../packages/types/src/stats.ts
846
+ function isTimeRange(value) {
847
+ return TIME_RANGES.includes(value);
848
+ }
849
+ function isAnalyticsMode(value) {
850
+ return ANALYTICS_MODES.includes(value);
851
+ }
852
+ function isAnalyticsStatusFilter(value) {
853
+ return ANALYTICS_STATUS_FILTERS.includes(value);
854
+ }
855
+ var TIME_RANGES, ANALYTICS_MODES, ANALYTICS_STATUS_FILTERS;
856
+ var init_stats = __esm(() => {
857
+ TIME_RANGES = Object.freeze([
858
+ "1h",
859
+ "6h",
860
+ "24h",
861
+ "7d",
862
+ "30d"
863
+ ]);
864
+ ANALYTICS_MODES = Object.freeze([
865
+ "normal",
866
+ "cumulative"
867
+ ]);
868
+ ANALYTICS_STATUS_FILTERS = Object.freeze([
869
+ "all",
870
+ "success",
871
+ "error"
872
+ ]);
873
+ });
874
+
875
+ // ../../packages/types/src/strategy.ts
876
+ function isLbStrategy(value) {
877
+ return LB_STRATEGIES.includes(value);
878
+ }
879
+ var StrategyName, LB_STRATEGIES;
880
+ var init_strategy = __esm(() => {
881
+ StrategyName = {
882
+ Session: "session"
883
+ };
884
+ LB_STRATEGIES = Object.freeze(Object.values(StrategyName));
885
+ });
886
+
887
+ // ../../packages/types/src/index.ts
888
+ var init_src = __esm(() => {
889
+ init_conversation();
890
+ init_conversation_links();
891
+ init_logging();
892
+ init_provider_metadata();
893
+ init_quota();
894
+ init_request();
895
+ init_request_events2();
896
+ init_stats();
897
+ init_strategy();
898
+ });
899
+
900
+ // ../../packages/core/src/strategy.ts
901
+ function isValidStrategy(strategy2) {
902
+ return isLbStrategy(strategy2);
903
+ }
904
+ function isAccountAvailable(account2, now = Date.now()) {
905
+ return !account2.paused && (!account2.rate_limited_until || account2.rate_limited_until < now);
906
+ }
907
+ var DEFAULT_STRATEGY;
908
+ var init_strategy2 = __esm(() => {
909
+ init_src();
910
+ DEFAULT_STRATEGY = StrategyName.Session;
911
+ });
912
+
913
+ // ../../packages/core/src/validation.ts
914
+ function validateString(value, field, options = {}) {
915
+ if (value === undefined || value === null) {
916
+ if (options.required) {
917
+ throw new ValidationError(`${field} is required`, field);
918
+ }
919
+ return;
920
+ }
921
+ if (typeof value !== "string") {
922
+ throw new ValidationError(`${field} must be a string`, field, value);
923
+ }
924
+ const sanitized = options.transform ? options.transform(value) : value;
925
+ if (options.minLength !== undefined && sanitized.length < options.minLength) {
926
+ throw new ValidationError(`${field} must be at least ${options.minLength} characters long`, field, value);
927
+ }
928
+ if (options.maxLength !== undefined && sanitized.length > options.maxLength) {
929
+ throw new ValidationError(`${field} must be at most ${options.maxLength} characters long`, field, value);
930
+ }
931
+ if (options.pattern && !options.pattern.test(sanitized)) {
932
+ throw new ValidationError(`${field} has an invalid format`, field, value);
933
+ }
934
+ if (options.allowedValues && !options.allowedValues.includes(sanitized)) {
935
+ throw new ValidationError(`${field} must be one of: ${options.allowedValues.join(", ")}`, field, value);
936
+ }
937
+ return sanitized;
938
+ }
939
+ function validateNumber(value, field, options = {}) {
940
+ if (value === undefined || value === null) {
941
+ if (options.required) {
942
+ throw new ValidationError(`${field} is required`, field);
943
+ }
944
+ return;
945
+ }
946
+ let num;
947
+ if (typeof value === "string") {
948
+ num = Number(value);
949
+ if (Number.isNaN(num)) {
950
+ throw new ValidationError(`${field} must be a valid number`, field, value);
951
+ }
952
+ } else if (typeof value === "number") {
953
+ num = value;
954
+ } else {
955
+ throw new ValidationError(`${field} must be a number`, field, value);
956
+ }
957
+ if (options.integer && !Number.isInteger(num)) {
958
+ throw new ValidationError(`${field} must be an integer`, field, value);
959
+ }
960
+ if (options.min !== undefined && num < options.min) {
961
+ throw new ValidationError(`${field} must be at least ${options.min}`, field, value);
962
+ }
963
+ if (options.max !== undefined && num > options.max) {
964
+ throw new ValidationError(`${field} must be at most ${options.max}`, field, value);
965
+ }
966
+ if (options.allowedValues && !options.allowedValues.includes(num)) {
967
+ throw new ValidationError(`${field} must be one of: ${options.allowedValues.join(", ")}`, field, value);
968
+ }
969
+ return num;
970
+ }
971
+ var sanitizers, patterns;
972
+ var init_validation = __esm(() => {
973
+ init_errors();
974
+ sanitizers = {
975
+ trim: (value) => value.trim(),
976
+ lowercase: (value) => value.toLowerCase(),
977
+ uppercase: (value) => value.toUpperCase(),
978
+ removeWhitespace: (value) => value.replace(/\s+/g, ""),
979
+ alphanumeric: (value) => value.replace(/[^a-zA-Z0-9]/g, ""),
980
+ alphanumericWithSpaces: (value) => value.replace(/[^a-zA-Z0-9\s]/g, ""),
981
+ email: (value) => value.trim().toLowerCase(),
982
+ url: (value) => {
983
+ try {
984
+ const parsed = new URL(value);
985
+ return parsed.toString();
986
+ } catch {
987
+ throw new ValidationError("Invalid URL format", "url", value);
988
+ }
989
+ }
990
+ };
991
+ patterns = {
992
+ email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
993
+ uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
994
+ alphanumeric: /^[a-zA-Z0-9]+$/,
995
+ alphanumericWithSpaces: /^[a-zA-Z0-9\s]+$/,
996
+ accountName: /^[a-zA-Z0-9\s\-_@.+]+$/,
997
+ apiPath: /^\/v1\/[a-zA-Z0-9\-_/]*$/
998
+ };
999
+ });
1000
+
1001
+ // ../../packages/core/src/index.ts
1002
+ var init_src2 = __esm(() => {
1003
+ init_constants();
1004
+ init_di();
1005
+ init_errors();
1006
+ init_models();
1007
+ init_pricing();
1008
+ init_validation();
1009
+ init_lifecycle();
1010
+ init_request_events();
1011
+ init_strategy2();
1012
+ });
1013
+
1014
+ // ../../packages/logger/src/file-writer.ts
1015
+ import {
1016
+ createWriteStream,
1017
+ existsSync,
1018
+ mkdirSync,
1019
+ statSync,
1020
+ unlinkSync
1021
+ } from "fs";
1022
+ import { tmpdir as tmpdir2 } from "os";
1023
+ import { join as join2 } from "path";
1024
+ function writeToStderr(message, error) {
1025
+ if (typeof process === "undefined") {
1026
+ return;
1027
+ }
1028
+ const formattedError = error instanceof Error ? error.stack ?? error.message : String(error);
1029
+ process.stderr?.write?.(`${message}: ${formattedError}
1030
+ `);
1031
+ }
1032
+
1033
+ class LogFileWriter {
1034
+ logDir;
1035
+ logFile;
1036
+ stream = null;
1037
+ maxFileSize = BUFFER_SIZES.LOG_FILE_MAX_SIZE;
1038
+ constructor() {
1039
+ this.logDir = join2(tmpdir2(), "agent-smith-logs");
1040
+ if (!existsSync(this.logDir)) {
1041
+ mkdirSync(this.logDir, { recursive: true });
1042
+ }
1043
+ this.logFile = join2(this.logDir, "app.log");
1044
+ this.initStream();
1045
+ }
1046
+ initStream() {
1047
+ if (existsSync(this.logFile)) {
1048
+ const stats2 = statSync(this.logFile);
1049
+ if (stats2.size > this.maxFileSize) {
1050
+ this.rotateLog();
1051
+ }
1052
+ }
1053
+ this.stream = createWriteStream(this.logFile, { flags: "a" });
1054
+ }
1055
+ rotateLog() {
1056
+ if (this.stream) {
1057
+ this.stream.end();
1058
+ }
1059
+ if (existsSync(this.logFile)) {
1060
+ try {
1061
+ unlinkSync(this.logFile);
1062
+ } catch (_e) {
1063
+ writeToStderr("Failed to rotate log", _e);
1064
+ }
1065
+ }
1066
+ }
1067
+ write(event) {
1068
+ if (!this.stream || this.stream.destroyed) {
1069
+ this.initStream();
1070
+ }
1071
+ const line = `${JSON.stringify(event)}
1072
+ `;
1073
+ if (this.stream) {
1074
+ this.stream.write(line);
1075
+ }
1076
+ }
1077
+ async readLogs(limit = LIMITS.LOG_READ_DEFAULT) {
1078
+ if (!existsSync(this.logFile)) {
1079
+ return [];
1080
+ }
1081
+ try {
1082
+ const content = await Bun.file(this.logFile).text();
1083
+ const lines = content.trim().split(`
1084
+ `).filter(Boolean);
1085
+ return lines.slice(-limit).map((line) => {
1086
+ try {
1087
+ return JSON.parse(line);
1088
+ } catch {
1089
+ return null;
1090
+ }
1091
+ }).filter((log) => log !== null);
1092
+ } catch (_e) {
1093
+ writeToStderr("Failed to read logs", _e);
1094
+ return [];
1095
+ }
1096
+ }
1097
+ close() {
1098
+ if (this.stream) {
1099
+ this.stream.end();
1100
+ this.stream = null;
1101
+ }
1102
+ }
1103
+ dispose() {
1104
+ this.close();
1105
+ }
1106
+ }
1107
+ var logFileWriter;
1108
+ var init_file_writer = __esm(() => {
1109
+ init_src2();
1110
+ logFileWriter = new LogFileWriter;
1111
+ registerDisposable(logFileWriter);
1112
+ });
1113
+
1114
+ // ../../packages/logger/src/index.ts
1115
+ import { EventEmitter as EventEmitter2 } from "events";
1116
+
1117
+ class Logger {
1118
+ level;
1119
+ prefix;
1120
+ format;
1121
+ silentConsole;
1122
+ constructor(prefix = "", level = 1 /* INFO */, options = {}) {
1123
+ this.prefix = prefix;
1124
+ this.level = this.getLogLevelFromEnv() || level;
1125
+ this.format = process.env.AGENT_SMITH_LOG_FORMAT || "pretty";
1126
+ this.silentConsole = options.silentConsole ?? !(process.env.AGENT_SMITH_DEBUG === "1" || this.level === 0 /* DEBUG */);
1127
+ }
1128
+ getLogLevelFromEnv() {
1129
+ const envLevel = process.env.AGENT_SMITH_LOG_LEVEL?.toUpperCase();
1130
+ if (envLevel && envLevel in LogLevel) {
1131
+ return LogLevel[envLevel];
1132
+ }
1133
+ return null;
1134
+ }
1135
+ formatMessage(level, message, data) {
1136
+ const timestamp = new Date().toISOString();
1137
+ if (this.format === "json") {
1138
+ const logEntry = {
1139
+ ts: timestamp,
1140
+ level,
1141
+ prefix: this.prefix || undefined,
1142
+ msg: message,
1143
+ ...data && { data }
1144
+ };
1145
+ return JSON.stringify(logEntry);
1146
+ } else {
1147
+ const prefix = this.prefix ? `[${this.prefix}] ` : "";
1148
+ const dataStr = data ? ` ${JSON.stringify(data)}` : "";
1149
+ return `[${timestamp}] ${level}: ${prefix}${message}${dataStr}`;
1150
+ }
1151
+ }
1152
+ debug(message, data) {
1153
+ if (this.level <= 0 /* DEBUG */) {
1154
+ const msg = this.formatMessage("DEBUG", message, data);
1155
+ const event = {
1156
+ ts: Date.now(),
1157
+ level: "DEBUG",
1158
+ msg: message
1159
+ };
1160
+ logBus.emit("log", event);
1161
+ logFileWriter.write(event);
1162
+ this.writeToStream(0 /* DEBUG */, msg);
1163
+ }
1164
+ }
1165
+ info(message, data) {
1166
+ if (this.level <= 1 /* INFO */) {
1167
+ const msg = this.formatMessage("INFO", message, data);
1168
+ const event = {
1169
+ ts: Date.now(),
1170
+ level: "INFO",
1171
+ msg: message
1172
+ };
1173
+ logBus.emit("log", event);
1174
+ logFileWriter.write(event);
1175
+ this.writeToStream(1 /* INFO */, msg);
1176
+ }
1177
+ }
1178
+ warn(message, data) {
1179
+ if (this.level <= 2 /* WARN */) {
1180
+ const msg = this.formatMessage("WARN", message, data);
1181
+ const event = {
1182
+ ts: Date.now(),
1183
+ level: "WARN",
1184
+ msg: message
1185
+ };
1186
+ logBus.emit("log", event);
1187
+ logFileWriter.write(event);
1188
+ this.writeToStream(2 /* WARN */, msg);
1189
+ }
1190
+ }
1191
+ error(message, error) {
1192
+ if (this.level <= 3 /* ERROR */) {
1193
+ const msg = this.formatMessage("ERROR", message, error);
1194
+ const event = {
1195
+ ts: Date.now(),
1196
+ level: "ERROR",
1197
+ msg: message
1198
+ };
1199
+ logBus.emit("log", event);
1200
+ logFileWriter.write(event);
1201
+ this.writeToStream(3 /* ERROR */, msg);
1202
+ }
1203
+ }
1204
+ setLevel(level) {
1205
+ this.level = level;
1206
+ this.silentConsole = !(process.env.AGENT_SMITH_DEBUG === "1" || this.level === 0 /* DEBUG */);
1207
+ }
1208
+ getLevel() {
1209
+ return this.level;
1210
+ }
1211
+ writeToStream(level, message) {
1212
+ if (this.silentConsole || typeof process === "undefined") {
1213
+ return;
1214
+ }
1215
+ const stream = level >= 2 /* WARN */ ? process.stderr : process.stdout;
1216
+ stream?.write?.(`${message}
1217
+ `);
1218
+ }
1219
+ }
1220
+ var LogLevel, logBus, log;
1221
+ var init_src3 = __esm(() => {
1222
+ init_file_writer();
1223
+ init_file_writer();
1224
+ ((LogLevel2) => {
1225
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
1226
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
1227
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
1228
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
1229
+ })(LogLevel ||= {});
1230
+ logBus = new EventEmitter2;
1231
+ log = new Logger;
1232
+ });
1233
+
1234
+ // ../../packages/config/src/paths-common.ts
1235
+ import { homedir } from "os";
1236
+ import { join as join3 } from "path";
1237
+ import { platform } from "process";
1238
+ function getPlatformConfigDir() {
1239
+ if (platform === "win32") {
1240
+ const baseDir = process.env.LOCALAPPDATA ?? process.env.APPDATA ?? join3(homedir(), "AppData", "Local");
1241
+ return join3(baseDir, "agent-smith");
1242
+ } else {
1243
+ const xdgConfig = process.env.XDG_CONFIG_HOME;
1244
+ const baseDir = xdgConfig ?? join3(homedir(), ".config");
1245
+ return join3(baseDir, "agent-smith");
1246
+ }
1247
+ }
1248
+ var init_paths_common = () => {};
1249
+
1250
+ // ../../packages/config/src/paths.ts
1251
+ import { join as join4 } from "path";
1252
+ function resolveConfigPath() {
1253
+ const explicitPath = process.env.AGENT_SMITH_CONFIG_PATH;
1254
+ if (explicitPath) {
1255
+ return explicitPath;
1256
+ }
1257
+ const configDir = getPlatformConfigDir();
1258
+ return join4(configDir, "agent-smith.json");
1259
+ }
1260
+ var init_paths = __esm(() => {
1261
+ init_paths_common();
1262
+ });
1263
+
1264
+ // ../../packages/config/src/index.ts
1265
+ import { EventEmitter as EventEmitter3 } from "events";
1266
+ import {
1267
+ chmodSync,
1268
+ existsSync as existsSync2,
1269
+ mkdirSync as mkdirSync2,
1270
+ readFileSync,
1271
+ renameSync,
1272
+ rmSync,
1273
+ statSync as statSync2,
1274
+ writeFileSync
1275
+ } from "fs";
1276
+ import { dirname } from "path";
1277
+ function parseNumber(value) {
1278
+ if (value === undefined) {
1279
+ return;
1280
+ }
1281
+ const parsed = Number(value);
1282
+ return Number.isFinite(parsed) ? parsed : undefined;
1283
+ }
1284
+ function normalizeEnrollmentEmail(value) {
1285
+ if (typeof value !== "string")
1286
+ return;
1287
+ const email = value.trim().toLowerCase();
1288
+ return email.length <= 254 && patterns.email.test(email) ? email : undefined;
1289
+ }
1290
+ function sanitizeEnrollmentEmails(value) {
1291
+ if (!Array.isArray(value))
1292
+ return;
1293
+ const emails = value.map(normalizeEnrollmentEmail).filter((email) => email !== undefined);
1294
+ return [...new Set(emails)].slice(0, MAX_ENROLLMENT_EMAILS);
1295
+ }
1296
+ function sanitizeConfigData(value) {
1297
+ if (!isRecord(value)) {
1298
+ return {};
1299
+ }
1300
+ const sanitized = {};
1301
+ for (const [key, entry] of Object.entries(value)) {
1302
+ if (key === "enrollment_emails") {
1303
+ const emails = sanitizeEnrollmentEmails(entry);
1304
+ if (emails)
1305
+ sanitized.enrollment_emails = emails;
1306
+ continue;
1307
+ }
1308
+ if (key === "team_routing") {
1309
+ const teamRouting = sanitizeTeamRouting(entry);
1310
+ if (teamRouting)
1311
+ sanitized.team_routing = teamRouting;
1312
+ continue;
1313
+ }
1314
+ if (key === "providers") {
1315
+ const providers = sanitizeProviderConfigs(entry);
1316
+ if (providers)
1317
+ sanitized.providers = providers;
1318
+ continue;
1319
+ }
1320
+ if (key === "provider_pools") {
1321
+ const providerPools = sanitizeProviderPools(entry);
1322
+ if (providerPools)
1323
+ sanitized.provider_pools = providerPools;
1324
+ continue;
1325
+ }
1326
+ if (key === "client") {
1327
+ const client = sanitizeClientRouting(entry);
1328
+ if (client)
1329
+ sanitized.client = client;
1330
+ continue;
1331
+ }
1332
+ if (key === "alerts") {
1333
+ const alerts = sanitizeAlerts(entry);
1334
+ if (alerts)
1335
+ sanitized.alerts = alerts;
1336
+ continue;
1337
+ }
1338
+ if (typeof entry === "string" || typeof entry === "boolean" || isFiniteNumber(entry)) {
1339
+ sanitized[key] = entry;
1340
+ }
1341
+ }
1342
+ if (!isLbStrategy(String(sanitized.lb_strategy ?? ""))) {
1343
+ delete sanitized.lb_strategy;
1344
+ }
1345
+ const numericKeys = [
1346
+ "retry_attempts",
1347
+ "max_body_bytes",
1348
+ "quota_threshold",
1349
+ "retry_delay_ms",
1350
+ "retry_backoff",
1351
+ "request_scoped_429_retry_delay_ms",
1352
+ "session_duration_ms",
1353
+ "port",
1354
+ "data_retention_days",
1355
+ "request_retention_days"
1356
+ ];
1357
+ for (const key of numericKeys) {
1358
+ const entry = sanitized[key];
1359
+ if (entry !== undefined && !isFiniteNumber(entry)) {
1360
+ delete sanitized[key];
1361
+ }
1362
+ }
1363
+ if (sanitized.client_id !== undefined && typeof sanitized.client_id !== "string") {
1364
+ delete sanitized.client_id;
1365
+ }
1366
+ return sanitized;
1367
+ }
1368
+ function filledText(value) {
1369
+ if (typeof value !== "string")
1370
+ return;
1371
+ const text = value.trim();
1372
+ return text.length > 0 && text.length <= MAX_ALERT_VALUE_LENGTH ? text : undefined;
1373
+ }
1374
+ function sanitizeHttpsUrl(value) {
1375
+ const text = filledText(value);
1376
+ if (!text)
1377
+ return;
1378
+ try {
1379
+ return new URL(text).protocol === "https:" ? text : undefined;
1380
+ } catch {
1381
+ return;
1382
+ }
1383
+ }
1384
+ function sanitizeAlerts(value) {
1385
+ if (!isRecord(value))
1386
+ return;
1387
+ const alerts = {};
1388
+ const slackWebhookUrl = sanitizeHttpsUrl(value.slack_webhook_url);
1389
+ if (slackWebhookUrl)
1390
+ alerts.slack_webhook_url = slackWebhookUrl;
1391
+ const slackBotToken = filledText(value.slack_bot_token);
1392
+ if (slackBotToken)
1393
+ alerts.slack_bot_token = slackBotToken;
1394
+ const slackChannel = filledText(value.slack_channel);
1395
+ if (slackChannel)
1396
+ alerts.slack_channel = slackChannel;
1397
+ const email = normalizeEnrollmentEmail(value.email);
1398
+ if (email)
1399
+ alerts.email = email;
1400
+ const emailFrom = filledText(value.email_from);
1401
+ if (emailFrom)
1402
+ alerts.email_from = emailFrom;
1403
+ const resendApiKey = filledText(value.resend_api_key);
1404
+ if (resendApiKey)
1405
+ alerts.resend_api_key = resendApiKey;
1406
+ return alerts;
1407
+ }
1408
+ function isProviderStrategy(value) {
1409
+ return typeof value === "string" && PROVIDER_STRATEGIES.includes(value);
1410
+ }
1411
+ function sanitizeProviderBaseUrl(value) {
1412
+ if (typeof value !== "string" || value.length === 0)
1413
+ return;
1414
+ try {
1415
+ const url = new URL(value);
1416
+ return url.protocol === "https:" || url.protocol === "http:" ? url.toString().replace(/\/$/, "") : undefined;
1417
+ } catch {
1418
+ return;
1419
+ }
1420
+ }
1421
+ function sanitizeClientRouting(value) {
1422
+ if (!isRecord(value))
1423
+ return;
1424
+ const client = {};
1425
+ if (typeof value.enabled === "boolean")
1426
+ client.enabled = value.enabled;
1427
+ if (typeof value.base_url === "string") {
1428
+ try {
1429
+ const url = new URL(value.base_url);
1430
+ if ((url.protocol === "http:" || url.protocol === "https:") && url.pathname === "/" && url.search === "" && url.hash === "" && url.username === "" && url.password === "") {
1431
+ client.base_url = url.origin;
1432
+ }
1433
+ } catch {}
1434
+ }
1435
+ if (typeof value.proxy_key_file === "string" && (value.proxy_key_file.startsWith("/") || value.proxy_key_file.startsWith("~/")) && value.proxy_key_file.length <= 1024) {
1436
+ client.proxy_key_file = value.proxy_key_file;
1437
+ }
1438
+ if (typeof value.keep_claude_login === "boolean") {
1439
+ client.keep_claude_login = value.keep_claude_login;
1440
+ }
1441
+ return Object.keys(client).length > 0 ? client : undefined;
1442
+ }
1443
+ function sanitizeProviderModels(value) {
1444
+ if (!isRecord(value))
1445
+ return;
1446
+ const models = {};
1447
+ for (const [pattern, target] of Object.entries(value)) {
1448
+ const wildcardIndex = pattern.indexOf("*");
1449
+ if (pattern.length === 0 || pattern.length > 200 || wildcardIndex !== -1 && wildcardIndex !== pattern.length - 1 || typeof target !== "string" || target.length === 0 || target.length > 200) {
1450
+ continue;
1451
+ }
1452
+ models[pattern] = target;
1453
+ }
1454
+ return Object.keys(models).length > 0 ? models : undefined;
1455
+ }
1456
+ function sanitizeProviderConfigs(value) {
1457
+ if (!isRecord(value))
1458
+ return;
1459
+ const providers = {};
1460
+ for (const [name, entry] of Object.entries(value)) {
1461
+ if (name === "pool" || !PROVIDER_NAME_PATTERN.test(name) || !isRecord(entry))
1462
+ continue;
1463
+ const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1464
+ const strategy3 = isProviderStrategy(entry.strategy) ? entry.strategy : builtin?.strategy;
1465
+ if (!strategy3)
1466
+ continue;
1467
+ const provider = { strategy: strategy3 };
1468
+ if (typeof entry.enabled === "boolean")
1469
+ provider.enabled = entry.enabled;
1470
+ const baseUrl = sanitizeProviderBaseUrl(entry.base_url);
1471
+ if (baseUrl)
1472
+ provider.base_url = baseUrl;
1473
+ const models = sanitizeProviderModels(entry.models);
1474
+ if (models)
1475
+ provider.models = models;
1476
+ providers[name] = provider;
1477
+ }
1478
+ return providers;
1479
+ }
1480
+ function sanitizeProviderPools(value) {
1481
+ if (!isRecord(value))
1482
+ return;
1483
+ const pools = {};
1484
+ for (const [wire, entries] of Object.entries(value)) {
1485
+ if (!isProviderWire(wire) || !Array.isArray(entries))
1486
+ continue;
1487
+ const providers = [...new Set(entries)].filter((provider) => typeof provider === "string" && PROVIDER_NAME_PATTERN.test(provider));
1488
+ if (providers.length > 0)
1489
+ pools[wire] = providers;
1490
+ }
1491
+ return pools;
1492
+ }
1493
+ function wireForStrategy(strategy3) {
1494
+ return strategy3 === "anthropic-api" || strategy3 === "claude-code" ? "anthropic-messages" : "openai-responses";
1495
+ }
1496
+ function isNonNegativeFiniteNumber(value) {
1497
+ return isFiniteNumber(value) && value >= 0;
1498
+ }
1499
+ function sanitizeTeamRouting(value) {
1500
+ if (!isRecord(value))
1501
+ return;
1502
+ const result = {};
1503
+ if (typeof value.enabled === "boolean")
1504
+ result.enabled = value.enabled;
1505
+ if (typeof value.distribution_enabled === "boolean") {
1506
+ result.distribution_enabled = value.distribution_enabled;
1507
+ }
1508
+ if (Array.isArray(value.allowlisted_account_uuids) && value.allowlisted_account_uuids.every((entry) => typeof entry === "string" && entry.length > 0 && entry.length <= 200)) {
1509
+ result.allowlisted_account_uuids = [...value.allowlisted_account_uuids];
1510
+ }
1511
+ if (isFiniteNumber(value.max_usage) && value.max_usage > 0 && value.max_usage <= 0.9) {
1512
+ result.max_usage = value.max_usage;
1513
+ }
1514
+ if (isNonNegativeFiniteNumber(value.admission_cap)) {
1515
+ result.admission_cap = Math.floor(value.admission_cap);
1516
+ }
1517
+ if (isNonNegativeFiniteNumber(value.admission_queue_limit)) {
1518
+ result.admission_queue_limit = Math.floor(value.admission_queue_limit);
1519
+ }
1520
+ if (isNonNegativeFiniteNumber(value.admission_wait_ms)) {
1521
+ result.admission_wait_ms = Math.floor(value.admission_wait_ms);
1522
+ }
1523
+ if (isNonNegativeFiniteNumber(value.hold_seconds)) {
1524
+ result.hold_seconds = Math.floor(value.hold_seconds);
1525
+ }
1526
+ if (isNonNegativeFiniteNumber(value.quota_probe_seconds)) {
1527
+ result.quota_probe_seconds = Math.min(Math.floor(value.quota_probe_seconds), 7 * 24 * 60 * 60);
1528
+ }
1529
+ return result;
1530
+ }
1531
+ function readClientRouting(configPath = resolveConfigPath()) {
1532
+ let data;
1533
+ try {
1534
+ data = JSON.parse(readFileSync(configPath, "utf8"));
1535
+ } catch {
1536
+ throw new Error("Agent Smith client config could not be read");
1537
+ }
1538
+ if (!isRecord(data) || data.client !== undefined && !isRecord(data.client) || isRecord(data.client) && data.client.enabled !== undefined && typeof data.client.enabled !== "boolean") {
1539
+ throw new Error("Agent Smith client config is invalid");
1540
+ }
1541
+ return clientRouting(sanitizeClientRouting(data.client));
1542
+ }
1543
+ function clientRouting(client) {
1544
+ return {
1545
+ enabled: client?.enabled === true,
1546
+ ...client?.base_url && { baseUrl: client.base_url },
1547
+ ...client?.proxy_key_file && { proxyKeyFile: client.proxy_key_file },
1548
+ ...client?.keep_claude_login === true && { keepClaudeLogin: true }
1549
+ };
1550
+ }
1551
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, MAX_ALERT_VALUE_LENGTH = 512, Config;
1552
+ var init_src4 = __esm(() => {
1553
+ init_src2();
1554
+ init_src3();
1555
+ init_src();
1556
+ init_paths();
1557
+ init_paths();
1558
+ init_paths_common();
1559
+ log2 = new Logger("Config");
1560
+ PROVIDER_STRATEGIES = [
1561
+ "anthropic-api",
1562
+ "openai-api",
1563
+ "claude-code",
1564
+ "codex"
1565
+ ];
1566
+ BUILTIN_PROVIDER_CONFIGS = [
1567
+ { name: "anthropic", enabled: true, strategy: "anthropic-api" },
1568
+ { name: "openai", enabled: true, strategy: "openai-api" },
1569
+ { name: "claude-code", enabled: false, strategy: "claude-code" },
1570
+ { name: "codex", enabled: false, strategy: "codex" }
1571
+ ];
1572
+ BUILTIN_PROVIDER_CONFIG_BY_NAME = new Map(BUILTIN_PROVIDER_CONFIGS.map((provider) => [provider.name, provider]));
1573
+ PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;
1574
+ TEAM_ROUTING_DEFAULTS = {
1575
+ enabled: false,
1576
+ distributionEnabled: true,
1577
+ allowlistedAccountUuids: [],
1578
+ maxUsage: 0.9,
1579
+ admissionCap: 5,
1580
+ admissionQueueLimit: 25,
1581
+ admissionWaitMs: 30000,
1582
+ holdSeconds: 0,
1583
+ quotaProbeSeconds: 0
1584
+ };
1585
+ Config = class Config extends EventEmitter3 {
1586
+ configPath;
1587
+ data = {};
1588
+ constructor(configPath) {
1589
+ super();
1590
+ this.configPath = configPath ?? resolveConfigPath();
1591
+ this.loadConfig();
1592
+ }
1593
+ loadConfig() {
1594
+ if (existsSync2(this.configPath)) {
1595
+ try {
1596
+ const content = readFileSync(this.configPath, "utf8");
1597
+ this.data = sanitizeConfigData(JSON.parse(content));
1598
+ } catch (error) {
1599
+ log2.error(`Failed to parse config file: ${error}`);
1600
+ this.data = {};
1601
+ return;
1602
+ }
1603
+ try {
1604
+ chmodSync(this.configPath, 384);
1605
+ } catch {
1606
+ let ownerOnly = false;
1607
+ try {
1608
+ ownerOnly = (statSync2(this.configPath).mode & 63) === 0;
1609
+ } catch {}
1610
+ if (!ownerOnly) {
1611
+ throw new Error("Config file must be owner-only");
1612
+ }
1613
+ }
1614
+ if ("default_agent_model" in this.data) {
1615
+ delete this.data.default_agent_model;
1616
+ this.saveConfig();
1617
+ }
1618
+ } else {
1619
+ const dir = dirname(this.configPath);
1620
+ mkdirSync2(dir, { recursive: true, mode: 448 });
1621
+ chmodSync(dir, 448);
1622
+ this.data = {
1623
+ lb_strategy: DEFAULT_STRATEGY
1624
+ };
1625
+ this.saveConfig();
1626
+ }
1627
+ }
1628
+ saveConfig() {
1629
+ try {
1630
+ this.writePrivately(this.data);
1631
+ } catch (error) {
1632
+ log2.error(`Failed to save config file: ${error}`);
1633
+ }
1634
+ }
1635
+ writePrivately(data) {
1636
+ const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1637
+ try {
1638
+ writeFileSync(temporary, JSON.stringify(data, null, 2), {
1639
+ mode: 384,
1640
+ flag: "wx"
1641
+ });
1642
+ renameSync(temporary, this.configPath);
1643
+ } finally {
1644
+ rmSync(temporary, { force: true });
1645
+ }
1646
+ }
1647
+ get(key, defaultValue) {
1648
+ const value = this.data[key];
1649
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1650
+ return value;
1651
+ }
1652
+ if (defaultValue !== undefined) {
1653
+ this.set(key, defaultValue);
1654
+ return defaultValue;
1655
+ }
1656
+ return;
1657
+ }
1658
+ set(key, value) {
1659
+ const oldValue = this.data[key];
1660
+ this.data[key] = value;
1661
+ this.saveConfig();
1662
+ this.emit("change", { key, oldValue, newValue: value });
1663
+ }
1664
+ getStrategy() {
1665
+ const envStrategy = process.env.AGENT_SMITH_LB_STRATEGY;
1666
+ if (envStrategy && isValidStrategy(envStrategy)) {
1667
+ return envStrategy;
1668
+ }
1669
+ const configStrategy = this.data.lb_strategy;
1670
+ if (configStrategy && isValidStrategy(configStrategy)) {
1671
+ return configStrategy;
1672
+ }
1673
+ return DEFAULT_STRATEGY;
1674
+ }
1675
+ setStrategy(strategy3) {
1676
+ if (!isValidStrategy(strategy3)) {
1677
+ throw new Error(`Invalid strategy: ${strategy3}`);
1678
+ }
1679
+ this.set("lb_strategy", strategy3);
1680
+ }
1681
+ clamp(n, min, max) {
1682
+ return Math.max(min, Math.min(max, n));
1683
+ }
1684
+ getDataRetentionDays() {
1685
+ const fromEnv = process.env.AGENT_SMITH_DATA_RETENTION_DAYS;
1686
+ if (fromEnv) {
1687
+ const n = parseInt(fromEnv, 10);
1688
+ if (!Number.isNaN(n))
1689
+ return this.clamp(n, 1, 365);
1690
+ }
1691
+ const fromFile = this.data.data_retention_days;
1692
+ if (typeof fromFile === "number")
1693
+ return this.clamp(fromFile, 1, 365);
1694
+ return 7;
1695
+ }
1696
+ setDataRetentionDays(days) {
1697
+ const clamped = this.clamp(days, 1, 365);
1698
+ this.set("data_retention_days", clamped);
1699
+ }
1700
+ getRequestRetentionDays() {
1701
+ const fromEnv = process.env.AGENT_SMITH_REQUEST_RETENTION_DAYS;
1702
+ if (fromEnv) {
1703
+ const n = parseInt(fromEnv, 10);
1704
+ if (!Number.isNaN(n))
1705
+ return this.clamp(n, 1, 3650);
1706
+ }
1707
+ const fromFile = this.data.request_retention_days;
1708
+ if (typeof fromFile === "number")
1709
+ return this.clamp(fromFile, 1, 3650);
1710
+ return 365;
1711
+ }
1712
+ setRequestRetentionDays(days) {
1713
+ const clamped = this.clamp(days, 1, 3650);
1714
+ this.set("request_retention_days", clamped);
1715
+ }
1716
+ getAllSettings() {
1717
+ const primitiveSettings = Object.fromEntries(Object.entries(this.data).filter(([, value]) => typeof value === "string" || typeof value === "number" || typeof value === "boolean"));
1718
+ return {
1719
+ ...primitiveSettings,
1720
+ lb_strategy: this.getStrategy(),
1721
+ data_retention_days: this.getDataRetentionDays(),
1722
+ request_retention_days: this.getRequestRetentionDays()
1723
+ };
1724
+ }
1725
+ getTeamRouting() {
1726
+ const file = this.data.team_routing;
1727
+ return {
1728
+ enabled: file?.enabled ?? TEAM_ROUTING_DEFAULTS.enabled,
1729
+ distributionEnabled: file?.distribution_enabled ?? TEAM_ROUTING_DEFAULTS.distributionEnabled,
1730
+ allowlistedAccountUuids: [
1731
+ ...file?.allowlisted_account_uuids ?? TEAM_ROUTING_DEFAULTS.allowlistedAccountUuids
1732
+ ],
1733
+ maxUsage: file?.max_usage ?? TEAM_ROUTING_DEFAULTS.maxUsage,
1734
+ admissionCap: file?.admission_cap ?? TEAM_ROUTING_DEFAULTS.admissionCap,
1735
+ admissionQueueLimit: file?.admission_queue_limit ?? TEAM_ROUTING_DEFAULTS.admissionQueueLimit,
1736
+ admissionWaitMs: file?.admission_wait_ms ?? TEAM_ROUTING_DEFAULTS.admissionWaitMs,
1737
+ holdSeconds: file?.hold_seconds ?? TEAM_ROUTING_DEFAULTS.holdSeconds,
1738
+ quotaProbeSeconds: file?.quota_probe_seconds ?? TEAM_ROUTING_DEFAULTS.quotaProbeSeconds
1739
+ };
1740
+ }
1741
+ getAlerts() {
1742
+ const file = this.data.alerts;
1743
+ return {
1744
+ slackWebhookUrl: file?.slack_webhook_url ?? null,
1745
+ slackBotToken: file?.slack_bot_token ?? null,
1746
+ slackChannel: file?.slack_channel ?? null,
1747
+ email: file?.email ?? null,
1748
+ emailFrom: file?.email_from ?? null,
1749
+ resendApiKey: file?.resend_api_key ?? null
1750
+ };
1751
+ }
1752
+ getClientRouting() {
1753
+ return clientRouting(this.data.client);
1754
+ }
1755
+ setClientRoutingEnabled(enabled) {
1756
+ this.persistStrictly("client", { ...this.data.client, enabled });
1757
+ }
1758
+ getBlockWhenAllFull() {
1759
+ return this.data.block_when_all_full !== false;
1760
+ }
1761
+ getProviderConfig(name) {
1762
+ const builtin = BUILTIN_PROVIDER_CONFIG_BY_NAME.get(name);
1763
+ const configured = this.data.providers?.[name];
1764
+ if (!builtin && !configured?.strategy)
1765
+ return;
1766
+ return {
1767
+ name,
1768
+ enabled: configured?.enabled ?? builtin?.enabled ?? true,
1769
+ strategy: configured?.strategy ?? builtin?.strategy ?? "anthropic-api",
1770
+ ...configured?.base_url && { baseUrl: configured.base_url },
1771
+ ...configured?.models && { models: { ...configured.models } }
1772
+ };
1773
+ }
1774
+ getProviderPool(wire) {
1775
+ return (this.data.provider_pools?.[wire] ?? []).filter((name) => {
1776
+ const provider = this.getProviderConfig(name);
1777
+ return provider?.enabled === true && wireForStrategy(provider.strategy) === wire;
1778
+ });
1779
+ }
1780
+ getProviderPools() {
1781
+ return Object.fromEntries(PROVIDER_WIRES.map((wire) => [wire, this.getProviderPool(wire)]).filter(([, providers]) => providers.length > 0));
1782
+ }
1783
+ getProviderConfigs() {
1784
+ const names = new Set(BUILTIN_PROVIDER_CONFIGS.map(({ name }) => name));
1785
+ for (const name of Object.keys(this.data.providers ?? {})) {
1786
+ names.add(name);
1787
+ }
1788
+ return [...names].map((name) => this.getProviderConfig(name)).filter((provider) => provider !== undefined);
1789
+ }
1790
+ setTeamRouting(value) {
1791
+ if (!isRecord(value)) {
1792
+ throw new Error("team routing configuration must be an object");
1793
+ }
1794
+ const allowed = new Set([
1795
+ "enabled",
1796
+ "distribution_enabled",
1797
+ "allowlisted_account_uuids",
1798
+ "max_usage",
1799
+ "admission_cap",
1800
+ "admission_queue_limit",
1801
+ "admission_wait_ms",
1802
+ "hold_seconds",
1803
+ "quota_probe_seconds"
1804
+ ]);
1805
+ if (Object.keys(value).some((key) => !allowed.has(key))) {
1806
+ throw new Error("team routing configuration contains an unknown field");
1807
+ }
1808
+ const sanitized = sanitizeTeamRouting(value);
1809
+ if (!sanitized) {
1810
+ throw new Error("team routing configuration must be an object");
1811
+ }
1812
+ for (const key of Object.keys(value)) {
1813
+ if (!(key in sanitized)) {
1814
+ throw new Error(`Invalid team routing field: ${key}`);
1815
+ }
1816
+ }
1817
+ const oldValue = this.data.team_routing;
1818
+ this.data.team_routing = sanitized;
1819
+ this.saveConfig();
1820
+ this.emit("change", {
1821
+ key: "team_routing",
1822
+ oldValue,
1823
+ newValue: sanitized
1824
+ });
1825
+ }
1826
+ allowAccountUuid(accountUuid) {
1827
+ const current = this.getTeamRouting().allowlistedAccountUuids;
1828
+ if (current.includes(accountUuid))
1829
+ return;
1830
+ this.persistAccountAllowlist([...current, accountUuid]);
1831
+ }
1832
+ removeAccountUuid(accountUuid) {
1833
+ const current = this.getTeamRouting().allowlistedAccountUuids;
1834
+ if (!current.includes(accountUuid))
1835
+ return;
1836
+ this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
1837
+ }
1838
+ persistAccountAllowlist(accountUuids) {
1839
+ this.persistStrictly("team_routing", {
1840
+ ...this.data.team_routing,
1841
+ allowlisted_account_uuids: accountUuids
1842
+ });
1843
+ }
1844
+ getEnrollmentEmails() {
1845
+ return [...this.data.enrollment_emails ?? []];
1846
+ }
1847
+ setEnrollmentEmails(emails) {
1848
+ const normalized = emails.map(normalizeEnrollmentEmail);
1849
+ if (normalized.some((email) => email === undefined)) {
1850
+ throw new ValidationError("Invalid enrollment email", "enrollment_emails");
1851
+ }
1852
+ const unique = [...new Set(normalized)];
1853
+ if (unique.length > MAX_ENROLLMENT_EMAILS) {
1854
+ throw new ValidationError(`At most ${MAX_ENROLLMENT_EMAILS} enrollment emails`, "enrollment_emails");
1855
+ }
1856
+ this.persistStrictly("enrollment_emails", unique);
1857
+ return [...unique];
1858
+ }
1859
+ persistStrictly(key, value) {
1860
+ const next = { ...this.data, [key]: value };
1861
+ this.writePrivately(next);
1862
+ const oldValue = this.data[key];
1863
+ this.data = next;
1864
+ this.emit("change", { key, oldValue, newValue: value });
1865
+ }
1866
+ getRuntime() {
1867
+ const defaults = {
1868
+ blockWhenAllFull: this.getBlockWhenAllFull(),
1869
+ clientId: "9d1c250a-e61b-44d9-88ed-5944d1962f5e",
1870
+ maxBodyBytes: 64 * 1024 * 1024,
1871
+ quotaThreshold: 0.98,
1872
+ requestScopedRetryDelayMs: 2000,
1873
+ retry: {
1874
+ attempts: 3,
1875
+ delayMs: TIME_CONSTANTS.RETRY_DELAY_DEFAULT,
1876
+ backoff: 2
1877
+ },
1878
+ sessionDurationMs: TIME_CONSTANTS.SESSION_DURATION_DEFAULT,
1879
+ port: NETWORK.DEFAULT_PORT,
1880
+ teamRouting: this.getTeamRouting()
1881
+ };
1882
+ if (process.env.AGENT_SMITH_CLIENT_ID) {
1883
+ defaults.clientId = process.env.AGENT_SMITH_CLIENT_ID;
1884
+ }
1885
+ const retryAttempts = parseNumber(process.env.AGENT_SMITH_RETRY_ATTEMPTS);
1886
+ if (retryAttempts !== undefined) {
1887
+ defaults.retry.attempts = retryAttempts;
1888
+ }
1889
+ const maxBodyBytes = parseNumber(process.env.AGENT_SMITH_MAX_BODY_BYTES);
1890
+ if (maxBodyBytes !== undefined) {
1891
+ defaults.maxBodyBytes = maxBodyBytes;
1892
+ }
1893
+ const quotaThreshold = parseNumber(process.env.AGENT_SMITH_QUOTA_THRESHOLD);
1894
+ if (quotaThreshold !== undefined && quotaThreshold > 0 && quotaThreshold <= 1) {
1895
+ defaults.quotaThreshold = quotaThreshold;
1896
+ }
1897
+ const retryDelayMs = parseNumber(process.env.AGENT_SMITH_RETRY_DELAY_MS);
1898
+ if (retryDelayMs !== undefined) {
1899
+ defaults.retry.delayMs = retryDelayMs;
1900
+ }
1901
+ const retryBackoff = parseNumber(process.env.AGENT_SMITH_RETRY_BACKOFF);
1902
+ if (retryBackoff !== undefined) {
1903
+ defaults.retry.backoff = retryBackoff;
1904
+ }
1905
+ const requestScopedRetryDelayMs = parseNumber(process.env.AGENT_SMITH_REQUEST_SCOPED_429_RETRY_DELAY_MS);
1906
+ if (requestScopedRetryDelayMs !== undefined) {
1907
+ defaults.requestScopedRetryDelayMs = requestScopedRetryDelayMs;
1908
+ }
1909
+ const sessionDurationMs = parseNumber(process.env.AGENT_SMITH_SESSION_DURATION_MS);
1910
+ if (sessionDurationMs !== undefined) {
1911
+ defaults.sessionDurationMs = sessionDurationMs;
1912
+ }
1913
+ const port = parseNumber(process.env.PORT);
1914
+ if (port !== undefined) {
1915
+ defaults.port = port;
1916
+ }
1917
+ if (this.data.client_id) {
1918
+ defaults.clientId = this.data.client_id;
1919
+ }
1920
+ if (typeof this.data.retry_attempts === "number") {
1921
+ defaults.retry.attempts = this.data.retry_attempts;
1922
+ }
1923
+ if (typeof this.data.max_body_bytes === "number") {
1924
+ defaults.maxBodyBytes = this.data.max_body_bytes;
1925
+ }
1926
+ if (typeof this.data.quota_threshold === "number" && this.data.quota_threshold > 0 && this.data.quota_threshold <= 1) {
1927
+ defaults.quotaThreshold = this.data.quota_threshold;
1928
+ }
1929
+ if (typeof this.data.retry_delay_ms === "number") {
1930
+ defaults.retry.delayMs = this.data.retry_delay_ms;
1931
+ }
1932
+ if (typeof this.data.retry_backoff === "number") {
1933
+ defaults.retry.backoff = this.data.retry_backoff;
1934
+ }
1935
+ if (typeof this.data.request_scoped_429_retry_delay_ms === "number") {
1936
+ defaults.requestScopedRetryDelayMs = this.data.request_scoped_429_retry_delay_ms;
1937
+ }
1938
+ if (typeof this.data.session_duration_ms === "number") {
1939
+ defaults.sessionDurationMs = this.data.session_duration_ms;
1940
+ }
1941
+ if (typeof this.data.port === "number") {
1942
+ defaults.port = this.data.port;
1943
+ }
1944
+ return defaults;
1945
+ }
1946
+ };
1947
+ });
1948
+
1949
+ // src/core/local-routing.ts
1950
+ import {
1951
+ accessSync,
1952
+ chmodSync as chmodSync2,
1953
+ constants,
1954
+ existsSync as existsSync3,
1955
+ mkdirSync as mkdirSync3,
1956
+ readFileSync as readFileSync2,
1957
+ statSync as statSync3,
1958
+ unlinkSync as unlinkSync2,
1959
+ writeFileSync as writeFileSync2
1960
+ } from "fs";
1961
+ import { homedir as homedir2 } from "os";
1962
+ import { dirname as dirname2, join as join5 } from "path";
1963
+ import { fileURLToPath } from "url";
1964
+ function shellQuote(value) {
1965
+ return `'${value.replaceAll("'", `'"'"'`)}'`;
1966
+ }
1967
+ function shellDoubleQuote(value) {
1968
+ return `"${value.replaceAll("\\", "\\\\").replaceAll('"', "\\\"")}"`;
1969
+ }
1970
+ function proxyBaseUrl(port, configuredBaseUrl, directProvider, wire, providerPoolWires) {
1971
+ const route = providerPoolWires?.includes(wire) ? `/v1/pool/${wire}` : `/v1/${directProvider}`;
1972
+ return `${configuredBaseUrl ?? `http://127.0.0.1:${port}`}${route}`;
1973
+ }
1974
+ function validateProxyKeyFile(proxyKeyFile) {
1975
+ const resolvedPath = proxyKeyFile.startsWith("~/") ? join5(homedir2(), proxyKeyFile.slice(2)) : proxyKeyFile;
1976
+ let metadata;
1977
+ try {
1978
+ metadata = statSync3(resolvedPath);
1979
+ } catch {
1980
+ throw new Error("Agent Smith forwarding-key file is not readable");
1981
+ }
1982
+ if (!metadata.isFile()) {
1983
+ throw new Error("Agent Smith forwarding-key path must be a file");
1984
+ }
1985
+ if ((metadata.mode & 63) !== 0) {
1986
+ throw new Error("Agent Smith forwarding-key file must be owner-only");
1987
+ }
1988
+ const key = readFileSync2(resolvedPath, "utf8").trim();
1989
+ if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
1990
+ throw new Error("Agent Smith forwarding-key file is invalid");
1991
+ }
1992
+ return resolvedPath;
1993
+ }
1994
+ function proxyKeySetup(proxyKeyFile) {
1995
+ if (!proxyKeyFile) {
1996
+ return `export AGENT_SMITH_PROXY_KEY=${shellQuote(LOCAL_CLIENT_KEY)}`;
1997
+ }
1998
+ return `if [ ! -r ${shellQuote(proxyKeyFile)} ]; then
1999
+ echo "Agent Smith forwarding-key file is not readable" >&2
2000
+ exit 1
2001
+ fi
2002
+ export AGENT_SMITH_PROXY_KEY=$(cat ${shellQuote(proxyKeyFile)})`;
2003
+ }
2004
+ function claudeProxyCredential(keepClaudeLogin) {
2005
+ if (!keepClaudeLogin) {
2006
+ return `export ANTHROPIC_API_KEY="$AGENT_SMITH_PROXY_KEY"`;
2007
+ }
2008
+ return `unset ANTHROPIC_API_KEY
2009
+ export ANTHROPIC_CUSTOM_HEADERS="\${ANTHROPIC_CUSTOM_HEADERS:+$ANTHROPIC_CUSTOM_HEADERS
2010
+ }x-api-key: $AGENT_SMITH_PROXY_KEY"`;
2011
+ }
2012
+ function claudeWrapper(claudePath, baseUrl, proxyKeyFile, keepClaudeLogin) {
2013
+ return `#!/bin/sh
2014
+ # Generated by agent-smith. This file delegates to the real Claude Code binary.
2015
+ unset AGENT_SMITH_ADMIN_KEY
2016
+ unset AGENT_SMITH_PROXY_KEY
2017
+ unset ANTHROPIC_AUTH_TOKEN
2018
+ ${proxyKeySetup(proxyKeyFile)}
2019
+ ${claudeProxyCredential(keepClaudeLogin)}
2020
+ unset AGENT_SMITH_PROXY_KEY
2021
+ export ANTHROPIC_BASE_URL=${shellQuote(baseUrl)}
2022
+ exec ${shellQuote(claudePath)} "$@"
2023
+ `;
2024
+ }
2025
+ function codexWrapper(codexPath, baseUrl, proxyKeyFile) {
2026
+ const config = [
2027
+ 'model_provider="agent_smith"',
2028
+ 'model_providers.agent_smith.name="Agent Smith"',
2029
+ `model_providers.agent_smith.base_url="${baseUrl}"`,
2030
+ 'model_providers.agent_smith.env_key="AGENT_SMITH_PROXY_KEY"',
2031
+ 'model_providers.agent_smith.wire_api="responses"',
2032
+ "model_providers.agent_smith.requires_openai_auth=false",
2033
+ "model_providers.agent_smith.supports_websockets=false"
2034
+ ];
2035
+ const overrides = config.map((entry) => ` -c ${shellQuote(entry)}`).join(" \\\n");
2036
+ return `#!/bin/sh
2037
+ # Generated by agent-smith. This file delegates to the real Codex binary.
2038
+ unset AGENT_SMITH_ADMIN_KEY
2039
+ unset AGENT_SMITH_PROXY_KEY
2040
+ ${proxyKeySetup(proxyKeyFile)}
2041
+ exec ${shellQuote(codexPath)} \\
2042
+ ${overrides} \\
2043
+ "$@"
2044
+ `;
2045
+ }
2046
+ async function installClientWrappers(options) {
2047
+ if (options.clientConfigPath) {
2048
+ const launcher = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./client-launcher.ts" : "./client-launcher.js", import.meta.url));
2049
+ mkdirSync3(options.binDir, { recursive: true, mode: 448 });
2050
+ for (const [tool, target] of [
2051
+ ["claude", options.claudePath],
2052
+ ["codex", options.codexPath]
2053
+ ]) {
2054
+ if (!target)
2055
+ continue;
2056
+ if (target === join5(options.binDir, tool))
2057
+ throw new Error("A client launcher cannot call itself");
2058
+ const wrapper = join5(options.binDir, tool);
2059
+ writeFileSync2(wrapper, `#!/bin/sh
2060
+ ${CONFIG_CLIENT_MARKER}
2061
+ exec ${[process.execPath, launcher, options.clientConfigPath, tool, target].map(shellQuote).join(" ")} "$@"
2062
+ `, { encoding: "utf8", mode: 448 });
2063
+ chmodSync2(wrapper, 448);
2064
+ }
2065
+ return;
2066
+ }
2067
+ if (options.baseUrl && !options.proxyKeyFile) {
2068
+ throw new Error("A configured Agent Smith server requires a forwarding key file");
2069
+ }
2070
+ mkdirSync3(options.binDir, { recursive: true, mode: 448 });
2071
+ const proxyKeyFile = options.proxyKeyFile ? validateProxyKeyFile(options.proxyKeyFile) : undefined;
2072
+ if (options.claudePath) {
2073
+ const claude = join5(options.binDir, "claude");
2074
+ writeFileSync2(claude, claudeWrapper(options.claudePath, proxyBaseUrl(options.port, options.baseUrl, "claude-code", "anthropic-messages", options.providerPoolWires), proxyKeyFile, options.keepClaudeLogin === true), {
2075
+ encoding: "utf8",
2076
+ mode: 448
2077
+ });
2078
+ chmodSync2(claude, 448);
2079
+ }
2080
+ if (options.codexPath) {
2081
+ const codex = join5(options.binDir, "codex");
2082
+ writeFileSync2(codex, codexWrapper(options.codexPath, proxyBaseUrl(options.port, options.baseUrl, "codex", "openai-responses", options.providerPoolWires), proxyKeyFile), {
2083
+ encoding: "utf8",
2084
+ mode: 448
2085
+ });
2086
+ chmodSync2(codex, 448);
2087
+ }
2088
+ }
2089
+ function defaultShellProfile() {
2090
+ const shell = process.env.SHELL?.split("/").pop();
2091
+ return join5(homedir2(), shell === "bash" ? ".bashrc" : ".zshrc");
2092
+ }
2093
+ function getLocalRoutingPaths() {
2094
+ const configDir = dirname2(resolveConfigPath());
2095
+ return {
2096
+ binDir: join5(configDir, "client-bin"),
2097
+ shellProfile: defaultShellProfile(),
2098
+ statePath: join5(configDir, "client-routing.json")
2099
+ };
2100
+ }
2101
+ function isExecutable(path) {
2102
+ try {
2103
+ accessSync(path, constants.X_OK);
2104
+ return true;
2105
+ } catch {
2106
+ return false;
2107
+ }
2108
+ }
2109
+ function findClientExecutable(name, binDir, path) {
2110
+ for (const directory of path.split(":")) {
2111
+ if (!directory || directory === binDir)
2112
+ continue;
2113
+ const candidate = join5(directory, name);
2114
+ if (isExecutable(candidate))
2115
+ return candidate;
2116
+ }
2117
+ throw new Error(`${name} was not found in PATH`);
2118
+ }
2119
+ function readSavedClientPaths(statePath) {
2120
+ if (!existsSync3(statePath))
2121
+ return null;
2122
+ try {
2123
+ const saved = JSON.parse(readFileSync2(statePath, "utf8"));
2124
+ if (typeof saved === "object" && saved !== null) {
2125
+ const { claudePath, codexPath } = saved;
2126
+ const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
2127
+ const validCodex = typeof codexPath === "string" && isExecutable(codexPath) ? codexPath : undefined;
2128
+ if (validClaude || validCodex) {
2129
+ return { claudePath: validClaude, codexPath: validCodex };
2130
+ }
2131
+ }
2132
+ } catch {}
2133
+ return null;
2134
+ }
2135
+ function installedRoutingStatus(paths = {}) {
2136
+ const defaults = getLocalRoutingPaths();
2137
+ const binDir = paths.binDir ?? defaults.binDir;
2138
+ const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2139
+ let shellProfileHasRouting = false;
2140
+ try {
2141
+ shellProfileHasRouting = existsSync3(shellProfile) && readFileSync2(shellProfile, "utf8").includes(ROUTING_BEGIN);
2142
+ } catch {}
2143
+ return {
2144
+ enabled: shellProfileHasRouting && (existsSync3(join5(binDir, "claude")) || existsSync3(join5(binDir, "codex"))),
2145
+ binDir,
2146
+ shellProfile
2147
+ };
2148
+ }
2149
+ function getLocalRoutingStatus(paths = {}) {
2150
+ const status = installedRoutingStatus(paths);
2151
+ if (!configClientWrappersInstalled(paths))
2152
+ return status;
2153
+ try {
2154
+ return { ...status, enabled: readClientRouting().enabled };
2155
+ } catch {
2156
+ return { ...status, enabled: false };
2157
+ }
2158
+ }
2159
+ function configClientWrappersInstalled(paths = {}) {
2160
+ const binDir = paths.binDir ?? getLocalRoutingPaths().binDir;
2161
+ const files = ["claude", "codex"].map((name) => join5(binDir, name)).filter(existsSync3);
2162
+ return installedRoutingStatus(paths).enabled && files.length > 0 && files.every((path) => readFileSync2(path, "utf8").includes(CONFIG_CLIENT_MARKER));
2163
+ }
2164
+ async function launchConfiguredClient(configPath, tool, target, args) {
2165
+ if (tool !== "claude" && tool !== "codex")
2166
+ throw new Error("Unknown Agent Smith client");
2167
+ const client = readClientRouting(configPath);
2168
+ const env = { ...process.env };
2169
+ delete env.AGENT_SMITH_ADMIN_KEY;
2170
+ delete env.AGENT_SMITH_PROXY_KEY;
2171
+ let command = [target, ...args];
2172
+ if (client.enabled) {
2173
+ if (!client.baseUrl || !client.proxyKeyFile)
2174
+ throw new Error("client.base_url and client.proxy_key_file are required");
2175
+ const keyFile = validateProxyKeyFile(client.proxyKeyFile);
2176
+ const wires = Object.keys(new Config(configPath).getProviderPools());
2177
+ const base = proxyBaseUrl(8080, client.baseUrl, tool === "claude" ? "claude-code" : "codex", tool === "claude" ? "anthropic-messages" : "openai-responses", wires);
2178
+ const script = tool === "claude" ? claudeWrapper(target, base, keyFile, client.keepClaudeLogin === true) : codexWrapper(target, base, keyFile);
2179
+ command = ["/bin/sh", "-c", script, "--", ...args];
2180
+ }
2181
+ const child = Bun.spawn(command, {
2182
+ env,
2183
+ stdin: "inherit",
2184
+ stdout: "inherit",
2185
+ stderr: "inherit"
2186
+ });
2187
+ const forward = {
2188
+ SIGINT: () => child.kill("SIGINT"),
2189
+ SIGTERM: () => child.kill("SIGTERM"),
2190
+ SIGHUP: () => child.kill("SIGHUP")
2191
+ };
2192
+ for (const [signal, listener] of Object.entries(forward))
2193
+ process.on(signal, listener);
2194
+ try {
2195
+ return await child.exited;
2196
+ } finally {
2197
+ for (const [signal, listener] of Object.entries(forward))
2198
+ process.off(signal, listener);
2199
+ }
2200
+ }
2201
+ async function enableLocalClientRouting(options) {
2202
+ const defaults = getLocalRoutingPaths();
2203
+ const binDir = options.binDir ?? defaults.binDir;
2204
+ const shellProfile = options.shellProfile ?? defaults.shellProfile;
2205
+ const statePath = options.statePath ?? defaults.statePath;
2206
+ const saved = readSavedClientPaths(statePath);
2207
+ const path = options.path ?? process.env.PATH ?? "";
2208
+ const discoverClient = (name) => {
2209
+ try {
2210
+ return findClientExecutable(name, binDir, path);
2211
+ } catch {
2212
+ return;
2213
+ }
2214
+ };
2215
+ const claudePath = options.claudePath ?? saved?.claudePath ?? discoverClient("claude");
2216
+ const codexPath = options.codexPath ?? saved?.codexPath ?? discoverClient("codex");
2217
+ if (!claudePath && !codexPath) {
2218
+ throw new Error("Neither Claude Code nor Codex was found in PATH");
2219
+ }
2220
+ await installClientWrappers({
2221
+ binDir,
2222
+ claudePath,
2223
+ codexPath,
2224
+ port: options.port,
2225
+ baseUrl: options.baseUrl,
2226
+ proxyKeyFile: options.proxyKeyFile,
2227
+ keepClaudeLogin: options.keepClaudeLogin,
2228
+ clientConfigPath: options.clientConfigPath,
2229
+ providerPoolWires: options.providerPoolWires ?? (options.clientConfigPath ? [] : Object.keys(new Config().getProviderPools()))
2230
+ });
2231
+ const existingProfile = existsSync3(shellProfile) ? readFileSync2(shellProfile, "utf8") : "";
2232
+ writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
2233
+ mkdirSync3(dirname2(statePath), { recursive: true, mode: 448 });
2234
+ writeFileSync2(statePath, JSON.stringify({ claudePath, codexPath }), {
2235
+ encoding: "utf8",
2236
+ mode: 384
2237
+ });
2238
+ chmodSync2(statePath, 384);
2239
+ return getLocalRoutingStatus({ binDir, shellProfile, statePath });
2240
+ }
2241
+ function disableLocalClientRouting(paths = {}) {
2242
+ const defaults = getLocalRoutingPaths();
2243
+ const binDir = paths.binDir ?? defaults.binDir;
2244
+ const shellProfile = paths.shellProfile ?? defaults.shellProfile;
2245
+ const statePath = paths.statePath ?? defaults.statePath;
2246
+ if (existsSync3(shellProfile)) {
2247
+ writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync2(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
2248
+ }
2249
+ for (const name of ["claude", "codex"]) {
2250
+ const wrapper = join5(binDir, name);
2251
+ if (existsSync3(wrapper))
2252
+ unlinkSync2(wrapper);
2253
+ }
2254
+ if (existsSync3(statePath))
2255
+ unlinkSync2(statePath);
2256
+ return getLocalRoutingStatus({ binDir, shellProfile, statePath });
2257
+ }
2258
+ function removeRoutingFromShellProfile(profile) {
2259
+ const start = profile.indexOf(ROUTING_BEGIN);
2260
+ if (start === -1)
2261
+ return profile;
2262
+ const end = profile.indexOf(ROUTING_END, start);
2263
+ if (end === -1)
2264
+ return profile;
2265
+ const afterEnd = end + ROUTING_END.length;
2266
+ const newlineLength = profile.slice(afterEnd, afterEnd + 1) === `
2267
+ ` ? 1 : 0;
2268
+ return `${profile.slice(0, start)}${profile.slice(afterEnd + newlineLength)}`;
2269
+ }
2270
+ function updateShellProfileForRouting(profile, binDir) {
2271
+ const withoutExistingBlock = removeRoutingFromShellProfile(profile);
2272
+ const separator = withoutExistingBlock.length === 0 || withoutExistingBlock.endsWith(`
2273
+ `) ? "" : `
2274
+ `;
2275
+ return `${withoutExistingBlock}${separator}${ROUTING_BEGIN}
2276
+ export PATH=${shellDoubleQuote(`${binDir}:$PATH`)}
2277
+ ${ROUTING_END}
2278
+ `;
2279
+ }
2280
+ var ROUTING_BEGIN = "# >>> agent-smith local routing >>>", ROUTING_END = "# <<< agent-smith local routing <<<", LOCAL_CLIENT_KEY = "agent-smith-local", CONFIG_CLIENT_MARKER = "# agent-smith config-driven client";
2281
+ var init_local_routing = __esm(() => {
2282
+ init_src4();
2283
+ });
2284
+
2285
+ // src/core/client-launcher.ts
2286
+ init_local_routing();
2287
+ try {
2288
+ const [configPath, tool, target, ...args] = process.argv.slice(2);
2289
+ if (!configPath || !tool || !target)
2290
+ throw new Error("Invalid Agent Smith client launcher");
2291
+ process.exitCode = await launchConfiguredClient(configPath, tool, target, args);
2292
+ } catch (error) {
2293
+ console.error(error instanceof Error ? error.message : "Agent Smith could not start the client");
2294
+ process.exitCode = 1;
2295
+ }