@relayplane/proxy 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,2685 @@
1
+ // src/proxy.ts
2
+ import * as http from "http";
3
+
4
+ // src/storage/store.ts
5
+ import Database from "better-sqlite3";
6
+
7
+ // node_modules/nanoid/index.js
8
+ import crypto from "crypto";
9
+
10
+ // node_modules/nanoid/url-alphabet/index.js
11
+ var urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
12
+
13
+ // node_modules/nanoid/index.js
14
+ var POOL_SIZE_MULTIPLIER = 128;
15
+ var pool;
16
+ var poolOffset;
17
+ var fillPool = (bytes) => {
18
+ if (!pool || pool.length < bytes) {
19
+ pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER);
20
+ crypto.randomFillSync(pool);
21
+ poolOffset = 0;
22
+ } else if (poolOffset + bytes > pool.length) {
23
+ crypto.randomFillSync(pool);
24
+ poolOffset = 0;
25
+ }
26
+ poolOffset += bytes;
27
+ };
28
+ var nanoid = (size = 21) => {
29
+ fillPool(size |= 0);
30
+ let id = "";
31
+ for (let i = poolOffset - size; i < poolOffset; i++) {
32
+ id += urlAlphabet[pool[i] & 63];
33
+ }
34
+ return id;
35
+ };
36
+
37
+ // src/storage/store.ts
38
+ import * as fs from "fs";
39
+ import * as path from "path";
40
+ import * as os from "os";
41
+
42
+ // src/storage/schema.ts
43
+ var SCHEMA_SQL = `
44
+ -- Runs table: stores all LLM invocations
45
+ CREATE TABLE IF NOT EXISTS runs (
46
+ id TEXT PRIMARY KEY,
47
+ prompt TEXT NOT NULL,
48
+ system_prompt TEXT,
49
+ task_type TEXT NOT NULL,
50
+ model TEXT NOT NULL,
51
+ success INTEGER NOT NULL,
52
+ output TEXT,
53
+ error TEXT,
54
+ duration_ms INTEGER NOT NULL,
55
+ tokens_in INTEGER,
56
+ tokens_out INTEGER,
57
+ cost_usd REAL,
58
+ metadata TEXT,
59
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
60
+ );
61
+
62
+ -- Index for task type queries
63
+ CREATE INDEX IF NOT EXISTS idx_runs_task_type ON runs(task_type);
64
+
65
+ -- Index for model queries
66
+ CREATE INDEX IF NOT EXISTS idx_runs_model ON runs(model);
67
+
68
+ -- Index for time-based queries
69
+ CREATE INDEX IF NOT EXISTS idx_runs_created_at ON runs(created_at);
70
+
71
+ -- Outcomes table: stores user feedback on runs
72
+ CREATE TABLE IF NOT EXISTS outcomes (
73
+ id TEXT PRIMARY KEY,
74
+ run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE,
75
+ success INTEGER NOT NULL,
76
+ quality TEXT,
77
+ latency_satisfactory INTEGER,
78
+ cost_satisfactory INTEGER,
79
+ feedback TEXT,
80
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
81
+ UNIQUE(run_id)
82
+ );
83
+
84
+ -- Index for run lookups
85
+ CREATE INDEX IF NOT EXISTS idx_outcomes_run_id ON outcomes(run_id);
86
+
87
+ -- Routing rules table: stores routing preferences
88
+ CREATE TABLE IF NOT EXISTS routing_rules (
89
+ id TEXT PRIMARY KEY,
90
+ task_type TEXT NOT NULL UNIQUE,
91
+ preferred_model TEXT NOT NULL,
92
+ source TEXT NOT NULL DEFAULT 'default',
93
+ confidence REAL,
94
+ sample_count INTEGER,
95
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
96
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
97
+ );
98
+
99
+ -- Index for task type lookups
100
+ CREATE INDEX IF NOT EXISTS idx_routing_rules_task_type ON routing_rules(task_type);
101
+
102
+ -- Suggestions table: stores routing improvement suggestions
103
+ CREATE TABLE IF NOT EXISTS suggestions (
104
+ id TEXT PRIMARY KEY,
105
+ task_type TEXT NOT NULL,
106
+ current_model TEXT NOT NULL,
107
+ suggested_model TEXT NOT NULL,
108
+ reason TEXT NOT NULL,
109
+ confidence REAL NOT NULL,
110
+ expected_improvement TEXT NOT NULL,
111
+ sample_count INTEGER NOT NULL,
112
+ accepted INTEGER,
113
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
114
+ accepted_at TEXT
115
+ );
116
+
117
+ -- Index for task type lookups
118
+ CREATE INDEX IF NOT EXISTS idx_suggestions_task_type ON suggestions(task_type);
119
+
120
+ -- Index for pending suggestions
121
+ CREATE INDEX IF NOT EXISTS idx_suggestions_accepted ON suggestions(accepted);
122
+
123
+ -- Schema version table for migrations
124
+ CREATE TABLE IF NOT EXISTS schema_version (
125
+ version INTEGER PRIMARY KEY,
126
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
127
+ );
128
+
129
+ -- Insert initial schema version
130
+ INSERT OR IGNORE INTO schema_version (version) VALUES (1);
131
+ `;
132
+ var DEFAULT_ROUTING_RULES = [
133
+ { taskType: "code_generation", preferredModel: "anthropic:claude-3-5-haiku-latest" },
134
+ { taskType: "code_review", preferredModel: "anthropic:claude-3-5-haiku-latest" },
135
+ { taskType: "summarization", preferredModel: "anthropic:claude-3-5-haiku-latest" },
136
+ { taskType: "analysis", preferredModel: "anthropic:claude-3-5-haiku-latest" },
137
+ { taskType: "creative_writing", preferredModel: "anthropic:claude-3-5-haiku-latest" },
138
+ { taskType: "data_extraction", preferredModel: "anthropic:claude-3-5-haiku-latest" },
139
+ { taskType: "translation", preferredModel: "anthropic:claude-3-5-haiku-latest" },
140
+ { taskType: "question_answering", preferredModel: "anthropic:claude-3-5-haiku-latest" },
141
+ { taskType: "general", preferredModel: "anthropic:claude-3-5-haiku-latest" }
142
+ ];
143
+ function generateSeedSQL() {
144
+ const values = DEFAULT_ROUTING_RULES.map((rule, index) => {
145
+ const id = `default-${rule.taskType}`;
146
+ return `('${id}', '${rule.taskType}', '${rule.preferredModel}', 'default', NULL, NULL, datetime('now'), datetime('now'))`;
147
+ }).join(",\n ");
148
+ return `
149
+ INSERT OR IGNORE INTO routing_rules (id, task_type, preferred_model, source, confidence, sample_count, created_at, updated_at)
150
+ VALUES
151
+ ${values};
152
+ `;
153
+ }
154
+
155
+ // src/storage/store.ts
156
+ function getDefaultDbPath() {
157
+ return path.join(os.homedir(), ".relayplane", "data.db");
158
+ }
159
+ var Store = class {
160
+ db;
161
+ dbPath;
162
+ /**
163
+ * Creates a new Store instance.
164
+ *
165
+ * @param dbPath - Path to the SQLite database file. Defaults to ~/.relayplane/data.db
166
+ */
167
+ constructor(dbPath) {
168
+ this.dbPath = dbPath ?? getDefaultDbPath();
169
+ const dir = path.dirname(this.dbPath);
170
+ if (!fs.existsSync(dir)) {
171
+ fs.mkdirSync(dir, { recursive: true });
172
+ }
173
+ this.db = new Database(this.dbPath);
174
+ this.db.pragma("journal_mode = WAL");
175
+ this.db.pragma("foreign_keys = ON");
176
+ this.initializeSchema();
177
+ }
178
+ /**
179
+ * Initializes the database schema.
180
+ */
181
+ initializeSchema() {
182
+ this.db.exec(SCHEMA_SQL);
183
+ this.db.exec(generateSeedSQL());
184
+ }
185
+ /**
186
+ * Closes the database connection.
187
+ */
188
+ close() {
189
+ this.db.close();
190
+ }
191
+ /**
192
+ * Gets the database path.
193
+ */
194
+ getDbPath() {
195
+ return this.dbPath;
196
+ }
197
+ // ============================================================================
198
+ // Runs
199
+ // ============================================================================
200
+ /**
201
+ * Records a new run.
202
+ */
203
+ recordRun(run) {
204
+ const id = nanoid();
205
+ const stmt = this.db.prepare(`
206
+ INSERT INTO runs (id, prompt, system_prompt, task_type, model, success, output, error, duration_ms, tokens_in, tokens_out, cost_usd, metadata, created_at)
207
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
208
+ `);
209
+ stmt.run(
210
+ id,
211
+ run.prompt,
212
+ run.systemPrompt,
213
+ run.taskType,
214
+ run.model,
215
+ run.success ? 1 : 0,
216
+ run.output,
217
+ run.error,
218
+ run.durationMs,
219
+ run.tokensIn,
220
+ run.tokensOut,
221
+ run.costUsd,
222
+ run.metadata
223
+ );
224
+ return id;
225
+ }
226
+ /**
227
+ * Gets a run by ID.
228
+ */
229
+ getRun(id) {
230
+ const stmt = this.db.prepare(`
231
+ SELECT id, prompt, system_prompt as systemPrompt, task_type as taskType, model, success, output, error, duration_ms as durationMs, tokens_in as tokensIn, tokens_out as tokensOut, cost_usd as costUsd, metadata, created_at as createdAt
232
+ FROM runs
233
+ WHERE id = ?
234
+ `);
235
+ const row = stmt.get(id);
236
+ if (!row) return null;
237
+ return {
238
+ ...row,
239
+ success: Boolean(row.success)
240
+ };
241
+ }
242
+ /**
243
+ * Gets runs with optional filters.
244
+ */
245
+ getRuns(options) {
246
+ const conditions = [];
247
+ const params = [];
248
+ if (options?.taskType) {
249
+ conditions.push("task_type = ?");
250
+ params.push(options.taskType);
251
+ }
252
+ if (options?.model) {
253
+ conditions.push("model = ?");
254
+ params.push(options.model);
255
+ }
256
+ if (options?.from) {
257
+ conditions.push("created_at >= ?");
258
+ params.push(options.from);
259
+ }
260
+ if (options?.to) {
261
+ conditions.push("created_at <= ?");
262
+ params.push(options.to);
263
+ }
264
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
265
+ const limit = options?.limit ?? 100;
266
+ const offset = options?.offset ?? 0;
267
+ const stmt = this.db.prepare(`
268
+ SELECT id, prompt, system_prompt as systemPrompt, task_type as taskType, model, success, output, error, duration_ms as durationMs, tokens_in as tokensIn, tokens_out as tokensOut, cost_usd as costUsd, metadata, created_at as createdAt
269
+ FROM runs
270
+ ${whereClause}
271
+ ORDER BY created_at DESC
272
+ LIMIT ? OFFSET ?
273
+ `);
274
+ params.push(limit, offset);
275
+ const rows = stmt.all(...params);
276
+ return rows.map((row) => ({
277
+ ...row,
278
+ success: Boolean(row.success)
279
+ }));
280
+ }
281
+ /**
282
+ * Counts runs with optional filters.
283
+ */
284
+ countRuns(options) {
285
+ const conditions = [];
286
+ const params = [];
287
+ if (options?.taskType) {
288
+ conditions.push("task_type = ?");
289
+ params.push(options.taskType);
290
+ }
291
+ if (options?.model) {
292
+ conditions.push("model = ?");
293
+ params.push(options.model);
294
+ }
295
+ if (options?.from) {
296
+ conditions.push("created_at >= ?");
297
+ params.push(options.from);
298
+ }
299
+ if (options?.to) {
300
+ conditions.push("created_at <= ?");
301
+ params.push(options.to);
302
+ }
303
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
304
+ const stmt = this.db.prepare(`
305
+ SELECT COUNT(*) as count
306
+ FROM runs
307
+ ${whereClause}
308
+ `);
309
+ const row = stmt.get(...params);
310
+ return row.count;
311
+ }
312
+ // ============================================================================
313
+ // Outcomes
314
+ // ============================================================================
315
+ /**
316
+ * Records an outcome for a run.
317
+ */
318
+ recordOutcome(outcome) {
319
+ const id = nanoid();
320
+ const stmt = this.db.prepare(`
321
+ INSERT INTO outcomes (id, run_id, success, quality, latency_satisfactory, cost_satisfactory, feedback, created_at)
322
+ VALUES (?, ?, ?, ?, ?, ?, ?, datetime('now'))
323
+ ON CONFLICT(run_id) DO UPDATE SET
324
+ success = excluded.success,
325
+ quality = excluded.quality,
326
+ latency_satisfactory = excluded.latency_satisfactory,
327
+ cost_satisfactory = excluded.cost_satisfactory,
328
+ feedback = excluded.feedback,
329
+ created_at = datetime('now')
330
+ `);
331
+ stmt.run(
332
+ id,
333
+ outcome.runId,
334
+ outcome.success ? 1 : 0,
335
+ outcome.quality,
336
+ outcome.latencySatisfactory != null ? outcome.latencySatisfactory ? 1 : 0 : null,
337
+ outcome.costSatisfactory != null ? outcome.costSatisfactory ? 1 : 0 : null,
338
+ outcome.feedback
339
+ );
340
+ return id;
341
+ }
342
+ /**
343
+ * Gets an outcome for a run.
344
+ */
345
+ getOutcome(runId) {
346
+ const stmt = this.db.prepare(`
347
+ SELECT id, run_id as runId, success, quality, latency_satisfactory as latencySatisfactory, cost_satisfactory as costSatisfactory, feedback, created_at as createdAt
348
+ FROM outcomes
349
+ WHERE run_id = ?
350
+ `);
351
+ const row = stmt.get(runId);
352
+ if (!row) return null;
353
+ return {
354
+ ...row,
355
+ success: Boolean(row.success),
356
+ latencySatisfactory: row.latencySatisfactory != null ? Boolean(row.latencySatisfactory) : null,
357
+ costSatisfactory: row.costSatisfactory != null ? Boolean(row.costSatisfactory) : null
358
+ };
359
+ }
360
+ /**
361
+ * Gets outcomes with optional filters.
362
+ */
363
+ getOutcomes(options) {
364
+ const conditions = [];
365
+ const params = [];
366
+ if (options?.taskType) {
367
+ conditions.push("r.task_type = ?");
368
+ params.push(options.taskType);
369
+ }
370
+ if (options?.model) {
371
+ conditions.push("r.model = ?");
372
+ params.push(options.model);
373
+ }
374
+ if (options?.from) {
375
+ conditions.push("o.created_at >= ?");
376
+ params.push(options.from);
377
+ }
378
+ if (options?.to) {
379
+ conditions.push("o.created_at <= ?");
380
+ params.push(options.to);
381
+ }
382
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
383
+ const limit = options?.limit ?? 100;
384
+ const stmt = this.db.prepare(`
385
+ SELECT o.id, o.run_id as runId, o.success, o.quality, o.latency_satisfactory as latencySatisfactory, o.cost_satisfactory as costSatisfactory, o.feedback, o.created_at as createdAt, r.task_type as taskType, r.model
386
+ FROM outcomes o
387
+ JOIN runs r ON o.run_id = r.id
388
+ ${whereClause}
389
+ ORDER BY o.created_at DESC
390
+ LIMIT ?
391
+ `);
392
+ params.push(limit);
393
+ const rows = stmt.all(...params);
394
+ return rows.map((row) => ({
395
+ ...row,
396
+ success: Boolean(row.success),
397
+ latencySatisfactory: row.latencySatisfactory != null ? Boolean(row.latencySatisfactory) : null,
398
+ costSatisfactory: row.costSatisfactory != null ? Boolean(row.costSatisfactory) : null
399
+ }));
400
+ }
401
+ // ============================================================================
402
+ // Routing Rules
403
+ // ============================================================================
404
+ /**
405
+ * Gets a routing rule for a task type.
406
+ */
407
+ getRule(taskType) {
408
+ const stmt = this.db.prepare(`
409
+ SELECT id, task_type as taskType, preferred_model as preferredModel, source, confidence, sample_count as sampleCount, created_at as createdAt, updated_at as updatedAt
410
+ FROM routing_rules
411
+ WHERE task_type = ?
412
+ `);
413
+ return stmt.get(taskType) ?? null;
414
+ }
415
+ /**
416
+ * Sets a routing rule for a task type.
417
+ */
418
+ setRule(taskType, preferredModel, source, confidence, sampleCount) {
419
+ const existingRule = this.getRule(taskType);
420
+ const id = existingRule?.id ?? nanoid();
421
+ const stmt = this.db.prepare(`
422
+ INSERT INTO routing_rules (id, task_type, preferred_model, source, confidence, sample_count, created_at, updated_at)
423
+ VALUES (?, ?, ?, ?, ?, ?, datetime('now'), datetime('now'))
424
+ ON CONFLICT(task_type) DO UPDATE SET
425
+ preferred_model = excluded.preferred_model,
426
+ source = excluded.source,
427
+ confidence = excluded.confidence,
428
+ sample_count = excluded.sample_count,
429
+ updated_at = datetime('now')
430
+ `);
431
+ stmt.run(id, taskType, preferredModel, source, confidence ?? null, sampleCount ?? null);
432
+ return id;
433
+ }
434
+ /**
435
+ * Lists all routing rules.
436
+ */
437
+ listRules() {
438
+ const stmt = this.db.prepare(`
439
+ SELECT id, task_type as taskType, preferred_model as preferredModel, source, confidence, sample_count as sampleCount, created_at as createdAt, updated_at as updatedAt
440
+ FROM routing_rules
441
+ ORDER BY task_type
442
+ `);
443
+ return stmt.all();
444
+ }
445
+ /**
446
+ * Deletes a routing rule and resets to default.
447
+ */
448
+ deleteRule(taskType) {
449
+ const defaultRule = DEFAULT_ROUTING_RULES.find((r) => r.taskType === taskType);
450
+ if (!defaultRule) return false;
451
+ this.setRule(taskType, defaultRule.preferredModel, "default");
452
+ return true;
453
+ }
454
+ // ============================================================================
455
+ // Suggestions
456
+ // ============================================================================
457
+ /**
458
+ * Records a suggestion.
459
+ */
460
+ recordSuggestion(suggestion) {
461
+ const id = nanoid();
462
+ const stmt = this.db.prepare(`
463
+ INSERT INTO suggestions (id, task_type, current_model, suggested_model, reason, confidence, expected_improvement, sample_count, accepted, created_at)
464
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'))
465
+ `);
466
+ stmt.run(
467
+ id,
468
+ suggestion.taskType,
469
+ suggestion.currentModel,
470
+ suggestion.suggestedModel,
471
+ suggestion.reason,
472
+ suggestion.confidence,
473
+ suggestion.expectedImprovement,
474
+ suggestion.sampleCount,
475
+ suggestion.accepted ?? null
476
+ );
477
+ return id;
478
+ }
479
+ /**
480
+ * Gets a suggestion by ID.
481
+ */
482
+ getSuggestion(id) {
483
+ const stmt = this.db.prepare(`
484
+ SELECT id, task_type as taskType, current_model as currentModel, suggested_model as suggestedModel, reason, confidence, expected_improvement as expectedImprovement, sample_count as sampleCount, accepted, created_at as createdAt, accepted_at as acceptedAt
485
+ FROM suggestions
486
+ WHERE id = ?
487
+ `);
488
+ const row = stmt.get(id);
489
+ if (!row) return null;
490
+ return {
491
+ ...row,
492
+ accepted: row.accepted != null ? Boolean(row.accepted) : null
493
+ };
494
+ }
495
+ /**
496
+ * Gets pending (unaccepted) suggestions.
497
+ */
498
+ getPendingSuggestions() {
499
+ const stmt = this.db.prepare(`
500
+ SELECT id, task_type as taskType, current_model as currentModel, suggested_model as suggestedModel, reason, confidence, expected_improvement as expectedImprovement, sample_count as sampleCount, accepted, created_at as createdAt, accepted_at as acceptedAt
501
+ FROM suggestions
502
+ WHERE accepted IS NULL
503
+ ORDER BY confidence DESC
504
+ `);
505
+ const rows = stmt.all();
506
+ return rows.map((row) => ({
507
+ ...row,
508
+ accepted: row.accepted != null ? Boolean(row.accepted) : null
509
+ }));
510
+ }
511
+ /**
512
+ * Accepts a suggestion.
513
+ */
514
+ acceptSuggestion(id) {
515
+ const suggestion = this.getSuggestion(id);
516
+ if (!suggestion) return false;
517
+ const updateStmt = this.db.prepare(`
518
+ UPDATE suggestions
519
+ SET accepted = 1, accepted_at = datetime('now')
520
+ WHERE id = ?
521
+ `);
522
+ updateStmt.run(id);
523
+ this.setRule(
524
+ suggestion.taskType,
525
+ suggestion.suggestedModel,
526
+ "learned",
527
+ suggestion.confidence,
528
+ suggestion.sampleCount
529
+ );
530
+ return true;
531
+ }
532
+ /**
533
+ * Rejects a suggestion.
534
+ */
535
+ rejectSuggestion(id) {
536
+ const stmt = this.db.prepare(`
537
+ UPDATE suggestions
538
+ SET accepted = 0, accepted_at = datetime('now')
539
+ WHERE id = ?
540
+ `);
541
+ const result = stmt.run(id);
542
+ return result.changes > 0;
543
+ }
544
+ // ============================================================================
545
+ // Statistics
546
+ // ============================================================================
547
+ /**
548
+ * Gets aggregated statistics.
549
+ */
550
+ getStats(options) {
551
+ const conditions = [];
552
+ const params = [];
553
+ if (options?.from) {
554
+ conditions.push("created_at >= ?");
555
+ params.push(options.from);
556
+ }
557
+ if (options?.to) {
558
+ conditions.push("created_at <= ?");
559
+ params.push(options.to);
560
+ }
561
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
562
+ const overallStmt = this.db.prepare(`
563
+ SELECT
564
+ COUNT(*) as totalRuns,
565
+ SUM(success) as successfulRuns,
566
+ AVG(duration_ms) as avgDurationMs
567
+ FROM runs
568
+ ${whereClause}
569
+ `);
570
+ const overall = overallStmt.get(...params);
571
+ const byTaskTypeStmt = this.db.prepare(`
572
+ SELECT
573
+ task_type as taskType,
574
+ COUNT(*) as runs,
575
+ AVG(success) as successRate,
576
+ AVG(duration_ms) as avgDurationMs
577
+ FROM runs
578
+ ${whereClause}
579
+ GROUP BY task_type
580
+ `);
581
+ const byTaskTypeRows = byTaskTypeStmt.all(...params);
582
+ const byTaskType = {};
583
+ for (const row of byTaskTypeRows) {
584
+ byTaskType[row.taskType] = {
585
+ runs: row.runs,
586
+ successRate: row.successRate,
587
+ avgDurationMs: row.avgDurationMs
588
+ };
589
+ }
590
+ const byModelStmt = this.db.prepare(`
591
+ SELECT
592
+ model,
593
+ COUNT(*) as runs,
594
+ AVG(success) as successRate,
595
+ AVG(duration_ms) as avgDurationMs
596
+ FROM runs
597
+ ${whereClause}
598
+ GROUP BY model
599
+ `);
600
+ const byModelRows = byModelStmt.all(...params);
601
+ const byModel = {};
602
+ for (const row of byModelRows) {
603
+ byModel[row.model] = {
604
+ runs: row.runs,
605
+ successRate: row.successRate,
606
+ avgDurationMs: row.avgDurationMs
607
+ };
608
+ }
609
+ return {
610
+ totalRuns: overall.totalRuns,
611
+ successfulRuns: overall.successfulRuns ?? 0,
612
+ avgDurationMs: overall.avgDurationMs ?? 0,
613
+ byTaskType,
614
+ byModel
615
+ };
616
+ }
617
+ /**
618
+ * Gets statistics for learning (outcomes joined with runs).
619
+ */
620
+ getLearningStats(taskType) {
621
+ const stmt = this.db.prepare(`
622
+ SELECT
623
+ r.model,
624
+ COUNT(*) as runs,
625
+ AVG(r.success) as successRate,
626
+ AVG(r.duration_ms) as avgDurationMs,
627
+ AVG(CASE WHEN o.success IS NOT NULL THEN o.success ELSE r.success END) as outcomeSuccessRate
628
+ FROM runs r
629
+ LEFT JOIN outcomes o ON r.id = o.run_id
630
+ WHERE r.task_type = ?
631
+ GROUP BY r.model
632
+ HAVING runs >= 5
633
+ `);
634
+ return stmt.all(taskType);
635
+ }
636
+ };
637
+
638
+ // src/routing/inference.ts
639
+ var TASK_PATTERNS = {
640
+ code_generation: [
641
+ { pattern: /\b(write|create|generate|implement|build|code|develop|make)\b.{0,50}\b(function|class|code|script|program|method|module|api|endpoint|component)\b/i, weight: 10 },
642
+ { pattern: /\b(write|create|generate)\b.{0,30}\b(python|javascript|typescript|java|go|rust|c\+\+|ruby|php|swift)\b/i, weight: 10 },
643
+ { pattern: /\bcreate a.{0,30}(that|which|to)\b/i, weight: 5 },
644
+ { pattern: /\bimplement\b.{0,50}\b(algorithm|logic|feature)\b/i, weight: 8 },
645
+ { pattern: /\bcode\s+for\b/i, weight: 7 },
646
+ { pattern: /\bwrite me\b.{0,30}\b(code|script|function)\b/i, weight: 9 },
647
+ { pattern: /```[\w]*\n/i, weight: 3 }
648
+ // Code blocks suggest code context
649
+ ],
650
+ code_review: [
651
+ { pattern: /\b(review|analyze|check|audit|inspect|evaluate|assess|critique)\b.{0,30}\b(code|function|class|script|implementation|pull request|pr|diff)\b/i, weight: 10 },
652
+ { pattern: /\b(what'?s? wrong|find\s+(bugs?|issues?|problems?|errors?))\b.{0,30}\b(code|function|this)\b/i, weight: 9 },
653
+ { pattern: /\b(improve|optimize|refactor)\b.{0,30}\b(code|function|this)\b/i, weight: 7 },
654
+ { pattern: /\blook\s+(at|over)\s+(this|my)\s+code\b/i, weight: 8 },
655
+ { pattern: /\bcode\s+review\b/i, weight: 10 },
656
+ { pattern: /\bcan you (check|review)\b/i, weight: 5 }
657
+ ],
658
+ summarization: [
659
+ { pattern: /\b(summarize|summarise|summary|tldr|tl;dr|recap|condense|brief|overview)\b/i, weight: 10 },
660
+ { pattern: /\b(give|provide|write)\s+(me\s+)?(a\s+)?(brief|short|quick|concise)\s+(summary|overview)\b/i, weight: 9 },
661
+ { pattern: /\bshorten\s+(this|the)\b/i, weight: 6 },
662
+ { pattern: /\bin\s+(brief|short|a nutshell)\b/i, weight: 7 },
663
+ { pattern: /\bkey\s+(points?|takeaways?)\b/i, weight: 8 },
664
+ { pattern: /\bmain\s+(ideas?|points?)\b/i, weight: 7 }
665
+ ],
666
+ analysis: [
667
+ { pattern: /\b(analyze|analyse|analysis|examine|investigate|assess|evaluate|study)\b/i, weight: 8 },
668
+ { pattern: /\b(compare|contrast|differentiate|distinguish)\b.{0,30}\b(between|and)\b/i, weight: 9 },
669
+ { pattern: /\b(pros?\s+and\s+cons?|advantages?\s+and\s+disadvantages?|strengths?\s+and\s+weaknesses?)\b/i, weight: 9 },
670
+ { pattern: /\b(what\s+are|explain)\s+(the\s+)?(implications?|consequences?|effects?|impacts?)\b/i, weight: 8 },
671
+ { pattern: /\bbreak\s*down\b/i, weight: 6 },
672
+ { pattern: /\bdeep\s*dive\b/i, weight: 7 },
673
+ { pattern: /\bcritical(ly)?\s+(analysis|evaluation|assessment)\b/i, weight: 9 }
674
+ ],
675
+ creative_writing: [
676
+ { pattern: /\b(write|create|compose|craft|author)\b.{0,30}\b(story|poem|essay|article|blog|post|narrative|fiction|novel|song|lyrics)\b/i, weight: 10 },
677
+ { pattern: /\b(creative|imaginative|fictional)\s+(writing|story|piece)\b/i, weight: 10 },
678
+ { pattern: /\bonce upon a time\b/i, weight: 8 },
679
+ { pattern: /\b(write|tell)\s+(me\s+)?(a\s+)?(short\s+)?story\b/i, weight: 9 },
680
+ { pattern: /\b(brainstorm|ideate)\b.{0,30}\b(ideas?|concepts?|themes?)\b/i, weight: 7 },
681
+ { pattern: /\bwrite\s+(in|like)\s+(the\s+)?style\s+of\b/i, weight: 8 },
682
+ { pattern: /\b(catchy|creative|engaging)\s+(title|headline|tagline|slogan)\b/i, weight: 7 }
683
+ ],
684
+ data_extraction: [
685
+ { pattern: /\b(extract|parse|pull|get|retrieve|find|identify)\b.{0,30}\b(data|information|details?|values?|fields?|entities?|names?|numbers?|dates?|emails?|phones?|addresses?)\b/i, weight: 10 },
686
+ { pattern: /\b(convert|transform)\b.{0,30}\b(to|into)\s+(json|csv|xml|yaml|table|structured)\b/i, weight: 9 },
687
+ { pattern: /\bstructured\s+(data|output|format)\b/i, weight: 8 },
688
+ { pattern: /\bnamed\s+entity\s+(recognition|extraction)\b/i, weight: 10 },
689
+ { pattern: /\b(scrape|crawl)\b/i, weight: 6 },
690
+ { pattern: /\bjson\s+(output|format|schema)\b/i, weight: 7 }
691
+ ],
692
+ translation: [
693
+ { pattern: /\b(translate|translation|translator)\b/i, weight: 10 },
694
+ { pattern: /\b(convert|change)\b.{0,20}\b(to|into)\s+(english|spanish|french|german|chinese|japanese|korean|portuguese|italian|russian|arabic|hindi|dutch)\b/i, weight: 9 },
695
+ { pattern: /\b(in|to)\s+(english|spanish|french|german|chinese|japanese|korean|portuguese|italian|russian|arabic|hindi|dutch)\b/i, weight: 6 },
696
+ { pattern: /\bfrom\s+(english|spanish|french|german|chinese|japanese|korean|portuguese|italian|russian|arabic|hindi|dutch)\s+to\b/i, weight: 10 },
697
+ { pattern: /\blocalize|localization\b/i, weight: 7 }
698
+ ],
699
+ question_answering: [
700
+ { pattern: /^(what|who|where|when|why|how|which|is|are|does|do|can|could|would|should|will|did)\s/i, weight: 7 },
701
+ { pattern: /\?$/i, weight: 5 },
702
+ { pattern: /\b(explain|describe|define|what\s+is|what\s+are|tell\s+me\s+about)\b/i, weight: 8 },
703
+ { pattern: /\b(answer|respond|reply)\b.{0,20}\b(question|query)\b/i, weight: 9 },
704
+ { pattern: /\bfaq\b/i, weight: 8 },
705
+ { pattern: /\bi\s+(want|need)\s+to\s+know\b/i, weight: 6 },
706
+ { pattern: /\bcan\s+you\s+(tell|explain|help)\b/i, weight: 5 }
707
+ ],
708
+ general: [
709
+ // Catch-all patterns with low weights
710
+ { pattern: /./i, weight: 1 }
711
+ ]
712
+ };
713
+ function inferTaskType(prompt) {
714
+ const normalizedPrompt = prompt.trim().toLowerCase();
715
+ const scores = {
716
+ code_generation: 0,
717
+ code_review: 0,
718
+ summarization: 0,
719
+ analysis: 0,
720
+ creative_writing: 0,
721
+ data_extraction: 0,
722
+ translation: 0,
723
+ question_answering: 0,
724
+ general: 0
725
+ };
726
+ for (const [taskType, patterns] of Object.entries(TASK_PATTERNS)) {
727
+ for (const { pattern, weight } of patterns) {
728
+ if (pattern.test(prompt)) {
729
+ scores[taskType] += weight;
730
+ }
731
+ }
732
+ }
733
+ let maxScore = 0;
734
+ let inferredType = "general";
735
+ for (const [taskType, score] of Object.entries(scores)) {
736
+ if (score > maxScore) {
737
+ maxScore = score;
738
+ inferredType = taskType;
739
+ }
740
+ }
741
+ if (maxScore <= 1) {
742
+ return "general";
743
+ }
744
+ return inferredType;
745
+ }
746
+ function getInferenceConfidence(prompt, taskType) {
747
+ const patterns = TASK_PATTERNS[taskType];
748
+ if (!patterns) return 0;
749
+ let totalWeight = 0;
750
+ let maxPossibleWeight = 0;
751
+ for (const { pattern, weight } of patterns) {
752
+ maxPossibleWeight += weight;
753
+ if (pattern.test(prompt)) {
754
+ totalWeight += weight;
755
+ }
756
+ }
757
+ if (maxPossibleWeight === 0) return 0;
758
+ return Math.min(totalWeight / maxPossibleWeight, 0.95);
759
+ }
760
+
761
+ // src/routing/engine.ts
762
+ var RoutingEngine = class {
763
+ store;
764
+ /**
765
+ * Creates a new RoutingEngine.
766
+ *
767
+ * @param store - The storage instance to use
768
+ */
769
+ constructor(store) {
770
+ this.store = store;
771
+ }
772
+ /**
773
+ * Infers the task type from a prompt.
774
+ *
775
+ * @param prompt - The prompt to analyze
776
+ * @returns The inferred task type
777
+ */
778
+ inferTaskType(prompt) {
779
+ return inferTaskType(prompt);
780
+ }
781
+ /**
782
+ * Gets the inference confidence for a task type.
783
+ *
784
+ * @param prompt - The prompt to analyze
785
+ * @param taskType - The task type to check
786
+ * @returns Confidence score (0-1)
787
+ */
788
+ getInferenceConfidence(prompt, taskType) {
789
+ return getInferenceConfidence(prompt, taskType);
790
+ }
791
+ /**
792
+ * Gets the routing rule for a task type.
793
+ *
794
+ * @param taskType - The task type to get the rule for
795
+ * @returns The routing rule, or null if not found
796
+ */
797
+ get(taskType) {
798
+ const record = this.store.getRule(taskType);
799
+ if (!record) return null;
800
+ return {
801
+ id: record.id,
802
+ taskType: record.taskType,
803
+ preferredModel: record.preferredModel,
804
+ source: record.source,
805
+ confidence: record.confidence ?? void 0,
806
+ sampleCount: record.sampleCount ?? void 0,
807
+ createdAt: record.createdAt,
808
+ updatedAt: record.updatedAt
809
+ };
810
+ }
811
+ /**
812
+ * Sets a routing rule for a task type.
813
+ *
814
+ * @param taskType - The task type to set the rule for
815
+ * @param preferredModel - The preferred model (format: "provider:model")
816
+ * @param source - How the rule was created
817
+ * @param options - Optional confidence and sample count
818
+ * @returns The rule ID
819
+ */
820
+ set(taskType, preferredModel, source = "user", options) {
821
+ return this.store.setRule(
822
+ taskType,
823
+ preferredModel,
824
+ source,
825
+ options?.confidence,
826
+ options?.sampleCount
827
+ );
828
+ }
829
+ /**
830
+ * Lists all routing rules.
831
+ *
832
+ * @returns Array of all routing rules
833
+ */
834
+ list() {
835
+ const records = this.store.listRules();
836
+ return records.map((record) => ({
837
+ id: record.id,
838
+ taskType: record.taskType,
839
+ preferredModel: record.preferredModel,
840
+ source: record.source,
841
+ confidence: record.confidence ?? void 0,
842
+ sampleCount: record.sampleCount ?? void 0,
843
+ createdAt: record.createdAt,
844
+ updatedAt: record.updatedAt
845
+ }));
846
+ }
847
+ /**
848
+ * Deletes a routing rule and resets to default.
849
+ *
850
+ * @param taskType - The task type to reset
851
+ * @returns True if the rule was reset
852
+ */
853
+ delete(taskType) {
854
+ return this.store.deleteRule(taskType);
855
+ }
856
+ /**
857
+ * Gets the preferred model for a task type.
858
+ *
859
+ * @param taskType - The task type
860
+ * @returns The preferred model string, or a default
861
+ */
862
+ getPreferredModel(taskType) {
863
+ const rule = this.get(taskType);
864
+ return rule?.preferredModel ?? "local:llama3.2";
865
+ }
866
+ /**
867
+ * Parses a model string into provider and model name.
868
+ *
869
+ * @param modelString - The model string (format: "provider:model")
870
+ * @returns Object with provider and model
871
+ */
872
+ parseModel(modelString) {
873
+ const parts = modelString.split(":");
874
+ if (parts.length < 2) {
875
+ return { provider: "local", model: modelString };
876
+ }
877
+ return { provider: parts[0], model: parts.slice(1).join(":") };
878
+ }
879
+ /**
880
+ * Resolves the model to use for a prompt.
881
+ *
882
+ * @param prompt - The prompt to analyze
883
+ * @param overrideTaskType - Optional task type override
884
+ * @param overrideModel - Optional model override
885
+ * @returns Object with resolved taskType, model, provider, and confidence
886
+ */
887
+ resolve(prompt, overrideTaskType, overrideModel) {
888
+ const taskType = overrideTaskType ?? this.inferTaskType(prompt);
889
+ const confidence = this.getInferenceConfidence(prompt, taskType);
890
+ let model;
891
+ if (overrideModel) {
892
+ model = overrideModel;
893
+ } else {
894
+ model = this.getPreferredModel(taskType);
895
+ }
896
+ const { provider, model: modelName } = this.parseModel(model);
897
+ return {
898
+ taskType,
899
+ model,
900
+ provider,
901
+ modelName,
902
+ confidence
903
+ };
904
+ }
905
+ };
906
+
907
+ // src/learning/outcomes.ts
908
+ var OutcomeRecorder = class {
909
+ store;
910
+ /**
911
+ * Creates a new OutcomeRecorder.
912
+ *
913
+ * @param store - The storage instance to use
914
+ */
915
+ constructor(store) {
916
+ this.store = store;
917
+ }
918
+ /**
919
+ * Records an outcome for a run.
920
+ *
921
+ * @param input - The outcome input
922
+ * @returns The recorded outcome
923
+ * @throws If the run ID is not found
924
+ */
925
+ record(input) {
926
+ const run = this.store.getRun(input.runId);
927
+ if (!run) {
928
+ throw new Error(`Run not found: ${input.runId}`);
929
+ }
930
+ const id = this.store.recordOutcome({
931
+ runId: input.runId,
932
+ success: input.success,
933
+ quality: input.quality ?? null,
934
+ latencySatisfactory: input.latencySatisfactory ?? null,
935
+ costSatisfactory: input.costSatisfactory ?? null,
936
+ feedback: input.feedback ?? null
937
+ });
938
+ const outcome = this.store.getOutcome(input.runId);
939
+ if (!outcome) {
940
+ throw new Error("Failed to record outcome");
941
+ }
942
+ return {
943
+ id: outcome.id,
944
+ runId: outcome.runId,
945
+ success: outcome.success,
946
+ quality: outcome.quality ?? void 0,
947
+ latencySatisfactory: outcome.latencySatisfactory ?? void 0,
948
+ costSatisfactory: outcome.costSatisfactory ?? void 0,
949
+ feedback: outcome.feedback ?? void 0,
950
+ recordedAt: outcome.createdAt
951
+ };
952
+ }
953
+ /**
954
+ * Gets an outcome for a run.
955
+ *
956
+ * @param runId - The run ID
957
+ * @returns The outcome, or null if not found
958
+ */
959
+ get(runId) {
960
+ const outcome = this.store.getOutcome(runId);
961
+ if (!outcome) return null;
962
+ return {
963
+ id: outcome.id,
964
+ runId: outcome.runId,
965
+ success: outcome.success,
966
+ quality: outcome.quality ?? void 0,
967
+ latencySatisfactory: outcome.latencySatisfactory ?? void 0,
968
+ costSatisfactory: outcome.costSatisfactory ?? void 0,
969
+ feedback: outcome.feedback ?? void 0,
970
+ recordedAt: outcome.createdAt
971
+ };
972
+ }
973
+ /**
974
+ * Gets outcome statistics for a task type.
975
+ *
976
+ * @param taskType - The task type to get stats for
977
+ * @returns Outcome statistics
978
+ */
979
+ getTaskStats(taskType) {
980
+ const outcomes = this.store.getOutcomes({ taskType, limit: 1e3 });
981
+ if (outcomes.length === 0) {
982
+ return {
983
+ totalOutcomes: 0,
984
+ successRate: 0,
985
+ qualityDistribution: {},
986
+ latencySatisfactionRate: 0,
987
+ costSatisfactionRate: 0
988
+ };
989
+ }
990
+ let successCount = 0;
991
+ let latencySatisfiedCount = 0;
992
+ let latencyRatedCount = 0;
993
+ let costSatisfiedCount = 0;
994
+ let costRatedCount = 0;
995
+ const qualityDistribution = {};
996
+ for (const outcome of outcomes) {
997
+ if (outcome.success) successCount++;
998
+ if (outcome.quality) {
999
+ qualityDistribution[outcome.quality] = (qualityDistribution[outcome.quality] ?? 0) + 1;
1000
+ }
1001
+ if (outcome.latencySatisfactory != null) {
1002
+ latencyRatedCount++;
1003
+ if (outcome.latencySatisfactory) latencySatisfiedCount++;
1004
+ }
1005
+ if (outcome.costSatisfactory != null) {
1006
+ costRatedCount++;
1007
+ if (outcome.costSatisfactory) costSatisfiedCount++;
1008
+ }
1009
+ }
1010
+ return {
1011
+ totalOutcomes: outcomes.length,
1012
+ successRate: successCount / outcomes.length,
1013
+ qualityDistribution,
1014
+ latencySatisfactionRate: latencyRatedCount > 0 ? latencySatisfiedCount / latencyRatedCount : 0,
1015
+ costSatisfactionRate: costRatedCount > 0 ? costSatisfiedCount / costRatedCount : 0
1016
+ };
1017
+ }
1018
+ };
1019
+
1020
+ // src/learning/savings.ts
1021
+ var MODEL_PRICING = {
1022
+ // Anthropic models
1023
+ "claude-3-5-haiku-latest": { input: 0.25, output: 1.25 },
1024
+ "claude-3-5-haiku-20241022": { input: 0.25, output: 1.25 },
1025
+ "claude-3-5-sonnet-latest": { input: 3, output: 15 },
1026
+ "claude-3-5-sonnet-20241022": { input: 3, output: 15 },
1027
+ "claude-sonnet-4-20250514": { input: 3, output: 15 },
1028
+ "claude-3-opus-latest": { input: 15, output: 75 },
1029
+ "claude-3-opus-20240229": { input: 15, output: 75 },
1030
+ "claude-opus-4-5-20250514": { input: 15, output: 75 },
1031
+ // OpenAI models
1032
+ "gpt-4o": { input: 2.5, output: 10 },
1033
+ "gpt-4o-mini": { input: 0.15, output: 0.6 },
1034
+ "gpt-4.1": { input: 2, output: 8 },
1035
+ "gpt-4-turbo": { input: 10, output: 30 },
1036
+ // Google models
1037
+ "gemini-1.5-flash": { input: 0.075, output: 0.3 },
1038
+ "gemini-1.5-pro": { input: 1.25, output: 5 },
1039
+ "gemini-2.0-flash": { input: 0.1, output: 0.4 },
1040
+ // xAI models
1041
+ "grok-2": { input: 2, output: 10 },
1042
+ "grok-2-latest": { input: 2, output: 10 },
1043
+ // Moonshot models
1044
+ "moonshot-v1-8k": { input: 0.1, output: 0.1 },
1045
+ "moonshot-v1-32k": { input: 0.2, output: 0.2 }
1046
+ };
1047
+ var BASELINE_MODEL = "claude-3-opus-latest";
1048
+ function calculateCost(model, tokensIn, tokensOut) {
1049
+ const modelName = model.includes(":") ? model.split(":")[1] : model;
1050
+ const pricing = MODEL_PRICING[modelName] ?? MODEL_PRICING[model] ?? { input: 1, output: 3 };
1051
+ const inputCost = tokensIn / 1e6 * pricing.input;
1052
+ const outputCost = tokensOut / 1e6 * pricing.output;
1053
+ return inputCost + outputCost;
1054
+ }
1055
+ function getModelPricing(model) {
1056
+ const modelName = model.includes(":") ? model.split(":")[1] : model;
1057
+ return MODEL_PRICING[modelName] ?? MODEL_PRICING[model] ?? null;
1058
+ }
1059
+ function calculateSavings(store, days = 30) {
1060
+ const to = /* @__PURE__ */ new Date();
1061
+ const from = /* @__PURE__ */ new Date();
1062
+ from.setDate(from.getDate() - days);
1063
+ const fromStr = from.toISOString();
1064
+ const toStr = to.toISOString();
1065
+ const runs = store.getRuns({
1066
+ from: fromStr,
1067
+ to: toStr,
1068
+ limit: 1e5
1069
+ // Get all runs
1070
+ });
1071
+ const byModel = {};
1072
+ const byTaskType = {};
1073
+ let totalTokensIn = 0;
1074
+ let totalTokensOut = 0;
1075
+ let actualCost = 0;
1076
+ let baselineCost = 0;
1077
+ const baselinePricing = MODEL_PRICING[BASELINE_MODEL] ?? { input: 15, output: 75 };
1078
+ for (const run of runs) {
1079
+ const tokensIn = run.tokensIn ?? 0;
1080
+ const tokensOut = run.tokensOut ?? 0;
1081
+ const modelName = run.model.includes(":") ? run.model.split(":")[1] ?? run.model : run.model;
1082
+ const runCost = calculateCost(run.model, tokensIn, tokensOut);
1083
+ actualCost += runCost;
1084
+ const baselineRunCost = tokensIn / 1e6 * (baselinePricing?.input ?? 15) + tokensOut / 1e6 * (baselinePricing?.output ?? 75);
1085
+ baselineCost += baselineRunCost;
1086
+ totalTokensIn += tokensIn;
1087
+ totalTokensOut += tokensOut;
1088
+ if (!byModel[modelName]) {
1089
+ byModel[modelName] = {
1090
+ runs: 0,
1091
+ tokensIn: 0,
1092
+ tokensOut: 0,
1093
+ cost: 0,
1094
+ successRate: 0,
1095
+ avgLatencyMs: 0
1096
+ };
1097
+ }
1098
+ const modelStats = byModel[modelName];
1099
+ modelStats.runs++;
1100
+ modelStats.tokensIn += tokensIn;
1101
+ modelStats.tokensOut += tokensOut;
1102
+ modelStats.cost += runCost;
1103
+ modelStats.avgLatencyMs += run.durationMs;
1104
+ if (run.success) {
1105
+ modelStats.successRate++;
1106
+ }
1107
+ if (!byTaskType[run.taskType]) {
1108
+ byTaskType[run.taskType] = { runs: 0, cost: 0, totalCost: 0 };
1109
+ }
1110
+ const taskStats = byTaskType[run.taskType];
1111
+ taskStats.runs++;
1112
+ taskStats.totalCost += runCost;
1113
+ }
1114
+ for (const model of Object.keys(byModel)) {
1115
+ const stats = byModel[model];
1116
+ stats.successRate = stats.runs > 0 ? stats.successRate / stats.runs : 0;
1117
+ stats.avgLatencyMs = stats.runs > 0 ? stats.avgLatencyMs / stats.runs : 0;
1118
+ }
1119
+ const byTaskTypeFinal = {};
1120
+ for (const [taskType, stats] of Object.entries(byTaskType)) {
1121
+ byTaskTypeFinal[taskType] = {
1122
+ runs: stats.runs,
1123
+ cost: stats.totalCost,
1124
+ avgCostPerRun: stats.runs > 0 ? stats.totalCost / stats.runs : 0
1125
+ };
1126
+ }
1127
+ const savings = baselineCost - actualCost;
1128
+ const savingsPercent = baselineCost > 0 ? savings / baselineCost * 100 : 0;
1129
+ return {
1130
+ periodDays: days,
1131
+ period: {
1132
+ from: fromStr,
1133
+ to: toStr
1134
+ },
1135
+ totalRuns: runs.length,
1136
+ totalTokensIn,
1137
+ totalTokensOut,
1138
+ actualCost,
1139
+ baselineCost,
1140
+ savings: Math.max(0, savings),
1141
+ // Don't report negative savings
1142
+ savingsPercent: Math.max(0, savingsPercent),
1143
+ byModel,
1144
+ byTaskType: byTaskTypeFinal
1145
+ };
1146
+ }
1147
+
1148
+ // src/learning/patterns.ts
1149
+ var MIN_RUNS_FOR_SUGGESTION = 10;
1150
+ var MIN_CONFIDENCE_THRESHOLD = 0.6;
1151
+ var MIN_IMPROVEMENT_THRESHOLD = 0.1;
1152
+ var MIN_COST_IMPROVEMENT_THRESHOLD = 0.2;
1153
+ var PatternDetector = class {
1154
+ store;
1155
+ /**
1156
+ * Creates a new PatternDetector.
1157
+ *
1158
+ * @param store - The storage instance to use
1159
+ */
1160
+ constructor(store) {
1161
+ this.store = store;
1162
+ }
1163
+ /**
1164
+ * Analyzes a task type and generates suggestions if appropriate.
1165
+ *
1166
+ * @param taskType - The task type to analyze
1167
+ * @returns Array of suggestions
1168
+ */
1169
+ analyzeTaskType(taskType) {
1170
+ const stats = this.store.getLearningStats(taskType);
1171
+ if (stats.length < 2) {
1172
+ return [];
1173
+ }
1174
+ const currentRule = this.store.getRule(taskType);
1175
+ if (!currentRule) return [];
1176
+ const currentModel = currentRule.preferredModel;
1177
+ const currentStats = stats.find((s) => s.model === currentModel);
1178
+ if (!currentStats) return [];
1179
+ const currentModelName = currentModel.includes(":") ? currentModel.split(":")[1] : currentModel;
1180
+ const currentPricing = MODEL_PRICING[currentModelName];
1181
+ const suggestions = [];
1182
+ for (const modelStats of stats) {
1183
+ if (modelStats.model === currentModel) continue;
1184
+ if (modelStats.runs < MIN_RUNS_FOR_SUGGESTION) continue;
1185
+ const successImprovement = modelStats.outcomeSuccessRate - currentStats.outcomeSuccessRate;
1186
+ const latencyImprovement = (currentStats.avgDurationMs - modelStats.avgDurationMs) / currentStats.avgDurationMs;
1187
+ const suggestedModelName = modelStats.model.includes(":") ? modelStats.model.split(":")[1] : modelStats.model;
1188
+ const suggestedPricing = MODEL_PRICING[suggestedModelName];
1189
+ let costImprovement = 0;
1190
+ if (currentPricing && suggestedPricing) {
1191
+ const currentAvgCost = (currentPricing.input + currentPricing.output) / 2;
1192
+ const suggestedAvgCost = (suggestedPricing.input + suggestedPricing.output) / 2;
1193
+ costImprovement = (currentAvgCost - suggestedAvgCost) / currentAvgCost;
1194
+ }
1195
+ const isSignificantlyBetter = successImprovement > MIN_IMPROVEMENT_THRESHOLD || successImprovement >= 0 && latencyImprovement > MIN_IMPROVEMENT_THRESHOLD || successImprovement >= -0.05 && costImprovement > MIN_COST_IMPROVEMENT_THRESHOLD;
1196
+ if (!isSignificantlyBetter) continue;
1197
+ const sampleConfidence = Math.min(modelStats.runs / 50, 1);
1198
+ const improvementConfidence = Math.min(
1199
+ Math.abs(successImprovement) / 0.3 + Math.abs(latencyImprovement) / 0.5 + Math.abs(costImprovement) / 0.5,
1200
+ 1
1201
+ );
1202
+ const confidence = (sampleConfidence + improvementConfidence) / 2;
1203
+ if (confidence < MIN_CONFIDENCE_THRESHOLD) continue;
1204
+ const reasons = [];
1205
+ if (successImprovement > 0) {
1206
+ reasons.push(`${(successImprovement * 100).toFixed(0)}% higher success rate`);
1207
+ }
1208
+ if (latencyImprovement > 0) {
1209
+ reasons.push(`${(latencyImprovement * 100).toFixed(0)}% faster`);
1210
+ }
1211
+ if (costImprovement > 0) {
1212
+ reasons.push(`${(costImprovement * 100).toFixed(0)}% cheaper`);
1213
+ }
1214
+ const suggestion = {
1215
+ id: nanoid(),
1216
+ taskType,
1217
+ currentModel,
1218
+ suggestedModel: modelStats.model,
1219
+ reason: reasons.join(", "),
1220
+ confidence,
1221
+ expectedImprovement: {
1222
+ successRate: successImprovement > 0 ? successImprovement : void 0,
1223
+ latency: latencyImprovement > 0 ? latencyImprovement : void 0,
1224
+ cost: costImprovement > 0 ? costImprovement : void 0
1225
+ },
1226
+ sampleCount: modelStats.runs,
1227
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1228
+ };
1229
+ suggestions.push(suggestion);
1230
+ }
1231
+ suggestions.sort((a, b) => b.confidence - a.confidence);
1232
+ return suggestions;
1233
+ }
1234
+ /**
1235
+ * Analyzes all task types and generates suggestions.
1236
+ *
1237
+ * @returns Array of all suggestions across task types
1238
+ */
1239
+ analyzeAll() {
1240
+ const taskTypes = [
1241
+ "code_generation",
1242
+ "code_review",
1243
+ "summarization",
1244
+ "analysis",
1245
+ "creative_writing",
1246
+ "data_extraction",
1247
+ "translation",
1248
+ "question_answering",
1249
+ "general"
1250
+ ];
1251
+ const allSuggestions = [];
1252
+ for (const taskType of taskTypes) {
1253
+ const suggestions = this.analyzeTaskType(taskType);
1254
+ allSuggestions.push(...suggestions);
1255
+ }
1256
+ allSuggestions.sort((a, b) => b.confidence - a.confidence);
1257
+ return allSuggestions;
1258
+ }
1259
+ /**
1260
+ * Stores suggestions in the database.
1261
+ *
1262
+ * @param suggestions - The suggestions to store
1263
+ * @returns Array of suggestion IDs
1264
+ */
1265
+ storeSuggestions(suggestions) {
1266
+ const ids = [];
1267
+ for (const suggestion of suggestions) {
1268
+ const id = this.store.recordSuggestion({
1269
+ taskType: suggestion.taskType,
1270
+ currentModel: suggestion.currentModel,
1271
+ suggestedModel: suggestion.suggestedModel,
1272
+ reason: suggestion.reason,
1273
+ confidence: suggestion.confidence,
1274
+ expectedImprovement: JSON.stringify(suggestion.expectedImprovement),
1275
+ sampleCount: suggestion.sampleCount,
1276
+ accepted: null
1277
+ });
1278
+ ids.push(id);
1279
+ }
1280
+ return ids;
1281
+ }
1282
+ /**
1283
+ * Generates and stores new suggestions, returning only new ones.
1284
+ *
1285
+ * @returns Array of new suggestions
1286
+ */
1287
+ generateSuggestions() {
1288
+ const suggestions = this.analyzeAll();
1289
+ const pending = this.store.getPendingSuggestions();
1290
+ const existingKeys = new Set(
1291
+ pending.map((s) => `${s.taskType}:${s.suggestedModel}`)
1292
+ );
1293
+ const newSuggestions = suggestions.filter(
1294
+ (s) => !existingKeys.has(`${s.taskType}:${s.suggestedModel}`)
1295
+ );
1296
+ this.storeSuggestions(newSuggestions);
1297
+ return newSuggestions;
1298
+ }
1299
+ };
1300
+
1301
+ // src/relay.ts
1302
+ var RelayPlane = class {
1303
+ store;
1304
+ _routing;
1305
+ outcomeRecorder;
1306
+ patternDetector;
1307
+ config;
1308
+ adapterRegistry = null;
1309
+ /**
1310
+ * Creates a new RelayPlane instance.
1311
+ *
1312
+ * @param config - Configuration options
1313
+ */
1314
+ constructor(config = {}) {
1315
+ this.config = {
1316
+ dbPath: config.dbPath ?? getDefaultDbPath(),
1317
+ defaultProvider: config.defaultProvider ?? "local",
1318
+ defaultModel: config.defaultModel ?? "llama3.2",
1319
+ providers: config.providers ?? {}
1320
+ };
1321
+ this.store = new Store(this.config.dbPath);
1322
+ this._routing = new RoutingEngine(this.store);
1323
+ this.outcomeRecorder = new OutcomeRecorder(this.store);
1324
+ this.patternDetector = new PatternDetector(this.store);
1325
+ }
1326
+ /**
1327
+ * Gets the routing engine for direct access.
1328
+ */
1329
+ get routing() {
1330
+ return this._routing;
1331
+ }
1332
+ /**
1333
+ * Runs a prompt through the appropriate model.
1334
+ *
1335
+ * @param input - The run input
1336
+ * @returns The run result
1337
+ */
1338
+ async run(input) {
1339
+ const startTime = Date.now();
1340
+ const resolved = this._routing.resolve(input.prompt, input.taskType, input.model);
1341
+ const adapter = await this.getAdapter(resolved.provider);
1342
+ if (!adapter) {
1343
+ const runId2 = this.store.recordRun({
1344
+ prompt: input.prompt,
1345
+ systemPrompt: input.systemPrompt ?? null,
1346
+ taskType: resolved.taskType,
1347
+ model: resolved.model,
1348
+ success: false,
1349
+ output: null,
1350
+ error: `No adapter configured for provider: ${resolved.provider}`,
1351
+ durationMs: Date.now() - startTime,
1352
+ tokensIn: null,
1353
+ tokensOut: null,
1354
+ costUsd: null,
1355
+ metadata: input.metadata ? JSON.stringify(input.metadata) : null
1356
+ });
1357
+ return {
1358
+ runId: runId2,
1359
+ success: false,
1360
+ error: `No adapter configured for provider: ${resolved.provider}`,
1361
+ taskType: resolved.taskType,
1362
+ model: resolved.model,
1363
+ durationMs: Date.now() - startTime,
1364
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1365
+ };
1366
+ }
1367
+ const providerConfig = this.config.providers?.[resolved.provider];
1368
+ const apiKey = providerConfig?.apiKey ?? this.getEnvApiKey(resolved.provider);
1369
+ const fullInput = input.systemPrompt ? `${input.systemPrompt}
1370
+
1371
+ ${input.prompt}` : input.prompt;
1372
+ const result = await adapter.execute({
1373
+ model: resolved.modelName,
1374
+ input: fullInput,
1375
+ apiKey: apiKey ?? "",
1376
+ baseUrl: providerConfig?.baseUrl
1377
+ });
1378
+ const durationMs = Date.now() - startTime;
1379
+ const tokensIn = result.tokensIn ?? 0;
1380
+ const tokensOut = result.tokensOut ?? 0;
1381
+ const costUsd = calculateCost(resolved.model, tokensIn, tokensOut);
1382
+ const runId = this.store.recordRun({
1383
+ prompt: input.prompt,
1384
+ systemPrompt: input.systemPrompt ?? null,
1385
+ taskType: resolved.taskType,
1386
+ model: resolved.model,
1387
+ success: result.success,
1388
+ output: result.output ?? null,
1389
+ error: result.error?.message ?? null,
1390
+ durationMs,
1391
+ tokensIn: result.tokensIn ?? null,
1392
+ tokensOut: result.tokensOut ?? null,
1393
+ costUsd: costUsd > 0 ? costUsd : null,
1394
+ metadata: input.metadata ? JSON.stringify(input.metadata) : null
1395
+ });
1396
+ return {
1397
+ runId,
1398
+ success: result.success,
1399
+ output: result.output,
1400
+ error: result.error?.message,
1401
+ taskType: resolved.taskType,
1402
+ model: resolved.model,
1403
+ durationMs,
1404
+ tokensIn: result.tokensIn,
1405
+ tokensOut: result.tokensOut,
1406
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1407
+ };
1408
+ }
1409
+ /**
1410
+ * Gets an adapter for a provider.
1411
+ * Note: In the standalone proxy package, adapters are not used.
1412
+ * The proxy handles provider calls directly via HTTP.
1413
+ */
1414
+ async getAdapter(_provider) {
1415
+ return null;
1416
+ }
1417
+ /**
1418
+ * Gets an API key from environment variables.
1419
+ */
1420
+ getEnvApiKey(provider) {
1421
+ const envVars = {
1422
+ openai: "OPENAI_API_KEY",
1423
+ anthropic: "ANTHROPIC_API_KEY",
1424
+ google: "GOOGLE_API_KEY",
1425
+ xai: "XAI_API_KEY",
1426
+ moonshot: "MOONSHOT_API_KEY",
1427
+ local: ""
1428
+ };
1429
+ const envVar = envVars[provider];
1430
+ return envVar ? process.env[envVar] : void 0;
1431
+ }
1432
+ /**
1433
+ * Records an outcome for a run.
1434
+ *
1435
+ * @param runId - The run ID
1436
+ * @param outcome - The outcome details
1437
+ * @returns The recorded outcome
1438
+ */
1439
+ recordOutcome(runId, outcome) {
1440
+ return this.outcomeRecorder.record({
1441
+ runId,
1442
+ ...outcome
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Gets an outcome for a run.
1447
+ *
1448
+ * @param runId - The run ID
1449
+ * @returns The outcome, or null if not found
1450
+ */
1451
+ getOutcome(runId) {
1452
+ return this.outcomeRecorder.get(runId);
1453
+ }
1454
+ /**
1455
+ * Gets statistics for runs.
1456
+ *
1457
+ * @param options - Optional filters
1458
+ * @returns Statistics object
1459
+ */
1460
+ stats(options) {
1461
+ const raw = this.store.getStats(options);
1462
+ const byTaskType = {};
1463
+ const taskTypes = [
1464
+ "code_generation",
1465
+ "code_review",
1466
+ "summarization",
1467
+ "analysis",
1468
+ "creative_writing",
1469
+ "data_extraction",
1470
+ "translation",
1471
+ "question_answering",
1472
+ "general"
1473
+ ];
1474
+ for (const taskType of taskTypes) {
1475
+ const taskStats = raw.byTaskType[taskType];
1476
+ byTaskType[taskType] = {
1477
+ taskType,
1478
+ totalRuns: taskStats?.runs ?? 0,
1479
+ successfulRuns: Math.round((taskStats?.runs ?? 0) * (taskStats?.successRate ?? 0)),
1480
+ successRate: taskStats?.successRate ?? 0,
1481
+ avgDurationMs: taskStats?.avgDurationMs ?? 0,
1482
+ byModel: {}
1483
+ };
1484
+ }
1485
+ for (const [model, modelStats] of Object.entries(raw.byModel)) {
1486
+ for (const taskType of taskTypes) {
1487
+ if (!byTaskType[taskType].byModel[model]) {
1488
+ byTaskType[taskType].byModel[model] = {
1489
+ runs: 0,
1490
+ successRate: 0,
1491
+ avgDurationMs: 0
1492
+ };
1493
+ }
1494
+ }
1495
+ }
1496
+ return {
1497
+ totalRuns: raw.totalRuns,
1498
+ overallSuccessRate: raw.totalRuns > 0 ? raw.successfulRuns / raw.totalRuns : 0,
1499
+ byTaskType,
1500
+ period: {
1501
+ from: options?.from ?? "",
1502
+ to: options?.to ?? (/* @__PURE__ */ new Date()).toISOString()
1503
+ }
1504
+ };
1505
+ }
1506
+ /**
1507
+ * Gets a savings report.
1508
+ *
1509
+ * @param days - Number of days to include (default: 30)
1510
+ * @returns Savings report
1511
+ */
1512
+ savingsReport(days = 30) {
1513
+ return calculateSavings(this.store, days);
1514
+ }
1515
+ /**
1516
+ * Gets routing improvement suggestions.
1517
+ *
1518
+ * @returns Array of suggestions
1519
+ */
1520
+ getSuggestions() {
1521
+ const pending = this.store.getPendingSuggestions();
1522
+ return pending.map((record) => ({
1523
+ id: record.id,
1524
+ taskType: record.taskType,
1525
+ currentModel: record.currentModel,
1526
+ suggestedModel: record.suggestedModel,
1527
+ reason: record.reason,
1528
+ confidence: record.confidence,
1529
+ expectedImprovement: JSON.parse(record.expectedImprovement),
1530
+ sampleCount: record.sampleCount,
1531
+ createdAt: record.createdAt,
1532
+ accepted: record.accepted ?? void 0,
1533
+ acceptedAt: record.acceptedAt ?? void 0
1534
+ }));
1535
+ }
1536
+ /**
1537
+ * Generates new suggestions based on current data.
1538
+ *
1539
+ * @returns Array of newly generated suggestions
1540
+ */
1541
+ generateSuggestions() {
1542
+ return this.patternDetector.generateSuggestions();
1543
+ }
1544
+ /**
1545
+ * Accepts a suggestion and updates routing.
1546
+ *
1547
+ * @param suggestionId - The suggestion ID to accept
1548
+ * @returns True if successful
1549
+ */
1550
+ acceptSuggestion(suggestionId) {
1551
+ return this.store.acceptSuggestion(suggestionId);
1552
+ }
1553
+ /**
1554
+ * Rejects a suggestion.
1555
+ *
1556
+ * @param suggestionId - The suggestion ID to reject
1557
+ * @returns True if successful
1558
+ */
1559
+ rejectSuggestion(suggestionId) {
1560
+ return this.store.rejectSuggestion(suggestionId);
1561
+ }
1562
+ /**
1563
+ * Closes the RelayPlane instance and releases resources.
1564
+ */
1565
+ close() {
1566
+ this.store.close();
1567
+ }
1568
+ };
1569
+
1570
+ // src/proxy.ts
1571
+ var DEFAULT_ENDPOINTS = {
1572
+ anthropic: {
1573
+ baseUrl: "https://api.anthropic.com/v1",
1574
+ apiKeyEnv: "ANTHROPIC_API_KEY"
1575
+ },
1576
+ openai: {
1577
+ baseUrl: "https://api.openai.com/v1",
1578
+ apiKeyEnv: "OPENAI_API_KEY"
1579
+ },
1580
+ google: {
1581
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta",
1582
+ apiKeyEnv: "GEMINI_API_KEY"
1583
+ },
1584
+ xai: {
1585
+ baseUrl: "https://api.x.ai/v1",
1586
+ apiKeyEnv: "XAI_API_KEY"
1587
+ },
1588
+ moonshot: {
1589
+ baseUrl: "https://api.moonshot.cn/v1",
1590
+ apiKeyEnv: "MOONSHOT_API_KEY"
1591
+ }
1592
+ };
1593
+ var MODEL_MAPPING = {
1594
+ // Anthropic models (using correct API model IDs)
1595
+ "claude-opus-4-5": { provider: "anthropic", model: "claude-opus-4-5-20250514" },
1596
+ "claude-sonnet-4": { provider: "anthropic", model: "claude-sonnet-4-20250514" },
1597
+ "claude-3-5-sonnet": { provider: "anthropic", model: "claude-3-5-sonnet-20241022" },
1598
+ "claude-3-5-haiku": { provider: "anthropic", model: "claude-3-5-haiku-20241022" },
1599
+ haiku: { provider: "anthropic", model: "claude-3-5-haiku-20241022" },
1600
+ sonnet: { provider: "anthropic", model: "claude-3-5-sonnet-20241022" },
1601
+ opus: { provider: "anthropic", model: "claude-3-opus-20240229" },
1602
+ // OpenAI models
1603
+ "gpt-4o": { provider: "openai", model: "gpt-4o" },
1604
+ "gpt-4o-mini": { provider: "openai", model: "gpt-4o-mini" },
1605
+ "gpt-4.1": { provider: "openai", model: "gpt-4.1" }
1606
+ };
1607
+ var DEFAULT_ROUTING = {
1608
+ code_generation: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1609
+ code_review: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1610
+ summarization: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1611
+ analysis: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1612
+ creative_writing: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1613
+ data_extraction: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1614
+ translation: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1615
+ question_answering: { provider: "anthropic", model: "claude-3-5-haiku-latest" },
1616
+ general: { provider: "anthropic", model: "claude-3-5-haiku-latest" }
1617
+ };
1618
+ function extractPromptText(messages) {
1619
+ return messages.map((msg) => {
1620
+ if (typeof msg.content === "string") return msg.content;
1621
+ if (Array.isArray(msg.content)) {
1622
+ return msg.content.map((c) => {
1623
+ const part = c;
1624
+ return part.type === "text" ? part.text ?? "" : "";
1625
+ }).join(" ");
1626
+ }
1627
+ return "";
1628
+ }).join("\n");
1629
+ }
1630
+ async function forwardToAnthropic(request, targetModel, apiKey, betaHeaders) {
1631
+ const anthropicBody = buildAnthropicBody(request, targetModel, false);
1632
+ const headers = {
1633
+ "Content-Type": "application/json",
1634
+ "x-api-key": apiKey,
1635
+ "anthropic-version": "2023-06-01"
1636
+ };
1637
+ if (betaHeaders) {
1638
+ headers["anthropic-beta"] = betaHeaders;
1639
+ }
1640
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
1641
+ method: "POST",
1642
+ headers,
1643
+ body: JSON.stringify(anthropicBody)
1644
+ });
1645
+ return response;
1646
+ }
1647
+ async function forwardToAnthropicStream(request, targetModel, apiKey, betaHeaders) {
1648
+ const anthropicBody = buildAnthropicBody(request, targetModel, true);
1649
+ const headers = {
1650
+ "Content-Type": "application/json",
1651
+ "x-api-key": apiKey,
1652
+ "anthropic-version": "2023-06-01"
1653
+ };
1654
+ if (betaHeaders) {
1655
+ headers["anthropic-beta"] = betaHeaders;
1656
+ }
1657
+ const response = await fetch("https://api.anthropic.com/v1/messages", {
1658
+ method: "POST",
1659
+ headers,
1660
+ body: JSON.stringify(anthropicBody)
1661
+ });
1662
+ return response;
1663
+ }
1664
+ function convertMessagesToAnthropic(messages) {
1665
+ const result = [];
1666
+ for (const msg of messages) {
1667
+ const m = msg;
1668
+ if (m.role === "system") continue;
1669
+ if (m.role === "tool") {
1670
+ result.push({
1671
+ role: "user",
1672
+ content: [
1673
+ {
1674
+ type: "tool_result",
1675
+ tool_use_id: m.tool_call_id,
1676
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
1677
+ }
1678
+ ]
1679
+ });
1680
+ continue;
1681
+ }
1682
+ if (m.role === "assistant" && m.tool_calls && m.tool_calls.length > 0) {
1683
+ const content = [];
1684
+ if (m.content && typeof m.content === "string") {
1685
+ content.push({ type: "text", text: m.content });
1686
+ }
1687
+ for (const tc of m.tool_calls) {
1688
+ content.push({
1689
+ type: "tool_use",
1690
+ id: tc.id,
1691
+ name: tc.function.name,
1692
+ input: JSON.parse(tc.function.arguments || "{}")
1693
+ });
1694
+ }
1695
+ result.push({ role: "assistant", content });
1696
+ continue;
1697
+ }
1698
+ result.push({
1699
+ role: m.role === "assistant" ? "assistant" : "user",
1700
+ content: m.content
1701
+ });
1702
+ }
1703
+ return result;
1704
+ }
1705
+ function buildAnthropicBody(request, targetModel, stream) {
1706
+ const anthropicMessages = convertMessagesToAnthropic(request.messages);
1707
+ const systemMessage = request.messages.find((m) => m.role === "system");
1708
+ const anthropicBody = {
1709
+ model: targetModel,
1710
+ messages: anthropicMessages,
1711
+ max_tokens: request.max_tokens ?? 4096,
1712
+ stream
1713
+ };
1714
+ if (systemMessage) {
1715
+ anthropicBody["system"] = systemMessage.content;
1716
+ }
1717
+ if (request.temperature !== void 0) {
1718
+ anthropicBody["temperature"] = request.temperature;
1719
+ }
1720
+ if (request.tools && Array.isArray(request.tools)) {
1721
+ anthropicBody["tools"] = convertToolsToAnthropic(request.tools);
1722
+ }
1723
+ if (request.tool_choice) {
1724
+ anthropicBody["tool_choice"] = convertToolChoiceToAnthropic(request.tool_choice);
1725
+ }
1726
+ return anthropicBody;
1727
+ }
1728
+ function convertToolsToAnthropic(tools) {
1729
+ return tools.map((tool) => {
1730
+ const t = tool;
1731
+ if (t.type === "function" && t.function) {
1732
+ return {
1733
+ name: t.function.name,
1734
+ description: t.function.description,
1735
+ input_schema: t.function.parameters || { type: "object", properties: {} }
1736
+ };
1737
+ }
1738
+ return tool;
1739
+ });
1740
+ }
1741
+ function convertToolChoiceToAnthropic(toolChoice) {
1742
+ if (toolChoice === "auto") return { type: "auto" };
1743
+ if (toolChoice === "none") return { type: "none" };
1744
+ if (toolChoice === "required") return { type: "any" };
1745
+ const tc = toolChoice;
1746
+ if (tc.type === "function" && tc.function?.name) {
1747
+ return { type: "tool", name: tc.function.name };
1748
+ }
1749
+ return toolChoice;
1750
+ }
1751
+ async function forwardToOpenAI(request, targetModel, apiKey) {
1752
+ const openaiBody = {
1753
+ ...request,
1754
+ model: targetModel,
1755
+ stream: false
1756
+ };
1757
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
1758
+ method: "POST",
1759
+ headers: {
1760
+ "Content-Type": "application/json",
1761
+ Authorization: `Bearer ${apiKey}`
1762
+ },
1763
+ body: JSON.stringify(openaiBody)
1764
+ });
1765
+ return response;
1766
+ }
1767
+ async function forwardToOpenAIStream(request, targetModel, apiKey) {
1768
+ const openaiBody = {
1769
+ ...request,
1770
+ model: targetModel,
1771
+ stream: true
1772
+ };
1773
+ const response = await fetch("https://api.openai.com/v1/chat/completions", {
1774
+ method: "POST",
1775
+ headers: {
1776
+ "Content-Type": "application/json",
1777
+ Authorization: `Bearer ${apiKey}`
1778
+ },
1779
+ body: JSON.stringify(openaiBody)
1780
+ });
1781
+ return response;
1782
+ }
1783
+ async function forwardToXAI(request, targetModel, apiKey) {
1784
+ const xaiBody = {
1785
+ ...request,
1786
+ model: targetModel,
1787
+ stream: false
1788
+ };
1789
+ const response = await fetch("https://api.x.ai/v1/chat/completions", {
1790
+ method: "POST",
1791
+ headers: {
1792
+ "Content-Type": "application/json",
1793
+ Authorization: `Bearer ${apiKey}`
1794
+ },
1795
+ body: JSON.stringify(xaiBody)
1796
+ });
1797
+ return response;
1798
+ }
1799
+ async function forwardToXAIStream(request, targetModel, apiKey) {
1800
+ const xaiBody = {
1801
+ ...request,
1802
+ model: targetModel,
1803
+ stream: true
1804
+ };
1805
+ const response = await fetch("https://api.x.ai/v1/chat/completions", {
1806
+ method: "POST",
1807
+ headers: {
1808
+ "Content-Type": "application/json",
1809
+ Authorization: `Bearer ${apiKey}`
1810
+ },
1811
+ body: JSON.stringify(xaiBody)
1812
+ });
1813
+ return response;
1814
+ }
1815
+ async function forwardToMoonshot(request, targetModel, apiKey) {
1816
+ const moonshotBody = {
1817
+ ...request,
1818
+ model: targetModel,
1819
+ stream: false
1820
+ };
1821
+ const response = await fetch("https://api.moonshot.cn/v1/chat/completions", {
1822
+ method: "POST",
1823
+ headers: {
1824
+ "Content-Type": "application/json",
1825
+ Authorization: `Bearer ${apiKey}`
1826
+ },
1827
+ body: JSON.stringify(moonshotBody)
1828
+ });
1829
+ return response;
1830
+ }
1831
+ async function forwardToMoonshotStream(request, targetModel, apiKey) {
1832
+ const moonshotBody = {
1833
+ ...request,
1834
+ model: targetModel,
1835
+ stream: true
1836
+ };
1837
+ const response = await fetch("https://api.moonshot.cn/v1/chat/completions", {
1838
+ method: "POST",
1839
+ headers: {
1840
+ "Content-Type": "application/json",
1841
+ Authorization: `Bearer ${apiKey}`
1842
+ },
1843
+ body: JSON.stringify(moonshotBody)
1844
+ });
1845
+ return response;
1846
+ }
1847
+ function convertMessagesToGemini(messages) {
1848
+ const geminiContents = [];
1849
+ for (const msg of messages) {
1850
+ if (msg.role === "system") continue;
1851
+ const role = msg.role === "assistant" ? "model" : "user";
1852
+ if (typeof msg.content === "string") {
1853
+ geminiContents.push({
1854
+ role,
1855
+ parts: [{ text: msg.content }]
1856
+ });
1857
+ } else if (Array.isArray(msg.content)) {
1858
+ const parts = msg.content.map((part) => {
1859
+ const p = part;
1860
+ if (p.type === "text") {
1861
+ return { text: p.text };
1862
+ }
1863
+ if (p.type === "image_url" && p.image_url?.url) {
1864
+ const url = p.image_url.url;
1865
+ if (url.startsWith("data:")) {
1866
+ const match = url.match(/^data:([^;]+);base64,(.+)$/);
1867
+ if (match) {
1868
+ return {
1869
+ inline_data: {
1870
+ mime_type: match[1],
1871
+ data: match[2]
1872
+ }
1873
+ };
1874
+ }
1875
+ }
1876
+ return { text: `[Image: ${url}]` };
1877
+ }
1878
+ return { text: "" };
1879
+ });
1880
+ geminiContents.push({ role, parts });
1881
+ }
1882
+ }
1883
+ return geminiContents;
1884
+ }
1885
+ async function forwardToGemini(request, targetModel, apiKey) {
1886
+ const systemMessage = request.messages.find((m) => m.role === "system");
1887
+ const geminiContents = convertMessagesToGemini(request.messages);
1888
+ const geminiBody = {
1889
+ contents: geminiContents,
1890
+ generationConfig: {
1891
+ maxOutputTokens: request.max_tokens ?? 4096
1892
+ }
1893
+ };
1894
+ if (request.temperature !== void 0) {
1895
+ geminiBody["generationConfig"]["temperature"] = request.temperature;
1896
+ }
1897
+ if (systemMessage && typeof systemMessage.content === "string") {
1898
+ geminiBody["systemInstruction"] = {
1899
+ parts: [{ text: systemMessage.content }]
1900
+ };
1901
+ }
1902
+ const response = await fetch(
1903
+ `https://generativelanguage.googleapis.com/v1beta/models/${targetModel}:generateContent?key=${apiKey}`,
1904
+ {
1905
+ method: "POST",
1906
+ headers: {
1907
+ "Content-Type": "application/json"
1908
+ },
1909
+ body: JSON.stringify(geminiBody)
1910
+ }
1911
+ );
1912
+ return response;
1913
+ }
1914
+ async function forwardToGeminiStream(request, targetModel, apiKey) {
1915
+ const systemMessage = request.messages.find((m) => m.role === "system");
1916
+ const geminiContents = convertMessagesToGemini(request.messages);
1917
+ const geminiBody = {
1918
+ contents: geminiContents,
1919
+ generationConfig: {
1920
+ maxOutputTokens: request.max_tokens ?? 4096
1921
+ }
1922
+ };
1923
+ if (request.temperature !== void 0) {
1924
+ geminiBody["generationConfig"]["temperature"] = request.temperature;
1925
+ }
1926
+ if (systemMessage && typeof systemMessage.content === "string") {
1927
+ geminiBody["systemInstruction"] = {
1928
+ parts: [{ text: systemMessage.content }]
1929
+ };
1930
+ }
1931
+ const response = await fetch(
1932
+ `https://generativelanguage.googleapis.com/v1beta/models/${targetModel}:streamGenerateContent?alt=sse&key=${apiKey}`,
1933
+ {
1934
+ method: "POST",
1935
+ headers: {
1936
+ "Content-Type": "application/json"
1937
+ },
1938
+ body: JSON.stringify(geminiBody)
1939
+ }
1940
+ );
1941
+ return response;
1942
+ }
1943
+ function convertGeminiResponse(geminiData, model) {
1944
+ const candidate = geminiData.candidates?.[0];
1945
+ const text = candidate?.content?.parts?.map((p) => p.text ?? "").join("") ?? "";
1946
+ let finishReason = "stop";
1947
+ if (candidate?.finishReason === "MAX_TOKENS") {
1948
+ finishReason = "length";
1949
+ } else if (candidate?.finishReason === "SAFETY") {
1950
+ finishReason = "content_filter";
1951
+ }
1952
+ return {
1953
+ id: `chatcmpl-${Date.now()}`,
1954
+ object: "chat.completion",
1955
+ created: Math.floor(Date.now() / 1e3),
1956
+ model,
1957
+ choices: [
1958
+ {
1959
+ index: 0,
1960
+ message: {
1961
+ role: "assistant",
1962
+ content: text
1963
+ },
1964
+ finish_reason: finishReason
1965
+ }
1966
+ ],
1967
+ usage: {
1968
+ prompt_tokens: geminiData.usageMetadata?.promptTokenCount ?? 0,
1969
+ completion_tokens: geminiData.usageMetadata?.candidatesTokenCount ?? 0,
1970
+ total_tokens: (geminiData.usageMetadata?.promptTokenCount ?? 0) + (geminiData.usageMetadata?.candidatesTokenCount ?? 0)
1971
+ }
1972
+ };
1973
+ }
1974
+ function convertGeminiStreamEvent(eventData, messageId, model, isFirst) {
1975
+ const candidate = eventData.candidates?.[0];
1976
+ const text = candidate?.content?.parts?.map((p) => p.text ?? "").join("") ?? "";
1977
+ const choice = {
1978
+ index: 0,
1979
+ delta: {},
1980
+ finish_reason: null
1981
+ };
1982
+ if (isFirst) {
1983
+ choice["delta"] = { role: "assistant", content: text };
1984
+ } else if (text) {
1985
+ choice["delta"] = { content: text };
1986
+ }
1987
+ if (candidate?.finishReason) {
1988
+ let finishReason = "stop";
1989
+ if (candidate.finishReason === "MAX_TOKENS") {
1990
+ finishReason = "length";
1991
+ } else if (candidate.finishReason === "SAFETY") {
1992
+ finishReason = "content_filter";
1993
+ }
1994
+ choice["finish_reason"] = finishReason;
1995
+ }
1996
+ const chunk = {
1997
+ id: messageId,
1998
+ object: "chat.completion.chunk",
1999
+ created: Math.floor(Date.now() / 1e3),
2000
+ model,
2001
+ choices: [choice]
2002
+ };
2003
+ return `data: ${JSON.stringify(chunk)}
2004
+
2005
+ `;
2006
+ }
2007
+ async function* convertGeminiStream(response, model) {
2008
+ const reader = response.body?.getReader();
2009
+ if (!reader) {
2010
+ throw new Error("No response body");
2011
+ }
2012
+ const decoder = new TextDecoder();
2013
+ let buffer = "";
2014
+ const messageId = `chatcmpl-${Date.now()}`;
2015
+ let isFirst = true;
2016
+ try {
2017
+ while (true) {
2018
+ const { done, value } = await reader.read();
2019
+ if (done) break;
2020
+ buffer += decoder.decode(value, { stream: true });
2021
+ const lines = buffer.split("\n");
2022
+ buffer = lines.pop() || "";
2023
+ for (const line of lines) {
2024
+ if (line.startsWith("data: ")) {
2025
+ const jsonStr = line.slice(6);
2026
+ if (jsonStr.trim() === "[DONE]") {
2027
+ yield "data: [DONE]\n\n";
2028
+ continue;
2029
+ }
2030
+ try {
2031
+ const parsed = JSON.parse(jsonStr);
2032
+ const converted = convertGeminiStreamEvent(parsed, messageId, model, isFirst);
2033
+ if (converted) {
2034
+ yield converted;
2035
+ isFirst = false;
2036
+ }
2037
+ } catch {
2038
+ }
2039
+ }
2040
+ }
2041
+ }
2042
+ yield "data: [DONE]\n\n";
2043
+ } finally {
2044
+ reader.releaseLock();
2045
+ }
2046
+ }
2047
+ function convertAnthropicResponse(anthropicData) {
2048
+ const textBlocks = anthropicData.content?.filter((c) => c.type === "text") ?? [];
2049
+ const toolBlocks = anthropicData.content?.filter((c) => c.type === "tool_use") ?? [];
2050
+ const textContent = textBlocks.map((c) => c.text ?? "").join("");
2051
+ const message = {
2052
+ role: "assistant",
2053
+ content: textContent || null
2054
+ };
2055
+ if (toolBlocks.length > 0) {
2056
+ message["tool_calls"] = toolBlocks.map((block) => ({
2057
+ id: block.id || `call_${Date.now()}`,
2058
+ type: "function",
2059
+ function: {
2060
+ name: block.name,
2061
+ arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input ?? {})
2062
+ }
2063
+ }));
2064
+ }
2065
+ let finishReason = "stop";
2066
+ if (anthropicData.stop_reason === "tool_use") {
2067
+ finishReason = "tool_calls";
2068
+ } else if (anthropicData.stop_reason === "end_turn") {
2069
+ finishReason = "stop";
2070
+ } else if (anthropicData.stop_reason) {
2071
+ finishReason = anthropicData.stop_reason;
2072
+ }
2073
+ return {
2074
+ id: anthropicData.id || `chatcmpl-${Date.now()}`,
2075
+ object: "chat.completion",
2076
+ created: Math.floor(Date.now() / 1e3),
2077
+ model: anthropicData.model,
2078
+ choices: [
2079
+ {
2080
+ index: 0,
2081
+ message,
2082
+ finish_reason: finishReason
2083
+ }
2084
+ ],
2085
+ usage: {
2086
+ prompt_tokens: anthropicData.usage?.input_tokens ?? 0,
2087
+ completion_tokens: anthropicData.usage?.output_tokens ?? 0,
2088
+ total_tokens: (anthropicData.usage?.input_tokens ?? 0) + (anthropicData.usage?.output_tokens ?? 0)
2089
+ }
2090
+ };
2091
+ }
2092
+ function convertAnthropicStreamEvent(eventType, eventData, messageId, model, toolState) {
2093
+ const choice = { index: 0, delta: {}, finish_reason: null };
2094
+ const baseChunk = {
2095
+ id: messageId,
2096
+ object: "chat.completion.chunk",
2097
+ created: Math.floor(Date.now() / 1e3),
2098
+ model,
2099
+ choices: [choice]
2100
+ };
2101
+ switch (eventType) {
2102
+ case "message_start": {
2103
+ const msg = eventData["message"];
2104
+ baseChunk.id = msg?.["id"] || messageId;
2105
+ choice.delta = { role: "assistant", content: "" };
2106
+ return `data: ${JSON.stringify(baseChunk)}
2107
+
2108
+ `;
2109
+ }
2110
+ case "content_block_start": {
2111
+ const contentBlock = eventData["content_block"];
2112
+ const blockIndex = eventData["index"];
2113
+ if (contentBlock?.["type"] === "tool_use") {
2114
+ const toolId = contentBlock["id"];
2115
+ const toolName = contentBlock["name"];
2116
+ toolState.tools.set(blockIndex ?? toolState.currentToolIndex, {
2117
+ id: toolId,
2118
+ name: toolName,
2119
+ arguments: ""
2120
+ });
2121
+ toolState.currentToolIndex = blockIndex ?? toolState.currentToolIndex;
2122
+ choice.delta = {
2123
+ tool_calls: [{
2124
+ index: blockIndex ?? 0,
2125
+ id: toolId,
2126
+ type: "function",
2127
+ function: { name: toolName, arguments: "" }
2128
+ }]
2129
+ };
2130
+ return `data: ${JSON.stringify(baseChunk)}
2131
+
2132
+ `;
2133
+ }
2134
+ return null;
2135
+ }
2136
+ case "content_block_delta": {
2137
+ const delta = eventData["delta"];
2138
+ const blockIndex = eventData["index"];
2139
+ if (delta?.["type"] === "text_delta") {
2140
+ choice.delta = { content: delta["text"] };
2141
+ return `data: ${JSON.stringify(baseChunk)}
2142
+
2143
+ `;
2144
+ }
2145
+ if (delta?.["type"] === "input_json_delta") {
2146
+ const partialJson = delta["partial_json"] || "";
2147
+ const tool = toolState.tools.get(blockIndex ?? toolState.currentToolIndex);
2148
+ if (tool) {
2149
+ tool.arguments += partialJson;
2150
+ }
2151
+ choice.delta = {
2152
+ tool_calls: [{
2153
+ index: blockIndex ?? 0,
2154
+ function: { arguments: partialJson }
2155
+ }]
2156
+ };
2157
+ return `data: ${JSON.stringify(baseChunk)}
2158
+
2159
+ `;
2160
+ }
2161
+ return null;
2162
+ }
2163
+ case "message_delta": {
2164
+ const delta = eventData["delta"];
2165
+ const stopReason = delta?.["stop_reason"];
2166
+ if (stopReason === "tool_use") {
2167
+ choice.finish_reason = "tool_calls";
2168
+ } else if (stopReason === "end_turn") {
2169
+ choice.finish_reason = "stop";
2170
+ } else {
2171
+ choice.finish_reason = stopReason || "stop";
2172
+ }
2173
+ choice.delta = {};
2174
+ return `data: ${JSON.stringify(baseChunk)}
2175
+
2176
+ `;
2177
+ }
2178
+ case "message_stop": {
2179
+ return "data: [DONE]\n\n";
2180
+ }
2181
+ default:
2182
+ return null;
2183
+ }
2184
+ }
2185
+ async function* convertAnthropicStream(response, model) {
2186
+ const reader = response.body?.getReader();
2187
+ if (!reader) {
2188
+ throw new Error("No response body");
2189
+ }
2190
+ const decoder = new TextDecoder();
2191
+ let buffer = "";
2192
+ let messageId = `chatcmpl-${Date.now()}`;
2193
+ const toolState = {
2194
+ currentToolIndex: 0,
2195
+ tools: /* @__PURE__ */ new Map()
2196
+ };
2197
+ try {
2198
+ while (true) {
2199
+ const { done, value } = await reader.read();
2200
+ if (done) break;
2201
+ buffer += decoder.decode(value, { stream: true });
2202
+ const lines = buffer.split("\n");
2203
+ buffer = lines.pop() || "";
2204
+ let eventType = "";
2205
+ let eventData = "";
2206
+ for (const line of lines) {
2207
+ if (line.startsWith("event: ")) {
2208
+ eventType = line.slice(7).trim();
2209
+ } else if (line.startsWith("data: ")) {
2210
+ eventData = line.slice(6);
2211
+ } else if (line === "" && eventType && eventData) {
2212
+ try {
2213
+ const parsed = JSON.parse(eventData);
2214
+ const converted = convertAnthropicStreamEvent(eventType, parsed, messageId, model, toolState);
2215
+ if (converted) {
2216
+ yield converted;
2217
+ }
2218
+ } catch {
2219
+ }
2220
+ eventType = "";
2221
+ eventData = "";
2222
+ }
2223
+ }
2224
+ }
2225
+ } finally {
2226
+ reader.releaseLock();
2227
+ }
2228
+ }
2229
+ async function* pipeOpenAIStream(response) {
2230
+ const reader = response.body?.getReader();
2231
+ if (!reader) {
2232
+ throw new Error("No response body");
2233
+ }
2234
+ const decoder = new TextDecoder();
2235
+ try {
2236
+ while (true) {
2237
+ const { done, value } = await reader.read();
2238
+ if (done) break;
2239
+ yield decoder.decode(value, { stream: true });
2240
+ }
2241
+ } finally {
2242
+ reader.releaseLock();
2243
+ }
2244
+ }
2245
+ function parsePreferredModel(preferredModel) {
2246
+ const [provider, model] = preferredModel.split(":");
2247
+ if (!provider || !model) return null;
2248
+ const validProviders = ["openai", "anthropic", "google", "xai", "moonshot", "local"];
2249
+ if (!validProviders.includes(provider)) return null;
2250
+ return { provider, model };
2251
+ }
2252
+ function resolveExplicitModel(modelName) {
2253
+ if (MODEL_MAPPING[modelName]) {
2254
+ return MODEL_MAPPING[modelName];
2255
+ }
2256
+ if (modelName.startsWith("claude-")) {
2257
+ return { provider: "anthropic", model: modelName };
2258
+ }
2259
+ if (modelName.startsWith("gpt-") || modelName.startsWith("o1-") || modelName.startsWith("o3-") || modelName.startsWith("chatgpt-") || modelName.startsWith("text-") || modelName.startsWith("dall-e") || modelName.startsWith("whisper") || modelName.startsWith("tts-")) {
2260
+ return { provider: "openai", model: modelName };
2261
+ }
2262
+ if (modelName.startsWith("gemini-") || modelName.startsWith("palm-")) {
2263
+ return { provider: "google", model: modelName };
2264
+ }
2265
+ if (modelName.startsWith("grok-")) {
2266
+ return { provider: "xai", model: modelName };
2267
+ }
2268
+ if (modelName.startsWith("moonshot-")) {
2269
+ return { provider: "moonshot", model: modelName };
2270
+ }
2271
+ if (modelName.includes("/")) {
2272
+ const [provider, model] = modelName.split("/");
2273
+ const validProviders = ["openai", "anthropic", "google", "xai", "moonshot", "local"];
2274
+ if (provider && model && validProviders.includes(provider)) {
2275
+ return { provider, model };
2276
+ }
2277
+ }
2278
+ return null;
2279
+ }
2280
+ async function startProxy(config = {}) {
2281
+ const port = config.port ?? 3001;
2282
+ const host = config.host ?? "127.0.0.1";
2283
+ const verbose = config.verbose ?? false;
2284
+ const relay = new RelayPlane({ dbPath: config.dbPath });
2285
+ const log = (msg) => {
2286
+ if (verbose) console.log(`[relayplane] ${msg}`);
2287
+ };
2288
+ const server = http.createServer(async (req, res) => {
2289
+ res.setHeader("Access-Control-Allow-Origin", "*");
2290
+ res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
2291
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
2292
+ if (req.method === "OPTIONS") {
2293
+ res.writeHead(204);
2294
+ res.end();
2295
+ return;
2296
+ }
2297
+ if (req.method !== "POST" || !req.url?.includes("/chat/completions")) {
2298
+ if (req.method === "GET" && req.url?.includes("/models")) {
2299
+ res.writeHead(200, { "Content-Type": "application/json" });
2300
+ res.end(
2301
+ JSON.stringify({
2302
+ object: "list",
2303
+ data: [
2304
+ { id: "relayplane:auto", object: "model", owned_by: "relayplane" },
2305
+ { id: "relayplane:cost", object: "model", owned_by: "relayplane" },
2306
+ { id: "relayplane:quality", object: "model", owned_by: "relayplane" }
2307
+ ]
2308
+ })
2309
+ );
2310
+ return;
2311
+ }
2312
+ res.writeHead(404, { "Content-Type": "application/json" });
2313
+ res.end(JSON.stringify({ error: "Not found" }));
2314
+ return;
2315
+ }
2316
+ let body = "";
2317
+ for await (const chunk of req) {
2318
+ body += chunk;
2319
+ }
2320
+ let request;
2321
+ try {
2322
+ request = JSON.parse(body);
2323
+ } catch {
2324
+ res.writeHead(400, { "Content-Type": "application/json" });
2325
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
2326
+ return;
2327
+ }
2328
+ const isStreaming = request.stream === true;
2329
+ const requestedModel = request.model;
2330
+ let routingMode = "auto";
2331
+ let targetModel = "";
2332
+ let targetProvider = "anthropic";
2333
+ if (requestedModel.startsWith("relayplane:")) {
2334
+ if (requestedModel.includes(":cost")) {
2335
+ routingMode = "cost";
2336
+ } else if (requestedModel.includes(":quality")) {
2337
+ routingMode = "quality";
2338
+ }
2339
+ } else {
2340
+ routingMode = "passthrough";
2341
+ const resolved = resolveExplicitModel(requestedModel);
2342
+ if (resolved) {
2343
+ targetProvider = resolved.provider;
2344
+ targetModel = resolved.model;
2345
+ log(`Pass-through mode: ${requestedModel} \u2192 ${targetProvider}/${targetModel}`);
2346
+ } else {
2347
+ res.writeHead(400, { "Content-Type": "application/json" });
2348
+ res.end(JSON.stringify({ error: `Unknown model: ${requestedModel}` }));
2349
+ return;
2350
+ }
2351
+ }
2352
+ log(`Received request for model: ${requestedModel} (mode: ${routingMode}, stream: ${isStreaming})`);
2353
+ const promptText = extractPromptText(request.messages);
2354
+ const taskType = inferTaskType(promptText);
2355
+ const confidence = getInferenceConfidence(promptText, taskType);
2356
+ log(`Inferred task: ${taskType} (confidence: ${confidence.toFixed(2)})`);
2357
+ if (routingMode !== "passthrough") {
2358
+ const rule = relay.routing.get(taskType);
2359
+ if (rule && rule.preferredModel) {
2360
+ const parsed = parsePreferredModel(rule.preferredModel);
2361
+ if (parsed) {
2362
+ targetProvider = parsed.provider;
2363
+ targetModel = parsed.model;
2364
+ log(`Using learned rule: ${rule.preferredModel}`);
2365
+ } else {
2366
+ const defaultRoute = DEFAULT_ROUTING[taskType];
2367
+ targetProvider = defaultRoute.provider;
2368
+ targetModel = defaultRoute.model;
2369
+ }
2370
+ } else {
2371
+ const defaultRoute = DEFAULT_ROUTING[taskType];
2372
+ targetProvider = defaultRoute.provider;
2373
+ targetModel = defaultRoute.model;
2374
+ }
2375
+ if (routingMode === "cost") {
2376
+ const simpleTasks = ["summarization", "data_extraction", "translation", "question_answering"];
2377
+ if (simpleTasks.includes(taskType)) {
2378
+ targetModel = "claude-3-5-haiku-latest";
2379
+ targetProvider = "anthropic";
2380
+ }
2381
+ } else if (routingMode === "quality") {
2382
+ const qualityModel = process.env["RELAYPLANE_QUALITY_MODEL"] || "claude-3-5-sonnet-latest";
2383
+ targetModel = qualityModel;
2384
+ targetProvider = "anthropic";
2385
+ }
2386
+ }
2387
+ log(`Routing to: ${targetProvider}/${targetModel}`);
2388
+ const apiKeyEnv = DEFAULT_ENDPOINTS[targetProvider]?.apiKeyEnv ?? `${targetProvider.toUpperCase()}_API_KEY`;
2389
+ const apiKey = process.env[apiKeyEnv];
2390
+ if (!apiKey) {
2391
+ res.writeHead(500, { "Content-Type": "application/json" });
2392
+ res.end(JSON.stringify({ error: `Missing ${apiKeyEnv} environment variable` }));
2393
+ return;
2394
+ }
2395
+ const startTime = Date.now();
2396
+ const betaHeaders = req.headers["anthropic-beta"];
2397
+ if (isStreaming) {
2398
+ await handleStreamingRequest(
2399
+ res,
2400
+ request,
2401
+ targetProvider,
2402
+ targetModel,
2403
+ apiKey,
2404
+ relay,
2405
+ promptText,
2406
+ taskType,
2407
+ confidence,
2408
+ routingMode,
2409
+ startTime,
2410
+ log,
2411
+ betaHeaders
2412
+ );
2413
+ } else {
2414
+ await handleNonStreamingRequest(
2415
+ res,
2416
+ request,
2417
+ targetProvider,
2418
+ targetModel,
2419
+ apiKey,
2420
+ relay,
2421
+ promptText,
2422
+ taskType,
2423
+ confidence,
2424
+ routingMode,
2425
+ startTime,
2426
+ log,
2427
+ betaHeaders
2428
+ );
2429
+ }
2430
+ });
2431
+ return new Promise((resolve, reject) => {
2432
+ server.on("error", reject);
2433
+ server.listen(port, host, () => {
2434
+ console.log(`RelayPlane proxy listening on http://${host}:${port}`);
2435
+ console.log(` Models: relayplane:auto, relayplane:cost, relayplane:quality`);
2436
+ console.log(` Endpoint: POST /v1/chat/completions`);
2437
+ console.log(` Streaming: \u2705 Enabled`);
2438
+ resolve(server);
2439
+ });
2440
+ });
2441
+ }
2442
+ async function handleStreamingRequest(res, request, targetProvider, targetModel, apiKey, relay, promptText, taskType, confidence, routingMode, startTime, log, betaHeaders) {
2443
+ let providerResponse;
2444
+ try {
2445
+ switch (targetProvider) {
2446
+ case "anthropic":
2447
+ providerResponse = await forwardToAnthropicStream(request, targetModel, apiKey, betaHeaders);
2448
+ break;
2449
+ case "google":
2450
+ providerResponse = await forwardToGeminiStream(request, targetModel, apiKey);
2451
+ break;
2452
+ case "xai":
2453
+ providerResponse = await forwardToXAIStream(request, targetModel, apiKey);
2454
+ break;
2455
+ case "moonshot":
2456
+ providerResponse = await forwardToMoonshotStream(request, targetModel, apiKey);
2457
+ break;
2458
+ default:
2459
+ providerResponse = await forwardToOpenAIStream(request, targetModel, apiKey);
2460
+ }
2461
+ if (!providerResponse.ok) {
2462
+ const errorData = await providerResponse.json();
2463
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2464
+ res.end(JSON.stringify(errorData));
2465
+ return;
2466
+ }
2467
+ } catch (err) {
2468
+ const errorMsg = err instanceof Error ? err.message : String(err);
2469
+ res.writeHead(500, { "Content-Type": "application/json" });
2470
+ res.end(JSON.stringify({ error: `Provider error: ${errorMsg}` }));
2471
+ return;
2472
+ }
2473
+ res.writeHead(200, {
2474
+ "Content-Type": "text/event-stream",
2475
+ "Cache-Control": "no-cache",
2476
+ "Connection": "keep-alive"
2477
+ });
2478
+ try {
2479
+ switch (targetProvider) {
2480
+ case "anthropic":
2481
+ for await (const chunk of convertAnthropicStream(providerResponse, targetModel)) {
2482
+ res.write(chunk);
2483
+ }
2484
+ break;
2485
+ case "google":
2486
+ for await (const chunk of convertGeminiStream(providerResponse, targetModel)) {
2487
+ res.write(chunk);
2488
+ }
2489
+ break;
2490
+ default:
2491
+ for await (const chunk of pipeOpenAIStream(providerResponse)) {
2492
+ res.write(chunk);
2493
+ }
2494
+ }
2495
+ } catch (err) {
2496
+ log(`Streaming error: ${err}`);
2497
+ }
2498
+ const durationMs = Date.now() - startTime;
2499
+ relay.run({
2500
+ prompt: promptText.slice(0, 500),
2501
+ taskType,
2502
+ model: `${targetProvider}:${targetModel}`
2503
+ }).then((runResult) => {
2504
+ log(`Completed streaming in ${durationMs}ms, runId: ${runResult.runId}`);
2505
+ }).catch((err) => {
2506
+ log(`Failed to record run: ${err}`);
2507
+ });
2508
+ res.end();
2509
+ }
2510
+ async function handleNonStreamingRequest(res, request, targetProvider, targetModel, apiKey, relay, promptText, taskType, confidence, routingMode, startTime, log, betaHeaders) {
2511
+ let providerResponse;
2512
+ let responseData;
2513
+ try {
2514
+ switch (targetProvider) {
2515
+ case "anthropic": {
2516
+ providerResponse = await forwardToAnthropic(request, targetModel, apiKey, betaHeaders);
2517
+ const rawData = await providerResponse.json();
2518
+ if (!providerResponse.ok) {
2519
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2520
+ res.end(JSON.stringify(rawData));
2521
+ return;
2522
+ }
2523
+ responseData = convertAnthropicResponse(rawData);
2524
+ break;
2525
+ }
2526
+ case "google": {
2527
+ providerResponse = await forwardToGemini(request, targetModel, apiKey);
2528
+ const rawData = await providerResponse.json();
2529
+ if (!providerResponse.ok) {
2530
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2531
+ res.end(JSON.stringify(rawData));
2532
+ return;
2533
+ }
2534
+ responseData = convertGeminiResponse(rawData, targetModel);
2535
+ break;
2536
+ }
2537
+ case "xai": {
2538
+ providerResponse = await forwardToXAI(request, targetModel, apiKey);
2539
+ responseData = await providerResponse.json();
2540
+ if (!providerResponse.ok) {
2541
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2542
+ res.end(JSON.stringify(responseData));
2543
+ return;
2544
+ }
2545
+ break;
2546
+ }
2547
+ case "moonshot": {
2548
+ providerResponse = await forwardToMoonshot(request, targetModel, apiKey);
2549
+ responseData = await providerResponse.json();
2550
+ if (!providerResponse.ok) {
2551
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2552
+ res.end(JSON.stringify(responseData));
2553
+ return;
2554
+ }
2555
+ break;
2556
+ }
2557
+ default: {
2558
+ providerResponse = await forwardToOpenAI(request, targetModel, apiKey);
2559
+ responseData = await providerResponse.json();
2560
+ if (!providerResponse.ok) {
2561
+ res.writeHead(providerResponse.status, { "Content-Type": "application/json" });
2562
+ res.end(JSON.stringify(responseData));
2563
+ return;
2564
+ }
2565
+ }
2566
+ }
2567
+ } catch (err) {
2568
+ const errorMsg = err instanceof Error ? err.message : String(err);
2569
+ res.writeHead(500, { "Content-Type": "application/json" });
2570
+ res.end(JSON.stringify({ error: `Provider error: ${errorMsg}` }));
2571
+ return;
2572
+ }
2573
+ const durationMs = Date.now() - startTime;
2574
+ try {
2575
+ const runResult = await relay.run({
2576
+ prompt: promptText.slice(0, 500),
2577
+ taskType,
2578
+ model: `${targetProvider}:${targetModel}`
2579
+ });
2580
+ responseData["_relayplane"] = {
2581
+ runId: runResult.runId,
2582
+ routedTo: `${targetProvider}/${targetModel}`,
2583
+ taskType,
2584
+ confidence,
2585
+ durationMs,
2586
+ mode: routingMode
2587
+ };
2588
+ log(`Completed in ${durationMs}ms, runId: ${runResult.runId}`);
2589
+ } catch (err) {
2590
+ log(`Failed to record run: ${err}`);
2591
+ }
2592
+ res.writeHead(200, { "Content-Type": "application/json" });
2593
+ res.end(JSON.stringify(responseData));
2594
+ }
2595
+
2596
+ // src/types.ts
2597
+ import { z } from "zod";
2598
+ var TaskTypes = [
2599
+ "code_generation",
2600
+ "code_review",
2601
+ "summarization",
2602
+ "analysis",
2603
+ "creative_writing",
2604
+ "data_extraction",
2605
+ "translation",
2606
+ "question_answering",
2607
+ "general"
2608
+ ];
2609
+ var TaskTypeSchema = z.enum(TaskTypes);
2610
+ var Providers = ["openai", "anthropic", "google", "xai", "moonshot", "local"];
2611
+ var ProviderSchema = z.enum(Providers);
2612
+ var RelayPlaneConfigSchema = z.object({
2613
+ dbPath: z.string().optional(),
2614
+ providers: z.record(ProviderSchema, z.object({
2615
+ apiKey: z.string().optional(),
2616
+ baseUrl: z.string().optional()
2617
+ })).optional(),
2618
+ defaultProvider: ProviderSchema.optional(),
2619
+ defaultModel: z.string().optional()
2620
+ });
2621
+ var RunInputSchema = z.object({
2622
+ prompt: z.string().min(1),
2623
+ systemPrompt: z.string().optional(),
2624
+ taskType: TaskTypeSchema.optional(),
2625
+ model: z.string().optional(),
2626
+ metadata: z.record(z.unknown()).optional()
2627
+ });
2628
+ var RuleSources = ["default", "user", "learned"];
2629
+ var RoutingRuleSchema = z.object({
2630
+ id: z.string(),
2631
+ taskType: TaskTypeSchema,
2632
+ preferredModel: z.string(),
2633
+ source: z.enum(RuleSources),
2634
+ confidence: z.number().min(0).max(1).optional(),
2635
+ sampleCount: z.number().int().positive().optional(),
2636
+ createdAt: z.string(),
2637
+ updatedAt: z.string()
2638
+ });
2639
+ var OutcomeQualities = ["excellent", "good", "acceptable", "poor", "failed"];
2640
+ var OutcomeInputSchema = z.object({
2641
+ runId: z.string().min(1),
2642
+ success: z.boolean(),
2643
+ quality: z.enum(OutcomeQualities).optional(),
2644
+ latencySatisfactory: z.boolean().optional(),
2645
+ costSatisfactory: z.boolean().optional(),
2646
+ feedback: z.string().optional()
2647
+ });
2648
+ var SuggestionSchema = z.object({
2649
+ id: z.string(),
2650
+ taskType: TaskTypeSchema,
2651
+ currentModel: z.string(),
2652
+ suggestedModel: z.string(),
2653
+ reason: z.string(),
2654
+ confidence: z.number().min(0).max(1),
2655
+ expectedImprovement: z.object({
2656
+ successRate: z.number().optional(),
2657
+ latency: z.number().optional(),
2658
+ cost: z.number().optional()
2659
+ }),
2660
+ sampleCount: z.number().int().positive(),
2661
+ createdAt: z.string(),
2662
+ accepted: z.boolean().optional(),
2663
+ acceptedAt: z.string().optional()
2664
+ });
2665
+ export {
2666
+ DEFAULT_ENDPOINTS,
2667
+ MODEL_MAPPING,
2668
+ MODEL_PRICING,
2669
+ OutcomeRecorder,
2670
+ PatternDetector,
2671
+ ProviderSchema,
2672
+ Providers,
2673
+ RelayPlane,
2674
+ RoutingEngine,
2675
+ Store,
2676
+ TaskTypeSchema,
2677
+ TaskTypes,
2678
+ calculateCost,
2679
+ calculateSavings,
2680
+ getInferenceConfidence,
2681
+ getModelPricing,
2682
+ inferTaskType,
2683
+ startProxy
2684
+ };
2685
+ //# sourceMappingURL=index.mjs.map