clawmux 0.3.0 → 0.3.1

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.
Files changed (3) hide show
  1. package/dist/cli.cjs +3563 -110
  2. package/dist/index.cjs +38 -6
  3. package/package.json +1 -1
package/dist/cli.cjs CHANGED
@@ -79,8 +79,8 @@ async function writeWebResponse(res, response) {
79
79
  }
80
80
 
81
81
  // src/cli.ts
82
- var import_promises = require("node:fs/promises");
83
- var import_node_path2 = require("node:path");
82
+ var import_promises6 = require("node:fs/promises");
83
+ var import_node_path6 = require("node:path");
84
84
  var import_node_child_process = require("node:child_process");
85
85
  var import_node_os = require("node:os");
86
86
 
@@ -156,101 +156,3553 @@ async function parseJsonBody(req) {
156
156
  if (text.length === 0) {
157
157
  return { body: null, error: null };
158
158
  }
159
- return { body: JSON.parse(text), error: null };
160
- } catch {
159
+ return { body: JSON.parse(text), error: null };
160
+ } catch {
161
+ return {
162
+ body: null,
163
+ error: jsonResponse({ error: "invalid JSON body" }, 400)
164
+ };
165
+ }
166
+ }
167
+ async function dispatch(req) {
168
+ const url = new URL(req.url);
169
+ const { pathname } = url;
170
+ const method = req.method.toUpperCase();
171
+ for (const route of routes) {
172
+ if (route.method === method && route.match(pathname)) {
173
+ const handler = customHandlers.get(route.key) ?? route.handler;
174
+ if (method === "POST") {
175
+ const { body, error } = await parseJsonBody(req);
176
+ if (error)
177
+ return error;
178
+ return handler(req, body);
179
+ }
180
+ return handler(req, null);
181
+ }
182
+ }
183
+ return jsonResponse({ error: "not found" }, 404);
184
+ }
185
+ function setRouteHandler(path, handler) {
186
+ customHandlers.set(path, handler);
187
+ }
188
+ function clearCustomHandlers() {
189
+ customHandlers.clear();
190
+ }
191
+
192
+ // src/utils/runtime.ts
193
+ var import_promises = require("node:fs/promises");
194
+ var isBun = typeof globalThis.Bun !== "undefined";
195
+ async function readFileText(path) {
196
+ if (isBun) {
197
+ const bun = globalThis.Bun;
198
+ return bun.file(path).text();
199
+ }
200
+ return import_promises.readFile(path, "utf-8");
201
+ }
202
+ async function fileExists(path) {
203
+ if (isBun) {
204
+ const bun = globalThis.Bun;
205
+ return bun.file(path).exists();
206
+ }
207
+ try {
208
+ await import_promises.access(path);
209
+ return true;
210
+ } catch {
211
+ return false;
212
+ }
213
+ }
214
+
215
+ // src/proxy/server.ts
216
+ function createServer(config) {
217
+ if (isBun) {
218
+ return createBunServer(config);
219
+ }
220
+ return createNodeServer(config);
221
+ }
222
+ function createBunServer(config) {
223
+ let server = null;
224
+ return {
225
+ start() {
226
+ if (server)
227
+ return;
228
+ const bun = globalThis.Bun;
229
+ server = bun.serve({
230
+ port: config.port,
231
+ hostname: config.host,
232
+ fetch: dispatch
233
+ });
234
+ },
235
+ stop() {
236
+ if (!server)
237
+ return;
238
+ server.stop(true);
239
+ server = null;
240
+ }
241
+ };
242
+ }
243
+ function createNodeServer(config) {
244
+ let server = null;
245
+ return {
246
+ async start() {
247
+ if (server)
248
+ return;
249
+ const { createServer: createHttpServer } = await import("node:http");
250
+ const { toWebRequest: toWebRequest2, writeWebResponse: writeWebResponse2 } = await Promise.resolve().then(() => exports_node_http_adapter);
251
+ const httpServer = createHttpServer(async (req, res) => {
252
+ try {
253
+ const webReq = toWebRequest2(req);
254
+ const webRes = await dispatch(webReq);
255
+ await writeWebResponse2(res, webRes);
256
+ } catch (err) {
257
+ const message = err instanceof Error ? err.message : String(err);
258
+ res.writeHead(500, { "content-type": "application/json" });
259
+ res.end(JSON.stringify({ error: message }));
260
+ }
261
+ });
262
+ await new Promise((resolve) => {
263
+ httpServer.listen(config.port, config.host, resolve);
264
+ });
265
+ server = httpServer;
266
+ },
267
+ stop() {
268
+ if (!server)
269
+ return;
270
+ server.close();
271
+ server = null;
272
+ }
273
+ };
274
+ }
275
+
276
+ // src/config/loader.ts
277
+ var import_promises2 = require("node:fs/promises");
278
+ var import_node_path = require("node:path");
279
+
280
+ // src/config/defaults.ts
281
+ var DEFAULT_CONFIG = {
282
+ compression: {
283
+ threshold: 0.75,
284
+ model: "",
285
+ targetRatio: 0.6
286
+ },
287
+ routing: {
288
+ models: {
289
+ LIGHT: "",
290
+ MEDIUM: "",
291
+ HEAVY: ""
292
+ },
293
+ contextWindows: {}
294
+ },
295
+ server: {
296
+ port: 3456,
297
+ host: "127.0.0.1"
298
+ }
299
+ };
300
+ function applyDefaults(partial) {
301
+ const defaults = DEFAULT_CONFIG;
302
+ return {
303
+ compression: {
304
+ threshold: partial.compression.threshold ?? defaults.compression.threshold,
305
+ model: partial.compression.model ?? defaults.compression.model,
306
+ targetRatio: partial.compression.targetRatio ?? defaults.compression.targetRatio
307
+ },
308
+ routing: {
309
+ models: {
310
+ LIGHT: partial.routing.models.LIGHT ?? defaults.routing.models.LIGHT,
311
+ MEDIUM: partial.routing.models.MEDIUM ?? defaults.routing.models.MEDIUM,
312
+ HEAVY: partial.routing.models.HEAVY ?? defaults.routing.models.HEAVY
313
+ },
314
+ contextWindows: { ...defaults.routing.contextWindows, ...partial.routing.contextWindows }
315
+ },
316
+ server: {
317
+ port: partial.server?.port ?? defaults.server.port,
318
+ host: partial.server?.host ?? defaults.server.host
319
+ }
320
+ };
321
+ }
322
+
323
+ // src/config/validator.ts
324
+ function isObject(value) {
325
+ return typeof value === "object" && value !== null && !Array.isArray(value);
326
+ }
327
+ function requireNumber(errors, path, value) {
328
+ if (typeof value !== "number") {
329
+ errors.push(`${path}: must be a number, got ${typeof value}`);
330
+ return false;
331
+ }
332
+ return true;
333
+ }
334
+ function requireString(errors, path, value) {
335
+ if (typeof value !== "string") {
336
+ errors.push(`${path}: must be a string, got ${typeof value}`);
337
+ return false;
338
+ }
339
+ return true;
340
+ }
341
+ function requireInRange(errors, path, value, min, max) {
342
+ if (value < min || value > max) {
343
+ errors.push(`${path}: must be between ${min} and ${max}, got ${value}`);
344
+ }
345
+ }
346
+ function checkRequiredString(errors, errorPath, obj, key) {
347
+ if (!isObject(obj)) {
348
+ errors.push(`${errorPath}: is required`);
349
+ return;
350
+ }
351
+ const value = obj[key];
352
+ if (typeof value !== "string" || value === "") {
353
+ errors.push(`${errorPath}: is required`);
354
+ return;
355
+ }
356
+ return value;
357
+ }
358
+ function checkProviderModelFormat(errors, path, model) {
359
+ if (!model.includes("/")) {
360
+ errors.push(`${path} must be in 'provider/model' format (e.g., 'anthropic/claude-sonnet-4-20250514')`);
361
+ return;
362
+ }
363
+ const providerName = model.split("/", 2)[0];
364
+ if (providerName.toLowerCase().startsWith("clawmux-")) {
365
+ errors.push(`Self-referencing model detected: ${model}. This would cause an infinite routing loop.`);
366
+ }
367
+ }
368
+ function checkOptionalNumberRange(errors, path, value, min, max) {
369
+ if (requireNumber(errors, path, value)) {
370
+ requireInRange(errors, path, value, min, max);
371
+ }
372
+ }
373
+ function validateConfig(raw) {
374
+ const errors = [];
375
+ const obj = isObject(raw) ? raw : {};
376
+ const compression = isObject(obj.compression) ? obj.compression : {};
377
+ const threshold = compression.threshold;
378
+ if (threshold === undefined) {
379
+ errors.push("compression.threshold: is required");
380
+ } else {
381
+ checkOptionalNumberRange(errors, "compression.threshold", threshold, 0.1, 0.95);
382
+ }
383
+ if (compression.model === undefined || compression.model === "") {
384
+ errors.push("compression.model: is required");
385
+ } else if (requireString(errors, "compression.model", compression.model)) {
386
+ checkProviderModelFormat(errors, "compression.model", compression.model);
387
+ }
388
+ if (compression.targetRatio !== undefined) {
389
+ checkOptionalNumberRange(errors, "compression.targetRatio", compression.targetRatio, 0.2, 0.9);
390
+ }
391
+ const routing = isObject(obj.routing) ? obj.routing : {};
392
+ const models = isObject(routing.models) ? routing.models : {};
393
+ const light = checkRequiredString(errors, "routing.models.LIGHT", models, "LIGHT");
394
+ const medium = checkRequiredString(errors, "routing.models.MEDIUM", models, "MEDIUM");
395
+ const heavy = checkRequiredString(errors, "routing.models.HEAVY", models, "HEAVY");
396
+ if (light)
397
+ checkProviderModelFormat(errors, "routing.models.LIGHT", light);
398
+ if (medium)
399
+ checkProviderModelFormat(errors, "routing.models.MEDIUM", medium);
400
+ if (heavy)
401
+ checkProviderModelFormat(errors, "routing.models.HEAVY", heavy);
402
+ if (routing.contextWindows !== undefined) {
403
+ if (!isObject(routing.contextWindows)) {
404
+ errors.push("routing.contextWindows: must be an object");
405
+ } else {
406
+ for (const [key, value] of Object.entries(routing.contextWindows)) {
407
+ if (typeof key !== "string") {
408
+ errors.push(`routing.contextWindows: keys must be strings`);
409
+ }
410
+ if (typeof value !== "number" || value <= 0) {
411
+ errors.push(`routing.contextWindows["${key}"]: must be a positive number, got ${String(value)}`);
412
+ }
413
+ }
414
+ }
415
+ }
416
+ const server = obj.server !== undefined && isObject(obj.server) ? obj.server : null;
417
+ if (server !== null && server.port !== undefined) {
418
+ checkOptionalNumberRange(errors, "server.port", server.port, 1024, 65535);
419
+ }
420
+ if (errors.length > 0) {
421
+ return { valid: false, errors };
422
+ }
423
+ return { valid: true, config: applyDefaults(obj) };
424
+ }
425
+
426
+ // src/config/loader.ts
427
+ function findConfigPath() {
428
+ const envPath = process.env.CLAWMUX_CONFIG;
429
+ if (envPath) {
430
+ return import_node_path.resolve(envPath);
431
+ }
432
+ return import_node_path.resolve(process.cwd(), "clawmux.json");
433
+ }
434
+ async function loadConfig(configPath) {
435
+ const filePath = configPath ?? findConfigPath();
436
+ let raw;
437
+ try {
438
+ raw = await import_promises2.readFile(filePath, "utf-8");
439
+ } catch (err) {
440
+ const message = err instanceof Error ? err.message : String(err);
441
+ return {
442
+ valid: false,
443
+ errors: [`Failed to read config file at ${filePath}: ${message}`]
444
+ };
445
+ }
446
+ let parsed;
447
+ try {
448
+ parsed = JSON.parse(raw);
449
+ } catch (err) {
450
+ const message = err instanceof Error ? err.message : String(err);
451
+ return {
452
+ valid: false,
453
+ errors: [`Invalid JSON in config file ${filePath}: ${message}`]
454
+ };
455
+ }
456
+ return validateConfig(parsed);
457
+ }
458
+
459
+ // src/config/watcher.ts
460
+ var import_node_fs = require("node:fs");
461
+ var import_promises3 = require("node:fs/promises");
462
+ function createConfigWatcher(configPath, onReload, options) {
463
+ const debounceMs = options?.debounceMs ?? 2000;
464
+ let watcher = null;
465
+ let debounceTimer = null;
466
+ let reloading = false;
467
+ let pendingReload = false;
468
+ async function reloadConfig() {
469
+ if (reloading) {
470
+ pendingReload = true;
471
+ return;
472
+ }
473
+ reloading = true;
474
+ try {
475
+ let raw;
476
+ try {
477
+ raw = await import_promises3.readFile(configPath, "utf-8");
478
+ } catch {
479
+ console.warn(`[config] Config file ${configPath} not found, keeping old config`);
480
+ return;
481
+ }
482
+ let parsed;
483
+ try {
484
+ parsed = JSON.parse(raw);
485
+ } catch (err) {
486
+ const message = err instanceof Error ? err.message : String(err);
487
+ console.warn(`[config] Invalid JSON in config change, ignored: ${message}`);
488
+ return;
489
+ }
490
+ const result = validateConfig(parsed);
491
+ if (result.valid) {
492
+ onReload(result.config);
493
+ console.log("[config] Reloaded clawmux.json");
494
+ } else {
495
+ console.warn(`[config] Invalid config change ignored: ${result.errors.join(", ")}`);
496
+ }
497
+ } finally {
498
+ reloading = false;
499
+ if (pendingReload) {
500
+ pendingReload = false;
501
+ scheduleReload();
502
+ }
503
+ }
504
+ }
505
+ function scheduleReload() {
506
+ if (debounceTimer !== null) {
507
+ clearTimeout(debounceTimer);
508
+ }
509
+ debounceTimer = setTimeout(() => {
510
+ debounceTimer = null;
511
+ reloadConfig();
512
+ }, debounceMs);
513
+ }
514
+ return {
515
+ start() {
516
+ if (watcher !== null)
517
+ return;
518
+ watcher = import_node_fs.watch(configPath, (eventType) => {
519
+ if (eventType === "rename") {
520
+ console.warn(`[config] Config file ${configPath} was deleted, keeping old config`);
521
+ return;
522
+ }
523
+ scheduleReload();
524
+ });
525
+ watcher.on("error", (err) => {
526
+ console.warn(`[config] Watcher error: ${err instanceof Error ? err.message : String(err)}`);
527
+ });
528
+ },
529
+ stop() {
530
+ if (debounceTimer !== null) {
531
+ clearTimeout(debounceTimer);
532
+ debounceTimer = null;
533
+ }
534
+ if (watcher !== null) {
535
+ watcher.close();
536
+ watcher = null;
537
+ }
538
+ },
539
+ isWatching() {
540
+ return watcher !== null;
541
+ }
542
+ };
543
+ }
544
+
545
+ // src/openclaw/config-reader.ts
546
+ var import_promises4 = require("node:fs/promises");
547
+ var import_node_path2 = require("node:path");
548
+ var ENV_VAR_PATTERN = /^\$\{([^}]+)\}$/;
549
+ function resolveEnvVar(value) {
550
+ const match = value.match(ENV_VAR_PATTERN);
551
+ if (match) {
552
+ return process.env[match[1]] ?? "";
553
+ }
554
+ return value;
555
+ }
556
+ function getHomeDir() {
557
+ return process.env.HOME ?? "/root";
558
+ }
559
+ function getConfigPath(override) {
560
+ if (override)
561
+ return override;
562
+ if (process.env.OPENCLAW_CONFIG_PATH)
563
+ return process.env.OPENCLAW_CONFIG_PATH;
564
+ return import_node_path2.join(getHomeDir(), ".openclaw", "openclaw.json");
565
+ }
566
+ async function readOpenClawConfig(configPath) {
567
+ const path = getConfigPath(configPath);
568
+ let text;
569
+ try {
570
+ text = await import_promises4.readFile(path, "utf-8");
571
+ } catch (err) {
572
+ const code = err.code;
573
+ if (code === "ENOENT" || code === "ENOTDIR") {
574
+ throw new Error(`openclaw.json not found at ${path}. Ensure OpenClaw is installed.`);
575
+ }
576
+ throw err;
577
+ }
578
+ try {
579
+ return JSON.parse(text);
580
+ } catch (err) {
581
+ const message = err instanceof Error ? err.message : String(err);
582
+ throw new Error(`Failed to parse openclaw.json: ${message}`);
583
+ }
584
+ }
585
+ function getAuthProfilesPath(agentId) {
586
+ const id = agentId ?? "main";
587
+ return import_node_path2.join(getHomeDir(), ".openclaw", "agents", id, "agent", "auth-profiles.json");
588
+ }
589
+ async function readAuthProfiles(agentId, profilesPath) {
590
+ const path = profilesPath ?? getAuthProfilesPath(agentId);
591
+ let text;
592
+ try {
593
+ text = await import_promises4.readFile(path, "utf-8");
594
+ } catch {
595
+ return [];
596
+ }
597
+ try {
598
+ const parsed = JSON.parse(text);
599
+ if (Array.isArray(parsed))
600
+ return parsed;
601
+ if (parsed && typeof parsed === "object" && parsed.profiles) {
602
+ return Object.entries(parsed.profiles).map(([key, profile]) => ({
603
+ provider: profile.provider ?? key.split(":")[0],
604
+ apiKey: profile.access ?? profile.apiKey,
605
+ token: profile.token
606
+ })).filter((p) => {
607
+ const token = p.apiKey ?? p.token;
608
+ if (!token || !token.includes("."))
609
+ return true;
610
+ try {
611
+ const payload = token.split(".")[1];
612
+ const decoded = JSON.parse(Buffer.from(payload, "base64").toString());
613
+ if (decoded.exp && decoded.exp * 1000 < Date.now())
614
+ return false;
615
+ } catch (_) {
616
+ return true;
617
+ }
618
+ return true;
619
+ });
620
+ }
621
+ return [];
622
+ } catch (err) {
623
+ const message = err instanceof Error ? err.message : String(err);
624
+ throw new Error(`Failed to parse auth-profiles.json: ${message}`);
625
+ }
626
+ }
627
+ function getProviderConfig(provider, config) {
628
+ return config.models?.providers?.[provider];
629
+ }
630
+ function lookupContextWindowFromConfig(modelKey, config) {
631
+ const [provider, ...rest] = modelKey.split("/");
632
+ const modelId = rest.join("/");
633
+ if (!provider || !modelId)
634
+ return;
635
+ const providerConfig = config.models?.providers?.[provider];
636
+ if (!providerConfig?.models)
637
+ return;
638
+ const model = providerConfig.models.find((m) => m.id === modelId);
639
+ return model?.contextWindow;
640
+ }
641
+
642
+ // src/openclaw/model-limits.ts
643
+ var import_promises5 = require("node:fs/promises");
644
+ var import_node_path3 = require("node:path");
645
+ var DEFAULT_CONTEXT_TOKENS = 200000;
646
+ var cachedCatalog = null;
647
+ function resolveContextWindow(modelKey, clawmuxContextWindows, openclawConfig, piAiCatalog) {
648
+ const fromClawmux = clawmuxContextWindows[modelKey];
649
+ if (typeof fromClawmux === "number" && fromClawmux > 0) {
650
+ return fromClawmux;
651
+ }
652
+ const fromOpenclaw = lookupContextWindowFromConfig(modelKey, openclawConfig);
653
+ if (typeof fromOpenclaw === "number" && fromOpenclaw > 0) {
654
+ return fromOpenclaw;
655
+ }
656
+ if (piAiCatalog) {
657
+ const [provider, ...rest] = modelKey.split("/");
658
+ const modelId = rest.join("/");
659
+ if (provider && modelId) {
660
+ const providerModels = piAiCatalog[provider];
661
+ if (providerModels) {
662
+ const entry = providerModels[modelId];
663
+ if (entry && typeof entry.contextWindow === "number" && entry.contextWindow > 0) {
664
+ return entry.contextWindow;
665
+ }
666
+ }
667
+ }
668
+ }
669
+ return DEFAULT_CONTEXT_TOKENS;
670
+ }
671
+ function resolveCompressionContextWindow(routingModels, clawmuxContextWindows, openclawConfig, piAiCatalog) {
672
+ const modelKeys = [routingModels.LIGHT, routingModels.MEDIUM, routingModels.HEAVY];
673
+ const uniqueKeys = [...new Set(modelKeys.filter((k) => k !== ""))];
674
+ if (uniqueKeys.length === 0) {
675
+ return DEFAULT_CONTEXT_TOKENS;
676
+ }
677
+ let min = Infinity;
678
+ for (const key of uniqueKeys) {
679
+ const window = resolveContextWindow(key, clawmuxContextWindows, openclawConfig, piAiCatalog);
680
+ if (window < min) {
681
+ min = window;
682
+ }
683
+ }
684
+ return min === Infinity ? DEFAULT_CONTEXT_TOKENS : min;
685
+ }
686
+ async function findOpenClawNodeModulesPath() {
687
+ try {
688
+ const { execSync } = await import("node:child_process");
689
+ const whichResult = execSync("which openclaw", { encoding: "utf-8" }).trim();
690
+ if (!whichResult)
691
+ return;
692
+ const resolved = await import_promises5.realpath(whichResult);
693
+ let dir = import_node_path3.dirname(resolved);
694
+ for (let i = 0;i < 10; i++) {
695
+ const candidate = import_node_path3.join(dir, "node_modules", "@mariozechner", "pi-ai", "dist", "models.generated.js");
696
+ try {
697
+ if (await fileExists(candidate)) {
698
+ return candidate;
699
+ }
700
+ } catch {}
701
+ const parent = import_node_path3.dirname(dir);
702
+ if (parent === dir)
703
+ break;
704
+ dir = parent;
705
+ }
706
+ } catch {}
707
+ const homeDir = process.env.HOME ?? "/root";
708
+ const fallbackPaths = [
709
+ import_node_path3.join(homeDir, ".npm-global", "lib", "node_modules", "openclaw", "node_modules", "@mariozechner", "pi-ai", "dist", "models.generated.js"),
710
+ import_node_path3.join(homeDir, ".local", "lib", "node_modules", "openclaw", "node_modules", "@mariozechner", "pi-ai", "dist", "models.generated.js")
711
+ ];
712
+ for (const path of fallbackPaths) {
713
+ try {
714
+ if (await fileExists(path)) {
715
+ return path;
716
+ }
717
+ } catch {}
718
+ }
719
+ return;
720
+ }
721
+ function parseCatalogFromSource(source) {
722
+ const modelsMatch = source.match(/export\s+const\s+MODELS\s*=\s*(\{[\s\S]*\});?\s*$/m);
723
+ if (!modelsMatch)
724
+ return;
725
+ try {
726
+ const fn = new Function(`return (${modelsMatch[1]});`);
727
+ const result = fn();
728
+ if (typeof result === "object" && result !== null && !Array.isArray(result)) {
729
+ return result;
730
+ }
731
+ } catch (err) {
732
+ console.warn("[clawmux] Failed to parse pi-ai model catalog:", err instanceof Error ? err.message : String(err));
733
+ }
734
+ return;
735
+ }
736
+ async function loadPiAiCatalog() {
737
+ if (cachedCatalog !== null) {
738
+ return cachedCatalog;
739
+ }
740
+ const filePath = await findOpenClawNodeModulesPath();
741
+ if (!filePath) {
742
+ console.warn("[clawmux] pi-ai model catalog not found — using default context windows");
743
+ cachedCatalog = undefined;
744
+ return;
745
+ }
746
+ try {
747
+ const source = await readFileText(filePath);
748
+ const catalog = parseCatalogFromSource(source);
749
+ if (catalog) {
750
+ const providerCount = Object.keys(catalog).length;
751
+ const modelCount = Object.values(catalog).reduce((sum, models) => sum + Object.keys(models).length, 0);
752
+ console.log(`[clawmux] Loaded pi-ai model catalog: ${providerCount} providers, ${modelCount} models`);
753
+ cachedCatalog = catalog;
754
+ return catalog;
755
+ }
756
+ console.warn("[clawmux] pi-ai model catalog found but could not be parsed");
757
+ cachedCatalog = undefined;
758
+ return;
759
+ } catch (err) {
760
+ console.warn("[clawmux] Failed to load pi-ai model catalog:", err instanceof Error ? err.message : String(err));
761
+ cachedCatalog = undefined;
762
+ return;
763
+ }
764
+ }
765
+
766
+ // src/adapters/registry.ts
767
+ var adapters = new Map;
768
+ function registerAdapter(adapter) {
769
+ adapters.set(adapter.apiType, adapter);
770
+ }
771
+ function getAdapter(apiType) {
772
+ return adapters.get(apiType);
773
+ }
774
+
775
+ // src/adapters/anthropic.ts
776
+ class AnthropicAdapter {
777
+ apiType = "anthropic-messages";
778
+ parseRequest(body) {
779
+ const raw = body;
780
+ const model = String(raw.model ?? "");
781
+ const messages = raw.messages ?? [];
782
+ const stream = raw.stream !== false;
783
+ const maxTokens = typeof raw.max_tokens === "number" ? raw.max_tokens : undefined;
784
+ const system = raw.system;
785
+ return {
786
+ model,
787
+ messages,
788
+ system,
789
+ stream,
790
+ maxTokens,
791
+ rawBody: raw
792
+ };
793
+ }
794
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
795
+ const url = `${baseUrl}/v1/messages`;
796
+ const headers = {
797
+ "x-api-key": auth.apiKey,
798
+ "anthropic-version": "2023-06-01",
799
+ "content-type": "application/json"
800
+ };
801
+ let bodyObj = {
802
+ ...parsed.rawBody,
803
+ model: targetModel
804
+ };
805
+ const isHaiku = targetModel.toLowerCase().includes("haiku");
806
+ const hasThinking = "thinking" in parsed.rawBody;
807
+ if (hasThinking && !isHaiku) {
808
+ headers["anthropic-beta"] = "interleaved-thinking-2025-05-14";
809
+ }
810
+ if (isHaiku && "thinking" in bodyObj) {
811
+ const { thinking: _, ...rest } = bodyObj;
812
+ bodyObj = rest;
813
+ }
814
+ return {
815
+ url,
816
+ method: "POST",
817
+ headers,
818
+ body: JSON.stringify(bodyObj)
819
+ };
820
+ }
821
+ modifyMessages(rawBody, compressedMessages) {
822
+ return {
823
+ ...rawBody,
824
+ messages: compressedMessages
825
+ };
826
+ }
827
+ parseResponse(body) {
828
+ const raw = body;
829
+ const id = String(raw.id ?? "");
830
+ const model = String(raw.model ?? "");
831
+ let content = "";
832
+ const contentBlocks = raw.content;
833
+ if (Array.isArray(contentBlocks)) {
834
+ const textParts = [];
835
+ for (const block of contentBlocks) {
836
+ if (typeof block === "object" && block !== null && block.type === "text" && typeof block.text === "string") {
837
+ textParts.push(block.text);
838
+ }
839
+ }
840
+ content = textParts.join("");
841
+ }
842
+ const stopReason = typeof raw.stop_reason === "string" ? raw.stop_reason : null;
843
+ let usage;
844
+ const rawUsage = raw.usage;
845
+ if (rawUsage) {
846
+ usage = {
847
+ inputTokens: typeof rawUsage.input_tokens === "number" ? rawUsage.input_tokens : 0,
848
+ outputTokens: typeof rawUsage.output_tokens === "number" ? rawUsage.output_tokens : 0
849
+ };
850
+ }
851
+ return { id, model, content, role: "assistant", stopReason, usage };
852
+ }
853
+ buildResponse(parsed) {
854
+ const result = {
855
+ id: parsed.id,
856
+ type: "message",
857
+ role: "assistant",
858
+ model: parsed.model,
859
+ content: [{ type: "text", text: parsed.content }],
860
+ stop_reason: parsed.stopReason
861
+ };
862
+ if (parsed.usage) {
863
+ result.usage = {
864
+ input_tokens: parsed.usage.inputTokens,
865
+ output_tokens: parsed.usage.outputTokens
866
+ };
867
+ }
868
+ return result;
869
+ }
870
+ parseStreamChunk(chunk) {
871
+ const events = [];
872
+ let eventType = "";
873
+ let dataStr = "";
874
+ for (const line of chunk.split(`
875
+ `)) {
876
+ if (line.startsWith("event: ")) {
877
+ eventType = line.slice(7).trim();
878
+ } else if (line.startsWith("data: ")) {
879
+ dataStr = line.slice(6);
880
+ }
881
+ }
882
+ if (!eventType && !dataStr)
883
+ return events;
884
+ if (eventType === "ping" || eventType === "content_block_start") {
885
+ return events;
886
+ }
887
+ let data = {};
888
+ if (dataStr) {
889
+ try {
890
+ data = JSON.parse(dataStr);
891
+ } catch {
892
+ return events;
893
+ }
894
+ }
895
+ switch (eventType) {
896
+ case "message_start": {
897
+ const message = data.message;
898
+ events.push({
899
+ type: "message_start",
900
+ id: String(message?.id ?? data.id ?? ""),
901
+ model: String(message?.model ?? data.model ?? "")
902
+ });
903
+ break;
904
+ }
905
+ case "content_block_delta": {
906
+ const delta = data.delta;
907
+ if (delta?.type === "text_delta" && typeof delta.text === "string") {
908
+ events.push({
909
+ type: "content_delta",
910
+ text: delta.text,
911
+ index: typeof data.index === "number" ? data.index : 0
912
+ });
913
+ }
914
+ break;
915
+ }
916
+ case "content_block_stop": {
917
+ events.push({
918
+ type: "content_stop",
919
+ index: typeof data.index === "number" ? data.index : 0
920
+ });
921
+ break;
922
+ }
923
+ case "message_delta": {
924
+ const rawUsage = data.usage;
925
+ let usage;
926
+ if (rawUsage) {
927
+ usage = {
928
+ inputTokens: typeof rawUsage.input_tokens === "number" ? rawUsage.input_tokens : 0,
929
+ outputTokens: typeof rawUsage.output_tokens === "number" ? rawUsage.output_tokens : 0
930
+ };
931
+ }
932
+ events.push({ type: "message_stop", usage });
933
+ break;
934
+ }
935
+ case "message_stop": {
936
+ events.push({ type: "message_stop" });
937
+ break;
938
+ }
939
+ }
940
+ return events;
941
+ }
942
+ buildStreamChunk(event) {
943
+ switch (event.type) {
944
+ case "message_start":
945
+ return `event: message_start
946
+ data: ${JSON.stringify({
947
+ type: "message_start",
948
+ message: {
949
+ id: event.id,
950
+ type: "message",
951
+ role: "assistant",
952
+ model: event.model
953
+ }
954
+ })}
955
+
956
+ `;
957
+ case "content_delta":
958
+ return `event: content_block_delta
959
+ data: ${JSON.stringify({
960
+ type: "content_block_delta",
961
+ index: event.index,
962
+ delta: { type: "text_delta", text: event.text }
963
+ })}
964
+
965
+ `;
966
+ case "content_stop":
967
+ return `event: content_block_stop
968
+ data: ${JSON.stringify({
969
+ type: "content_block_stop",
970
+ index: event.index
971
+ })}
972
+
973
+ `;
974
+ case "message_stop":
975
+ if (event.usage) {
976
+ return `event: message_delta
977
+ data: ${JSON.stringify({
978
+ type: "message_delta",
979
+ usage: {
980
+ input_tokens: event.usage.inputTokens,
981
+ output_tokens: event.usage.outputTokens
982
+ }
983
+ })}
984
+
985
+ ` + `event: message_stop
986
+ data: ${JSON.stringify({
987
+ type: "message_stop"
988
+ })}
989
+
990
+ `;
991
+ }
992
+ return `event: message_stop
993
+ data: ${JSON.stringify({
994
+ type: "message_stop"
995
+ })}
996
+
997
+ `;
998
+ case "error":
999
+ return `event: error
1000
+ data: ${JSON.stringify({
1001
+ type: "error",
1002
+ error: { message: event.message }
1003
+ })}
1004
+
1005
+ `;
1006
+ default:
1007
+ return "";
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ // src/adapters/openai-shared.ts
1013
+ function isRecord(value) {
1014
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1015
+ }
1016
+ function isMessageArray(value) {
1017
+ if (!Array.isArray(value))
1018
+ return false;
1019
+ return value.every((item) => isRecord(item) && typeof item.role === "string" && ("content" in item));
1020
+ }
1021
+ function extractSystemMessage(messages) {
1022
+ const systemMessages = [];
1023
+ const filtered = [];
1024
+ for (const msg of messages) {
1025
+ if (msg.role === "system" || msg.role === "developer") {
1026
+ if (typeof msg.content === "string") {
1027
+ systemMessages.push(msg.content);
1028
+ } else if (Array.isArray(msg.content)) {
1029
+ for (const part of msg.content) {
1030
+ if (isRecord(part) && part.type === "text" && typeof part.text === "string") {
1031
+ systemMessages.push(part.text);
1032
+ }
1033
+ }
1034
+ }
1035
+ } else {
1036
+ filtered.push(msg);
1037
+ }
1038
+ }
1039
+ return {
1040
+ system: systemMessages.length > 0 ? systemMessages.join(`
1041
+ `) : undefined,
1042
+ filtered
1043
+ };
1044
+ }
1045
+ function parseOpenAIBody(body) {
1046
+ if (!isRecord(body)) {
1047
+ throw new Error("Request body must be a JSON object");
1048
+ }
1049
+ const model = typeof body.model === "string" ? body.model : "";
1050
+ if (!model) {
1051
+ throw new Error("Missing required field: model");
1052
+ }
1053
+ const rawMessages = body.messages ?? body.input;
1054
+ if (!isMessageArray(rawMessages)) {
1055
+ throw new Error("Request must contain a valid 'messages' or 'input' array");
1056
+ }
1057
+ const { system, filtered } = extractSystemMessage(rawMessages);
1058
+ const stream = body.stream === true;
1059
+ const rawMax = body.max_tokens ?? body.max_output_tokens;
1060
+ const maxTokens = typeof rawMax === "number" ? rawMax : undefined;
1061
+ const rawBody = { ...body };
1062
+ return {
1063
+ model,
1064
+ messages: filtered,
1065
+ system,
1066
+ stream,
1067
+ maxTokens,
1068
+ rawBody
1069
+ };
1070
+ }
1071
+
1072
+ // src/adapters/openai-completions.ts
1073
+ class OpenAICompletionsAdapter {
1074
+ apiType = "openai-completions";
1075
+ parseRequest(body) {
1076
+ return parseOpenAIBody(body);
1077
+ }
1078
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
1079
+ const { rawBody } = parsed;
1080
+ const upstreamBody = {
1081
+ ...rawBody,
1082
+ model: targetModel
1083
+ };
1084
+ return {
1085
+ url: /\/v\d+\/?$/.test(baseUrl) ? `${baseUrl.replace(/\/$/, "")}/chat/completions` : `${baseUrl}/v1/chat/completions`,
1086
+ method: "POST",
1087
+ headers: {
1088
+ "Content-Type": "application/json",
1089
+ Authorization: `Bearer ${auth.apiKey}`
1090
+ },
1091
+ body: JSON.stringify(upstreamBody)
1092
+ };
1093
+ }
1094
+ modifyMessages(rawBody, compressedMessages) {
1095
+ return {
1096
+ ...rawBody,
1097
+ messages: compressedMessages
1098
+ };
1099
+ }
1100
+ parseResponse(body) {
1101
+ const raw = body;
1102
+ const id = String(raw.id ?? "");
1103
+ const model = String(raw.model ?? "");
1104
+ let content = "";
1105
+ let stopReason = null;
1106
+ const choices = raw.choices;
1107
+ if (Array.isArray(choices) && choices.length > 0) {
1108
+ const choice = choices[0];
1109
+ const message = choice.message;
1110
+ if (message && typeof message.content === "string") {
1111
+ content = message.content;
1112
+ }
1113
+ if (typeof choice.finish_reason === "string") {
1114
+ stopReason = choice.finish_reason;
1115
+ }
1116
+ }
1117
+ let usage;
1118
+ const rawUsage = raw.usage;
1119
+ if (rawUsage) {
1120
+ usage = {
1121
+ inputTokens: typeof rawUsage.prompt_tokens === "number" ? rawUsage.prompt_tokens : 0,
1122
+ outputTokens: typeof rawUsage.completion_tokens === "number" ? rawUsage.completion_tokens : 0
1123
+ };
1124
+ }
1125
+ return { id, model, content, role: "assistant", stopReason, usage };
1126
+ }
1127
+ buildResponse(parsed) {
1128
+ const result = {
1129
+ id: parsed.id,
1130
+ object: "chat.completion",
1131
+ model: parsed.model,
1132
+ choices: [
1133
+ {
1134
+ index: 0,
1135
+ message: { role: "assistant", content: parsed.content },
1136
+ finish_reason: parsed.stopReason
1137
+ }
1138
+ ]
1139
+ };
1140
+ if (parsed.usage) {
1141
+ result.usage = {
1142
+ prompt_tokens: parsed.usage.inputTokens,
1143
+ completion_tokens: parsed.usage.outputTokens,
1144
+ total_tokens: parsed.usage.inputTokens + parsed.usage.outputTokens
1145
+ };
1146
+ }
1147
+ return result;
1148
+ }
1149
+ parseStreamChunk(chunk) {
1150
+ const events = [];
1151
+ for (const line of chunk.split(`
1152
+ `)) {
1153
+ const trimmed = line.trim();
1154
+ if (!trimmed.startsWith("data: "))
1155
+ continue;
1156
+ const payload = trimmed.slice(6);
1157
+ if (payload === "[DONE]") {
1158
+ events.push({ type: "message_stop" });
1159
+ continue;
1160
+ }
1161
+ let data;
1162
+ try {
1163
+ data = JSON.parse(payload);
1164
+ } catch {
1165
+ continue;
1166
+ }
1167
+ const choices = data.choices;
1168
+ if (!Array.isArray(choices) || choices.length === 0) {
1169
+ if (data.id && data.model) {
1170
+ events.push({
1171
+ type: "message_start",
1172
+ id: String(data.id),
1173
+ model: String(data.model)
1174
+ });
1175
+ }
1176
+ continue;
1177
+ }
1178
+ const choice = choices[0];
1179
+ const delta = choice.delta;
1180
+ const finishReason = choice.finish_reason;
1181
+ if (delta?.role === "assistant" && !delta.content) {
1182
+ events.push({
1183
+ type: "message_start",
1184
+ id: String(data.id ?? ""),
1185
+ model: String(data.model ?? "")
1186
+ });
1187
+ } else if (typeof delta?.content === "string") {
1188
+ events.push({
1189
+ type: "content_delta",
1190
+ text: delta.content,
1191
+ index: typeof choice.index === "number" ? choice.index : 0
1192
+ });
1193
+ }
1194
+ if (typeof finishReason === "string" && finishReason !== "") {
1195
+ events.push({
1196
+ type: "content_stop",
1197
+ index: typeof choice.index === "number" ? choice.index : 0
1198
+ });
1199
+ let usage;
1200
+ const rawUsage = data.usage;
1201
+ if (rawUsage) {
1202
+ usage = {
1203
+ inputTokens: typeof rawUsage.prompt_tokens === "number" ? rawUsage.prompt_tokens : 0,
1204
+ outputTokens: typeof rawUsage.completion_tokens === "number" ? rawUsage.completion_tokens : 0
1205
+ };
1206
+ }
1207
+ events.push({ type: "message_stop", usage });
1208
+ }
1209
+ }
1210
+ return events;
1211
+ }
1212
+ buildStreamChunk(event) {
1213
+ switch (event.type) {
1214
+ case "message_start":
1215
+ return `data: ${JSON.stringify({
1216
+ id: event.id,
1217
+ object: "chat.completion.chunk",
1218
+ model: event.model,
1219
+ choices: [
1220
+ {
1221
+ index: 0,
1222
+ delta: { role: "assistant", content: "" },
1223
+ finish_reason: null
1224
+ }
1225
+ ]
1226
+ })}
1227
+
1228
+ `;
1229
+ case "content_delta":
1230
+ return `data: ${JSON.stringify({
1231
+ id: "",
1232
+ object: "chat.completion.chunk",
1233
+ choices: [
1234
+ {
1235
+ index: event.index,
1236
+ delta: { content: event.text },
1237
+ finish_reason: null
1238
+ }
1239
+ ]
1240
+ })}
1241
+
1242
+ `;
1243
+ case "content_stop":
1244
+ return `data: ${JSON.stringify({
1245
+ id: "",
1246
+ object: "chat.completion.chunk",
1247
+ choices: [
1248
+ {
1249
+ index: event.index,
1250
+ delta: {},
1251
+ finish_reason: "stop"
1252
+ }
1253
+ ]
1254
+ })}
1255
+
1256
+ `;
1257
+ case "message_stop":
1258
+ return `data: [DONE]
1259
+
1260
+ `;
1261
+ case "error":
1262
+ return `data: ${JSON.stringify({
1263
+ error: { message: event.message }
1264
+ })}
1265
+
1266
+ `;
1267
+ default:
1268
+ return "";
1269
+ }
1270
+ }
1271
+ }
1272
+ var openaiCompletionsAdapter = new OpenAICompletionsAdapter;
1273
+ registerAdapter(openaiCompletionsAdapter);
1274
+
1275
+ // src/adapters/openai-responses.ts
1276
+ class OpenAIResponsesAdapter {
1277
+ apiType = "openai-responses";
1278
+ parseRequest(body) {
1279
+ return parseOpenAIBody(body);
1280
+ }
1281
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
1282
+ const { rawBody } = parsed;
1283
+ const upstreamBody = {
1284
+ ...rawBody,
1285
+ model: targetModel
1286
+ };
1287
+ return {
1288
+ url: `${baseUrl}/v1/responses`,
1289
+ method: "POST",
1290
+ headers: {
1291
+ "Content-Type": "application/json",
1292
+ Authorization: `Bearer ${auth.apiKey}`
1293
+ },
1294
+ body: JSON.stringify(upstreamBody)
1295
+ };
1296
+ }
1297
+ modifyMessages(rawBody, compressedMessages) {
1298
+ const hasInput = "input" in rawBody;
1299
+ const fieldName = hasInput ? "input" : "messages";
1300
+ return {
1301
+ ...rawBody,
1302
+ [fieldName]: compressedMessages
1303
+ };
1304
+ }
1305
+ parseResponse(body) {
1306
+ const raw = body;
1307
+ const id = String(raw.id ?? "");
1308
+ const model = String(raw.model ?? "");
1309
+ let content = "";
1310
+ let stopReason = null;
1311
+ const output = raw.output;
1312
+ if (Array.isArray(output)) {
1313
+ const textParts = [];
1314
+ for (const item of output) {
1315
+ if (item.type === "message") {
1316
+ const msgContent = item.content;
1317
+ if (Array.isArray(msgContent)) {
1318
+ for (const part of msgContent) {
1319
+ if (part.type === "output_text" && typeof part.text === "string") {
1320
+ textParts.push(part.text);
1321
+ }
1322
+ }
1323
+ }
1324
+ }
1325
+ }
1326
+ content = textParts.join("");
1327
+ }
1328
+ if (typeof raw.status === "string") {
1329
+ stopReason = raw.status;
1330
+ }
1331
+ let usage;
1332
+ const rawUsage = raw.usage;
1333
+ if (rawUsage) {
1334
+ usage = {
1335
+ inputTokens: typeof rawUsage.input_tokens === "number" ? rawUsage.input_tokens : 0,
1336
+ outputTokens: typeof rawUsage.output_tokens === "number" ? rawUsage.output_tokens : 0
1337
+ };
1338
+ }
1339
+ return { id, model, content, role: "assistant", stopReason, usage };
1340
+ }
1341
+ buildResponse(parsed) {
1342
+ const result = {
1343
+ id: parsed.id,
1344
+ object: "response",
1345
+ model: parsed.model,
1346
+ status: parsed.stopReason ?? "completed",
1347
+ output: [
1348
+ {
1349
+ type: "message",
1350
+ role: "assistant",
1351
+ content: [
1352
+ { type: "output_text", text: parsed.content }
1353
+ ]
1354
+ }
1355
+ ]
1356
+ };
1357
+ if (parsed.usage) {
1358
+ result.usage = {
1359
+ input_tokens: parsed.usage.inputTokens,
1360
+ output_tokens: parsed.usage.outputTokens,
1361
+ total_tokens: parsed.usage.inputTokens + parsed.usage.outputTokens
1362
+ };
1363
+ }
1364
+ return result;
1365
+ }
1366
+ parseStreamChunk(chunk) {
1367
+ const events = [];
1368
+ for (const line of chunk.split(`
1369
+ `)) {
1370
+ const trimmed = line.trim();
1371
+ if (!trimmed.startsWith("data: "))
1372
+ continue;
1373
+ const payload = trimmed.slice(6);
1374
+ if (payload === "[DONE]") {
1375
+ events.push({ type: "message_stop" });
1376
+ continue;
1377
+ }
1378
+ let data;
1379
+ try {
1380
+ data = JSON.parse(payload);
1381
+ } catch {
1382
+ continue;
1383
+ }
1384
+ const eventType = String(data.type ?? "");
1385
+ switch (eventType) {
1386
+ case "response.created": {
1387
+ const response = data.response;
1388
+ events.push({
1389
+ type: "message_start",
1390
+ id: String(response?.id ?? data.id ?? ""),
1391
+ model: String(response?.model ?? data.model ?? "")
1392
+ });
1393
+ break;
1394
+ }
1395
+ case "response.output_text.delta": {
1396
+ events.push({
1397
+ type: "content_delta",
1398
+ text: typeof data.delta === "string" ? data.delta : "",
1399
+ index: typeof data.output_index === "number" ? data.output_index : 0
1400
+ });
1401
+ break;
1402
+ }
1403
+ case "response.output_text.done": {
1404
+ events.push({
1405
+ type: "content_stop",
1406
+ index: typeof data.output_index === "number" ? data.output_index : 0
1407
+ });
1408
+ break;
1409
+ }
1410
+ case "response.completed": {
1411
+ let usage;
1412
+ const response = data.response;
1413
+ const rawUsage = response?.usage;
1414
+ if (rawUsage) {
1415
+ usage = {
1416
+ inputTokens: typeof rawUsage.input_tokens === "number" ? rawUsage.input_tokens : 0,
1417
+ outputTokens: typeof rawUsage.output_tokens === "number" ? rawUsage.output_tokens : 0
1418
+ };
1419
+ }
1420
+ events.push({ type: "message_stop", usage });
1421
+ break;
1422
+ }
1423
+ }
1424
+ }
1425
+ return events;
1426
+ }
1427
+ buildStreamChunk(event) {
1428
+ switch (event.type) {
1429
+ case "message_start":
1430
+ return `data: ${JSON.stringify({
1431
+ type: "response.created",
1432
+ response: {
1433
+ id: event.id,
1434
+ object: "response",
1435
+ model: event.model,
1436
+ status: "in_progress"
1437
+ }
1438
+ })}
1439
+
1440
+ `;
1441
+ case "content_delta":
1442
+ return `data: ${JSON.stringify({
1443
+ type: "response.output_text.delta",
1444
+ output_index: event.index,
1445
+ delta: event.text
1446
+ })}
1447
+
1448
+ `;
1449
+ case "content_stop":
1450
+ return `data: ${JSON.stringify({
1451
+ type: "response.output_text.done",
1452
+ output_index: event.index
1453
+ })}
1454
+
1455
+ `;
1456
+ case "message_stop":
1457
+ if (event.usage) {
1458
+ return `data: ${JSON.stringify({
1459
+ type: "response.completed",
1460
+ response: {
1461
+ usage: {
1462
+ input_tokens: event.usage.inputTokens,
1463
+ output_tokens: event.usage.outputTokens
1464
+ }
1465
+ }
1466
+ })}
1467
+
1468
+ `;
1469
+ }
1470
+ return `data: ${JSON.stringify({
1471
+ type: "response.completed"
1472
+ })}
1473
+
1474
+ `;
1475
+ case "error":
1476
+ return `data: ${JSON.stringify({
1477
+ type: "error",
1478
+ error: { message: event.message }
1479
+ })}
1480
+
1481
+ `;
1482
+ default:
1483
+ return "";
1484
+ }
1485
+ }
1486
+ }
1487
+ var openaiResponsesAdapter = new OpenAIResponsesAdapter;
1488
+ registerAdapter(openaiResponsesAdapter);
1489
+
1490
+ // src/adapters/google.ts
1491
+ function googleRoleToStandard(role) {
1492
+ if (role === "model")
1493
+ return "assistant";
1494
+ return role ?? "user";
1495
+ }
1496
+ function standardRoleToGoogle(role) {
1497
+ if (role === "assistant")
1498
+ return "model";
1499
+ return "user";
1500
+ }
1501
+ function contentsToMessages(contents) {
1502
+ return contents.map((c) => {
1503
+ const text = c.parts.filter((p) => p.text !== undefined).map((p) => p.text).join("");
1504
+ return {
1505
+ role: googleRoleToStandard(c.role),
1506
+ content: text || c.parts
1507
+ };
1508
+ });
1509
+ }
1510
+ function messagesToContents(messages) {
1511
+ return messages.map((m) => ({
1512
+ role: standardRoleToGoogle(m.role),
1513
+ parts: typeof m.content === "string" ? [{ text: m.content }] : Array.isArray(m.content) ? m.content : [{ text: String(m.content) }]
1514
+ }));
1515
+ }
1516
+ function mapGoogleFinishReason(reason) {
1517
+ if (reason === null)
1518
+ return null;
1519
+ switch (reason) {
1520
+ case "STOP":
1521
+ return "stop";
1522
+ case "MAX_TOKENS":
1523
+ return "max_tokens";
1524
+ case "SAFETY":
1525
+ return "content_filter";
1526
+ default:
1527
+ return reason.toLowerCase();
1528
+ }
1529
+ }
1530
+ function mapStopReasonToGoogle(reason) {
1531
+ if (reason === null)
1532
+ return "STOP";
1533
+ switch (reason) {
1534
+ case "stop":
1535
+ return "STOP";
1536
+ case "max_tokens":
1537
+ return "MAX_TOKENS";
1538
+ case "content_filter":
1539
+ return "SAFETY";
1540
+ default:
1541
+ return reason.toUpperCase();
1542
+ }
1543
+ }
1544
+
1545
+ class GoogleGenerativeAIAdapter {
1546
+ apiType = "google-generative-ai";
1547
+ parseRequest(body) {
1548
+ const raw = body;
1549
+ const model = raw.model ?? "";
1550
+ const contents = raw.contents ?? [];
1551
+ const messages = contentsToMessages(contents);
1552
+ let system;
1553
+ if (raw.systemInstruction?.parts) {
1554
+ system = raw.systemInstruction.parts.filter((p) => p.text !== undefined).map((p) => p.text).join("");
1555
+ }
1556
+ return {
1557
+ model,
1558
+ messages,
1559
+ system,
1560
+ stream: raw.stream !== false,
1561
+ maxTokens: raw.generationConfig?.maxOutputTokens,
1562
+ rawBody: raw
1563
+ };
1564
+ }
1565
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
1566
+ const endpoint = parsed.stream ? `${baseUrl}/v1beta/models/${targetModel}:streamGenerateContent?alt=sse` : `${baseUrl}/v1beta/models/${targetModel}:generateContent`;
1567
+ const contents = messagesToContents(parsed.messages);
1568
+ const requestBody = {
1569
+ ...parsed.rawBody,
1570
+ contents
1571
+ };
1572
+ delete requestBody.model;
1573
+ delete requestBody.stream;
1574
+ if (parsed.system) {
1575
+ requestBody.systemInstruction = {
1576
+ parts: [{ text: parsed.system }]
1577
+ };
1578
+ }
1579
+ if (parsed.maxTokens !== undefined) {
1580
+ requestBody.generationConfig = {
1581
+ ...requestBody.generationConfig,
1582
+ maxOutputTokens: parsed.maxTokens
1583
+ };
1584
+ }
1585
+ return {
1586
+ url: endpoint,
1587
+ method: "POST",
1588
+ headers: {
1589
+ "Content-Type": "application/json",
1590
+ [auth.headerName || "x-goog-api-key"]: auth.headerValue || auth.apiKey
1591
+ },
1592
+ body: JSON.stringify(requestBody)
1593
+ };
1594
+ }
1595
+ modifyMessages(rawBody, compressedMessages) {
1596
+ return {
1597
+ ...rawBody,
1598
+ contents: messagesToContents(compressedMessages)
1599
+ };
1600
+ }
1601
+ parseResponse(body) {
1602
+ const raw = body;
1603
+ const candidates = raw.candidates;
1604
+ const candidate = candidates?.[0];
1605
+ const content = candidate?.content;
1606
+ const text = content?.parts?.filter((p) => p.text !== undefined).map((p) => p.text).join("") ?? "";
1607
+ const finishReason = candidate?.finishReason;
1608
+ const usageMeta = raw.usageMetadata;
1609
+ return {
1610
+ id: raw.id ?? `google-${Date.now()}`,
1611
+ model: raw.modelVersion ?? "",
1612
+ content: text,
1613
+ role: "assistant",
1614
+ stopReason: mapGoogleFinishReason(finishReason ?? null),
1615
+ usage: usageMeta ? {
1616
+ inputTokens: usageMeta.promptTokenCount ?? 0,
1617
+ outputTokens: usageMeta.candidatesTokenCount ?? 0
1618
+ } : undefined
1619
+ };
1620
+ }
1621
+ buildResponse(parsed) {
1622
+ const result = {
1623
+ candidates: [
1624
+ {
1625
+ content: {
1626
+ parts: [{ text: parsed.content }],
1627
+ role: "model"
1628
+ },
1629
+ finishReason: mapStopReasonToGoogle(parsed.stopReason)
1630
+ }
1631
+ ]
1632
+ };
1633
+ if (parsed.usage) {
1634
+ result.usageMetadata = {
1635
+ promptTokenCount: parsed.usage.inputTokens,
1636
+ candidatesTokenCount: parsed.usage.outputTokens
1637
+ };
1638
+ }
1639
+ return result;
1640
+ }
1641
+ parseStreamChunk(chunk) {
1642
+ const events = [];
1643
+ const lines = chunk.split(`
1644
+ `);
1645
+ for (const line of lines) {
1646
+ const trimmed = line.trim();
1647
+ if (!trimmed.startsWith("data:"))
1648
+ continue;
1649
+ const jsonStr = trimmed.slice(5).trim();
1650
+ if (jsonStr === "" || jsonStr === "[DONE]")
1651
+ continue;
1652
+ let parsed;
1653
+ try {
1654
+ parsed = JSON.parse(jsonStr);
1655
+ } catch {
1656
+ continue;
1657
+ }
1658
+ const candidates = parsed.candidates;
1659
+ const candidate = candidates?.[0];
1660
+ if (!candidate)
1661
+ continue;
1662
+ const content = candidate.content;
1663
+ const text = content?.parts?.filter((p) => p.text !== undefined).map((p) => p.text).join("") ?? "";
1664
+ const finishReason = candidate.finishReason;
1665
+ if (content?.role === "model" && text !== "") {
1666
+ events.push({
1667
+ type: "message_start",
1668
+ id: parsed.id ?? `google-${Date.now()}`,
1669
+ model: parsed.modelVersion ?? ""
1670
+ });
1671
+ events.push({ type: "content_delta", text, index: 0 });
1672
+ } else if (text !== "") {
1673
+ events.push({ type: "content_delta", text, index: 0 });
1674
+ }
1675
+ if (finishReason && finishReason !== "FINISH_REASON_UNSPECIFIED") {
1676
+ const usageMeta = parsed.usageMetadata;
1677
+ events.push({ type: "content_stop", index: 0 });
1678
+ events.push({
1679
+ type: "message_stop",
1680
+ usage: usageMeta ? {
1681
+ inputTokens: usageMeta.promptTokenCount ?? 0,
1682
+ outputTokens: usageMeta.candidatesTokenCount ?? 0
1683
+ } : undefined
1684
+ });
1685
+ }
1686
+ }
1687
+ return events;
1688
+ }
1689
+ buildStreamChunk(event) {
1690
+ switch (event.type) {
1691
+ case "message_start":
1692
+ return `data: ${JSON.stringify({
1693
+ candidates: [
1694
+ {
1695
+ content: { parts: [{ text: "" }], role: "model" }
1696
+ }
1697
+ ]
1698
+ })}
1699
+
1700
+ `;
1701
+ case "content_delta":
1702
+ return `data: ${JSON.stringify({
1703
+ candidates: [
1704
+ {
1705
+ content: { parts: [{ text: event.text }], role: "model" }
1706
+ }
1707
+ ]
1708
+ })}
1709
+
1710
+ `;
1711
+ case "content_stop":
1712
+ return "";
1713
+ case "message_stop":
1714
+ return `data: ${JSON.stringify({
1715
+ candidates: [
1716
+ {
1717
+ content: { parts: [{ text: "" }], role: "model" },
1718
+ finishReason: "STOP"
1719
+ }
1720
+ ],
1721
+ ...event.usage ? {
1722
+ usageMetadata: {
1723
+ promptTokenCount: event.usage.inputTokens,
1724
+ candidatesTokenCount: event.usage.outputTokens
1725
+ }
1726
+ } : {}
1727
+ })}
1728
+
1729
+ `;
1730
+ case "error":
1731
+ return `data: ${JSON.stringify({
1732
+ error: { message: event.message }
1733
+ })}
1734
+
1735
+ `;
1736
+ }
1737
+ }
1738
+ }
1739
+ var googleAdapter = new GoogleGenerativeAIAdapter;
1740
+ registerAdapter(googleAdapter);
1741
+
1742
+ // src/adapters/ollama.ts
1743
+ class OllamaAdapter {
1744
+ apiType = "ollama";
1745
+ parseRequest(body) {
1746
+ const raw = body;
1747
+ const model = raw.model ?? "";
1748
+ const messages = raw.messages ?? [];
1749
+ const stream = raw.stream !== false;
1750
+ let system;
1751
+ const filteredMessages = [];
1752
+ for (const msg of messages) {
1753
+ if (msg.role === "system" && typeof msg.content === "string") {
1754
+ system = msg.content;
1755
+ } else {
1756
+ filteredMessages.push(msg);
1757
+ }
1758
+ }
1759
+ return {
1760
+ model,
1761
+ messages: filteredMessages,
1762
+ system,
1763
+ stream,
1764
+ maxTokens: raw.options?.num_predict,
1765
+ rawBody: raw
1766
+ };
1767
+ }
1768
+ buildUpstreamRequest(parsed, targetModel, baseUrl, _auth) {
1769
+ const messages = [];
1770
+ if (parsed.system) {
1771
+ messages.push({ role: "system", content: parsed.system });
1772
+ }
1773
+ messages.push(...parsed.messages);
1774
+ const requestBody = {
1775
+ ...parsed.rawBody,
1776
+ model: targetModel,
1777
+ messages,
1778
+ stream: parsed.stream
1779
+ };
1780
+ if (parsed.maxTokens !== undefined) {
1781
+ requestBody.options = {
1782
+ ...requestBody.options,
1783
+ num_predict: parsed.maxTokens
1784
+ };
1785
+ }
1786
+ return {
1787
+ url: `${baseUrl}/api/chat`,
1788
+ method: "POST",
1789
+ headers: {
1790
+ "Content-Type": "application/json"
1791
+ },
1792
+ body: JSON.stringify(requestBody)
1793
+ };
1794
+ }
1795
+ modifyMessages(rawBody, compressedMessages) {
1796
+ return {
1797
+ ...rawBody,
1798
+ messages: compressedMessages
1799
+ };
1800
+ }
1801
+ parseResponse(body) {
1802
+ const raw = body;
1803
+ const message = raw.message;
1804
+ const model = raw.model ?? "";
1805
+ return {
1806
+ id: `ollama-${Date.now()}`,
1807
+ model,
1808
+ content: message?.content ?? "",
1809
+ role: "assistant",
1810
+ stopReason: raw.done === true ? "stop" : null,
1811
+ usage: raw.prompt_eval_count !== undefined || raw.eval_count !== undefined ? {
1812
+ inputTokens: raw.prompt_eval_count ?? 0,
1813
+ outputTokens: raw.eval_count ?? 0
1814
+ } : undefined
1815
+ };
1816
+ }
1817
+ buildResponse(parsed) {
1818
+ const result = {
1819
+ model: parsed.model,
1820
+ message: {
1821
+ role: "assistant",
1822
+ content: parsed.content
1823
+ },
1824
+ done: parsed.stopReason === "stop"
1825
+ };
1826
+ if (parsed.usage) {
1827
+ result.prompt_eval_count = parsed.usage.inputTokens;
1828
+ result.eval_count = parsed.usage.outputTokens;
1829
+ }
1830
+ return result;
1831
+ }
1832
+ parseStreamChunk(chunk) {
1833
+ const events = [];
1834
+ const lines = chunk.split(`
1835
+ `);
1836
+ for (const line of lines) {
1837
+ const trimmed = line.trim();
1838
+ if (trimmed === "")
1839
+ continue;
1840
+ let parsed;
1841
+ try {
1842
+ parsed = JSON.parse(trimmed);
1843
+ } catch {
1844
+ continue;
1845
+ }
1846
+ const message = parsed.message;
1847
+ const done = parsed.done === true;
1848
+ if (message?.role === "assistant" && !done) {
1849
+ if (events.length === 0 && message.content !== undefined) {
1850
+ events.push({
1851
+ type: "message_start",
1852
+ id: `ollama-${Date.now()}`,
1853
+ model: parsed.model ?? ""
1854
+ });
1855
+ }
1856
+ if (message.content !== undefined) {
1857
+ events.push({
1858
+ type: "content_delta",
1859
+ text: message.content,
1860
+ index: 0
1861
+ });
1862
+ }
1863
+ }
1864
+ if (done) {
1865
+ events.push({ type: "content_stop", index: 0 });
1866
+ events.push({
1867
+ type: "message_stop",
1868
+ usage: parsed.prompt_eval_count !== undefined || parsed.eval_count !== undefined ? {
1869
+ inputTokens: parsed.prompt_eval_count ?? 0,
1870
+ outputTokens: parsed.eval_count ?? 0
1871
+ } : undefined
1872
+ });
1873
+ }
1874
+ }
1875
+ return events;
1876
+ }
1877
+ buildStreamChunk(event) {
1878
+ switch (event.type) {
1879
+ case "message_start":
1880
+ return `${JSON.stringify({
1881
+ model: event.model,
1882
+ message: { role: "assistant", content: "" },
1883
+ done: false
1884
+ })}
1885
+ `;
1886
+ case "content_delta":
1887
+ return `${JSON.stringify({
1888
+ message: { role: "assistant", content: event.text },
1889
+ done: false
1890
+ })}
1891
+ `;
1892
+ case "content_stop":
1893
+ return "";
1894
+ case "message_stop":
1895
+ return `${JSON.stringify({
1896
+ done: true,
1897
+ ...event.usage ? {
1898
+ prompt_eval_count: event.usage.inputTokens,
1899
+ eval_count: event.usage.outputTokens
1900
+ } : {}
1901
+ })}
1902
+ `;
1903
+ case "error":
1904
+ return `${JSON.stringify({
1905
+ error: event.message,
1906
+ done: true
1907
+ })}
1908
+ `;
1909
+ }
1910
+ }
1911
+ }
1912
+ var ollamaAdapter = new OllamaAdapter;
1913
+ registerAdapter(ollamaAdapter);
1914
+
1915
+ // src/utils/aws-sigv4.ts
1916
+ var import_node_crypto = require("node:crypto");
1917
+ var SERVICE = "bedrock";
1918
+ function sha256(data) {
1919
+ return import_node_crypto.createHash("sha256").update(data).digest("hex");
1920
+ }
1921
+ function hmacSha256(key, data) {
1922
+ return import_node_crypto.createHmac("sha256", key).update(data).digest();
1923
+ }
1924
+ function hmacSha256Hex(key, data) {
1925
+ return import_node_crypto.createHmac("sha256", key).update(data).digest("hex");
1926
+ }
1927
+ function awsUriEncode(str) {
1928
+ return encodeURIComponent(str).replace(/!/g, "%21").replace(/'/g, "%27").replace(/\(/g, "%28").replace(/\)/g, "%29").replace(/\*/g, "%2A");
1929
+ }
1930
+ function buildCanonicalUri(pathname) {
1931
+ if (pathname === "" || pathname === "/")
1932
+ return "/";
1933
+ const segments = pathname.split("/");
1934
+ return segments.map((segment) => segment === "" ? "" : awsUriEncode(awsUriEncode(segment))).join("/");
1935
+ }
1936
+ function formatDateStamp(date) {
1937
+ return date.toISOString().slice(0, 10).replace(/-/g, "");
1938
+ }
1939
+ function formatAmzDate(date) {
1940
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
1941
+ }
1942
+ function deriveSigningKey(secretKey, dateStamp, region, service) {
1943
+ const kDate = hmacSha256(`AWS4${secretKey}`, dateStamp);
1944
+ const kRegion = hmacSha256(kDate, region);
1945
+ const kService = hmacSha256(kRegion, service);
1946
+ return hmacSha256(kService, "aws4_request");
1947
+ }
1948
+ function signRequest(request, credentials, now) {
1949
+ const date = now ?? new Date;
1950
+ const dateStamp = formatDateStamp(date);
1951
+ const amzDate = formatAmzDate(date);
1952
+ const url = new URL(request.url);
1953
+ const canonicalUri = buildCanonicalUri(url.pathname);
1954
+ const sortedParams = [...url.searchParams.entries()].sort((a, b) => a[0].localeCompare(b[0]));
1955
+ const canonicalQueryString = sortedParams.map(([k, v]) => `${awsUriEncode(k)}=${awsUriEncode(v)}`).join("&");
1956
+ const payloadHash = sha256(request.body);
1957
+ const headersToSign = {};
1958
+ for (const [k, v] of Object.entries(request.headers)) {
1959
+ headersToSign[k.toLowerCase()] = v.trim();
1960
+ }
1961
+ headersToSign["host"] = url.host;
1962
+ headersToSign["x-amz-date"] = amzDate;
1963
+ headersToSign["x-amz-content-sha256"] = payloadHash;
1964
+ if (credentials.sessionToken) {
1965
+ headersToSign["x-amz-security-token"] = credentials.sessionToken;
1966
+ }
1967
+ const sortedHeaderKeys = Object.keys(headersToSign).sort();
1968
+ const canonicalHeaders = sortedHeaderKeys.map((k) => `${k}:${headersToSign[k]}`).join(`
1969
+ `) + `
1970
+ `;
1971
+ const signedHeaders = sortedHeaderKeys.join(";");
1972
+ const canonicalRequest = [
1973
+ request.method,
1974
+ canonicalUri,
1975
+ canonicalQueryString,
1976
+ canonicalHeaders,
1977
+ signedHeaders,
1978
+ payloadHash
1979
+ ].join(`
1980
+ `);
1981
+ const credentialScope = `${dateStamp}/${credentials.region}/${SERVICE}/aws4_request`;
1982
+ const stringToSign = [
1983
+ "AWS4-HMAC-SHA256",
1984
+ amzDate,
1985
+ credentialScope,
1986
+ sha256(canonicalRequest)
1987
+ ].join(`
1988
+ `);
1989
+ const signingKey = deriveSigningKey(credentials.secretAccessKey, dateStamp, credentials.region, SERVICE);
1990
+ const signature = hmacSha256Hex(signingKey, stringToSign);
1991
+ const authorization = `AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${credentialScope}, ` + `SignedHeaders=${signedHeaders}, Signature=${signature}`;
1992
+ const result = {
1993
+ Authorization: authorization,
1994
+ "x-amz-date": amzDate,
1995
+ "x-amz-content-sha256": payloadHash
1996
+ };
1997
+ if (credentials.sessionToken) {
1998
+ result["x-amz-security-token"] = credentials.sessionToken;
1999
+ }
2000
+ return result;
2001
+ }
2002
+ function extractRegionFromUrl(url) {
2003
+ const match = url.match(/\.([a-z0-9-]+)\.amazonaws\.com/);
2004
+ return match?.[1];
2005
+ }
2006
+
2007
+ // src/adapters/bedrock.ts
2008
+ function bedrockMessagesToStandard(messages) {
2009
+ return messages.map((m) => {
2010
+ if (typeof m.content === "string") {
2011
+ return { role: m.role, content: m.content };
2012
+ }
2013
+ const textParts = m.content.filter((b) => b.text !== undefined);
2014
+ if (textParts.length === 1) {
2015
+ return { role: m.role, content: textParts[0].text };
2016
+ }
2017
+ return { role: m.role, content: m.content };
2018
+ });
2019
+ }
2020
+ function standardMessagesToBedrock(messages) {
2021
+ return messages.map((m) => {
2022
+ if (typeof m.content === "string") {
2023
+ return { role: m.role, content: [{ text: m.content }] };
2024
+ }
2025
+ if (Array.isArray(m.content)) {
2026
+ return { role: m.role, content: m.content };
2027
+ }
2028
+ return { role: m.role, content: [{ text: String(m.content) }] };
2029
+ });
2030
+ }
2031
+ function mapBedrockStopReason(reason) {
2032
+ if (reason === null)
2033
+ return null;
2034
+ switch (reason) {
2035
+ case "end_turn":
2036
+ return "stop";
2037
+ case "max_tokens":
2038
+ return "max_tokens";
2039
+ case "content_filtered":
2040
+ return "content_filter";
2041
+ default:
2042
+ return reason;
2043
+ }
2044
+ }
2045
+ function mapStopReasonToBedrock(reason) {
2046
+ if (reason === null)
2047
+ return "end_turn";
2048
+ switch (reason) {
2049
+ case "stop":
2050
+ return "end_turn";
2051
+ case "max_tokens":
2052
+ return "max_tokens";
2053
+ case "content_filter":
2054
+ return "content_filtered";
2055
+ default:
2056
+ return reason;
2057
+ }
2058
+ }
2059
+
2060
+ class BedrockAdapter {
2061
+ apiType = "bedrock-converse-stream";
2062
+ parseRequest(body) {
2063
+ const raw = body;
2064
+ const model = raw.modelId ?? "";
2065
+ const messages = raw.messages ? bedrockMessagesToStandard(raw.messages) : [];
2066
+ let system;
2067
+ if (raw.system && raw.system.length > 0) {
2068
+ if (raw.system.length === 1) {
2069
+ system = raw.system[0].text;
2070
+ } else {
2071
+ system = raw.system.map((s) => ({ type: "text", text: s.text }));
2072
+ }
2073
+ }
2074
+ return {
2075
+ model,
2076
+ messages,
2077
+ system,
2078
+ stream: true,
2079
+ maxTokens: raw.inferenceConfig?.maxTokens,
2080
+ rawBody: raw
2081
+ };
2082
+ }
2083
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
2084
+ const bedrockMessages = standardMessagesToBedrock(parsed.messages);
2085
+ const requestBody = {
2086
+ ...parsed.rawBody,
2087
+ messages: bedrockMessages
2088
+ };
2089
+ delete requestBody.modelId;
2090
+ if (parsed.system) {
2091
+ if (typeof parsed.system === "string") {
2092
+ requestBody.system = [{ text: parsed.system }];
2093
+ } else {
2094
+ requestBody.system = parsed.system.map((s) => ({ text: s.text }));
2095
+ }
2096
+ }
2097
+ if (parsed.maxTokens !== undefined) {
2098
+ requestBody.inferenceConfig = {
2099
+ ...requestBody.inferenceConfig,
2100
+ maxTokens: parsed.maxTokens
2101
+ };
2102
+ }
2103
+ const url = `${baseUrl}/model/${targetModel}/converse-stream`;
2104
+ const body = JSON.stringify(requestBody);
2105
+ const headers = {
2106
+ "Content-Type": "application/json"
2107
+ };
2108
+ if (auth.awsAccessKeyId && auth.awsSecretKey && auth.awsRegion) {
2109
+ const sigv4Headers = signRequest({ method: "POST", url, headers, body }, {
2110
+ accessKeyId: auth.awsAccessKeyId,
2111
+ secretAccessKey: auth.awsSecretKey,
2112
+ sessionToken: auth.awsSessionToken,
2113
+ region: auth.awsRegion
2114
+ });
2115
+ Object.assign(headers, sigv4Headers);
2116
+ } else if (auth.apiKey) {
2117
+ headers[auth.headerName || "Authorization"] = auth.headerValue || auth.apiKey;
2118
+ }
2119
+ return { url, method: "POST", headers, body };
2120
+ }
2121
+ modifyMessages(rawBody, compressedMessages) {
2122
+ return {
2123
+ ...rawBody,
2124
+ messages: standardMessagesToBedrock(compressedMessages)
2125
+ };
2126
+ }
2127
+ parseResponse(body) {
2128
+ const raw = body;
2129
+ const output = raw.output;
2130
+ const message = output?.message;
2131
+ const text = message?.content?.filter((b) => b.text !== undefined).map((b) => b.text).join("") ?? "";
2132
+ const stopReason = raw.stopReason;
2133
+ const usage = raw.usage;
2134
+ return {
2135
+ id: raw.requestId ?? `bedrock-${Date.now()}`,
2136
+ model: raw.modelId ?? "",
2137
+ content: text,
2138
+ role: "assistant",
2139
+ stopReason: mapBedrockStopReason(stopReason ?? null),
2140
+ usage: usage ? {
2141
+ inputTokens: usage.inputTokens ?? 0,
2142
+ outputTokens: usage.outputTokens ?? 0
2143
+ } : undefined
2144
+ };
2145
+ }
2146
+ buildResponse(parsed) {
2147
+ const result = {
2148
+ output: {
2149
+ message: {
2150
+ role: "assistant",
2151
+ content: [{ text: parsed.content }]
2152
+ }
2153
+ },
2154
+ stopReason: mapStopReasonToBedrock(parsed.stopReason)
2155
+ };
2156
+ if (parsed.usage) {
2157
+ result.usage = {
2158
+ inputTokens: parsed.usage.inputTokens,
2159
+ outputTokens: parsed.usage.outputTokens
2160
+ };
2161
+ }
2162
+ return result;
2163
+ }
2164
+ parseStreamChunk(chunk) {
2165
+ const events = [];
2166
+ const lines = chunk.split(`
2167
+ `);
2168
+ for (const line of lines) {
2169
+ const trimmed = line.trim();
2170
+ if (trimmed === "")
2171
+ continue;
2172
+ let parsed;
2173
+ try {
2174
+ parsed = JSON.parse(trimmed);
2175
+ } catch {
2176
+ continue;
2177
+ }
2178
+ if (parsed.messageStart !== undefined) {
2179
+ const start = parsed.messageStart;
2180
+ events.push({
2181
+ type: "message_start",
2182
+ id: `bedrock-${Date.now()}`,
2183
+ model: ""
2184
+ });
2185
+ }
2186
+ if (parsed.contentBlockDelta !== undefined) {
2187
+ const delta = parsed.contentBlockDelta;
2188
+ events.push({
2189
+ type: "content_delta",
2190
+ text: delta.delta?.text ?? "",
2191
+ index: delta.contentBlockIndex ?? 0
2192
+ });
2193
+ }
2194
+ if (parsed.contentBlockStop !== undefined) {
2195
+ const stop = parsed.contentBlockStop;
2196
+ events.push({
2197
+ type: "content_stop",
2198
+ index: stop.contentBlockIndex ?? 0
2199
+ });
2200
+ }
2201
+ if (parsed.messageStop !== undefined) {
2202
+ const stop = parsed.messageStop;
2203
+ events.push({
2204
+ type: "message_stop",
2205
+ usage: undefined
2206
+ });
2207
+ }
2208
+ if (parsed.metadata !== undefined) {
2209
+ const meta = parsed.metadata;
2210
+ if (meta.usage) {
2211
+ events.push({
2212
+ type: "message_stop",
2213
+ usage: {
2214
+ inputTokens: meta.usage.inputTokens ?? 0,
2215
+ outputTokens: meta.usage.outputTokens ?? 0
2216
+ }
2217
+ });
2218
+ }
2219
+ }
2220
+ }
2221
+ return events;
2222
+ }
2223
+ buildStreamChunk(event) {
2224
+ switch (event.type) {
2225
+ case "message_start":
2226
+ return `${JSON.stringify({
2227
+ messageStart: { role: "assistant" }
2228
+ })}
2229
+ `;
2230
+ case "content_delta":
2231
+ return `${JSON.stringify({
2232
+ contentBlockDelta: {
2233
+ delta: { text: event.text },
2234
+ contentBlockIndex: event.index
2235
+ }
2236
+ })}
2237
+ `;
2238
+ case "content_stop":
2239
+ return `${JSON.stringify({
2240
+ contentBlockStop: { contentBlockIndex: event.index }
2241
+ })}
2242
+ `;
2243
+ case "message_stop":
2244
+ if (event.usage) {
2245
+ return `${JSON.stringify({
2246
+ messageStop: { stopReason: "end_turn" }
2247
+ })}
2248
+ ${JSON.stringify({
2249
+ metadata: {
2250
+ usage: {
2251
+ inputTokens: event.usage.inputTokens,
2252
+ outputTokens: event.usage.outputTokens
2253
+ }
2254
+ }
2255
+ })}
2256
+ `;
2257
+ }
2258
+ return `${JSON.stringify({
2259
+ messageStop: { stopReason: "end_turn" }
2260
+ })}
2261
+ `;
2262
+ case "error":
2263
+ return `${JSON.stringify({
2264
+ error: { message: event.message }
2265
+ })}
2266
+ `;
2267
+ }
2268
+ }
2269
+ }
2270
+ var bedrockAdapter = new BedrockAdapter;
2271
+ registerAdapter(bedrockAdapter);
2272
+
2273
+ // src/adapters/openai-codex.ts
2274
+ class OpenAICodexAdapter {
2275
+ apiType = "openai-codex-responses";
2276
+ parseRequest(body) {
2277
+ return parseOpenAIBody(body);
2278
+ }
2279
+ buildUpstreamRequest(parsed, targetModel, baseUrl, auth) {
2280
+ const { rawBody } = parsed;
2281
+ const upstreamBody = { ...rawBody };
2282
+ upstreamBody.model = targetModel;
2283
+ upstreamBody.stream = true;
2284
+ upstreamBody.store = false;
2285
+ if (!upstreamBody.instructions) {
2286
+ upstreamBody.instructions = upstreamBody.system ?? "You are a helpful assistant.";
2287
+ }
2288
+ delete upstreamBody.system;
2289
+ if (!upstreamBody.input && upstreamBody.messages) {
2290
+ upstreamBody.input = upstreamBody.messages;
2291
+ delete upstreamBody.messages;
2292
+ }
2293
+ delete upstreamBody.max_tokens;
2294
+ delete upstreamBody.max_output_tokens;
2295
+ return {
2296
+ url: `${baseUrl}/codex/responses`,
2297
+ method: "POST",
2298
+ headers: {
2299
+ "Content-Type": "application/json",
2300
+ Authorization: `Bearer ${auth.apiKey}`
2301
+ },
2302
+ body: JSON.stringify(upstreamBody)
2303
+ };
2304
+ }
2305
+ modifyMessages(rawBody, compressedMessages) {
2306
+ return openaiResponsesAdapter.modifyMessages(rawBody, compressedMessages);
2307
+ }
2308
+ parseResponse(body) {
2309
+ return openaiResponsesAdapter.parseResponse(body);
2310
+ }
2311
+ buildResponse(parsed) {
2312
+ return openaiResponsesAdapter.buildResponse(parsed);
2313
+ }
2314
+ parseStreamChunk(chunk) {
2315
+ return openaiResponsesAdapter.parseStreamChunk(chunk);
2316
+ }
2317
+ buildStreamChunk(event) {
2318
+ return openaiResponsesAdapter.buildStreamChunk(event);
2319
+ }
2320
+ }
2321
+ var openaiCodexAdapter = new OpenAICodexAdapter;
2322
+ registerAdapter(openaiCodexAdapter);
2323
+
2324
+ // src/compression/compaction-detector.ts
2325
+ var COMPACTION_PATTERNS = [
2326
+ "merge these partial summaries into a single cohesive summary",
2327
+ "preserve all opaque identifiers exactly as written",
2328
+ "your task is to create a detailed summary of the conversation so far",
2329
+ "do not use any tools. you must respond with only the <summary>",
2330
+ "important: do not use any tools",
2331
+ "summarize the conversation",
2332
+ "create a summary of our conversation",
2333
+ "compact the conversation"
2334
+ ];
2335
+ function extractTextFromContent(content) {
2336
+ if (typeof content === "string")
2337
+ return content;
2338
+ if (Array.isArray(content)) {
2339
+ return content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(`
2340
+ `);
2341
+ }
2342
+ return "";
2343
+ }
2344
+ function detectCompaction(headers, messages) {
2345
+ for (const [key, value] of Object.entries(headers)) {
2346
+ if (key.toLowerCase() === "x-request-compaction" && value === "true") {
2347
+ return { isCompaction: true, detectedBy: "header", confidence: 1 };
2348
+ }
2349
+ }
2350
+ let lastUserMessage;
2351
+ for (let i = messages.length - 1;i >= 0; i--) {
2352
+ if (messages[i].role === "user") {
2353
+ lastUserMessage = messages[i];
2354
+ break;
2355
+ }
2356
+ }
2357
+ if (lastUserMessage) {
2358
+ const text = extractTextFromContent(lastUserMessage.content).toLowerCase();
2359
+ for (const pattern of COMPACTION_PATTERNS) {
2360
+ if (text.includes(pattern)) {
2361
+ return { isCompaction: true, detectedBy: "prompt_pattern", confidence: 0.95 };
2362
+ }
2363
+ }
2364
+ }
2365
+ return { isCompaction: false, detectedBy: "none", confidence: 0 };
2366
+ }
2367
+
2368
+ // src/utils/token-estimator.ts
2369
+ var TOKENS_PER_CJK = 2.5;
2370
+ var CHARS_PER_ASCII_TOKEN = 4;
2371
+ var MESSAGE_OVERHEAD = 4;
2372
+ function isCJK(charCode) {
2373
+ return charCode >= 12288 && charCode <= 40959 || charCode >= 44032 && charCode <= 55215 || charCode >= 63744 && charCode <= 64255;
2374
+ }
2375
+ function estimateTokens(text) {
2376
+ if (text.length === 0)
2377
+ return 0;
2378
+ let asciiSegmentLength = 0;
2379
+ let tokenCount = 0;
2380
+ for (let i = 0;i < text.length; i++) {
2381
+ const code = text.charCodeAt(i);
2382
+ if (isCJK(code)) {
2383
+ tokenCount += asciiSegmentLength / CHARS_PER_ASCII_TOKEN;
2384
+ asciiSegmentLength = 0;
2385
+ tokenCount += TOKENS_PER_CJK;
2386
+ } else {
2387
+ asciiSegmentLength++;
2388
+ }
2389
+ }
2390
+ tokenCount += asciiSegmentLength / CHARS_PER_ASCII_TOKEN;
2391
+ return Math.ceil(tokenCount);
2392
+ }
2393
+ function estimateMessagesTokens(messages) {
2394
+ let total = 0;
2395
+ for (const message of messages) {
2396
+ total += MESSAGE_OVERHEAD;
2397
+ if (typeof message.content === "string") {
2398
+ total += estimateTokens(message.content);
2399
+ } else if (Array.isArray(message.content)) {
2400
+ for (const block of message.content) {
2401
+ if (block.type === "text" && block.text !== undefined) {
2402
+ total += estimateTokens(block.text);
2403
+ }
2404
+ }
2405
+ }
2406
+ }
2407
+ return total;
2408
+ }
2409
+
2410
+ // src/compression/synthetic-response.ts
2411
+ function messageContentToString(content) {
2412
+ if (typeof content === "string")
2413
+ return content;
2414
+ if (Array.isArray(content)) {
2415
+ return content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(`
2416
+ `);
2417
+ }
2418
+ return JSON.stringify(content);
2419
+ }
2420
+ function formatRecentMessages(messages) {
2421
+ return messages.map((m) => `[${m.role}]: ${messageContentToString(m.content)}`).join(`
2422
+
2423
+ `);
2424
+ }
2425
+ function buildSyntheticSummaryResponse(summary, recentMessages, model) {
2426
+ const recentText = formatRecentMessages(recentMessages);
2427
+ const content = `<summary>
2428
+ ${summary}
2429
+ </summary>
2430
+
2431
+ <recent_messages>
2432
+ ${recentText}
2433
+ </recent_messages>`;
2434
+ return {
2435
+ id: `msg_precomputed_${Date.now()}`,
2436
+ model,
2437
+ content,
2438
+ role: "assistant",
2439
+ stopReason: "end_turn",
2440
+ usage: { inputTokens: 0, outputTokens: estimateTokens(content) }
2441
+ };
2442
+ }
2443
+ function buildSyntheticHttpResponse(parsed, adapter) {
2444
+ const body = adapter.buildResponse ? adapter.buildResponse(parsed) : {
2445
+ id: parsed.id,
2446
+ type: "message",
2447
+ role: "assistant",
2448
+ model: parsed.model,
2449
+ content: [{ type: "text", text: parsed.content }],
2450
+ stop_reason: parsed.stopReason,
2451
+ usage: parsed.usage ? {
2452
+ input_tokens: parsed.usage.inputTokens,
2453
+ output_tokens: parsed.usage.outputTokens
2454
+ } : undefined
2455
+ };
2456
+ return new Response(JSON.stringify(body), {
2457
+ status: 200,
2458
+ headers: {
2459
+ "content-type": "application/json",
2460
+ "x-synthetic-response": "true"
2461
+ }
2462
+ });
2463
+ }
2464
+
2465
+ // src/routing/local-classifier.ts
2466
+ var import_transformers = require("@huggingface/transformers");
2467
+ var CAT_L = "L";
2468
+ var CAT_M = "M";
2469
+ var CAT_H = "H";
2470
+ var CAT_Q = "Q";
2471
+ var TIER_MAP = {
2472
+ L: "LIGHT",
2473
+ M: "MEDIUM",
2474
+ H: "HEAVY"
2475
+ };
2476
+ var MODEL_ID = "Xenova/multilingual-e5-small";
2477
+ var E5_PREFIX = "query: ";
2478
+ var BATCH_SIZE = 32;
2479
+ var TRAINING_LIGHT = [
2480
+ "안녕하세요",
2481
+ "안녕",
2482
+ "안녕히 가세요",
2483
+ "안녕히 계세요",
2484
+ "반갑습니다",
2485
+ "잘 지내시죠",
2486
+ "오랜만이에요",
2487
+ "고마워",
2488
+ "감사합니다",
2489
+ "고맙습니다",
2490
+ "네 고마워요",
2491
+ "정말 감사합니다",
2492
+ "도와줘서 고마워",
2493
+ "네",
2494
+ "예",
2495
+ "아니요",
2496
+ "좋아요",
2497
+ "알겠습니다",
2498
+ "확인했습니다",
2499
+ "그래요",
2500
+ "맞아요",
2501
+ "아 네",
2502
+ "Python이 뭐야?",
2503
+ "JavaScript가 뭐야?",
2504
+ "오늘 날씨 어때?",
2505
+ "지금 몇 시야?",
2506
+ "이거 뭐야?",
2507
+ "TypeScript가 뭐예요?",
2508
+ "API가 뭐야?",
2509
+ "HTML이 뭐야?",
2510
+ "CSS가 뭐야?",
2511
+ "Hello",
2512
+ "Hi",
2513
+ "Hey there",
2514
+ "Good morning",
2515
+ "Good afternoon",
2516
+ "How are you",
2517
+ "What's up",
2518
+ "Thanks",
2519
+ "Thank you",
2520
+ "Got it",
2521
+ "OK",
2522
+ "Sounds good",
2523
+ "I see",
2524
+ "Understood",
2525
+ "Great thanks",
2526
+ "What is Python?",
2527
+ "What time is it?",
2528
+ "What's the weather?",
2529
+ "Who is Einstein?",
2530
+ "Where is Seoul?",
2531
+ "How old are you?",
2532
+ "yes",
2533
+ "no",
2534
+ "maybe",
2535
+ "sure",
2536
+ "please",
2537
+ "done",
2538
+ "ok",
2539
+ "cool",
2540
+ "nice",
2541
+ "awesome"
2542
+ ];
2543
+ var TRAINING_MEDIUM = [
2544
+ "Write a quicksort function in TypeScript",
2545
+ "Implement a binary search tree with insert and delete",
2546
+ "Create a REST API endpoint for user authentication",
2547
+ "Write a function to merge two sorted arrays",
2548
+ "Implement a linked list in Python",
2549
+ "Write a unit test for the calculator module",
2550
+ "Create a simple Express.js middleware for logging",
2551
+ "Write a regex to validate email addresses",
2552
+ "Implement a LRU cache with get and put operations",
2553
+ "Create a React component for a todo list",
2554
+ "Write a SQL query to join two tables",
2555
+ "Implement a basic JWT authentication flow",
2556
+ "Write a function to parse CSV files",
2557
+ "Create a simple WebSocket server",
2558
+ "Implement bubble sort in Java",
2559
+ "Write a Python script to read a JSON file",
2560
+ "Create a Docker compose file for a web app",
2561
+ "Write a Git pre-commit hook",
2562
+ "REST API에 로그인 엔드포인트 추가해줘",
2563
+ "이 함수에 에러 핸들링 추가해줘",
2564
+ "TypeScript로 이벤트 이미터 만들어줘",
2565
+ "데이터베이스 마이그레이션 스크립트 작성해줘",
2566
+ "React 컴포넌트에 상태 관리 추가해줘",
2567
+ "Express 라우터에 CORS 미들웨어 추가해줘",
2568
+ "테스트 코드 작성해줘",
2569
+ "이 코드 리팩토링해줘",
2570
+ "Explain the difference between let and const in JavaScript",
2571
+ "What's the difference between SQL and NoSQL databases",
2572
+ "Explain how async await works in Python",
2573
+ "Describe the MVC architecture pattern",
2574
+ "Explain what Docker containers are",
2575
+ "REST와 GraphQL의 차이점을 설명해줘",
2576
+ "이벤트 루프가 어떻게 동작하는지 설명해줘",
2577
+ "클로저가 뭐야? 설명해줘",
2578
+ "Set up a Node.js project with TypeScript and ESLint",
2579
+ "Create a basic CI/CD pipeline using GitHub Actions",
2580
+ "Configure Nginx as a reverse proxy for a Node.js app",
2581
+ `이 함수를 리팩토링해줘:
2582
+ function processUsers(data) {
2583
+ var result = [];
2584
+ for (var i = 0; i < data.length; i++) {
2585
+ if (data[i].active == true && data[i].age > 18) {
2586
+ var name = data[i].firstName + ' ' + data[i].lastName;
2587
+ var obj = { name: name, email: data[i].email, role: data[i].isAdmin ? 'admin' : 'user' };
2588
+ if (data[i].department !== null && data[i].department !== undefined) {
2589
+ obj.department = data[i].department.name;
2590
+ obj.manager = data[i].department.manager ? data[i].department.manager.name : 'N/A';
2591
+ }
2592
+ result.push(obj);
2593
+ }
2594
+ }
2595
+ result.sort(function(a, b) { return a.name > b.name ? 1 : -1; });
2596
+ return result;
2597
+ }`,
2598
+ `Refactor this code to use modern JavaScript:
2599
+ function getItems(list) {
2600
+ var items = [];
2601
+ for (var i = 0; i < list.length; i++) {
2602
+ if (list[i].active === true) {
2603
+ items.push(list[i].name);
2604
+ }
2605
+ }
2606
+ return items;
2607
+ }`
2608
+ ];
2609
+ var TRAINING_HEAVY = [
2610
+ "Design a distributed consensus algorithm for a multi-region database with strong consistency and Byzantine fault tolerance",
2611
+ "Explain the theoretical foundations of quantum computing and how quantum entanglement can be used for cryptographic key distribution",
2612
+ "Analyze the trade-offs between eventual consistency and strong consistency in distributed systems, including CAP theorem implications",
2613
+ "Design a fault-tolerant microservices architecture for a real-time trading platform handling millions of transactions per second",
2614
+ "Propose a novel approach to solving the traveling salesman problem that improves upon current approximation algorithms",
2615
+ "Design a machine learning pipeline for real-time fraud detection in financial transactions with sub-millisecond latency requirements",
2616
+ "Compare and contrast different consensus protocols (Paxos, Raft, PBFT) and recommend the best one for a blockchain-based supply chain system",
2617
+ "Architect a system that can handle 10 million concurrent WebSocket connections with horizontal scaling",
2618
+ "Design a real-time data streaming architecture combining Kafka, Flink, and a time-series database for IoT sensor data",
2619
+ "메모리 릭이 발생하는데 프로파일러에서 이벤트 루프 블로킹과 GC 지연이 동시에 나타나. 마이크로서비스 간 gRPC 연결 풀링도 의심되는 상황인데 원인 분석 방법을 단계별로 설명해줘",
2620
+ "대규모 분산 시스템에서 파티션 톨런스와 일관성을 동시에 보장하는 방법을 설계해줘",
2621
+ "실시간 추천 시스템을 위한 아키텍처를 설계해줘. 1초 이내에 개인화된 추천을 제공해야 해",
2622
+ "카프카 기반 이벤트 드리븐 아키텍처에서 순서 보장과 정확히 한 번 처리를 어떻게 보장할 수 있을까?",
2623
+ "마이크로서비스 간의 분산 트랜잭션을 사가 패턴으로 구현하는 방법을 단계별로 설명해줘",
2624
+ "Debug a memory leak in a production Node.js application where the heap grows indefinitely but garbage collection logs show normal behavior",
2625
+ "Investigate why our Kubernetes pods are being OOMKilled despite having memory limits set to 4GB and actual usage reported as 2GB",
2626
+ "Find the root cause of intermittent 500ms latency spikes in our PostgreSQL queries that happen every 15 minutes",
2627
+ "Design a multi-tenant SaaS platform with shared infrastructure but isolated data, supporting custom domains and white-labeling",
2628
+ "Implement a distributed task scheduler that guarantees at-least-once execution with idempotency support across multiple data centers"
2629
+ ];
2630
+ var TRAINING_Q = [
2631
+ "아까 그거 다시 해줘",
2632
+ "그거 좀 더 자세히 설명해줘",
2633
+ "아까 말한 거 그대로 해줘",
2634
+ "이거 수정해줘",
2635
+ "저거 어디 있지",
2636
+ "그거 어떻게 됐어",
2637
+ "위에꺼 다시 한번",
2638
+ "그거 그대로 해줘",
2639
+ "아까 한 거 다시",
2640
+ "그 코드 다시 보여줘",
2641
+ "저번에 한 거 기억나?",
2642
+ "그 부분 수정해줘",
2643
+ "Do that again",
2644
+ "What about the thing we discussed earlier",
2645
+ "Show me that again",
2646
+ "Can you fix that",
2647
+ "Change it like I said before",
2648
+ "Continue from where we left off",
2649
+ "That thing from earlier, do it again",
2650
+ "Remember what we were working on",
2651
+ "Go back to the previous one",
2652
+ "Make it like the other one",
2653
+ "The same thing but different",
2654
+ "Update the one from before",
2655
+ "그거 해줘",
2656
+ "이거 해줘",
2657
+ "저거 어때",
2658
+ "How about this one",
2659
+ "What about that",
2660
+ "Try the other approach",
2661
+ "Use the one I mentioned",
2662
+ "Fix the issue",
2663
+ "그냥 그거",
2664
+ "이건 어때",
2665
+ "Make it better",
2666
+ "Change it",
2667
+ "이거 수정해"
2668
+ ];
2669
+ var Q_PATTERNS = [
2670
+ /^(아까|그거|저거|이거|그|위에|아래|저번|이전|전에).*(다시|해줘|해|보여|설명|수정|변경|삭제|추가|해봐)/,
2671
+ /^(그거|저거|이거|그|이|저)(만|만큼|대로|처럼|같이)?\s*(해줘|해|놔|둬|봐|어때|어떻게)/,
2672
+ /^(그거|저거|이거)\s*$/,
2673
+ /(아까|저번에|전에|위에서|앞에서|이전에).*(그|그거|그것|그때|했던|말한)/,
2674
+ /^(이거|저거|그거)(\s*.*)?$/
2675
+ ];
2676
+ var DEICTIC_WORDS = new Set(["그거", "저거", "이거", "그것", "이것", "저것", "아까", "저번"]);
2677
+ function matchesQPattern(text) {
2678
+ const trimmed = text.trim();
2679
+ for (const pattern of Q_PATTERNS) {
2680
+ if (pattern.test(trimmed))
2681
+ return true;
2682
+ }
2683
+ if (trimmed.length < 20) {
2684
+ for (const word of DEICTIC_WORDS) {
2685
+ if (trimmed.includes(word))
2686
+ return true;
2687
+ }
2688
+ }
2689
+ return false;
2690
+ }
2691
+ var CODE_PATTERN = /[{}();]|function |const |let |var |class |import |export |=>|\bdef \b|\bfn\b/;
2692
+ var TECH_TERMS = /\b(implement|create|design|architect|debug|refactor|migrate|deploy|build|write|develop)\b/i;
2693
+ function isLikelyLight(text) {
2694
+ const trimmed = text.trim();
2695
+ if (trimmed.length <= 20 && !CODE_PATTERN.test(trimmed) && !TECH_TERMS.test(trimmed)) {
2696
+ return true;
2697
+ }
2698
+ return false;
2699
+ }
2700
+ var extractorPromise = null;
2701
+ function getExtractor() {
2702
+ if (!extractorPromise) {
2703
+ console.log("[clawmux] Loading embedding model...");
2704
+ extractorPromise = import_transformers.pipeline("feature-extraction", MODEL_ID).then((pipe) => {
2705
+ console.log("[clawmux] Embedding model loaded");
2706
+ return pipe;
2707
+ });
2708
+ }
2709
+ return extractorPromise;
2710
+ }
2711
+ var centroidsPromise = null;
2712
+ async function computeMeanEmbedding(texts) {
2713
+ const extractor = await getExtractor();
2714
+ const allEmbeddings = [];
2715
+ for (let i = 0;i < texts.length; i += BATCH_SIZE) {
2716
+ const batch = texts.slice(i, i + BATCH_SIZE).map((t) => E5_PREFIX + t);
2717
+ const output = await extractor(batch, { pooling: "mean", normalize: true });
2718
+ const list = output.tolist();
2719
+ for (const emb of list) {
2720
+ allEmbeddings.push(emb);
2721
+ }
2722
+ }
2723
+ if (allEmbeddings.length === 0)
2724
+ return [];
2725
+ const dim = allEmbeddings[0].length;
2726
+ const mean = new Array(dim).fill(0);
2727
+ for (const emb of allEmbeddings) {
2728
+ for (let j = 0;j < dim; j++) {
2729
+ mean[j] += emb[j] / allEmbeddings.length;
2730
+ }
2731
+ }
2732
+ const magnitude = Math.sqrt(mean.reduce((sum, v) => sum + v * v, 0));
2733
+ if (magnitude > 0) {
2734
+ for (let j = 0;j < dim; j++)
2735
+ mean[j] /= magnitude;
2736
+ }
2737
+ return mean;
2738
+ }
2739
+ function getCentroids() {
2740
+ if (!centroidsPromise) {
2741
+ centroidsPromise = (async () => {
2742
+ console.log("[clawmux] Computing category centroids...");
2743
+ const [cL, cM, cH, cQ] = await Promise.all([
2744
+ computeMeanEmbedding(TRAINING_LIGHT),
2745
+ computeMeanEmbedding(TRAINING_MEDIUM),
2746
+ computeMeanEmbedding(TRAINING_HEAVY),
2747
+ computeMeanEmbedding(TRAINING_Q)
2748
+ ]);
2749
+ console.log(`[clawmux] Centroids ready: L=${TRAINING_LIGHT.length} M=${TRAINING_MEDIUM.length} ` + `H=${TRAINING_HEAVY.length} Q=${TRAINING_Q.length} samples`);
2750
+ return { [CAT_L]: cL, [CAT_M]: cM, [CAT_H]: cH, [CAT_Q]: cQ };
2751
+ })();
2752
+ }
2753
+ return centroidsPromise;
2754
+ }
2755
+ function cosineSimilarity(a, b) {
2756
+ let dot = 0;
2757
+ let magA = 0;
2758
+ let magB = 0;
2759
+ for (let i = 0;i < a.length; i++) {
2760
+ dot += a[i] * b[i];
2761
+ magA += a[i] * a[i];
2762
+ magB += b[i] * b[i];
2763
+ }
2764
+ const denom = Math.sqrt(magA) * Math.sqrt(magB);
2765
+ return denom > 0 ? dot / denom : 0;
2766
+ }
2767
+ async function classifyLocal(messages, config) {
2768
+ const userText = extractLastUserText(messages);
2769
+ if (!userText) {
2770
+ return {
2771
+ tier: "MEDIUM",
2772
+ confidence: 0,
2773
+ reasoning: "No user message found",
2774
+ error: "No user message found in request"
2775
+ };
2776
+ }
2777
+ const centroids = await getCentroids();
2778
+ const extractor = await getExtractor();
2779
+ const output = await extractor([E5_PREFIX + userText], { pooling: "mean", normalize: true });
2780
+ const inputEmb = output.tolist()[0];
2781
+ let bestCat = CAT_M;
2782
+ let bestSim = -Infinity;
2783
+ for (const [cat, centroid] of Object.entries(centroids)) {
2784
+ const sim = cosineSimilarity(inputEmb, centroid);
2785
+ if (sim > bestSim) {
2786
+ bestSim = sim;
2787
+ bestCat = cat;
2788
+ }
2789
+ }
2790
+ if (isLikelyLight(userText) && bestCat !== CAT_Q) {
2791
+ bestCat = CAT_L;
2792
+ bestSim = Math.max(bestSim, 0.7);
2793
+ }
2794
+ const heuristicQ = matchesQPattern(userText);
2795
+ if (bestCat === CAT_Q || heuristicQ) {
2796
+ const contextText = buildContextText(messages, userText, config?.contextMessages ?? 10);
2797
+ const ctxOutput = await extractor([E5_PREFIX + contextText], { pooling: "mean", normalize: true });
2798
+ const contextEmb = ctxOutput.tolist()[0];
2799
+ let reBestCat = CAT_M;
2800
+ let reBestSim = -Infinity;
2801
+ for (const [cat, centroid] of Object.entries(centroids)) {
2802
+ if (cat === CAT_Q)
2803
+ continue;
2804
+ const sim = cosineSimilarity(contextEmb, centroid);
2805
+ if (sim > reBestSim) {
2806
+ reBestSim = sim;
2807
+ reBestCat = cat;
2808
+ }
2809
+ }
2810
+ const tier2 = TIER_MAP[reBestCat] ?? "MEDIUM";
2811
+ return {
2812
+ tier: tier2,
2813
+ confidence: reBestSim,
2814
+ reasoning: `Re-classified with context (initial: Q, heuristic: ${heuristicQ})`
2815
+ };
2816
+ }
2817
+ const tier = TIER_MAP[bestCat] ?? "MEDIUM";
2818
+ return { tier, confidence: bestSim };
2819
+ }
2820
+ function extractLastUserText(messages) {
2821
+ for (let i = messages.length - 1;i >= 0; i--) {
2822
+ const msg = messages[i];
2823
+ if (msg.role !== "user")
2824
+ continue;
2825
+ if (typeof msg.content === "string") {
2826
+ return msg.content;
2827
+ }
2828
+ if (Array.isArray(msg.content)) {
2829
+ const parts = [];
2830
+ for (const block of msg.content) {
2831
+ if (block.type === "text" && block.text) {
2832
+ parts.push(block.text);
2833
+ }
2834
+ }
2835
+ if (parts.length > 0)
2836
+ return parts.join(" ");
2837
+ }
2838
+ }
2839
+ return;
2840
+ }
2841
+ function buildContextText(allMessages, currentText, contextCount) {
2842
+ const relevantMessages = allMessages.filter((m) => m.role === "user" || m.role === "assistant");
2843
+ const lastN = relevantMessages.slice(-contextCount);
2844
+ const parts = [];
2845
+ for (const msg of lastN) {
2846
+ let text;
2847
+ if (typeof msg.content === "string") {
2848
+ text = msg.content;
2849
+ } else if (Array.isArray(msg.content)) {
2850
+ text = msg.content.filter((b) => b.type === "text" && b.text).map((b) => b.text).join(" ");
2851
+ } else {
2852
+ continue;
2853
+ }
2854
+ parts.push(`[${msg.role}]: ${text}`);
2855
+ }
2856
+ const lastPart = parts[parts.length - 1];
2857
+ if (!lastPart || !lastPart.includes(currentText)) {
2858
+ parts.push(`[user]: ${currentText}`);
2859
+ }
2860
+ return parts.join(`
2861
+ `);
2862
+ }
2863
+
2864
+ // src/openclaw/auth-resolver.ts
2865
+ var PROVIDER_ENV_VARS = {
2866
+ anthropic: "ANTHROPIC_API_KEY",
2867
+ openai: "OPENAI_API_KEY",
2868
+ google: "GEMINI_API_KEY",
2869
+ gemini: "GEMINI_API_KEY",
2870
+ zai: "ZAI_API_KEY",
2871
+ aws: "AWS_ACCESS_KEY_ID",
2872
+ bedrock: "AWS_ACCESS_KEY_ID"
2873
+ };
2874
+ function getEnvFallback(provider) {
2875
+ const exact = PROVIDER_ENV_VARS[provider];
2876
+ if (exact)
2877
+ return process.env[exact];
2878
+ for (const [key, envVar] of Object.entries(PROVIDER_ENV_VARS)) {
2879
+ if (provider.startsWith(key)) {
2880
+ return process.env[envVar];
2881
+ }
2882
+ }
2883
+ return;
2884
+ }
2885
+ function formatAuth(apiKey, providerConfig) {
2886
+ const api = providerConfig?.api ?? "";
2887
+ if (api === "anthropic-messages") {
2888
+ return { apiKey, headerName: "x-api-key", headerValue: apiKey };
2889
+ }
2890
+ if (api === "openai-completions" || api === "openai-responses") {
2891
+ return { apiKey, headerName: "Authorization", headerValue: `Bearer ${apiKey}` };
2892
+ }
2893
+ if (api === "google-generative-ai") {
2894
+ return { apiKey, headerName: "x-goog-api-key", headerValue: apiKey };
2895
+ }
2896
+ if (api === "bedrock-converse-stream") {
2897
+ const secretKey = process.env.AWS_SECRET_ACCESS_KEY ?? "";
2898
+ const sessionToken = process.env.AWS_SESSION_TOKEN;
2899
+ const region = process.env.AWS_REGION ?? process.env.AWS_DEFAULT_REGION ?? extractRegionFromUrl(providerConfig?.baseUrl ?? "") ?? "us-east-1";
161
2900
  return {
162
- body: null,
163
- error: jsonResponse({ error: "invalid JSON body" }, 400)
2901
+ apiKey,
2902
+ headerName: "Authorization",
2903
+ headerValue: "",
2904
+ awsAccessKeyId: apiKey,
2905
+ awsSecretKey: secretKey,
2906
+ awsSessionToken: sessionToken,
2907
+ awsRegion: region
164
2908
  };
165
2909
  }
2910
+ return { apiKey, headerName: "Authorization", headerValue: `Bearer ${apiKey}` };
166
2911
  }
167
- async function dispatch(req) {
168
- const url = new URL(req.url);
169
- const { pathname } = url;
170
- const method = req.method.toUpperCase();
171
- for (const route of routes) {
172
- if (route.method === method && route.match(pathname)) {
173
- const handler = customHandlers.get(route.key) ?? route.handler;
174
- if (method === "POST") {
175
- const { body, error } = await parseJsonBody(req);
176
- if (error)
177
- return error;
178
- return handler(req, body);
2912
+ var NO_AUTH_APIS = new Set(["ollama"]);
2913
+ function resolveApiKey(provider, openclawConfig, authProfiles) {
2914
+ const providerConfig = getProviderConfig(provider, openclawConfig);
2915
+ const api = providerConfig?.api ?? "";
2916
+ if (NO_AUTH_APIS.has(api)) {
2917
+ return { apiKey: "ollama-local", headerName: "", headerValue: "" };
2918
+ }
2919
+ for (const profile of authProfiles) {
2920
+ if (profile.provider === provider) {
2921
+ const key = profile.apiKey ?? profile.token;
2922
+ if (key) {
2923
+ const resolved = resolveEnvVar(key);
2924
+ if (resolved) {
2925
+ return formatAuth(resolved, providerConfig);
2926
+ }
179
2927
  }
180
- return handler(req, null);
181
2928
  }
182
2929
  }
183
- return jsonResponse({ error: "not found" }, 404);
2930
+ if (providerConfig?.apiKey) {
2931
+ const resolved = resolveEnvVar(providerConfig.apiKey);
2932
+ if (resolved) {
2933
+ return formatAuth(resolved, providerConfig);
2934
+ }
2935
+ }
2936
+ const envKey = getEnvFallback(provider);
2937
+ if (envKey) {
2938
+ return formatAuth(envKey, providerConfig);
2939
+ }
2940
+ return;
184
2941
  }
185
2942
 
186
- // src/utils/runtime.ts
187
- var isBun = typeof globalThis.Bun !== "undefined";
2943
+ // src/adapters/stream-transformer.ts
2944
+ var encoder = new TextEncoder;
2945
+ var decoder = new TextDecoder;
2946
+ function createStreamTranslator(sourceAdapter, targetAdapter) {
2947
+ if (sourceAdapter.apiType === targetAdapter.apiType) {
2948
+ return new TransformStream;
2949
+ }
2950
+ let buffer = "";
2951
+ return new TransformStream({
2952
+ transform(chunk, controller) {
2953
+ if (!sourceAdapter.parseStreamChunk || !targetAdapter.buildStreamChunk) {
2954
+ controller.enqueue(chunk);
2955
+ return;
2956
+ }
2957
+ buffer += decoder.decode(chunk, { stream: true });
2958
+ let delimiterIndex;
2959
+ while ((delimiterIndex = buffer.indexOf(`
188
2960
 
189
- // src/proxy/server.ts
190
- function createServer(config) {
191
- if (isBun) {
192
- return createBunServer(config);
2961
+ `)) !== -1) {
2962
+ const frame = buffer.slice(0, delimiterIndex);
2963
+ buffer = buffer.slice(delimiterIndex + 2);
2964
+ if (frame.trim() === "")
2965
+ continue;
2966
+ const events = sourceAdapter.parseStreamChunk(frame);
2967
+ for (const event of events) {
2968
+ const translated = targetAdapter.buildStreamChunk(event);
2969
+ controller.enqueue(encoder.encode(translated));
2970
+ }
2971
+ }
2972
+ },
2973
+ flush(controller) {
2974
+ if (buffer.trim() !== "" && sourceAdapter.parseStreamChunk && targetAdapter.buildStreamChunk) {
2975
+ const events = sourceAdapter.parseStreamChunk(buffer);
2976
+ for (const event of events) {
2977
+ const translated = targetAdapter.buildStreamChunk(event);
2978
+ controller.enqueue(encoder.encode(translated));
2979
+ }
2980
+ }
2981
+ }
2982
+ });
2983
+ }
2984
+ function getStreamContentType(adapter) {
2985
+ switch (adapter.apiType) {
2986
+ case "anthropic-messages":
2987
+ case "openai-completions":
2988
+ case "openai-responses":
2989
+ return "text/event-stream";
2990
+ case "google-generative-ai":
2991
+ return "application/json";
2992
+ case "ollama":
2993
+ return "application/x-ndjson";
2994
+ case "bedrock-converse-stream":
2995
+ return "application/vnd.amazon.eventstream";
2996
+ default:
2997
+ return "text/event-stream";
193
2998
  }
194
- return createNodeServer(config);
195
2999
  }
196
- function createBunServer(config) {
197
- let server = null;
3000
+ async function translateResponse(sourceAdapter, targetAdapter, upstreamResponse, streaming) {
3001
+ if (sourceAdapter.apiType === targetAdapter.apiType) {
3002
+ return upstreamResponse;
3003
+ }
3004
+ if (!streaming) {
3005
+ return translateNonStreamingResponse(sourceAdapter, targetAdapter, upstreamResponse);
3006
+ }
3007
+ return translateStreamingResponse(sourceAdapter, targetAdapter, upstreamResponse);
3008
+ }
3009
+ async function translateNonStreamingResponse(sourceAdapter, targetAdapter, upstreamResponse) {
3010
+ if (!sourceAdapter.parseResponse || !targetAdapter.buildResponse) {
3011
+ return upstreamResponse;
3012
+ }
3013
+ const body = await upstreamResponse.json();
3014
+ const parsed = sourceAdapter.parseResponse(body);
3015
+ const translated = targetAdapter.buildResponse(parsed);
3016
+ const headers = copyRelevantHeaders(upstreamResponse.headers);
3017
+ headers.set("content-type", "application/json");
3018
+ return new Response(JSON.stringify(translated), {
3019
+ status: upstreamResponse.status,
3020
+ headers
3021
+ });
3022
+ }
3023
+ function translateStreamingResponse(sourceAdapter, targetAdapter, upstreamResponse) {
3024
+ if (!upstreamResponse.body) {
3025
+ return upstreamResponse;
3026
+ }
3027
+ if (!sourceAdapter.parseStreamChunk || !targetAdapter.buildStreamChunk) {
3028
+ return upstreamResponse;
3029
+ }
3030
+ const translator = createStreamTranslator(sourceAdapter, targetAdapter);
3031
+ const translatedBody = upstreamResponse.body.pipeThrough(translator);
3032
+ const headers = copyRelevantHeaders(upstreamResponse.headers);
3033
+ headers.set("content-type", getStreamContentType(targetAdapter));
3034
+ return new Response(translatedBody, {
3035
+ status: upstreamResponse.status,
3036
+ headers
3037
+ });
3038
+ }
3039
+ function copyRelevantHeaders(source) {
3040
+ const headers = new Headers;
3041
+ const passthrough = [
3042
+ "cache-control",
3043
+ "x-request-id",
3044
+ "x-ratelimit-limit",
3045
+ "x-ratelimit-remaining",
3046
+ "x-ratelimit-reset"
3047
+ ];
3048
+ for (const name of passthrough) {
3049
+ const value = source.get(name);
3050
+ if (value !== null) {
3051
+ headers.set(name, value);
3052
+ }
3053
+ }
3054
+ return headers;
3055
+ }
3056
+
3057
+ // src/compression/session-store.ts
3058
+ function djb2Hash(str) {
3059
+ let hash = 5381;
3060
+ for (let i = 0;i < str.length; i++) {
3061
+ hash = (hash << 5) + hash + str.charCodeAt(i) | 0;
3062
+ }
3063
+ return hash >>> 0;
3064
+ }
3065
+ function generateSessionId(messages) {
3066
+ const firstUserMessage = messages.find((m) => m.role === "user");
3067
+ if (!firstUserMessage)
3068
+ return "empty-session";
3069
+ const content = typeof firstUserMessage.content === "string" ? firstUserMessage.content : JSON.stringify(firstUserMessage.content);
3070
+ return `session-${djb2Hash(content)}`;
3071
+ }
3072
+ function createSessionStore(maxSessions = 500) {
3073
+ const store = new Map;
3074
+ function evictLru() {
3075
+ if (store.size < maxSessions)
3076
+ return;
3077
+ let oldestId = "";
3078
+ let oldestAccess = Infinity;
3079
+ for (const [id, session] of store) {
3080
+ if (session.lastAccess < oldestAccess) {
3081
+ oldestAccess = session.lastAccess;
3082
+ oldestId = id;
3083
+ }
3084
+ }
3085
+ if (oldestId)
3086
+ store.delete(oldestId);
3087
+ }
198
3088
  return {
199
- start() {
200
- if (server)
201
- return;
202
- const bun = globalThis.Bun;
203
- server = bun.serve({
204
- port: config.port,
205
- hostname: config.host,
206
- fetch: dispatch
207
- });
3089
+ get(id) {
3090
+ const session = store.get(id);
3091
+ if (session) {
3092
+ session.lastAccess = Date.now();
3093
+ }
3094
+ return session;
208
3095
  },
209
- stop() {
210
- if (!server)
3096
+ getOrCreate(id, messages) {
3097
+ const existing = store.get(id);
3098
+ if (existing) {
3099
+ existing.lastAccess = Date.now();
3100
+ return existing;
3101
+ }
3102
+ evictLru();
3103
+ const session = {
3104
+ id,
3105
+ messages,
3106
+ tokenCount: 0,
3107
+ compressionState: "idle",
3108
+ lastAccess: Date.now()
3109
+ };
3110
+ store.set(id, session);
3111
+ return session;
3112
+ },
3113
+ set(id, session) {
3114
+ if (!store.has(id)) {
3115
+ evictLru();
3116
+ }
3117
+ if (session.lastAccess === 0) {
3118
+ session.lastAccess = Date.now();
3119
+ }
3120
+ store.set(id, session);
3121
+ },
3122
+ update(id, updates) {
3123
+ const session = store.get(id);
3124
+ if (!session)
211
3125
  return;
212
- server.stop(true);
213
- server = null;
3126
+ Object.assign(session, updates);
3127
+ session.lastAccess = Date.now();
3128
+ return session;
3129
+ },
3130
+ delete(id) {
3131
+ return store.delete(id);
3132
+ },
3133
+ size() {
3134
+ return store.size;
3135
+ },
3136
+ has(id) {
3137
+ return store.has(id);
214
3138
  }
215
3139
  };
216
3140
  }
217
- function createNodeServer(config) {
218
- let server = null;
3141
+
3142
+ // src/compression/worker.ts
3143
+ var SUMMARY_PREFIX = "[Summary of previous conversation]";
3144
+ function messageContentToString2(content) {
3145
+ if (typeof content === "string")
3146
+ return content;
3147
+ if (Array.isArray(content)) {
3148
+ return content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(`
3149
+ `);
3150
+ }
3151
+ return JSON.stringify(content);
3152
+ }
3153
+ function estimateMessageTokens(msg) {
3154
+ const MESSAGE_OVERHEAD2 = 4;
3155
+ return MESSAGE_OVERHEAD2 + estimateTokens(messageContentToString2(msg.content));
3156
+ }
3157
+ function buildCompressionPrompt(messages, targetTokens) {
3158
+ const conversationText = messages.map((m) => `${m.role}: ${messageContentToString2(m.content)}`).join(`
3159
+
3160
+ `);
3161
+ return [
3162
+ {
3163
+ role: "system",
3164
+ content: [
3165
+ "You are a conversation summarizer. Produce a concise summary of the conversation below.",
3166
+ `Target length: approximately ${targetTokens} tokens.`,
3167
+ "Preserve: key decisions, code snippets, technical details, and action items.",
3168
+ "Format: plain text paragraphs. Start with the most important context."
3169
+ ].join(`
3170
+ `)
3171
+ },
3172
+ {
3173
+ role: "user",
3174
+ content: conversationText
3175
+ }
3176
+ ];
3177
+ }
3178
+ function buildCompressedMessages(summary) {
3179
+ return [
3180
+ {
3181
+ role: "user",
3182
+ content: `${SUMMARY_PREFIX}
3183
+ ${summary}`
3184
+ },
3185
+ {
3186
+ role: "assistant",
3187
+ content: "Understood. I have the context from our previous conversation. How can I help you continue?"
3188
+ }
3189
+ ];
3190
+ }
3191
+ function truncateToFit(messages, targetTokens) {
3192
+ const result = [];
3193
+ let usedTokens = 0;
3194
+ const firstMsg = messages[0];
3195
+ const firstContent = firstMsg ? messageContentToString2(firstMsg.content) : "";
3196
+ const hasSystemPrefix = firstMsg?.role === "user" && firstContent.startsWith(SUMMARY_PREFIX);
3197
+ if (hasSystemPrefix && firstMsg) {
3198
+ const tokens = estimateMessageTokens(firstMsg);
3199
+ result.push(firstMsg);
3200
+ usedTokens += tokens;
3201
+ }
3202
+ const tail = [];
3203
+ const startIdx = hasSystemPrefix ? 1 : 0;
3204
+ for (let i = messages.length - 1;i >= startIdx; i--) {
3205
+ const msg = messages[i];
3206
+ const tokens = estimateMessageTokens(msg);
3207
+ if (usedTokens + tokens > targetTokens)
3208
+ break;
3209
+ tail.unshift(msg);
3210
+ usedTokens += tokens;
3211
+ }
3212
+ return [...result, ...tail];
3213
+ }
3214
+ function createCompressionWorker(config) {
3215
+ let activeJobs = 0;
3216
+ let completedJobs = 0;
3217
+ let failedJobs = 0;
3218
+ function shouldCompress(session) {
3219
+ const thresholdTokens = config.threshold * config.contextWindow;
3220
+ return session.tokenCount >= thresholdTokens && session.compressionState === "idle";
3221
+ }
3222
+ function triggerCompression(session, sessionStore, makeApiCall) {
3223
+ if (activeJobs >= config.maxConcurrent)
3224
+ return;
3225
+ session.compressionState = "computing";
3226
+ session.snapshotIndex = session.messages.length;
3227
+ sessionStore.update(session.id, {
3228
+ compressionState: "computing",
3229
+ snapshotIndex: session.messages.length
3230
+ });
3231
+ activeJobs++;
3232
+ const targetTokens = config.targetRatio * config.contextWindow;
3233
+ const promptMessages = buildCompressionPrompt(session.messages, targetTokens);
3234
+ const sessionId = session.id;
3235
+ const originalMessages = [...session.messages];
3236
+ const jobPromise = Promise.race([
3237
+ makeApiCall(config.compressionModel, promptMessages),
3238
+ new Promise((_resolve, reject) => {
3239
+ setTimeout(() => reject(new Error("compression_timeout")), config.timeoutMs);
3240
+ })
3241
+ ]);
3242
+ jobPromise.then((summaryText) => {
3243
+ const compressed = buildCompressedMessages(summaryText);
3244
+ sessionStore.update(sessionId, {
3245
+ compressionState: "ready",
3246
+ compressedSummary: summaryText,
3247
+ compressedMessages: compressed
3248
+ });
3249
+ const current = sessionStore.get(sessionId);
3250
+ if (current) {
3251
+ session.compressionState = current.compressionState;
3252
+ session.compressedSummary = current.compressedSummary;
3253
+ session.compressedMessages = current.compressedMessages;
3254
+ }
3255
+ activeJobs--;
3256
+ completedJobs++;
3257
+ }).catch((error) => {
3258
+ if (error.message === "compression_timeout") {
3259
+ const truncated = truncateToFit(originalMessages, targetTokens);
3260
+ sessionStore.update(sessionId, {
3261
+ compressionState: "ready",
3262
+ compressedMessages: truncated
3263
+ });
3264
+ const current = sessionStore.get(sessionId);
3265
+ if (current) {
3266
+ session.compressionState = current.compressionState;
3267
+ session.compressedMessages = current.compressedMessages;
3268
+ }
3269
+ activeJobs--;
3270
+ completedJobs++;
3271
+ } else {
3272
+ sessionStore.update(sessionId, { compressionState: "idle" });
3273
+ session.compressionState = "idle";
3274
+ activeJobs--;
3275
+ failedJobs++;
3276
+ console.error(`[CompressionWorker] Job failed for session ${sessionId}:`, error.message);
3277
+ }
3278
+ });
3279
+ }
3280
+ function applyCompression(session) {
3281
+ if (session.compressionState !== "ready" || !session.compressedMessages) {
3282
+ return;
3283
+ }
3284
+ const compressed = session.compressedMessages;
3285
+ const snapshotIdx = session.snapshotIndex ?? session.messages.length - 3;
3286
+ const postSnapshotMessages = session.messages.slice(snapshotIdx);
3287
+ const combined = [...compressed, ...postSnapshotMessages];
3288
+ session.compressionState = "idle";
3289
+ session.compressedMessages = undefined;
3290
+ session.compressedSummary = undefined;
3291
+ session.snapshotIndex = undefined;
3292
+ return combined;
3293
+ }
3294
+ function getStats() {
3295
+ return { activeJobs, completedJobs, failedJobs };
3296
+ }
219
3297
  return {
220
- async start() {
221
- if (server)
222
- return;
223
- const { createServer: createHttpServer } = await import("node:http");
224
- const { toWebRequest: toWebRequest2, writeWebResponse: writeWebResponse2 } = await Promise.resolve().then(() => exports_node_http_adapter);
225
- const httpServer = createHttpServer(async (req, res) => {
226
- try {
227
- const webReq = toWebRequest2(req);
228
- const webRes = await dispatch(webReq);
229
- await writeWebResponse2(res, webRes);
230
- } catch (err) {
231
- const message = err instanceof Error ? err.message : String(err);
232
- res.writeHead(500, { "content-type": "application/json" });
233
- res.end(JSON.stringify({ error: message }));
3298
+ shouldCompress,
3299
+ triggerCompression,
3300
+ applyCompression,
3301
+ getStats
3302
+ };
3303
+ }
3304
+
3305
+ // src/proxy/compression-integration.ts
3306
+ var HARD_CEILING_RATIO = 0.9;
3307
+ function messagesToTokenMessages(messages) {
3308
+ return messages.map((m) => ({
3309
+ role: m.role,
3310
+ content: m.content
3311
+ }));
3312
+ }
3313
+ function extractResponseText(responseBody) {
3314
+ try {
3315
+ const parsed = JSON.parse(responseBody);
3316
+ if (Array.isArray(parsed.content)) {
3317
+ const textBlocks = parsed.content.filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text);
3318
+ if (textBlocks.length > 0)
3319
+ return textBlocks.join(`
3320
+ `);
3321
+ }
3322
+ if (Array.isArray(parsed.choices)) {
3323
+ const choices = parsed.choices;
3324
+ const first = choices[0];
3325
+ if (first) {
3326
+ const message = first.message;
3327
+ if (message && typeof message.content === "string") {
3328
+ return message.content;
234
3329
  }
3330
+ }
3331
+ }
3332
+ return JSON.stringify(parsed);
3333
+ } catch {
3334
+ return responseBody;
3335
+ }
3336
+ }
3337
+ function createMakeApiCall(adapter, compressionModel, baseUrl, auth) {
3338
+ const actualModelId = compressionModel.includes("/") ? compressionModel.split("/").slice(1).join("/") : compressionModel;
3339
+ return async (model, messages) => {
3340
+ const syntheticParsed = {
3341
+ model,
3342
+ messages: messages.map((m) => ({ role: m.role, content: m.content })),
3343
+ stream: false,
3344
+ maxTokens: 4096,
3345
+ rawBody: {
3346
+ model,
3347
+ messages,
3348
+ stream: false,
3349
+ max_tokens: 4096
3350
+ }
3351
+ };
3352
+ const upstream = adapter.buildUpstreamRequest(syntheticParsed, actualModelId, baseUrl, auth);
3353
+ const response = await fetch(upstream.url, {
3354
+ method: upstream.method,
3355
+ headers: upstream.headers,
3356
+ body: upstream.body
3357
+ });
3358
+ const body = await response.text();
3359
+ if (!response.ok) {
3360
+ throw new Error(`Compression API call failed: ${response.status} ${body}`);
3361
+ }
3362
+ return extractResponseText(body);
3363
+ };
3364
+ }
3365
+ function createCompressionMiddleware(config) {
3366
+ const contextWindow = config.resolvedContextWindow;
3367
+ const sessionStore = createSessionStore(config.maxSessions ?? 500);
3368
+ const worker = createCompressionWorker({
3369
+ threshold: config.threshold,
3370
+ targetRatio: config.targetRatio,
3371
+ compressionModel: config.compressionModel,
3372
+ contextWindow,
3373
+ maxConcurrent: 2,
3374
+ timeoutMs: 60000
3375
+ });
3376
+ function beforeForward(parsed, adapter) {
3377
+ const messages = parsed.messages;
3378
+ if (messages.length <= 1) {
3379
+ return { messages, wasCompressed: false };
3380
+ }
3381
+ const sessionId = generateSessionId(messages);
3382
+ const session = sessionStore.getOrCreate(sessionId, messages);
3383
+ const compressed = worker.applyCompression(session);
3384
+ if (compressed) {
3385
+ sessionStore.update(sessionId, {
3386
+ messages: compressed,
3387
+ compressionState: "idle",
3388
+ compressedMessages: undefined,
3389
+ compressedSummary: undefined,
3390
+ snapshotIndex: undefined
235
3391
  });
236
- await new Promise((resolve) => {
237
- httpServer.listen(config.port, config.host, resolve);
3392
+ const originalTokens = estimateMessagesTokens(messagesToTokenMessages(messages));
3393
+ const compressedTokens = estimateMessagesTokens(messagesToTokenMessages(compressed));
3394
+ if (config.statsTracker) {
3395
+ config.statsTracker.recordCompression(originalTokens, compressedTokens);
3396
+ }
3397
+ console.log(`[compression] Applied compression: ${originalTokens} → ${compressedTokens} tokens (${((1 - compressedTokens / originalTokens) * 100).toFixed(0)}% reduction)`);
3398
+ return { messages: compressed, wasCompressed: true };
3399
+ }
3400
+ const tokenCount = estimateMessagesTokens(messagesToTokenMessages(messages));
3401
+ const hardCeilingTokens = HARD_CEILING_RATIO * contextWindow;
3402
+ if (tokenCount >= hardCeilingTokens) {
3403
+ const targetTokens = config.targetRatio * contextWindow;
3404
+ const truncated = truncateToFit(messages, targetTokens);
3405
+ console.log(`[compression] Hard ceiling hit (${tokenCount} tokens >= ${Math.round(hardCeilingTokens)}), truncating to ${Math.round(targetTokens)} tokens`);
3406
+ return { messages: truncated, wasCompressed: true };
3407
+ }
3408
+ return { messages, wasCompressed: false };
3409
+ }
3410
+ function afterResponse(parsed, adapter, baseUrl, auth) {
3411
+ const messages = parsed.messages;
3412
+ if (messages.length <= 1)
3413
+ return;
3414
+ const sessionId = generateSessionId(messages);
3415
+ const session = sessionStore.getOrCreate(sessionId, messages);
3416
+ const tokenCount = estimateMessagesTokens(messagesToTokenMessages(messages));
3417
+ sessionStore.update(sessionId, {
3418
+ messages: [...messages],
3419
+ tokenCount
3420
+ });
3421
+ const updatedSession = sessionStore.get(sessionId);
3422
+ if (!updatedSession)
3423
+ return;
3424
+ if (worker.shouldCompress(updatedSession)) {
3425
+ const makeApiCall = createMakeApiCall(adapter, config.compressionModel, baseUrl, auth);
3426
+ worker.triggerCompression(updatedSession, sessionStore, makeApiCall);
3427
+ console.log(`[compression] Triggered background compression for session ${sessionId} (${tokenCount} tokens)`);
3428
+ }
3429
+ }
3430
+ function getSummaryForSession(messages) {
3431
+ if (messages.length <= 1)
3432
+ return;
3433
+ const sessionId = generateSessionId(messages);
3434
+ const session = sessionStore.get(sessionId);
3435
+ if (!session)
3436
+ return;
3437
+ if (session.compressionState === "ready" && session.compressedSummary) {
3438
+ const recentMessages = session.messages.slice(-3);
3439
+ const summary = session.compressedSummary;
3440
+ sessionStore.update(sessionId, {
3441
+ compressionState: "idle",
3442
+ compressedMessages: undefined,
3443
+ compressedSummary: undefined
238
3444
  });
239
- server = httpServer;
240
- },
241
- stop() {
242
- if (!server)
243
- return;
244
- server.close();
245
- server = null;
3445
+ return { summary, recentMessages };
3446
+ }
3447
+ return;
3448
+ }
3449
+ return {
3450
+ beforeForward,
3451
+ afterResponse,
3452
+ getSessionStore: () => sessionStore,
3453
+ getWorker: () => worker,
3454
+ getSummaryForSession
3455
+ };
3456
+ }
3457
+
3458
+ // src/proxy/pipeline.ts
3459
+ registerAdapter(new AnthropicAdapter);
3460
+ async function collectCodexStream(sourceAdapter, response) {
3461
+ const reader = response.body.getReader();
3462
+ const decoder2 = new TextDecoder;
3463
+ let buffer = "";
3464
+ let id = "";
3465
+ let model = "";
3466
+ const textParts = [];
3467
+ let usage;
3468
+ for (;; ) {
3469
+ const { done, value } = await reader.read();
3470
+ if (done)
3471
+ break;
3472
+ buffer += decoder2.decode(value, { stream: true });
3473
+ let idx;
3474
+ while ((idx = buffer.indexOf(`
3475
+
3476
+ `)) !== -1) {
3477
+ const frame = buffer.slice(0, idx);
3478
+ buffer = buffer.slice(idx + 2);
3479
+ if (!frame.trim() || !sourceAdapter.parseStreamChunk)
3480
+ continue;
3481
+ for (const event of sourceAdapter.parseStreamChunk(frame)) {
3482
+ if (event.type === "message_start") {
3483
+ id = event.id ?? "";
3484
+ model = event.model ?? "";
3485
+ } else if (event.type === "content_delta") {
3486
+ textParts.push(event.text ?? "");
3487
+ } else if (event.type === "message_stop" && event.usage) {
3488
+ usage = event.usage;
3489
+ }
3490
+ }
3491
+ }
3492
+ }
3493
+ return {
3494
+ id,
3495
+ model,
3496
+ content: textParts.join(""),
3497
+ role: "assistant",
3498
+ stopReason: "completed",
3499
+ usage
3500
+ };
3501
+ }
3502
+ function findProviderForModel(modelString, openclawConfig) {
3503
+ const providers = openclawConfig.models?.providers;
3504
+ if (!providers)
3505
+ return;
3506
+ const [providerName, modelId] = modelString.split("/", 2);
3507
+ if (!providerName || !modelId)
3508
+ return;
3509
+ const providerConfig = providers[providerName];
3510
+ if (!providerConfig)
3511
+ return;
3512
+ return {
3513
+ providerName,
3514
+ baseUrl: providerConfig.baseUrl ?? "",
3515
+ apiType: providerConfig.api ?? ""
3516
+ };
3517
+ }
3518
+ function jsonErrorResponse(message, status) {
3519
+ return new Response(JSON.stringify({ error: message }), {
3520
+ status,
3521
+ headers: { "content-type": "application/json" }
3522
+ });
3523
+ }
3524
+ async function handleApiRequest(req, body, apiType, config, openclawConfig, authProfiles, compressionMiddleware) {
3525
+ const adapter = getAdapter(apiType);
3526
+ if (!adapter) {
3527
+ return jsonErrorResponse(`Unknown API type: ${apiType}`, 500);
3528
+ }
3529
+ const parsed = adapter.parseRequest(body);
3530
+ const compactionHeaders = {};
3531
+ req.headers.forEach((value, key) => {
3532
+ compactionHeaders[key] = value;
3533
+ });
3534
+ const compaction = detectCompaction(compactionHeaders, parsed.messages);
3535
+ if (compaction.isCompaction && compressionMiddleware) {
3536
+ const summaryData = compressionMiddleware.getSummaryForSession(parsed.messages);
3537
+ if (summaryData) {
3538
+ const syntheticParsed = buildSyntheticSummaryResponse(summaryData.summary, summaryData.recentMessages, parsed.model);
3539
+ console.log(`[clawmux] Compaction detected (${compaction.detectedBy}) → returning synthetic response`);
3540
+ return buildSyntheticHttpResponse(syntheticParsed, adapter);
3541
+ }
3542
+ console.log(`[clawmux] Compaction detected but no summary available, forwarding to upstream`);
3543
+ }
3544
+ let effectiveParsed = parsed;
3545
+ if (compressionMiddleware) {
3546
+ const { messages: compressedMessages, wasCompressed } = compressionMiddleware.beforeForward(parsed, adapter);
3547
+ if (wasCompressed) {
3548
+ const modifiedRawBody = adapter.modifyMessages(parsed.rawBody, compressedMessages);
3549
+ effectiveParsed = {
3550
+ ...parsed,
3551
+ messages: compressedMessages,
3552
+ rawBody: modifiedRawBody
3553
+ };
246
3554
  }
3555
+ }
3556
+ const messages = effectiveParsed.messages;
3557
+ const classification = await classifyLocal(messages);
3558
+ const decision = {
3559
+ tier: classification.tier,
3560
+ model: config.routing.models[classification.tier],
3561
+ confidence: classification.confidence,
3562
+ overrideReason: classification.reasoning
3563
+ };
3564
+ const lookup = findProviderForModel(decision.model, openclawConfig);
3565
+ let providerName;
3566
+ let baseUrl;
3567
+ let targetApiType;
3568
+ if (lookup) {
3569
+ providerName = lookup.providerName;
3570
+ baseUrl = lookup.baseUrl;
3571
+ targetApiType = lookup.apiType;
3572
+ } else {
3573
+ const reqUrl = new URL(req.url);
3574
+ baseUrl = `${reqUrl.protocol}//${reqUrl.host}`;
3575
+ providerName = apiType.split("-")[0];
3576
+ targetApiType = apiType;
3577
+ }
3578
+ const auth = resolveApiKey(providerName, openclawConfig, authProfiles);
3579
+ if (!auth) {
3580
+ return jsonErrorResponse(`No auth credentials found for provider: ${providerName}`, 502);
3581
+ }
3582
+ const authInfo = {
3583
+ apiKey: auth.apiKey,
3584
+ headerName: auth.headerName,
3585
+ headerValue: auth.headerValue,
3586
+ awsAccessKeyId: auth.awsAccessKeyId,
3587
+ awsSecretKey: auth.awsSecretKey,
3588
+ awsSessionToken: auth.awsSessionToken,
3589
+ awsRegion: auth.awsRegion
247
3590
  };
3591
+ const actualModelId = decision.model.split("/").slice(1).join("/");
3592
+ const isCrossProvider = targetApiType !== "" && targetApiType !== apiType;
3593
+ const targetAdapter = isCrossProvider ? getAdapter(targetApiType) : undefined;
3594
+ const requestAdapter = targetAdapter ?? adapter;
3595
+ const upstream = requestAdapter.buildUpstreamRequest(effectiveParsed, actualModelId, baseUrl, authInfo);
3596
+ let upstreamResponse;
3597
+ try {
3598
+ upstreamResponse = await fetch(upstream.url, {
3599
+ method: upstream.method,
3600
+ headers: upstream.headers,
3601
+ body: upstream.body
3602
+ });
3603
+ } catch (err) {
3604
+ const message = err instanceof Error ? err.message : String(err);
3605
+ return jsonErrorResponse(`Upstream request failed: ${message}`, 502);
3606
+ }
3607
+ console.log(`[clawmux] [llm] ${decision.tier} → ${decision.model} | conf=${classification.confidence.toFixed(2)}${classification.reasoning ? ` | ${classification.reasoning}` : ""}`);
3608
+ if (compressionMiddleware && upstreamResponse.ok) {
3609
+ compressionMiddleware.afterResponse(parsed, adapter, baseUrl, authInfo);
3610
+ }
3611
+ const isCodexUpstream = targetApiType === "openai-codex-responses";
3612
+ if (isCodexUpstream && upstreamResponse.ok && upstreamResponse.body) {
3613
+ if (effectiveParsed.stream) {
3614
+ return translateResponse(requestAdapter, adapter, upstreamResponse, true);
3615
+ }
3616
+ const collected = await collectCodexStream(requestAdapter, upstreamResponse);
3617
+ const translated = adapter.buildResponse(collected);
3618
+ return new Response(JSON.stringify(translated), {
3619
+ status: 200,
3620
+ headers: { "content-type": "application/json" }
3621
+ });
3622
+ }
3623
+ if (targetAdapter && upstreamResponse.ok) {
3624
+ return translateResponse(targetAdapter, adapter, upstreamResponse, effectiveParsed.stream);
3625
+ }
3626
+ return new Response(upstreamResponse.body, {
3627
+ status: upstreamResponse.status,
3628
+ statusText: upstreamResponse.statusText,
3629
+ headers: upstreamResponse.headers
3630
+ });
3631
+ }
3632
+ function createResolvedCompressionMiddleware(config, openclawConfig, piAiCatalog, statsTracker) {
3633
+ const contextWindows = config.routing.contextWindows ?? {};
3634
+ const resolvedContextWindow = resolveCompressionContextWindow(config.routing.models, contextWindows, openclawConfig, piAiCatalog);
3635
+ const tiers = ["LIGHT", "MEDIUM", "HEAVY"];
3636
+ for (const tier of tiers) {
3637
+ const modelKey = config.routing.models[tier];
3638
+ if (modelKey) {
3639
+ const window = resolveContextWindow(modelKey, contextWindows, openclawConfig, piAiCatalog);
3640
+ console.log(`[clawmux] ${tier} → ${modelKey} contextWindow=${window}`);
3641
+ }
3642
+ }
3643
+ console.log(`[clawmux] Compression contextWindow=${resolvedContextWindow} (minimum across tiers)`);
3644
+ return createCompressionMiddleware({
3645
+ threshold: config.compression.threshold,
3646
+ targetRatio: config.compression.targetRatio ?? 0.6,
3647
+ compressionModel: config.compression.model,
3648
+ resolvedContextWindow,
3649
+ statsTracker
3650
+ });
3651
+ }
3652
+ var ROUTE_MAPPINGS = [
3653
+ { apiType: "anthropic-messages", key: "/v1/messages" },
3654
+ { apiType: "openai-completions", key: "/v1/chat/completions" },
3655
+ { apiType: "openai-responses", key: "/v1/responses" },
3656
+ { apiType: "google-generative-ai", key: "/v1beta/models/*" },
3657
+ { apiType: "ollama", key: "/api/chat" },
3658
+ { apiType: "bedrock-converse-stream", key: "/model/*/converse-stream" }
3659
+ ];
3660
+ function setupPipelineRoutes(config, openclawConfig, authProfiles, compressionMiddleware) {
3661
+ for (const mapping of ROUTE_MAPPINGS) {
3662
+ setRouteHandler(mapping.key, (req, body) => handleApiRequest(req, body, mapping.apiType, config, openclawConfig, authProfiles, compressionMiddleware));
3663
+ }
3664
+ }
3665
+
3666
+ // src/index.ts
3667
+ var import_node_path4 = require("node:path");
3668
+ async function bootstrap(portOverride) {
3669
+ const configPath = process.env.CLAWMUX_CONFIG ? import_node_path4.resolve(process.env.CLAWMUX_CONFIG) : import_node_path4.resolve(process.cwd(), "clawmux.json");
3670
+ const result = await loadConfig(configPath);
3671
+ if (!result.valid) {
3672
+ console.error("[clawmux] Config errors:");
3673
+ for (const err of result.errors)
3674
+ console.error(` - ${err}`);
3675
+ process.exit(1);
3676
+ }
3677
+ const config = result.config;
3678
+ const openclawConfig = await readOpenClawConfig();
3679
+ const authProfiles = await readAuthProfiles();
3680
+ const piAiCatalog = await loadPiAiCatalog();
3681
+ const compressionMiddleware = createResolvedCompressionMiddleware(config, openclawConfig, piAiCatalog);
3682
+ setupPipelineRoutes(config, openclawConfig, authProfiles, compressionMiddleware);
3683
+ const port = portOverride ?? parseInt(process.env.CLAWMUX_PORT ?? "3456", 10);
3684
+ const server = createServer({ port, host: "127.0.0.1" });
3685
+ server.start();
3686
+ console.log(`[clawmux] Proxy server running on http://127.0.0.1:${port}`);
3687
+ const watcher = createConfigWatcher(configPath, (newConfig) => {
3688
+ console.log("[clawmux] Config reloaded, updating routes...");
3689
+ clearCustomHandlers();
3690
+ const newCompression = createResolvedCompressionMiddleware(newConfig, openclawConfig, piAiCatalog);
3691
+ setupPipelineRoutes(newConfig, openclawConfig, authProfiles, newCompression);
3692
+ });
3693
+ watcher.start();
3694
+ }
3695
+ if (typeof Bun !== "undefined" && Bun.main === "/home/runner/work/ClawMux/ClawMux/src/index.ts") {
3696
+ bootstrap().catch((err) => {
3697
+ console.error(`[clawmux] Fatal: ${err.message}`);
3698
+ process.exit(1);
3699
+ });
248
3700
  }
249
3701
 
250
3702
  // src/utils/logger.ts
251
- var import_node_fs = require("node:fs");
252
- var import_node_path = require("node:path");
253
- var LOG_DIR = import_node_path.join(process.env.HOME ?? "/root", ".openclaw", "clawmux");
3703
+ var import_node_fs2 = require("node:fs");
3704
+ var import_node_path5 = require("node:path");
3705
+ var LOG_DIR = import_node_path5.join(process.env.HOME ?? "/root", ".openclaw", "clawmux");
254
3706
  var MAX_DAYS = 7;
255
3707
  var fileStream = null;
256
3708
  var currentDate = "";
@@ -259,7 +3711,7 @@ function todayString() {
259
3711
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
260
3712
  }
261
3713
  function logPath(date) {
262
- return import_node_path.join(LOG_DIR, `${date}.log`);
3714
+ return import_node_path5.join(LOG_DIR, `${date}.log`);
263
3715
  }
264
3716
  function rotateIfNeeded() {
265
3717
  const today = todayString();
@@ -269,15 +3721,15 @@ function rotateIfNeeded() {
269
3721
  fileStream.end();
270
3722
  }
271
3723
  currentDate = today;
272
- fileStream = import_node_fs.createWriteStream(logPath(today), { flags: "a" });
3724
+ fileStream = import_node_fs2.createWriteStream(logPath(today), { flags: "a" });
273
3725
  purgeOldLogs();
274
3726
  }
275
3727
  function purgeOldLogs() {
276
3728
  try {
277
- const files = import_node_fs.readdirSync(LOG_DIR).filter((f) => f.endsWith(".log")).sort();
3729
+ const files = import_node_fs2.readdirSync(LOG_DIR).filter((f) => f.endsWith(".log")).sort();
278
3730
  while (files.length > MAX_DAYS) {
279
3731
  const oldest = files.shift();
280
- import_node_fs.unlinkSync(import_node_path.join(LOG_DIR, oldest));
3732
+ import_node_fs2.unlinkSync(import_node_path5.join(LOG_DIR, oldest));
281
3733
  }
282
3734
  } catch (_) {}
283
3735
  }
@@ -294,7 +3746,7 @@ function writeLine(level, args) {
294
3746
  }
295
3747
  }
296
3748
  function initLogger() {
297
- import_node_fs.mkdirSync(LOG_DIR, { recursive: true });
3749
+ import_node_fs2.mkdirSync(LOG_DIR, { recursive: true });
298
3750
  rotateIfNeeded();
299
3751
  const origLog = console.log.bind(console);
300
3752
  const origError = console.error.bind(console);
@@ -317,7 +3769,7 @@ function getLogDir() {
317
3769
  }
318
3770
 
319
3771
  // src/cli.ts
320
- var VERSION2 = process.env.npm_package_version ?? "0.3.0";
3772
+ var VERSION2 = process.env.npm_package_version ?? "0.3.1";
321
3773
  var SERVICE_NAME = "clawmux";
322
3774
  var HELP = `Usage: clawmux <command>
323
3775
 
@@ -342,7 +3794,7 @@ var PROVIDER_KEY = "clawmux";
342
3794
  var PROVIDER_API = "anthropic-messages";
343
3795
  async function fileExistsLocal(path) {
344
3796
  try {
345
- await import_promises.access(path);
3797
+ await import_promises6.access(path);
346
3798
  return true;
347
3799
  } catch {
348
3800
  return false;
@@ -367,13 +3819,13 @@ function resolveClawmuxBin() {
367
3819
  return detectPackageManager() === "bunx" ? "bunx clawmux" : "npx clawmux";
368
3820
  }
369
3821
  }
370
- function getHomeDir() {
3822
+ function getHomeDir2() {
371
3823
  return process.env.HOME ?? "/root";
372
3824
  }
373
- var SYSTEMD_DIR = import_node_path2.join(getHomeDir(), ".config", "systemd", "user");
374
- var SYSTEMD_PATH = import_node_path2.join(SYSTEMD_DIR, `${SERVICE_NAME}.service`);
375
- var LAUNCHD_DIR = import_node_path2.join(getHomeDir(), "Library", "LaunchAgents");
376
- var LAUNCHD_PATH = import_node_path2.join(LAUNCHD_DIR, `com.${SERVICE_NAME}.plist`);
3825
+ var SYSTEMD_DIR = import_node_path6.join(getHomeDir2(), ".config", "systemd", "user");
3826
+ var SYSTEMD_PATH = import_node_path6.join(SYSTEMD_DIR, `${SERVICE_NAME}.service`);
3827
+ var LAUNCHD_DIR = import_node_path6.join(getHomeDir2(), "Library", "LaunchAgents");
3828
+ var LAUNCHD_PATH = import_node_path6.join(LAUNCHD_DIR, `com.${SERVICE_NAME}.plist`);
377
3829
  function buildSystemdUnit(bin, port, workDir) {
378
3830
  return `[Unit]
379
3831
  Description=ClawMux - Smart model routing proxy
@@ -392,7 +3844,7 @@ WantedBy=default.target
392
3844
  `;
393
3845
  }
394
3846
  function buildLaunchdPlist(bin, port, workDir) {
395
- const logDir = import_node_path2.join(getHomeDir(), ".openclaw", "clawmux");
3847
+ const logDir = import_node_path6.join(getHomeDir2(), ".openclaw", "clawmux");
396
3848
  return `<?xml version="1.0" encoding="UTF-8"?>
397
3849
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
398
3850
  <plist version="1.0">
@@ -431,8 +3883,8 @@ async function installService(port, workDir) {
431
3883
  const bin = resolveClawmuxBin();
432
3884
  const os = import_node_os.platform();
433
3885
  if (os === "linux") {
434
- await import_promises.mkdir(SYSTEMD_DIR, { recursive: true });
435
- await import_promises.writeFile(SYSTEMD_PATH, buildSystemdUnit(bin, port, workDir));
3886
+ await import_promises6.mkdir(SYSTEMD_DIR, { recursive: true });
3887
+ await import_promises6.writeFile(SYSTEMD_PATH, buildSystemdUnit(bin, port, workDir));
436
3888
  try {
437
3889
  import_node_child_process.execSync("systemctl --user daemon-reload", { stdio: "pipe" });
438
3890
  import_node_child_process.execSync(`systemctl --user enable ${SERVICE_NAME}`, { stdio: "pipe" });
@@ -446,10 +3898,10 @@ async function installService(port, workDir) {
446
3898
  console.warn(" You can start manually: clawmux start");
447
3899
  }
448
3900
  } else if (os === "darwin") {
449
- await import_promises.mkdir(LAUNCHD_DIR, { recursive: true });
450
- const logDir = import_node_path2.join(getHomeDir(), ".openclaw", "clawmux");
451
- await import_promises.mkdir(logDir, { recursive: true });
452
- await import_promises.writeFile(LAUNCHD_PATH, buildLaunchdPlist(bin, port, workDir));
3901
+ await import_promises6.mkdir(LAUNCHD_DIR, { recursive: true });
3902
+ const logDir = import_node_path6.join(getHomeDir2(), ".openclaw", "clawmux");
3903
+ await import_promises6.mkdir(logDir, { recursive: true });
3904
+ await import_promises6.writeFile(LAUNCHD_PATH, buildLaunchdPlist(bin, port, workDir));
453
3905
  try {
454
3906
  import_node_child_process.execSync(`launchctl load -w ${LAUNCHD_PATH}`, { stdio: "pipe" });
455
3907
  console.log("[info] launchd service installed and started");
@@ -512,7 +3964,7 @@ async function removeService() {
512
3964
  import_node_child_process.execSync(`systemctl --user disable ${SERVICE_NAME}`, { stdio: "pipe" });
513
3965
  } catch (_) {}
514
3966
  if (await fileExistsLocal(SYSTEMD_PATH)) {
515
- await import_promises.unlink(SYSTEMD_PATH);
3967
+ await import_promises6.unlink(SYSTEMD_PATH);
516
3968
  import_node_child_process.execSync("systemctl --user daemon-reload", { stdio: "pipe" });
517
3969
  console.log("[info] systemd service removed");
518
3970
  }
@@ -521,7 +3973,7 @@ async function removeService() {
521
3973
  import_node_child_process.execSync(`launchctl unload ${LAUNCHD_PATH}`, { stdio: "pipe" });
522
3974
  } catch (_) {}
523
3975
  if (await fileExistsLocal(LAUNCHD_PATH)) {
524
- await import_promises.unlink(LAUNCHD_PATH);
3976
+ await import_promises6.unlink(LAUNCHD_PATH);
525
3977
  console.log("[info] launchd plist removed");
526
3978
  }
527
3979
  }
@@ -596,8 +4048,8 @@ async function update() {
596
4048
  async function init() {
597
4049
  const args = process.argv.slice(2);
598
4050
  const noService = args.includes("--no-service");
599
- const homeDir = getHomeDir();
600
- const openclawConfigPath = process.env.OPENCLAW_CONFIG_PATH ?? import_node_path2.join(homeDir, ".openclaw", "openclaw.json");
4051
+ const homeDir = getHomeDir2();
4052
+ const openclawConfigPath = process.env.OPENCLAW_CONFIG_PATH ?? import_node_path6.join(homeDir, ".openclaw", "openclaw.json");
601
4053
  if (!await fileExistsLocal(openclawConfigPath)) {
602
4054
  console.error(`[error] OpenClaw config not found at ${openclawConfigPath}`);
603
4055
  console.error("Set OPENCLAW_CONFIG_PATH or ensure ~/.openclaw/openclaw.json exists");
@@ -605,25 +4057,25 @@ async function init() {
605
4057
  }
606
4058
  console.log(`[info] Using OpenClaw config: ${openclawConfigPath}`);
607
4059
  const backupPath = `${openclawConfigPath}.bak.${Date.now()}`;
608
- await import_promises.copyFile(openclawConfigPath, backupPath);
4060
+ await import_promises6.copyFile(openclawConfigPath, backupPath);
609
4061
  console.log(`[info] Backup created: ${backupPath}`);
610
- const clawmuxJsonPath = import_node_path2.join(process.cwd(), "clawmux.json");
611
- const examplePath = import_node_path2.join(process.cwd(), "clawmux.example.json");
4062
+ const clawmuxJsonPath = import_node_path6.join(process.cwd(), "clawmux.json");
4063
+ const examplePath = import_node_path6.join(process.cwd(), "clawmux.example.json");
612
4064
  if (!await fileExistsLocal(clawmuxJsonPath)) {
613
4065
  if (await fileExistsLocal(examplePath)) {
614
- await import_promises.copyFile(examplePath, clawmuxJsonPath);
4066
+ await import_promises6.copyFile(examplePath, clawmuxJsonPath);
615
4067
  console.log("[info] Created clawmux.json from clawmux.example.json");
616
4068
  } else {
617
4069
  const defaultConfig = {
618
4070
  compression: { threshold: 0.75, model: "" },
619
4071
  routing: { models: { LIGHT: "", MEDIUM: "", HEAVY: "" } }
620
4072
  };
621
- await import_promises.writeFile(clawmuxJsonPath, JSON.stringify(defaultConfig, null, 2) + `
4073
+ await import_promises6.writeFile(clawmuxJsonPath, JSON.stringify(defaultConfig, null, 2) + `
622
4074
  `);
623
4075
  console.log("[info] Created default clawmux.json (configure models before use)");
624
4076
  }
625
4077
  }
626
- const raw = await import_promises.readFile(openclawConfigPath, "utf-8");
4078
+ const raw = await import_promises6.readFile(openclawConfigPath, "utf-8");
627
4079
  const config = JSON.parse(raw);
628
4080
  if (!config.models)
629
4081
  config.models = {};
@@ -639,7 +4091,7 @@ async function init() {
639
4091
  api: PROVIDER_API,
640
4092
  models: [{ id: "auto", name: "ClawMux Auto Router" }]
641
4093
  };
642
- await import_promises.writeFile(openclawConfigPath, JSON.stringify(config, null, 2) + `
4094
+ await import_promises6.writeFile(openclawConfigPath, JSON.stringify(config, null, 2) + `
643
4095
  `);
644
4096
  console.log(` added ${PROVIDER_KEY} provider to openclaw.json`);
645
4097
  }
@@ -662,7 +4114,7 @@ Next steps:`);
662
4114
  console.log(" 3. Select a provider: openclaw provider clawmux-openai");
663
4115
  console.log(" 4. Start chatting: openclaw chat");
664
4116
  }
665
- function start() {
4117
+ async function start() {
666
4118
  const args = process.argv.slice(2);
667
4119
  let port = parseInt(process.env.CLAWMUX_PORT ?? "3456", 10);
668
4120
  const portIdx = args.indexOf("--port") !== -1 ? args.indexOf("--port") : args.indexOf("-p");
@@ -670,20 +4122,18 @@ function start() {
670
4122
  port = parseInt(args[portIdx + 1], 10);
671
4123
  }
672
4124
  initLogger();
673
- const server = createServer({ port, host: "127.0.0.1" });
674
- server.start();
675
- console.log(`[clawmux] Proxy server running on http://127.0.0.1:${port}`);
4125
+ await bootstrap(port);
676
4126
  console.log(`[clawmux] Logs: ${getLogDir()}`);
677
4127
  checkForUpdate();
678
4128
  }
679
4129
  async function uninstall() {
680
4130
  await removeService();
681
- const homeDir = getHomeDir();
682
- const openclawConfigPath = process.env.OPENCLAW_CONFIG_PATH ?? import_node_path2.join(homeDir, ".openclaw", "openclaw.json");
4131
+ const homeDir = getHomeDir2();
4132
+ const openclawConfigPath = process.env.OPENCLAW_CONFIG_PATH ?? import_node_path6.join(homeDir, ".openclaw", "openclaw.json");
683
4133
  if (await fileExistsLocal(openclawConfigPath)) {
684
4134
  const backupPath = `${openclawConfigPath}.bak.${Date.now()}`;
685
- await import_promises.copyFile(openclawConfigPath, backupPath);
686
- const raw = await import_promises.readFile(openclawConfigPath, "utf-8");
4135
+ await import_promises6.copyFile(openclawConfigPath, backupPath);
4136
+ const raw = await import_promises6.readFile(openclawConfigPath, "utf-8");
687
4137
  const config = JSON.parse(raw);
688
4138
  const models = config.models ?? {};
689
4139
  const providers = models.providers ?? {};
@@ -695,7 +4145,7 @@ async function uninstall() {
695
4145
  }
696
4146
  }
697
4147
  if (removed > 0) {
698
- await import_promises.writeFile(openclawConfigPath, JSON.stringify(config, null, 2) + `
4148
+ await import_promises6.writeFile(openclawConfigPath, JSON.stringify(config, null, 2) + `
699
4149
  `);
700
4150
  console.log(`[info] Removed ${removed} ClawMux provider(s) from openclaw.json`);
701
4151
  }
@@ -711,7 +4161,10 @@ switch (command) {
711
4161
  });
712
4162
  break;
713
4163
  case "start":
714
- start();
4164
+ start().catch((err) => {
4165
+ console.error(`[error] ${err.message}`);
4166
+ process.exit(1);
4167
+ });
715
4168
  break;
716
4169
  case "stop":
717
4170
  stopService();