@musistudio/claude-code-router 1.0.23 → 1.0.24

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/cli.js CHANGED
@@ -9138,7 +9138,7 @@ var require_reply = __commonJS({
9138
9138
  handled--;
9139
9139
  const result = reply[kReplyTrailers][trailerName](reply, payload, cb);
9140
9140
  if (typeof result === "object" && typeof result.then === "function") {
9141
- result.then((v) => cb(null, v), cb);
9141
+ result.then((v2) => cb(null, v2), cb);
9142
9142
  }
9143
9143
  }
9144
9144
  if (skipped) res.end(null, null, null);
@@ -13097,7 +13097,7 @@ var require_codegen = __commonJS({
13097
13097
  }
13098
13098
  exports2.or = or;
13099
13099
  function mappend(op) {
13100
- return (x, y2) => x === code_1.nil ? y2 : y2 === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y2)}`;
13100
+ return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
13101
13101
  }
13102
13102
  function par(x) {
13103
13103
  return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
@@ -15991,17 +15991,17 @@ var require_core = __commonJS({
15991
15991
  return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0;
15992
15992
  }
15993
15993
  validate(schemaKeyRef, data) {
15994
- let v;
15994
+ let v2;
15995
15995
  if (typeof schemaKeyRef == "string") {
15996
- v = this.getSchema(schemaKeyRef);
15997
- if (!v)
15996
+ v2 = this.getSchema(schemaKeyRef);
15997
+ if (!v2)
15998
15998
  throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
15999
15999
  } else {
16000
- v = this.compile(schemaKeyRef);
16000
+ v2 = this.compile(schemaKeyRef);
16001
16001
  }
16002
- const valid = v(data);
16003
- if (!("$async" in v))
16004
- this.errors = v.errors;
16002
+ const valid = v2(data);
16003
+ if (!("$async" in v2))
16004
+ this.errors = v2.errors;
16005
16005
  return valid;
16006
16006
  }
16007
16007
  compile(schema, _meta) {
@@ -16495,8 +16495,8 @@ var require_ref = __commonJS({
16495
16495
  return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
16496
16496
  }
16497
16497
  function callValidate(sch) {
16498
- const v = getValidate(cxt, sch);
16499
- callRef(cxt, v, sch, sch.$async);
16498
+ const v2 = getValidate(cxt, sch);
16499
+ callRef(cxt, v2, sch, sch.$async);
16500
16500
  }
16501
16501
  function inlineRefSchema(sch) {
16502
16502
  const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
@@ -16518,7 +16518,7 @@ var require_ref = __commonJS({
16518
16518
  return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
16519
16519
  }
16520
16520
  exports2.getValidate = getValidate;
16521
- function callRef(cxt, v, sch, $async) {
16521
+ function callRef(cxt, v2, sch, $async) {
16522
16522
  const { gen, it } = cxt;
16523
16523
  const { allErrors, schemaEnv: env, opts } = it;
16524
16524
  const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
@@ -16531,8 +16531,8 @@ var require_ref = __commonJS({
16531
16531
  throw new Error("async schema referenced by sync schema");
16532
16532
  const valid = gen.let("valid");
16533
16533
  gen.try(() => {
16534
- gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`);
16535
- addEvaluatedFrom(v);
16534
+ gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v2, passCxt)}`);
16535
+ addEvaluatedFrom(v2);
16536
16536
  if (!allErrors)
16537
16537
  gen.assign(valid, true);
16538
16538
  }, (e) => {
@@ -16544,7 +16544,7 @@ var require_ref = __commonJS({
16544
16544
  cxt.ok(valid);
16545
16545
  }
16546
16546
  function callSyncRef() {
16547
- cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
16547
+ cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
16548
16548
  }
16549
16549
  function addErrorsFrom(source) {
16550
16550
  const errs = (0, codegen_1._)`${source}.errors`;
@@ -17034,7 +17034,7 @@ var require_enum = __commonJS({
17034
17034
  cxt.pass(valid);
17035
17035
  function loopEnum() {
17036
17036
  gen.assign(valid, false);
17037
- gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
17037
+ gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break()));
17038
17038
  }
17039
17039
  function equalCode(vSchema, i) {
17040
17040
  const sch = schema[i];
@@ -18420,7 +18420,7 @@ var require_ajv = __commonJS({
18420
18420
  var Ajv = class extends core_1.default {
18421
18421
  _addVocabularies() {
18422
18422
  super._addVocabularies();
18423
- draft7_1.default.forEach((v) => this.addVocabulary(v));
18423
+ draft7_1.default.forEach((v2) => this.addVocabulary(v2));
18424
18424
  if (this.opts.discriminator)
18425
18425
  this.addKeyword(discriminator_1.default);
18426
18426
  }
@@ -20157,8 +20157,8 @@ var require_merge_json_schemas = __commonJS({
20157
20157
  for (const array of arrays) {
20158
20158
  const temp = [];
20159
20159
  for (const x of result) {
20160
- for (const y2 of array) {
20161
- temp.push([...x, y2]);
20160
+ for (const y of array) {
20161
+ temp.push([...x, y]);
20162
20162
  }
20163
20163
  }
20164
20164
  result = temp;
@@ -21449,9 +21449,9 @@ var require_ref2 = __commonJS({
21449
21449
  }
21450
21450
  function callValidate(schema) {
21451
21451
  const sch = compile_1.compileSchema.call(it.self, new compile_1.SchemaEnv({ schema, root, schemaPath: `/definitions/${ref}` }));
21452
- const v = (0, ref_1.getValidate)(cxt, sch);
21452
+ const v2 = (0, ref_1.getValidate)(cxt, sch);
21453
21453
  const errsCount = gen.const("_errs", names_1.default.errors);
21454
- (0, ref_1.callRef)(cxt, v, sch, sch.$async);
21454
+ (0, ref_1.callRef)(cxt, v2, sch, sch.$async);
21455
21455
  gen.assign(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
21456
21456
  }
21457
21457
  function inlineRefSchema(schema) {
@@ -21497,11 +21497,11 @@ var require_timestamp = __commonJS({
21497
21497
  const matches = DATE.exec(str);
21498
21498
  if (!matches)
21499
21499
  return false;
21500
- const y2 = +matches[1];
21500
+ const y = +matches[1];
21501
21501
  const m = +matches[2];
21502
21502
  const d = +matches[3];
21503
21503
  return m >= 1 && m <= 12 && d >= 1 && (d <= DAYS[m] || // leap year: https://tools.ietf.org/html/rfc3339#appendix-C
21504
- m === 2 && d === 29 && (y2 % 100 === 0 ? y2 % 400 === 0 : y2 % 4 === 0));
21504
+ m === 2 && d === 29 && (y % 100 === 0 ? y % 400 === 0 : y % 4 === 0));
21505
21505
  }
21506
21506
  function validTime(str) {
21507
21507
  const matches = TIME.exec(str);
@@ -21681,7 +21681,7 @@ var require_enum2 = __commonJS({
21681
21681
  }
21682
21682
  cxt.pass(valid);
21683
21683
  function loopEnum() {
21684
- gen.forOf("v", schemaValue, (v) => gen.if((0, codegen_1._)`${valid} = ${data} === ${v}`, () => gen.break()));
21684
+ gen.forOf("v", schemaValue, (v2) => gen.if((0, codegen_1._)`${valid} = ${data} === ${v2}`, () => gen.break()));
21685
21685
  }
21686
21686
  }
21687
21687
  };
@@ -23173,10 +23173,10 @@ var require_standalone3 = __commonJS({
23173
23173
  const { _n } = ajv.scope.opts;
23174
23174
  return typeof refsOrFunc == "function" ? funcExportCode(refsOrFunc.source) : refsOrFunc !== void 0 ? multiExportsCode(refsOrFunc, getValidate) : multiExportsCode(ajv.schemas, (sch) => sch.meta ? void 0 : ajv.compile(sch.schema));
23175
23175
  function getValidate(id2) {
23176
- const v = ajv.getSchema(id2);
23177
- if (!v)
23176
+ const v2 = ajv.getSchema(id2);
23177
+ if (!v2)
23178
23178
  throw new Error(`moduleCode: no schema with id ${id2}`);
23179
- return v;
23179
+ return v2;
23180
23180
  }
23181
23181
  function funcExportCode(source) {
23182
23182
  const usedValues = {};
@@ -23192,11 +23192,11 @@ var require_standalone3 = __commonJS({
23192
23192
  const usedValues = {};
23193
23193
  let code = (0, code_1._)`"use strict";`;
23194
23194
  for (const name in schemas) {
23195
- const v = getValidateFunc(schemas[name]);
23196
- if (v) {
23197
- const vCode = validateCode(usedValues, v.source);
23195
+ const v2 = getValidateFunc(schemas[name]);
23196
+ if (v2) {
23197
+ const vCode = validateCode(usedValues, v2.source);
23198
23198
  const exportSyntax = ajv.opts.code.esm ? (0, code_1._)`export const ${(0, code_1.getEsmExportName)(name)}` : (0, code_1._)`exports${(0, code_1.getProperty)(name)}`;
23199
- code = (0, code_1._)`${code}${_n}${exportSyntax} = ${(_a = v.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
23199
+ code = (0, code_1._)`${code}${_n}${exportSyntax} = ${(_a = v2.source) === null || _a === void 0 ? void 0 : _a.validateName};${_n}${vCode}`;
23200
23200
  }
23201
23201
  }
23202
23202
  return `${code}`;
@@ -23214,8 +23214,8 @@ var require_standalone3 = __commonJS({
23214
23214
  var _a;
23215
23215
  const vRef = (_a = n.value) === null || _a === void 0 ? void 0 : _a.ref;
23216
23216
  if (n.prefix === "validate" && typeof vRef == "function") {
23217
- const v = vRef;
23218
- return validateCode(usedValues, v.source);
23217
+ const v2 = vRef;
23218
+ return validateCode(usedValues, v2.source);
23219
23219
  } else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
23220
23220
  const { validate, validateName } = vRef;
23221
23221
  if (!validateName)
@@ -23911,8 +23911,8 @@ var require_valid = __commonJS({
23911
23911
  "use strict";
23912
23912
  var parse = require_parse3();
23913
23913
  var valid = (version2, options) => {
23914
- const v = parse(version2, options);
23915
- return v ? v.version : null;
23914
+ const v2 = parse(version2, options);
23915
+ return v2 ? v2.version : null;
23916
23916
  };
23917
23917
  module2.exports = valid;
23918
23918
  }
@@ -24831,10 +24831,10 @@ var require_max_satisfying = __commonJS({
24831
24831
  } catch (er) {
24832
24832
  return null;
24833
24833
  }
24834
- versions.forEach((v) => {
24835
- if (rangeObj.test(v)) {
24836
- if (!max || maxSV.compare(v) === -1) {
24837
- max = v;
24834
+ versions.forEach((v2) => {
24835
+ if (rangeObj.test(v2)) {
24836
+ if (!max || maxSV.compare(v2) === -1) {
24837
+ max = v2;
24838
24838
  maxSV = new SemVer(max, options);
24839
24839
  }
24840
24840
  }
@@ -24860,10 +24860,10 @@ var require_min_satisfying = __commonJS({
24860
24860
  } catch (er) {
24861
24861
  return null;
24862
24862
  }
24863
- versions.forEach((v) => {
24864
- if (rangeObj.test(v)) {
24865
- if (!min || minSV.compare(v) === 1) {
24866
- min = v;
24863
+ versions.forEach((v2) => {
24864
+ if (rangeObj.test(v2)) {
24865
+ if (!min || minSV.compare(v2) === 1) {
24866
+ min = v2;
24867
24867
  minSV = new SemVer(min, options);
24868
24868
  }
24869
24869
  }
@@ -25062,8 +25062,8 @@ var require_simplify = __commonJS({
25062
25062
  const set = [];
25063
25063
  let first = null;
25064
25064
  let prev = null;
25065
- const v = versions.sort((a, b) => compare(a, b, options));
25066
- for (const version2 of v) {
25065
+ const v2 = versions.sort((a, b) => compare(a, b, options));
25066
+ for (const version2 of v2) {
25067
25067
  const included = satisfies(version2, range, options);
25068
25068
  if (included) {
25069
25069
  prev = version2;
@@ -25085,11 +25085,11 @@ var require_simplify = __commonJS({
25085
25085
  for (const [min, max] of set) {
25086
25086
  if (min === max) {
25087
25087
  ranges.push(min);
25088
- } else if (!max && min === v[0]) {
25088
+ } else if (!max && min === v2[0]) {
25089
25089
  ranges.push("*");
25090
25090
  } else if (!max) {
25091
25091
  ranges.push(`>=${min}`);
25092
- } else if (min === v[0]) {
25092
+ } else if (min === v2[0]) {
25093
25093
  ranges.push(`<=${max}`);
25094
25094
  } else {
25095
25095
  ranges.push(`${min} - ${max}`);
@@ -26456,10 +26456,10 @@ var require_util2 = __commonJS({
26456
26456
  if (k2 === void 0) k2 = k;
26457
26457
  o[k2] = m[k];
26458
26458
  });
26459
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
26460
- Object.defineProperty(o, "default", { enumerable: true, value: v });
26461
- } : function(o, v) {
26462
- o["default"] = v;
26459
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
26460
+ Object.defineProperty(o, "default", { enumerable: true, value: v2 });
26461
+ } : function(o, v2) {
26462
+ o["default"] = v2;
26463
26463
  });
26464
26464
  var __importStar = exports2 && exports2.__importStar || function(mod) {
26465
26465
  if (mod && mod.__esModule) return mod;
@@ -26527,10 +26527,10 @@ var require_tokenizer = __commonJS({
26527
26527
  if (k2 === void 0) k2 = k;
26528
26528
  o[k2] = m[k];
26529
26529
  });
26530
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
26531
- Object.defineProperty(o, "default", { enumerable: true, value: v });
26532
- } : function(o, v) {
26533
- o["default"] = v;
26530
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
26531
+ Object.defineProperty(o, "default", { enumerable: true, value: v2 });
26532
+ } : function(o, v2) {
26533
+ o["default"] = v2;
26534
26534
  });
26535
26535
  var __importStar = exports2 && exports2.__importStar || function(mod) {
26536
26536
  if (mod && mod.__esModule) return mod;
@@ -26828,10 +26828,10 @@ var require_sets_lookup = __commonJS({
26828
26828
  if (k2 === void 0) k2 = k;
26829
26829
  o[k2] = m[k];
26830
26830
  });
26831
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
26832
- Object.defineProperty(o, "default", { enumerable: true, value: v });
26833
- } : function(o, v) {
26834
- o["default"] = v;
26831
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
26832
+ Object.defineProperty(o, "default", { enumerable: true, value: v2 });
26833
+ } : function(o, v2) {
26834
+ o["default"] = v2;
26835
26835
  });
26836
26836
  var __importStar = exports2 && exports2.__importStar || function(mod) {
26837
26837
  if (mod && mod.__esModule) return mod;
@@ -26883,10 +26883,10 @@ var require_write_set_tokens = __commonJS({
26883
26883
  if (k2 === void 0) k2 = k;
26884
26884
  o[k2] = m[k];
26885
26885
  });
26886
- var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v) {
26887
- Object.defineProperty(o, "default", { enumerable: true, value: v });
26888
- } : function(o, v) {
26889
- o["default"] = v;
26886
+ var __setModuleDefault = exports2 && exports2.__setModuleDefault || (Object.create ? function(o, v2) {
26887
+ Object.defineProperty(o, "default", { enumerable: true, value: v2 });
26888
+ } : function(o, v2) {
26889
+ o["default"] = v2;
26890
26890
  });
26891
26891
  var __importStar = exports2 && exports2.__importStar || function(mod) {
26892
26892
  if (mod && mod.__esModule) return mod;
@@ -34619,7 +34619,7 @@ var require_util3 = __commonJS({
34619
34619
  var { InvalidArgumentError, ConnectTimeoutError } = require_errors5();
34620
34620
  var { headerNameLowerCasedRecord } = require_constants3();
34621
34621
  var { tree } = require_tree();
34622
- var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v) => Number(v));
34622
+ var [nodeMajor, nodeMinor] = process.versions.node.split(".", 2).map((v2) => Number(v2));
34623
34623
  var BodyAsyncIterable = class {
34624
34624
  constructor(body) {
34625
34625
  this[kBody] = body;
@@ -35763,14 +35763,14 @@ var require_wrap_handler = __commonJS({
35763
35763
  onRequestUpgrade(controller, statusCode, headers, socket) {
35764
35764
  const rawHeaders = [];
35765
35765
  for (const [key, val] of Object.entries(headers)) {
35766
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
35766
+ rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v2) => Buffer.from(v2)) : Buffer.from(val));
35767
35767
  }
35768
35768
  this.#handler.onUpgrade?.(statusCode, rawHeaders, socket);
35769
35769
  }
35770
35770
  onResponseStart(controller, statusCode, headers, statusMessage) {
35771
35771
  const rawHeaders = [];
35772
35772
  for (const [key, val] of Object.entries(headers)) {
35773
- rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
35773
+ rawHeaders.push(Buffer.from(key), Array.isArray(val) ? val.map((v2) => Buffer.from(v2)) : Buffer.from(val));
35774
35774
  }
35775
35775
  if (this.#handler.onHeaders?.(statusCode, rawHeaders, () => controller.resume(), statusMessage) === false) {
35776
35776
  controller.pause();
@@ -35784,7 +35784,7 @@ var require_wrap_handler = __commonJS({
35784
35784
  onResponseEnd(controller, trailers) {
35785
35785
  const rawTrailers = [];
35786
35786
  for (const [key, val] of Object.entries(trailers)) {
35787
- rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map((v) => Buffer.from(v)) : Buffer.from(val));
35787
+ rawTrailers.push(Buffer.from(key), Array.isArray(val) ? val.map((v2) => Buffer.from(v2)) : Buffer.from(val));
35788
35788
  }
35789
35789
  this.#handler.onComplete?.(rawTrailers);
35790
35790
  }
@@ -44490,8 +44490,8 @@ var require_mock_utils = __commonJS({
44490
44490
  }
44491
44491
  if (value.includes(",")) {
44492
44492
  const values = value.split(",");
44493
- for (const v of values) {
44494
- normalizedQp.append(key, v);
44493
+ for (const v2 of values) {
44494
+ normalizedQp.append(key, v2);
44495
44495
  }
44496
44496
  continue;
44497
44497
  }
@@ -54958,7 +54958,7 @@ var initConfig = async () => {
54958
54958
  return config;
54959
54959
  };
54960
54960
 
54961
- // node_modules/.pnpm/@musistudio+llms@1.0.10_ws@8.18.3_zod@3.25.67/node_modules/@musistudio/llms/dist/esm/server.mjs
54961
+ // node_modules/.pnpm/@musistudio+llms@1.0.11_ws@8.18.3_zod@3.25.67/node_modules/@musistudio/llms/dist/esm/server.mjs
54962
54962
  var import_fastify = __toESM(require_fastify(), 1);
54963
54963
  var import_cors = __toESM(require_cors(), 1);
54964
54964
  var import_fs = require("fs");
@@ -54969,9 +54969,9 @@ var import_undici = __toESM(require_undici(), 1);
54969
54969
  var import_crypto = require("crypto");
54970
54970
  var import_crypto2 = require("crypto");
54971
54971
  var import_node_module = __toESM(require("node:module"), 1);
54972
- var Z = ((s) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(s, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : s)(function(s) {
54972
+ var Z = ((i) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(i, { get: (e, t) => (typeof require < "u" ? require : e)[t] }) : i)(function(i) {
54973
54973
  if (typeof require < "u") return require.apply(this, arguments);
54974
- throw Error('Dynamic require of "' + s + '" is not supported');
54974
+ throw Error('Dynamic require of "' + i + '" is not supported');
54975
54975
  });
54976
54976
  var I = class {
54977
54977
  config = {};
@@ -55037,22 +55037,22 @@ var I = class {
55037
55037
  return this.options.initialConfig && e.push("Initial Config"), this.options.useJsonFile && this.options.jsonPath && e.push(`JSON: ${this.options.jsonPath}`), this.options.useEnvFile && e.push(`ENV: ${this.options.envPath}`), this.options.useEnvironmentVariables && e.push("Environment Variables"), `Config sources: ${e.join(", ")}`;
55038
55038
  }
55039
55039
  };
55040
- function y(...s) {
55041
- if (console.log(...s), !(process.env.LOG === "true")) return;
55042
- let n = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${Array.isArray(s) ? s.map((r) => typeof r == "object" ? JSON.stringify(r) : String(r)).join(" ") : ""}
55040
+ function v(...i) {
55041
+ if (console.log(...i), !(process.env.LOG === "true")) return;
55042
+ let n = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${Array.isArray(i) ? i.map((r) => typeof r == "object" ? JSON.stringify(r) : String(r)).join(" ") : ""}
55043
55043
  `, o = process.env.LOG_FILE || "app.log";
55044
55044
  import_node_fs.default.appendFileSync(o, n, "utf8");
55045
55045
  }
55046
- function L(s, e = 500, t = "internal_error", n = "api_error") {
55047
- let o = new Error(s);
55046
+ function L(i, e = 500, t = "internal_error", n = "api_error") {
55047
+ let o = new Error(i);
55048
55048
  return o.statusCode = e, o.code = t, o.type = n, o;
55049
55049
  }
55050
- async function le(s, e, t) {
55051
- e.log.error(s);
55052
- let n = s.statusCode || 500, o = { error: { message: s.message || "Internal Server Error", type: s.type || "api_error", code: s.code || "internal_error" } };
55050
+ async function le(i, e, t) {
55051
+ e.log.error(i);
55052
+ let n = i.statusCode || 500, o = { error: { message: i.message || "Internal Server Error", type: i.type || "api_error", code: i.code || "internal_error" } };
55053
55053
  return t.code(n).send(o);
55054
55054
  }
55055
- function de(s, e, t) {
55055
+ function de(i, e, t) {
55056
55056
  let n = new Headers({ "Content-Type": "application/json" });
55057
55057
  t.headers && Object.entries(t.headers).forEach(([d, l]) => {
55058
55058
  n.set(d, l);
@@ -55063,54 +55063,54 @@ function de(s, e, t) {
55063
55063
  t.signal.addEventListener("abort", l), r.addEventListener("abort", l), o = d.signal;
55064
55064
  } else o = r;
55065
55065
  let c = { method: "POST", headers: n, body: JSON.stringify(e), signal: o };
55066
- return t.httpsProxy && (c.dispatcher = new import_undici.ProxyAgent(new URL(t.httpsProxy).toString())), y("final request:", typeof s == "string" ? s : s.toString(), t.httpsProxy, c), fetch(typeof s == "string" ? s : s.toString(), c);
55066
+ return t.httpsProxy && (c.dispatcher = new import_undici.ProxyAgent(new URL(t.httpsProxy).toString())), v("final request:", typeof i == "string" ? i : i.toString(), t.httpsProxy, c), fetch(typeof i == "string" ? i : i.toString(), c);
55067
55067
  }
55068
- var ue = async (s) => {
55069
- s.get("/", async (t, n) => ({ message: "LLMs API", version: "1.0.0" })), s.get("/health", async (t, n) => ({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
55070
- let e = s._server.transformerService.getTransformersWithEndpoint();
55071
- for (let { name: t, transformer: n } of e) n.endPoint && s.post(n.endPoint, async (o, r) => {
55072
- let c = o.body, d = o.provider, l = s._server.providerService.getProvider(d);
55068
+ var ue = async (i) => {
55069
+ i.get("/", async (t, n) => ({ message: "LLMs API", version: "1.0.0" })), i.get("/health", async (t, n) => ({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
55070
+ let e = i._server.transformerService.getTransformersWithEndpoint();
55071
+ for (let { name: t, transformer: n } of e) n.endPoint && i.post(n.endPoint, async (o, r) => {
55072
+ let c = o.body, d = o.provider, l = i._server.providerService.getProvider(d);
55073
55073
  if (!l) throw L(`Provider '${d}' not found`, 404, "provider_not_found");
55074
- let i = c, p = {};
55074
+ let s = c, p = {};
55075
55075
  if (typeof n.transformRequestOut == "function") {
55076
55076
  let a = await n.transformRequestOut(c);
55077
- a.body ? (i = a.body, p = a.config || {}) : i = a;
55077
+ a.body ? (s = a.body, p = a.config || {}) : s = a;
55078
55078
  }
55079
- if (y("use transformers:", l.transformer?.use), l.transformer?.use?.length) for (let a of l.transformer.use) {
55079
+ if (v("use transformers:", l.transformer?.use), l.transformer?.use?.length) for (let a of l.transformer.use) {
55080
55080
  if (!a || typeof a.transformRequestIn != "function") continue;
55081
- let v = await a.transformRequestIn(i, l);
55082
- v.body ? (i = v.body, p = { ...p, ...v.config }) : i = v;
55081
+ let y = await a.transformRequestIn(s, l);
55082
+ y.body ? (s = y.body, p = { ...p, ...y.config }) : s = y;
55083
55083
  }
55084
- if (l.transformer?.[o.body.model]?.use?.length) for (let a of l.transformer[o.body.model].use) !a || typeof a.transformRequestIn != "function" || (i = await a.transformRequestIn(i, l));
55085
- let _ = p.url || new URL(l.baseUrl), k = await de(_, i, { httpsProxy: s._server.configService.getHttpsProxy(), ...p, headers: { Authorization: `Bearer ${l.apiKey}`, ...p?.headers || {} } });
55084
+ if (l.transformer?.[o.body.model]?.use?.length) for (let a of l.transformer[o.body.model].use) !a || typeof a.transformRequestIn != "function" || (s = await a.transformRequestIn(s, l));
55085
+ let _ = p.url || new URL(l.baseUrl), k = await de(_, s, { httpsProxy: i._server.configService.getHttpsProxy(), ...p, headers: { Authorization: `Bearer ${l.apiKey}`, ...p?.headers || {} } });
55086
55086
  if (!k.ok) {
55087
55087
  let a = await k.text();
55088
- throw y(`Error response from ${_}: ${a}`), L(`Error from provider: ${a}`, k.status, "provider_response_error");
55088
+ throw v(`Error response from ${_}: ${a}`), L(`Error from provider: ${a}`, k.status, "provider_response_error");
55089
55089
  }
55090
55090
  let g = k;
55091
55091
  if (l.transformer?.use?.length) for (let a of l.transformer.use) !a || typeof a.transformResponseOut != "function" || (g = await a.transformResponseOut(g));
55092
55092
  if (l.transformer?.[o.body.model]?.use?.length) for (let a of l.transformer[o.body.model].use) !a || typeof a.transformResponseOut != "function" || (g = await a.transformResponseOut(g));
55093
55093
  return n.transformResponseIn && (g = await n.transformResponseIn(g)), g.ok || r.code(g.status), c?.stream === true ? (r.header("Content-Type", "text/event-stream"), r.header("Cache-Control", "no-cache"), r.header("Connection", "keep-alive"), r.send(g.body)) : g.json();
55094
55094
  });
55095
- s.post("/providers", { schema: { body: { type: "object", properties: { id: { type: "string" }, name: { type: "string" }, type: { type: "string", enum: ["openai", "anthropic"] }, baseUrl: { type: "string" }, apiKey: { type: "string" }, models: { type: "array", items: { type: "string" } } }, required: ["id", "name", "type", "baseUrl", "apiKey", "models"] } } }, async (t, n) => {
55095
+ i.post("/providers", { schema: { body: { type: "object", properties: { id: { type: "string" }, name: { type: "string" }, type: { type: "string", enum: ["openai", "anthropic"] }, baseUrl: { type: "string" }, apiKey: { type: "string" }, models: { type: "array", items: { type: "string" } } }, required: ["id", "name", "type", "baseUrl", "apiKey", "models"] } } }, async (t, n) => {
55096
55096
  let { name: o, type: r, baseUrl: c, apiKey: d, models: l } = t.body;
55097
55097
  if (!o?.trim()) throw L("Provider name is required", 400, "invalid_request");
55098
55098
  if (!c || !Ce(c)) throw L("Valid base URL is required", 400, "invalid_request");
55099
55099
  if (!d?.trim()) throw L("API key is required", 400, "invalid_request");
55100
55100
  if (!l || !Array.isArray(l) || l.length === 0) throw L("At least one model is required", 400, "invalid_request");
55101
- if (s._server.providerService.getProvider(id)) throw L(`Provider with ID '${id}' already exists`, 400, "provider_exists");
55102
- return s._server.providerService.registerProvider(t.body);
55103
- }), s.get("/providers", async (t, n) => s._server.providerService.getProviders()), s.get("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => {
55104
- let o = s._server.providerService.getProvider(t.params.id);
55101
+ if (i._server.providerService.getProvider(id)) throw L(`Provider with ID '${id}' already exists`, 400, "provider_exists");
55102
+ return i._server.providerService.registerProvider(t.body);
55103
+ }), i.get("/providers", async (t, n) => i._server.providerService.getProviders()), i.get("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => {
55104
+ let o = i._server.providerService.getProvider(t.params.id);
55105
55105
  return o || n.code(404).send({ error: "Provider not found" });
55106
- }), s.put("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, body: { type: "object", properties: { name: { type: "string" }, type: { type: "string", enum: ["openai", "anthropic"] }, baseUrl: { type: "string" }, apiKey: { type: "string" }, models: { type: "array", items: { type: "string" } }, enabled: { type: "boolean" } } } } }, async (t, n) => {
55107
- let o = s._server.providerService.updateProvider(t.params.id, t.body);
55106
+ }), i.put("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, body: { type: "object", properties: { name: { type: "string" }, type: { type: "string", enum: ["openai", "anthropic"] }, baseUrl: { type: "string" }, apiKey: { type: "string" }, models: { type: "array", items: { type: "string" } }, enabled: { type: "boolean" } } } } }, async (t, n) => {
55107
+ let o = i._server.providerService.updateProvider(t.params.id, t.body);
55108
55108
  return o || n.code(404).send({ error: "Provider not found" });
55109
- }), s.delete("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => s._server.providerService.deleteProvider(t.params.id) ? { message: "Provider deleted successfully" } : n.code(404).send({ error: "Provider not found" })), s.patch("/providers/:id/toggle", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, body: { type: "object", properties: { enabled: { type: "boolean" } }, required: ["enabled"] } } }, async (t, n) => s._server.providerService.toggleProvider(t.params.id, t.body.enabled) ? { message: `Provider ${t.body.enabled ? "enabled" : "disabled"} successfully` } : n.code(404).send({ error: "Provider not found" }));
55109
+ }), i.delete("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => i._server.providerService.deleteProvider(t.params.id) ? { message: "Provider deleted successfully" } : n.code(404).send({ error: "Provider not found" })), i.patch("/providers/:id/toggle", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] }, body: { type: "object", properties: { enabled: { type: "boolean" } }, required: ["enabled"] } } }, async (t, n) => i._server.providerService.toggleProvider(t.params.id, t.body.enabled) ? { message: `Provider ${t.body.enabled ? "enabled" : "disabled"} successfully` } : n.code(404).send({ error: "Provider not found" }));
55110
55110
  };
55111
- function Ce(s) {
55111
+ function Ce(i) {
55112
55112
  try {
55113
- return new URL(s), true;
55113
+ return new URL(i), true;
55114
55114
  } catch {
55115
55115
  return false;
55116
55116
  }
@@ -55186,9 +55186,9 @@ var q = class {
55186
55186
  }
55187
55187
  if (typeof r == "string") return this.transformerService.getTransformer(r);
55188
55188
  }).filter((r) => typeof r < "u") });
55189
- }), this.registerProvider({ name: t.name, baseUrl: t.api_base_url, apiKey: t.api_key, models: t.models || [], transformer: t.transformer ? n : void 0 }), y(`${t.name} provider registered`);
55189
+ }), this.registerProvider({ name: t.name, baseUrl: t.api_base_url, apiKey: t.api_key, models: t.models || [], transformer: t.transformer ? n : void 0 }), v(`${t.name} provider registered`);
55190
55190
  } catch (n) {
55191
- y(`${t.name} provider registered error: ${n}`);
55191
+ v(`${t.name} provider registered error: ${n}`);
55192
55192
  }
55193
55193
  });
55194
55194
  }
@@ -55263,9 +55263,9 @@ var q = class {
55263
55263
  }
55264
55264
  };
55265
55265
  var T = [];
55266
- for (let s = 0; s < 256; ++s) T.push((s + 256).toString(16).slice(1));
55267
- function fe(s, e = 0) {
55268
- return (T[s[e + 0]] + T[s[e + 1]] + T[s[e + 2]] + T[s[e + 3]] + "-" + T[s[e + 4]] + T[s[e + 5]] + "-" + T[s[e + 6]] + T[s[e + 7]] + "-" + T[s[e + 8]] + T[s[e + 9]] + "-" + T[s[e + 10]] + T[s[e + 11]] + T[s[e + 12]] + T[s[e + 13]] + T[s[e + 14]] + T[s[e + 15]]).toLowerCase();
55266
+ for (let i = 0; i < 256; ++i) T.push((i + 256).toString(16).slice(1));
55267
+ function fe(i, e = 0) {
55268
+ return (T[i[e + 0]] + T[i[e + 1]] + T[i[e + 2]] + T[i[e + 3]] + "-" + T[i[e + 4]] + T[i[e + 5]] + "-" + T[i[e + 6]] + T[i[e + 7]] + "-" + T[i[e + 8]] + T[i[e + 9]] + "-" + T[i[e + 10]] + T[i[e + 11]] + T[i[e + 12]] + T[i[e + 13]] + T[i[e + 14]] + T[i[e + 15]]).toLowerCase();
55269
55269
  }
55270
55270
  var J = new Uint8Array(256);
55271
55271
  var U = J.length;
@@ -55273,10 +55273,10 @@ function ee() {
55273
55273
  return U > J.length - 16 && ((0, import_crypto.randomFillSync)(J), U = 0), J.slice(U, U += 16);
55274
55274
  }
55275
55275
  var te = { randomUUID: import_crypto2.randomUUID };
55276
- function Re(s, e, t) {
55277
- if (te.randomUUID && !e && !s) return te.randomUUID();
55278
- s = s || {};
55279
- let n = s.random ?? s.rng?.() ?? ee();
55276
+ function Re(i, e, t) {
55277
+ if (te.randomUUID && !e && !i) return te.randomUUID();
55278
+ i = i || {};
55279
+ let n = i.random ?? i.rng?.() ?? ee();
55280
55280
  if (n.length < 16) throw new Error("Random bytes length must be >= 16");
55281
55281
  if (n[6] = n[6] & 15 | 64, n[8] = n[8] & 63 | 128, e) {
55282
55282
  if (t = t || 0, t < 0 || t + 16 > e.length) throw new RangeError(`UUID byte range ${t}:${t + 15} is out of buffer bounds`);
@@ -55290,7 +55290,7 @@ var j = class {
55290
55290
  name = "Anthropic";
55291
55291
  endPoint = "/v1/messages";
55292
55292
  async transformRequestOut(e) {
55293
- y("Anthropic Request:", JSON.stringify(e, null, 2));
55293
+ v("Anthropic Request:", JSON.stringify(e, null, 2));
55294
55294
  let t = [];
55295
55295
  if (e.system) {
55296
55296
  if (typeof e.system == "string") t.push({ role: "system", content: e.system });
@@ -55307,19 +55307,19 @@ var j = class {
55307
55307
  }
55308
55308
  if (Array.isArray(r.content)) {
55309
55309
  if (r.role === "user") {
55310
- let d = r.content.filter((i) => i.type === "tool_result" && i.tool_use_id);
55311
- d.length && d.forEach((i, p) => {
55312
- let _ = { role: "tool", content: typeof i.content == "string" ? i.content : JSON.stringify(i.content), tool_call_id: i.tool_use_id, cache_control: i.cache_control };
55310
+ let d = r.content.filter((s) => s.type === "tool_result" && s.tool_use_id);
55311
+ d.length && d.forEach((s, p) => {
55312
+ let _ = { role: "tool", content: typeof s.content == "string" ? s.content : JSON.stringify(s.content), tool_call_id: s.tool_use_id, cache_control: s.cache_control };
55313
55313
  t.push(_);
55314
55314
  });
55315
- let l = r.content.filter((i) => i.type === "text" && i.text || i.type === "image" && i.source);
55316
- l.length && t.push({ role: "user", content: l.map((i) => i?.type === "image" ? { type: "image_url", image_url: { url: i.source?.type === "base64" ? i.source.data : i.source.url }, media_type: i.source.media_type } : i) });
55315
+ let l = r.content.filter((s) => s.type === "text" && s.text || s.type === "image" && s.source);
55316
+ l.length && t.push({ role: "user", content: l.map((s) => s?.type === "image" ? { type: "image_url", image_url: { url: s.source?.type === "base64" ? s.source.data : s.source.url }, media_type: s.source.media_type } : s) });
55317
55317
  } else if (r.role === "assistant") {
55318
55318
  let d = { role: "assistant", content: null }, l = r.content.filter((p) => p.type === "text" && p.text);
55319
55319
  l.length && (d.content = l.map((p) => p.text).join(`
55320
55320
  `));
55321
- let i = r.content.filter((p) => p.type === "tool_use" && p.id);
55322
- i.length && (d.tool_calls = i.map((p) => ({ id: p.id, type: "function", function: { name: p.name, arguments: JSON.stringify(p.input || {}) } }))), t.push(d);
55321
+ let s = r.content.filter((p) => p.type === "tool_use" && p.id);
55322
+ s.length && (d.tool_calls = s.map((p) => ({ id: p.id, type: "function", function: { name: p.name, arguments: JSON.stringify(p.input || {}) } }))), t.push(d);
55323
55323
  }
55324
55324
  return;
55325
55325
  }
@@ -55341,14 +55341,14 @@ var j = class {
55341
55341
  }
55342
55342
  async convertOpenAIStreamToAnthropic(e) {
55343
55343
  return new ReadableStream({ async start(n) {
55344
- let o = new TextEncoder(), r = `msg_${Date.now()}`, c = "unknown", d = false, l = false, i = false, p = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map(), k = 0, g = 0, u = 0, a = false, v = false, h = 0, f = (x) => {
55344
+ let o = new TextEncoder(), r = `msg_${Date.now()}`, c = "unknown", d = false, l = false, s = false, p = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map(), k = 0, g = 0, u = 0, a = false, y = false, h = 0, f = (x) => {
55345
55345
  if (!a) try {
55346
55346
  n.enqueue(x);
55347
55347
  let b = new TextDecoder().decode(x);
55348
- y("send data:", b.trim());
55348
+ v("send data:", b.trim());
55349
55349
  } catch (b) {
55350
55350
  if (b instanceof TypeError && b.message.includes("Controller is already closed")) a = true;
55351
- else throw y(`send data error: ${b.message}`), b;
55351
+ else throw v(`send data error: ${b.message}`), b;
55352
55352
  }
55353
55353
  }, m = () => {
55354
55354
  if (!a) try {
@@ -55369,12 +55369,12 @@ var j = class {
55369
55369
  `);
55370
55370
  b = se.pop() || "";
55371
55371
  for (let ie of se) {
55372
- if (a || i) break;
55372
+ if (a || s) break;
55373
55373
  if (!ie.startsWith("data: ")) continue;
55374
55374
  let Q = ie.slice(6);
55375
55375
  if (Q !== "[DONE]") try {
55376
55376
  let O = JSON.parse(Q);
55377
- if (k++, y("Original Response:", JSON.stringify(O, null, 2)), O.error) {
55377
+ if (k++, v("Original Response:", JSON.stringify(O, null, 2)), O.error) {
55378
55378
  let C = { type: "error", message: { type: "api_error", message: JSON.stringify(O.error) } };
55379
55379
  f(o.encode(`event: error
55380
55380
  data: ${JSON.stringify(C)}
@@ -55382,7 +55382,7 @@ data: ${JSON.stringify(C)}
55382
55382
  `));
55383
55383
  continue;
55384
55384
  }
55385
- if (c = O.model || c, !d && !a && !i) {
55385
+ if (c = O.model || c, !d && !a && !s) {
55386
55386
  d = true;
55387
55387
  let C = { type: "message_start", message: { id: r, type: "message", role: "assistant", content: [], model: c, stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } } };
55388
55388
  f(o.encode(`event: message_start
@@ -55392,13 +55392,13 @@ data: ${JSON.stringify(C)}
55392
55392
  }
55393
55393
  let w = O.choices?.[0];
55394
55394
  if (!w) continue;
55395
- if (w?.delta?.thinking && !a && !i) {
55396
- if (!v) {
55395
+ if (w?.delta?.thinking && !a && !s) {
55396
+ if (!y) {
55397
55397
  let C = { type: "content_block_start", index: h, content_block: { type: "thinking", thinking: "" } };
55398
55398
  f(o.encode(`event: content_block_start
55399
55399
  data: ${JSON.stringify(C)}
55400
55400
 
55401
- `)), v = true;
55401
+ `)), y = true;
55402
55402
  }
55403
55403
  if (w.delta.thinking.signature) {
55404
55404
  let C = { type: "content_block_delta", index: h, delta: { type: "signature_delta", signature: w.delta.thinking.signature } };
@@ -55419,8 +55419,8 @@ data: ${JSON.stringify(C)}
55419
55419
  `));
55420
55420
  }
55421
55421
  }
55422
- if (w?.delta?.content && !a && !i) {
55423
- if (g++, !l && !i) {
55422
+ if (w?.delta?.content && !a && !s) {
55423
+ if (g++, !l && !s) {
55424
55424
  l = true;
55425
55425
  let C = { type: "content_block_start", index: h, content_block: { type: "text", text: "" } };
55426
55426
  f(o.encode(`event: content_block_start
@@ -55428,7 +55428,7 @@ data: ${JSON.stringify(C)}
55428
55428
 
55429
55429
  `));
55430
55430
  }
55431
- if (!a && !i) {
55431
+ if (!a && !s) {
55432
55432
  let C = { type: "content_block_delta", index: h, delta: { type: "text_delta", text: w.delta.content } };
55433
55433
  f(o.encode(`event: content_block_delta
55434
55434
  data: ${JSON.stringify(C)}
@@ -55436,7 +55436,7 @@ data: ${JSON.stringify(C)}
55436
55436
  `));
55437
55437
  }
55438
55438
  }
55439
- if (w?.delta?.annotations?.length && !a && !i) {
55439
+ if (w?.delta?.annotations?.length && !a && !s) {
55440
55440
  let C = { type: "content_block_stop", index: h };
55441
55441
  f(o.encode(`event: content_block_stop
55442
55442
  data: ${JSON.stringify(C)}
@@ -55455,7 +55455,7 @@ data: ${JSON.stringify(A)}
55455
55455
  `));
55456
55456
  });
55457
55457
  }
55458
- if (w?.delta?.tool_calls && !a && !i) {
55458
+ if (w?.delta?.tool_calls && !a && !s) {
55459
55459
  u++;
55460
55460
  let C = /* @__PURE__ */ new Set();
55461
55461
  for (let R of w.delta.tool_calls) {
@@ -55465,7 +55465,7 @@ data: ${JSON.stringify(A)}
55465
55465
  if (C.add(P), !_.has(P)) {
55466
55466
  let E = l ? _.size + 1 : _.size;
55467
55467
  if (E !== 0) {
55468
- y("content_block_stop2");
55468
+ v("content_block_stop2");
55469
55469
  let ge = { type: "content_block_stop", index: h };
55470
55470
  f(o.encode(`event: content_block_stop
55471
55471
  data: ${JSON.stringify(ge)}
@@ -55473,56 +55473,56 @@ data: ${JSON.stringify(ge)}
55473
55473
  `)), h++;
55474
55474
  }
55475
55475
  _.set(P, E);
55476
- let A = R.id || `call_${Date.now()}_${P}`, M = R.function?.name || `tool_${P}`, N = { type: "content_block_start", index: h, content_block: { type: "tool_use", id: A, name: M, input: {} } };
55476
+ let A = R.id || `call_${Date.now()}_${P}`, N = R.function?.name || `tool_${P}`, M = { type: "content_block_start", index: h, content_block: { type: "tool_use", id: A, name: N, input: {} } };
55477
55477
  f(o.encode(`event: content_block_start
55478
- data: ${JSON.stringify(N)}
55478
+ data: ${JSON.stringify(M)}
55479
55479
 
55480
55480
  `));
55481
- let $ = { id: A, name: M, arguments: "", contentBlockIndex: E };
55481
+ let $ = { id: A, name: N, arguments: "", contentBlockIndex: E };
55482
55482
  p.set(P, $);
55483
55483
  } else if (R.id && R.function?.name) {
55484
55484
  let E = p.get(P);
55485
55485
  E.id.startsWith("call_") && E.name.startsWith("tool_") && (E.id = R.id, E.name = R.function.name);
55486
55486
  }
55487
- if (R.function?.arguments && !a && !i) {
55487
+ if (R.function?.arguments && !a && !s) {
55488
55488
  if (_.get(P) === void 0) continue;
55489
55489
  let A = p.get(P);
55490
55490
  if (A) {
55491
55491
  A.arguments += R.function.arguments;
55492
55492
  try {
55493
- let M = null, N = A.arguments.trim();
55494
- if (N.startsWith("{") && N.endsWith("}")) try {
55495
- M = JSON.parse(N);
55493
+ let N = null, M = A.arguments.trim();
55494
+ if (M.startsWith("{") && M.endsWith("}")) try {
55495
+ N = JSON.parse(M);
55496
55496
  } catch ($) {
55497
- y("Tool call index:", P, "error", $.message);
55497
+ v("Tool call index:", P, "error", $.message);
55498
55498
  }
55499
- } catch (M) {
55500
- y("Tool call index:", P, "error", M.message);
55499
+ } catch (N) {
55500
+ v("Tool call index:", P, "error", N.message);
55501
55501
  }
55502
55502
  }
55503
55503
  try {
55504
- let M = { type: "content_block_delta", index: h, delta: { type: "input_json_delta", partial_json: R.function.arguments } };
55504
+ let N = { type: "content_block_delta", index: h, delta: { type: "input_json_delta", partial_json: R.function.arguments } };
55505
55505
  f(o.encode(`event: content_block_delta
55506
- data: ${JSON.stringify(M)}
55506
+ data: ${JSON.stringify(N)}
55507
55507
 
55508
55508
  `));
55509
55509
  } catch {
55510
55510
  try {
55511
- let N = R.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"'), $ = { type: "content_block_delta", index: h, delta: { type: "input_json_delta", partial_json: N } };
55511
+ let M = R.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"'), $ = { type: "content_block_delta", index: h, delta: { type: "input_json_delta", partial_json: M } };
55512
55512
  f(o.encode(`event: content_block_delta
55513
55513
  data: ${JSON.stringify($)}
55514
55514
 
55515
55515
  `));
55516
- } catch (N) {
55517
- console.error(N);
55516
+ } catch (M) {
55517
+ console.error(M);
55518
55518
  }
55519
55519
  }
55520
55520
  }
55521
55521
  }
55522
55522
  }
55523
- if (w?.finish_reason && !a && !i) {
55524
- if (i = true, g === 0 && u === 0 && console.error("Warning: No content in the stream response!"), (l || u > 0) && !a) {
55525
- y("content_block_stop hasTextContentStarted");
55523
+ if (w?.finish_reason && !a && !s) {
55524
+ if (s = true, g === 0 && u === 0 && console.error("Warning: No content in the stream response!"), (l || u > 0) && !a) {
55525
+ v("content_block_stop hasTextContentStarted");
55526
55526
  let C = { type: "content_block_stop", index: h };
55527
55527
  f(o.encode(`event: content_block_stop
55528
55528
  data: ${JSON.stringify(C)}
@@ -55546,7 +55546,7 @@ data: ${JSON.stringify(C)}
55546
55546
  break;
55547
55547
  }
55548
55548
  } catch (O) {
55549
- y(`parseError: ${O.name} message: ${O.message} stack: ${O.stack} data: ${Q}`);
55549
+ v(`parseError: ${O.name} message: ${O.message} stack: ${O.stack} data: ${Q}`);
55550
55550
  }
55551
55551
  }
55552
55552
  }
@@ -55565,11 +55565,11 @@ data: ${JSON.stringify(C)}
55565
55565
  }
55566
55566
  }
55567
55567
  }, cancel(n) {
55568
- y("cancle stream:", n);
55568
+ v("cancle stream:", n);
55569
55569
  } });
55570
55570
  }
55571
55571
  convertOpenAIResponseToAnthropic(e) {
55572
- y("Original OpenAI response:", JSON.stringify(e, null, 2));
55572
+ v("Original OpenAI response:", JSON.stringify(e, null, 2));
55573
55573
  let t = e.choices[0];
55574
55574
  if (!t) throw new Error("No choices found in OpenAI response");
55575
55575
  let n = [];
@@ -55588,17 +55588,17 @@ data: ${JSON.stringify(C)}
55588
55588
  n.push({ type: "tool_use", id: r.id, name: r.function.name, input: d });
55589
55589
  });
55590
55590
  let o = { id: e.id, type: "message", role: "assistant", model: e.model, content: n, stop_reason: t.finish_reason === "stop" ? "end_turn" : t.finish_reason === "length" ? "max_tokens" : t.finish_reason === "tool_calls" ? "tool_use" : t.finish_reason === "content_filter" ? "stop_sequence" : "end_turn", stop_sequence: null, usage: { input_tokens: e.usage?.prompt_tokens || 0, output_tokens: e.usage?.completion_tokens || 0 } };
55591
- return y("Conversion complete, final Anthropic response:", JSON.stringify(o, null, 2)), o;
55591
+ return v("Conversion complete, final Anthropic response:", JSON.stringify(o, null, 2)), o;
55592
55592
  }
55593
55593
  };
55594
- function ne(s) {
55595
- if (!(!s || typeof s != "object")) {
55596
- if (Array.isArray(s)) {
55597
- s.forEach(ne);
55594
+ function ne(i) {
55595
+ if (!(!i || typeof i != "object")) {
55596
+ if (Array.isArray(i)) {
55597
+ i.forEach(ne);
55598
55598
  return;
55599
55599
  }
55600
- delete s.$schema, delete s.additionalProperties, s.type === "string" && s.format && !["enum", "date-time"].includes(s.format) && delete s.format, Object.keys(s).forEach((e) => {
55601
- ne(s[e]);
55600
+ delete i.$schema, delete i.additionalProperties, i.type === "string" && i.format && !["enum", "date-time"].includes(i.format) && delete i.format, Object.keys(i).forEach((e) => {
55601
+ ne(i[e]);
55602
55602
  });
55603
55603
  }
55604
55604
  }
@@ -55606,25 +55606,26 @@ var D = class {
55606
55606
  name = "gemini";
55607
55607
  endPoint = "/v1beta/models/:modelAndAction";
55608
55608
  async transformRequestIn(e, t) {
55609
- return { body: { contents: e.messages.map((n) => {
55610
- let o;
55611
- n.role === "assistant" ? o = "model" : (["user", "system", "tool"].includes(n.role), o = "user");
55612
- let r = [];
55613
- return typeof n.content == "string" ? r.push({ text: n.content }) : Array.isArray(n.content) && r.push(...n.content.map((c) => {
55614
- if (c.type === "text") return { text: c.text || "" };
55615
- if (c.type === "image_url") return c.image_url.url.startsWith("http") ? { file_data: { mime_type: c.media_type, file_uri: c.image_url.url } } : { inlineData: { mime_type: c.media_type, data: c.image_url.url } };
55616
- })), Array.isArray(n.tool_calls) && r.push(...n.tool_calls.map((c) => ({ functionCall: { id: c.id || `tool_${Math.random().toString(36).substring(2, 15)}`, name: c.function.name, args: JSON.parse(c.function.arguments || "{}") } }))), { role: o, parts: r };
55617
- }), tools: [{ functionDeclarations: e.tools?.filter((n) => n.function.name !== "web_search")?.map((n) => (n.function.parameters && ne(n.function.parameters), { name: n.function.name, description: n.function.description, parameters: n.function.parameters })) || [] }, e.tools?.find((n) => n.function.name === "web_search") ? { google_search: {} } : void 0] }, config: { url: new URL(`./${e.model}:${e.stream ? "streamGenerateContent?alt=sse" : "generateContent"}`, t.baseUrl), headers: { "x-goog-api-key": t.apiKey, Authorization: void 0 } } };
55609
+ let n = [], o = e.tools?.filter((c) => c.function.name !== "web_search")?.map((c) => (c.function.parameters && ne(c.function.parameters), { name: c.function.name, description: c.function.description, parameters: c.function.parameters }));
55610
+ return o?.length && n.push({ functionDeclarations: o }), e.tools?.find((c) => c.function.name === "web_search") && n.push({ google_search: {} }), { body: { contents: e.messages.map((c) => {
55611
+ let d;
55612
+ c.role === "assistant" ? d = "model" : (["user", "system", "tool"].includes(c.role), d = "user");
55613
+ let l = [];
55614
+ return typeof c.content == "string" ? l.push({ text: c.content }) : Array.isArray(c.content) && l.push(...c.content.map((s) => {
55615
+ if (s.type === "text") return { text: s.text || "" };
55616
+ if (s.type === "image_url") return s.image_url.url.startsWith("http") ? { file_data: { mime_type: s.media_type, file_uri: s.image_url.url } } : { inlineData: { mime_type: s.media_type, data: s.image_url.url } };
55617
+ })), Array.isArray(c.tool_calls) && l.push(...c.tool_calls.map((s) => ({ functionCall: { id: s.id || `tool_${Math.random().toString(36).substring(2, 15)}`, name: s.function.name, args: JSON.parse(s.function.arguments || "{}") } }))), { role: d, parts: l };
55618
+ }), tools: n.length ? n : void 0 }, config: { url: new URL(`./${e.model}:${e.stream ? "streamGenerateContent?alt=sse" : "generateContent"}`, t.baseUrl), headers: { "x-goog-api-key": t.apiKey, Authorization: void 0 } } };
55618
55619
  }
55619
55620
  transformRequestOut(e) {
55620
- let t = e.contents, n = e.tools, o = e.model, r = e.max_tokens, c = e.temperature, d = e.stream, l = e.tool_choice, i = { messages: [], model: o, max_tokens: r, temperature: c, stream: d, tool_choice: l };
55621
+ let t = e.contents, n = e.tools, o = e.model, r = e.max_tokens, c = e.temperature, d = e.stream, l = e.tool_choice, s = { messages: [], model: o, max_tokens: r, temperature: c, stream: d, tool_choice: l };
55621
55622
  return Array.isArray(t) && t.forEach((p) => {
55622
- typeof p == "string" ? i.messages.push({ role: "user", content: p }) : typeof p.text == "string" ? i.messages.push({ role: "user", content: p.text || null }) : p.role === "user" ? i.messages.push({ role: "user", content: p?.parts?.map((_) => ({ type: "text", text: _.text || "" })) || [] }) : p.role === "model" && i.messages.push({ role: "assistant", content: p?.parts?.map((_) => ({ type: "text", text: _.text || "" })) || [] });
55623
- }), Array.isArray(n) && (i.tools = [], n.forEach((p) => {
55623
+ typeof p == "string" ? s.messages.push({ role: "user", content: p }) : typeof p.text == "string" ? s.messages.push({ role: "user", content: p.text || null }) : p.role === "user" ? s.messages.push({ role: "user", content: p?.parts?.map((_) => ({ type: "text", text: _.text || "" })) || [] }) : p.role === "model" && s.messages.push({ role: "assistant", content: p?.parts?.map((_) => ({ type: "text", text: _.text || "" })) || [] });
55624
+ }), Array.isArray(n) && (s.tools = [], n.forEach((p) => {
55624
55625
  Array.isArray(p.functionDeclarations) && p.functionDeclarations.forEach((_) => {
55625
- i.tools.push({ type: "function", function: { name: _.name, description: _.description, parameters: _.parameters } });
55626
+ s.tools.push({ type: "function", function: { name: _.name, description: _.description, parameters: _.parameters } });
55626
55627
  });
55627
- })), i;
55628
+ })), s;
55628
55629
  }
55629
55630
  async transformResponseOut(e) {
55630
55631
  if (e.headers.get("Content-Type")?.includes("application/json")) {
@@ -55637,20 +55638,18 @@ var D = class {
55637
55638
  if (c.startsWith("data: ")) {
55638
55639
  let l = c.slice(6).trim();
55639
55640
  if (l) {
55640
- y("gemini chunk:", l);
55641
+ v("gemini chunk:", l);
55641
55642
  try {
55642
- let i = JSON.parse(l);
55643
- y("groundingMetadata: ", JSON.stringify(i.candidates[0].groundingMetadata));
55644
- let p = i.candidates[0].content.parts?.filter((k) => k.functionCall)?.map((k) => ({ id: k.functionCall?.id || `tool_${Math.random().toString(36).substring(2, 15)}`, type: "function", function: { name: k.functionCall?.name, arguments: JSON.stringify(k.functionCall?.args || {}) } })), _ = { choices: [{ delta: { role: "assistant", content: i.candidates[0].content.parts?.filter((k) => k.text)?.map((k) => k.text)?.join(`
55645
- `), tool_calls: p.length > 0 ? p : void 0 }, finish_reason: i.candidates[0].finishReason?.toLowerCase() || null, index: i.candidates[0].index || p.length > 0 ? 1 : 0, logprobs: null }], created: parseInt((/* @__PURE__ */ new Date()).getTime() / 1e3 + "", 10), id: i.responseId || "", model: i.modelVersion || "", object: "chat.completion.chunk", system_fingerprint: "fp_a49d71b8a1", usage: { completion_tokens: i.usageMetadata.candidatesTokenCount, prompt_tokens: i.usageMetadata.promptTokenCount, total_tokens: i.usageMetadata.totalTokenCount } };
55646
- i.candidates[0]?.groundingMetadata?.groundingChunks?.length && (_.choices[0].delta.annotations = i.candidates[0].groundingMetadata.groundingChunks.map((k, g) => {
55647
- let u = i.candidates[0]?.groundingMetadata?.groundingSupports?.filter((a) => a.groundingChunkIndices.includes(g));
55643
+ let s = JSON.parse(l), p = s.candidates[0].content.parts?.filter((k) => k.functionCall)?.map((k) => ({ id: k.functionCall?.id || `tool_${Math.random().toString(36).substring(2, 15)}`, type: "function", function: { name: k.functionCall?.name, arguments: JSON.stringify(k.functionCall?.args || {}) } })), _ = { choices: [{ delta: { role: "assistant", content: s.candidates[0].content.parts?.filter((k) => k.text)?.map((k) => k.text)?.join(`
55644
+ `), tool_calls: p.length > 0 ? p : void 0 }, finish_reason: s.candidates[0].finishReason?.toLowerCase() || null, index: s.candidates[0].index || p.length > 0 ? 1 : 0, logprobs: null }], created: parseInt((/* @__PURE__ */ new Date()).getTime() / 1e3 + "", 10), id: s.responseId || "", model: s.modelVersion || "", object: "chat.completion.chunk", system_fingerprint: "fp_a49d71b8a1", usage: { completion_tokens: s.usageMetadata.candidatesTokenCount, prompt_tokens: s.usageMetadata.promptTokenCount, total_tokens: s.usageMetadata.totalTokenCount } };
55645
+ s.candidates[0]?.groundingMetadata?.groundingChunks?.length && (_.choices[0].delta.annotations = s.candidates[0].groundingMetadata.groundingChunks.map((k, g) => {
55646
+ let u = s.candidates[0]?.groundingMetadata?.groundingSupports?.filter((a) => a.groundingChunkIndices.includes(g));
55648
55647
  return { type: "url_citation", url_citation: { url: k.web.uri, title: k.web.title, content: u?.[0].segment.text, start_index: u?.[0].segment.startIndex, end_index: u?.[0].segment.endIndex } };
55649
55648
  })), d.enqueue(n.encode(`data: ${JSON.stringify(_)}
55650
55649
 
55651
55650
  `));
55652
- } catch (i) {
55653
- y("Error parsing Gemini stream chunk", l, i.message);
55651
+ } catch (s) {
55652
+ v("Error parsing Gemini stream chunk", l, s.message);
55654
55653
  }
55655
55654
  }
55656
55655
  }
@@ -55658,8 +55657,8 @@ var D = class {
55658
55657
  let d = e.body.getReader(), l = "";
55659
55658
  try {
55660
55659
  for (; ; ) {
55661
- let { done: i, value: p } = await d.read();
55662
- if (i) {
55660
+ let { done: s, value: p } = await d.read();
55661
+ if (s) {
55663
55662
  l && o(l, c);
55664
55663
  break;
55665
55664
  }
@@ -55669,8 +55668,8 @@ var D = class {
55669
55668
  l = _.pop() || "";
55670
55669
  for (let k of _) o(k, c);
55671
55670
  }
55672
- } catch (i) {
55673
- c.error(i);
55671
+ } catch (s) {
55672
+ c.error(s);
55674
55673
  } finally {
55675
55674
  c.close();
55676
55675
  }
@@ -55695,8 +55694,8 @@ var B = class {
55695
55694
  let l = e.body.getReader();
55696
55695
  try {
55697
55696
  for (; ; ) {
55698
- let { done: i, value: p } = await l.read();
55699
- if (i) break;
55697
+ let { done: s, value: p } = await l.read();
55698
+ if (s) break;
55700
55699
  let k = t.decode(p, { stream: true }).split(`
55701
55700
  `);
55702
55701
  for (let g of k) if (g.startsWith("data: ") && g.trim() !== "data: [DONE]") try {
@@ -55705,17 +55704,17 @@ var B = class {
55705
55704
  o += u.choices[0].delta.reasoning_content;
55706
55705
  let a = { ...u, choices: [{ ...u.choices[0], delta: { ...u.choices[0].delta, thinking: { content: u.choices[0].delta.reasoning_content } } }] };
55707
55706
  delete a.choices[0].delta.reasoning_content;
55708
- let v = `data: ${JSON.stringify(a)}
55707
+ let y = `data: ${JSON.stringify(a)}
55709
55708
 
55710
55709
  `;
55711
- d.enqueue(n.encode(v));
55710
+ d.enqueue(n.encode(y));
55712
55711
  continue;
55713
55712
  }
55714
55713
  if (u.choices?.[0]?.delta?.content && o && !r) {
55715
55714
  r = true;
55716
- let a = Date.now().toString(), v = { ...u, choices: [{ ...u.choices[0], delta: { ...u.choices[0].delta, content: null, thinking: { content: o, signature: a } } }] };
55717
- delete v.choices[0].delta.reasoning_content;
55718
- let h = `data: ${JSON.stringify(v)}
55715
+ let a = Date.now().toString(), y = { ...u, choices: [{ ...u.choices[0], delta: { ...u.choices[0].delta, content: null, thinking: { content: o, signature: a } } }] };
55716
+ delete y.choices[0].delta.reasoning_content;
55717
+ let h = `data: ${JSON.stringify(y)}
55719
55718
 
55720
55719
  `;
55721
55720
  d.enqueue(n.encode(h));
@@ -55734,13 +55733,13 @@ var B = class {
55734
55733
  else d.enqueue(n.encode(g + `
55735
55734
  `));
55736
55735
  }
55737
- } catch (i) {
55738
- d.error(i);
55736
+ } catch (s) {
55737
+ d.error(s);
55739
55738
  } finally {
55740
55739
  try {
55741
55740
  l.releaseLock();
55742
- } catch (i) {
55743
- console.error("Error releasing reader lock:", i);
55741
+ } catch (s) {
55742
+ console.error("Error releasing reader lock:", s);
55744
55743
  }
55745
55744
  d.close();
55746
55745
  }
@@ -55773,8 +55772,8 @@ Examples:
55773
55772
  let l = e.body.getReader();
55774
55773
  try {
55775
55774
  for (; ; ) {
55776
- let { done: i, value: p } = await l.read();
55777
- if (i) break;
55775
+ let { done: s, value: p } = await l.read();
55776
+ if (s) break;
55778
55777
  let k = t.decode(p, { stream: true }).split(`
55779
55778
  `);
55780
55779
  for (let g of k) if (g.startsWith("data: ") && g.trim() !== "data: [DONE]") try {
@@ -55787,8 +55786,8 @@ Examples:
55787
55786
  } else if (o > -1 && a.index === o && a.function.arguments) {
55788
55787
  r += a.function.arguments;
55789
55788
  try {
55790
- let v = JSON.parse(r);
55791
- u.choices = [{ delta: { role: "assistant", content: v.response || "" } }];
55789
+ let y = JSON.parse(r);
55790
+ u.choices = [{ delta: { role: "assistant", content: y.response || "" } }];
55792
55791
  let h = `data: ${JSON.stringify(u)}
55793
55792
 
55794
55793
  `;
@@ -55811,13 +55810,13 @@ Examples:
55811
55810
  else d.enqueue(n.encode(g + `
55812
55811
  `));
55813
55812
  }
55814
- } catch (i) {
55815
- d.error(i);
55813
+ } catch (s) {
55814
+ d.error(s);
55816
55815
  } finally {
55817
55816
  try {
55818
55817
  l.releaseLock();
55819
- } catch (i) {
55820
- console.error("Error releasing reader lock:", i);
55818
+ } catch (s) {
55819
+ console.error("Error releasing reader lock:", s);
55821
55820
  }
55822
55821
  d.close();
55823
55822
  }
@@ -55842,19 +55841,19 @@ var z = class {
55842
55841
  return new Response(JSON.stringify(t), { status: e.status, statusText: e.statusText, headers: e.headers });
55843
55842
  } else if (e.headers.get("Content-Type")?.includes("stream")) {
55844
55843
  if (!e.body) return e;
55845
- let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", c = false, d = false, l = "", i = new ReadableStream({ async start(p) {
55846
- let _ = e.body.getReader(), k = (u, a, v) => {
55844
+ let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", c = false, d = false, l = "", s = new ReadableStream({ async start(p) {
55845
+ let _ = e.body.getReader(), k = (u, a, y) => {
55847
55846
  let h = u.split(`
55848
55847
  `);
55849
- for (let f of h) f.trim() && a.enqueue(v.encode(f + `
55848
+ for (let f of h) f.trim() && a.enqueue(y.encode(f + `
55850
55849
  `));
55851
55850
  }, g = (u, a) => {
55852
- let { controller: v, encoder: h } = a;
55851
+ let { controller: y, encoder: h } = a;
55853
55852
  if (u.startsWith("data: ") && u.trim() !== "data: [DONE]") {
55854
55853
  let f = u.slice(6);
55855
55854
  try {
55856
55855
  let m = JSON.parse(f);
55857
- if (m.usage && (y("usage", m.usage, d), m.choices[0].finish_reason = d ? "tool_calls" : "stop"), m.choices?.[0]?.finish_reason === "error" && v.enqueue(h.encode(`data: ${JSON.stringify({ error: m.choices?.[0].error })}
55856
+ if (m.usage && (v("usage", m.usage, d), m.choices[0].finish_reason = d ? "tool_calls" : "stop"), m.choices?.[0]?.finish_reason === "error" && y.enqueue(h.encode(`data: ${JSON.stringify({ error: m.choices?.[0].error })}
55858
55857
 
55859
55858
  `)), m.choices?.[0]?.delta?.content && !a.hasTextContent() && a.setHasTextContent(true), m.choices?.[0]?.delta?.reasoning) {
55860
55859
  a.appendReasoningContent(m.choices[0].delta.reasoning);
@@ -55863,7 +55862,7 @@ var z = class {
55863
55862
  let b = `data: ${JSON.stringify(x)}
55864
55863
 
55865
55864
  `;
55866
- v.enqueue(h.encode(b));
55865
+ y.enqueue(h.encode(b));
55867
55866
  return;
55868
55867
  }
55869
55868
  if (m.choices?.[0]?.delta?.content && a.reasoningContent() && !a.isReasoningComplete()) {
@@ -55873,20 +55872,20 @@ var z = class {
55873
55872
  let X = `data: ${JSON.stringify(b)}
55874
55873
 
55875
55874
  `;
55876
- v.enqueue(h.encode(X));
55875
+ y.enqueue(h.encode(X));
55877
55876
  }
55878
55877
  m.choices?.[0]?.delta?.reasoning && delete m.choices[0].delta.reasoning, m.choices?.[0]?.delta?.tool_calls?.length && !Number.isNaN(parseInt(m.choices?.[0]?.delta?.tool_calls[0].id, 10)) && m.choices?.[0]?.delta?.tool_calls.forEach((x) => {
55879
55878
  x.id = `call_${H()}`;
55880
- }), m.choices?.[0]?.delta?.tool_calls?.length && !d && (y("hasToolCall", true), d = true), m.choices?.[0]?.delta?.tool_calls?.length && a.hasTextContent() && (typeof m.choices[0].index == "number" ? m.choices[0].index += 1 : m.choices[0].index = 1);
55879
+ }), m.choices?.[0]?.delta?.tool_calls?.length && !d && (v("hasToolCall", true), d = true), m.choices?.[0]?.delta?.tool_calls?.length && a.hasTextContent() && (typeof m.choices[0].index == "number" ? m.choices[0].index += 1 : m.choices[0].index = 1);
55881
55880
  let S = `data: ${JSON.stringify(m)}
55882
55881
 
55883
55882
  `;
55884
- v.enqueue(h.encode(S));
55883
+ y.enqueue(h.encode(S));
55885
55884
  } catch {
55886
- v.enqueue(h.encode(u + `
55885
+ y.enqueue(h.encode(u + `
55887
55886
  `));
55888
55887
  }
55889
- } else v.enqueue(h.encode(u + `
55888
+ } else y.enqueue(h.encode(u + `
55890
55889
  `));
55891
55890
  };
55892
55891
  try {
@@ -55897,15 +55896,15 @@ var z = class {
55897
55896
  break;
55898
55897
  }
55899
55898
  if (!a || a.length === 0) continue;
55900
- let v;
55899
+ let y;
55901
55900
  try {
55902
- v = t.decode(a, { stream: true });
55901
+ y = t.decode(a, { stream: true });
55903
55902
  } catch (f) {
55904
55903
  console.warn("Failed to decode chunk", f);
55905
55904
  continue;
55906
55905
  }
55907
- if (v.length === 0) continue;
55908
- if (l += v, l.length > 1e6) {
55906
+ if (y.length === 0) continue;
55907
+ if (l += y, l.length > 1e6) {
55909
55908
  console.warn("Buffer size exceeds limit, processing partial data");
55910
55909
  let f = l.split(`
55911
55910
  `);
@@ -55939,7 +55938,7 @@ var z = class {
55939
55938
  p.close();
55940
55939
  }
55941
55940
  } });
55942
- return new Response(i, { status: e.status, statusText: e.statusText, headers: { "Content-Type": e.headers.get("Content-Type") || "text/plain", "Cache-Control": "no-cache", Connection: "keep-alive" } });
55941
+ return new Response(s, { status: e.status, statusText: e.statusText, headers: { "Content-Type": e.headers.get("Content-Type") || "text/plain", "Cache-Control": "no-cache", Connection: "keep-alive" } });
55943
55942
  }
55944
55943
  return e;
55945
55944
  }
@@ -55972,14 +55971,14 @@ var G = class {
55972
55971
  return new Response(JSON.stringify(t), { status: e.status, statusText: e.statusText, headers: e.headers });
55973
55972
  } else if (e.headers.get("Content-Type")?.includes("stream")) {
55974
55973
  if (!e.body) return e;
55975
- let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", c = false, d = "", l = new ReadableStream({ async start(i) {
55974
+ let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", c = false, d = "", l = new ReadableStream({ async start(s) {
55976
55975
  let p = e.body.getReader(), _ = (g, u, a) => {
55977
- let v = g.split(`
55976
+ let y = g.split(`
55978
55977
  `);
55979
- for (let h of v) h.trim() && u.enqueue(a.encode(h + `
55978
+ for (let h of y) h.trim() && u.enqueue(a.encode(h + `
55980
55979
  `));
55981
55980
  }, k = (g, u) => {
55982
- let { controller: a, encoder: v } = u;
55981
+ let { controller: a, encoder: y } = u;
55983
55982
  if (g.startsWith("data: ") && g.trim() !== "data: [DONE]") {
55984
55983
  let h = g.slice(6);
55985
55984
  try {
@@ -55991,19 +55990,19 @@ var G = class {
55991
55990
  let m = `data: ${JSON.stringify(f)}
55992
55991
 
55993
55992
  `;
55994
- a.enqueue(v.encode(m));
55993
+ a.enqueue(y.encode(m));
55995
55994
  } catch {
55996
- a.enqueue(v.encode(g + `
55995
+ a.enqueue(y.encode(g + `
55997
55996
  `));
55998
55997
  }
55999
- } else a.enqueue(v.encode(g + `
55998
+ } else a.enqueue(y.encode(g + `
56000
55999
  `));
56001
56000
  };
56002
56001
  try {
56003
56002
  for (; ; ) {
56004
56003
  let { done: g, value: u } = await p.read();
56005
56004
  if (g) {
56006
- d.trim() && _(d, i, n);
56005
+ d.trim() && _(d, s, n);
56007
56006
  break;
56008
56007
  }
56009
56008
  if (!u || u.length === 0) continue;
@@ -56021,32 +56020,32 @@ var G = class {
56021
56020
  `);
56022
56021
  d = h.pop() || "";
56023
56022
  for (let f of h) if (f.trim()) try {
56024
- k(f, { controller: i, encoder: n, hasTextContent: () => o, setHasTextContent: (m) => o = m, reasoningContent: () => r, appendReasoningContent: (m) => r += m, isReasoningComplete: () => c, setReasoningComplete: (m) => c = m });
56023
+ k(f, { controller: s, encoder: n, hasTextContent: () => o, setHasTextContent: (m) => o = m, reasoningContent: () => r, appendReasoningContent: (m) => r += m, isReasoningComplete: () => c, setReasoningComplete: (m) => c = m });
56025
56024
  } catch (m) {
56026
- console.error("Error processing line:", f, m), i.enqueue(n.encode(f + `
56025
+ console.error("Error processing line:", f, m), s.enqueue(n.encode(f + `
56027
56026
  `));
56028
56027
  }
56029
56028
  continue;
56030
56029
  }
56031
- let v = d.split(`
56030
+ let y = d.split(`
56032
56031
  `);
56033
- d = v.pop() || "";
56034
- for (let h of v) if (h.trim()) try {
56035
- k(h, { controller: i, encoder: n, hasTextContent: () => o, setHasTextContent: (f) => o = f, reasoningContent: () => r, appendReasoningContent: (f) => r += f, isReasoningComplete: () => c, setReasoningComplete: (f) => c = f });
56032
+ d = y.pop() || "";
56033
+ for (let h of y) if (h.trim()) try {
56034
+ k(h, { controller: s, encoder: n, hasTextContent: () => o, setHasTextContent: (f) => o = f, reasoningContent: () => r, appendReasoningContent: (f) => r += f, isReasoningComplete: () => c, setReasoningComplete: (f) => c = f });
56036
56035
  } catch (f) {
56037
- console.error("Error processing line:", h, f), i.enqueue(n.encode(h + `
56036
+ console.error("Error processing line:", h, f), s.enqueue(n.encode(h + `
56038
56037
  `));
56039
56038
  }
56040
56039
  }
56041
56040
  } catch (g) {
56042
- console.error("Stream error:", g), i.error(g);
56041
+ console.error("Stream error:", g), s.error(g);
56043
56042
  } finally {
56044
56043
  try {
56045
56044
  p.releaseLock();
56046
56045
  } catch (g) {
56047
56046
  console.error("Error releasing reader lock:", g);
56048
56047
  }
56049
- i.close();
56048
+ s.close();
56050
56049
  }
56051
56050
  } });
56052
56051
  return new Response(l, { status: e.status, statusText: e.statusText, headers: { "Content-Type": e.headers.get("Content-Type") || "text/plain", "Cache-Control": "no-cache", Connection: "keep-alive" } });
@@ -56071,7 +56070,7 @@ var Y = class {
56071
56070
  }
56072
56071
  transformers = /* @__PURE__ */ new Map();
56073
56072
  registerTransformer(e, t) {
56074
- this.transformers.set(e, t), y(`register transformer: ${e}${t.endPoint ? ` (endpoint: ${t.endPoint})` : " (no endpoint)"}`);
56073
+ this.transformers.set(e, t), v(`register transformer: ${e}${t.endPoint ? ` (endpoint: ${t.endPoint})` : " (no endpoint)"}`);
56075
56074
  }
56076
56075
  getTransformer(e) {
56077
56076
  return this.transformers.get(e);
@@ -56101,7 +56100,7 @@ var Y = class {
56101
56100
  try {
56102
56101
  let t = import_node_module.default._load;
56103
56102
  if (import_node_module.default._load = function(n, o, r) {
56104
- return n === "claude-code-router" ? { log: y } : t.apply(import_node_module.default, arguments);
56103
+ return n === "claude-code-router" ? { log: v } : t.apply(import_node_module.default, arguments);
56105
56104
  }, e.path) {
56106
56105
  let n = Z(Z.resolve(e.path));
56107
56106
  if (n) {
@@ -56112,14 +56111,14 @@ var Y = class {
56112
56111
  }
56113
56112
  return false;
56114
56113
  } catch (t) {
56115
- return y(`load transformer (${e.path}) error:`, t.message, t.stack), false;
56114
+ return v(`load transformer (${e.path}) error:`, t.message, t.stack), false;
56116
56115
  }
56117
56116
  }
56118
56117
  async initialize() {
56119
56118
  try {
56120
56119
  await this.registerDefaultTransformersInternal(), await this.loadFromConfig();
56121
56120
  } catch (e) {
56122
- y("TransformerService init error:", e);
56121
+ v("TransformerService init error:", e);
56123
56122
  }
56124
56123
  }
56125
56124
  async registerDefaultTransformersInternal() {
@@ -56132,7 +56131,7 @@ var Y = class {
56132
56131
  }
56133
56132
  });
56134
56133
  } catch (e) {
56135
- y("transformer regist error:", e);
56134
+ v("transformer regist error:", e);
56136
56135
  }
56137
56136
  }
56138
56137
  async loadFromConfig() {
@@ -56141,8 +56140,8 @@ var Y = class {
56141
56140
  }
56142
56141
  };
56143
56142
  function Pe() {
56144
- let s = (0, import_fastify.default)({ bodyLimit: 52428800 });
56145
- return s.setErrorHandler(le), s.register(import_cors.default), s;
56143
+ let i = (0, import_fastify.default)({ bodyLimit: 52428800 });
56144
+ return i.setErrorHandler(le), i.register(import_cors.default), i;
56146
56145
  }
56147
56146
  var re = class {
56148
56147
  app;
@@ -56175,13 +56174,13 @@ var re = class {
56175
56174
  }
56176
56175
  }), this.app.register(ue);
56177
56176
  let e = await this.app.listen({ port: parseInt(this.configService.get("PORT") || "3000", 10), host: this.configService.get("HOST") || "127.0.0.1" });
56178
- y(`\u{1F680} LLMs API server listening on ${e}`);
56177
+ v(`\u{1F680} LLMs API server listening on ${e}`);
56179
56178
  let t = async (n) => {
56180
- y(`Received ${n}, shutting down gracefully...`), await this.app.close(), process.exit(0);
56179
+ v(`Received ${n}, shutting down gracefully...`), await this.app.close(), process.exit(0);
56181
56180
  };
56182
56181
  process.on("SIGINT", () => t("SIGINT")), process.on("SIGTERM", () => t("SIGTERM"));
56183
56182
  } catch (e) {
56184
- y(`Error starting server: ${e}`), process.exit(1);
56183
+ v(`Error starting server: ${e}`), process.exit(1);
56185
56184
  }
56186
56185
  }
56187
56186
  };
@@ -56218,6 +56217,55 @@ function log(...args) {
56218
56217
 
56219
56218
  // src/utils/router.ts
56220
56219
  var enc = (0, import_tiktoken.get_encoding)("cl100k_base");
56220
+ var calculateTokenCount = (messages, system, tools) => {
56221
+ let tokenCount = 0;
56222
+ if (Array.isArray(messages)) {
56223
+ messages.forEach((message) => {
56224
+ if (typeof message.content === "string") {
56225
+ tokenCount += enc.encode(message.content).length;
56226
+ } else if (Array.isArray(message.content)) {
56227
+ message.content.forEach((contentPart) => {
56228
+ if (contentPart.type === "text") {
56229
+ tokenCount += enc.encode(contentPart.text).length;
56230
+ } else if (contentPart.type === "tool_use") {
56231
+ tokenCount += enc.encode(
56232
+ JSON.stringify(contentPart.input)
56233
+ ).length;
56234
+ } else if (contentPart.type === "tool_result") {
56235
+ tokenCount += enc.encode(
56236
+ typeof contentPart.content === "string" ? contentPart.content : JSON.stringify(contentPart.content)
56237
+ ).length;
56238
+ }
56239
+ });
56240
+ }
56241
+ });
56242
+ }
56243
+ if (typeof system === "string") {
56244
+ tokenCount += enc.encode(system).length;
56245
+ } else if (Array.isArray(system)) {
56246
+ system.forEach((item) => {
56247
+ if (item.type !== "text") return;
56248
+ if (typeof item.text === "string") {
56249
+ tokenCount += enc.encode(item.text).length;
56250
+ } else if (Array.isArray(item.text)) {
56251
+ item.text.forEach((textPart) => {
56252
+ tokenCount += enc.encode(textPart || "").length;
56253
+ });
56254
+ }
56255
+ });
56256
+ }
56257
+ if (tools) {
56258
+ tools.forEach((tool) => {
56259
+ if (tool.description) {
56260
+ tokenCount += enc.encode(tool.name + tool.description).length;
56261
+ }
56262
+ if (tool.input_schema) {
56263
+ tokenCount += enc.encode(JSON.stringify(tool.input_schema)).length;
56264
+ }
56265
+ });
56266
+ }
56267
+ return tokenCount;
56268
+ };
56221
56269
  var getUseModel = (req, tokenCount, config) => {
56222
56270
  if (req.body.model.includes(",")) {
56223
56271
  return req.body.model;
@@ -56239,56 +56287,26 @@ var getUseModel = (req, tokenCount, config) => {
56239
56287
  }
56240
56288
  return config.Router.default;
56241
56289
  };
56242
- var router = async (req, res, config) => {
56290
+ var router = async (req, _res, config) => {
56243
56291
  const { messages, system = [], tools } = req.body;
56244
56292
  try {
56245
- let tokenCount = 0;
56246
- if (Array.isArray(messages)) {
56247
- messages.forEach((message) => {
56248
- if (typeof message.content === "string") {
56249
- tokenCount += enc.encode(message.content).length;
56250
- } else if (Array.isArray(message.content)) {
56251
- message.content.forEach((contentPart) => {
56252
- if (contentPart.type === "text") {
56253
- tokenCount += enc.encode(contentPart.text).length;
56254
- } else if (contentPart.type === "tool_use") {
56255
- tokenCount += enc.encode(
56256
- JSON.stringify(contentPart.input)
56257
- ).length;
56258
- } else if (contentPart.type === "tool_result") {
56259
- tokenCount += enc.encode(
56260
- typeof contentPart.content === "string" ? contentPart.content : JSON.stringify(contentPart.content)
56261
- ).length;
56262
- }
56263
- });
56264
- }
56265
- });
56266
- }
56267
- if (typeof system === "string") {
56268
- tokenCount += enc.encode(system).length;
56269
- } else if (Array.isArray(system)) {
56270
- system.forEach((item) => {
56271
- if (item.type !== "text") return;
56272
- if (typeof item.text === "string") {
56273
- tokenCount += enc.encode(item.text).length;
56274
- } else if (Array.isArray(item.text)) {
56275
- item.text.forEach((textPart) => {
56276
- tokenCount += enc.encode(textPart || "").length;
56277
- });
56278
- }
56279
- });
56293
+ const tokenCount = calculateTokenCount(
56294
+ messages,
56295
+ system,
56296
+ tools
56297
+ );
56298
+ let model;
56299
+ if (config.CUSTOM_ROUTER_PATH) {
56300
+ try {
56301
+ const customRouter = require(config.CUSTOM_ROUTER_PATH);
56302
+ model = await customRouter(req, config);
56303
+ } catch (e) {
56304
+ log("failed to load custom router", e.message);
56305
+ }
56280
56306
  }
56281
- if (tools) {
56282
- tools.forEach((tool) => {
56283
- if (tool.description) {
56284
- tokenCount += enc.encode(tool.name + tool.description).length;
56285
- }
56286
- if (tool.input_schema) {
56287
- tokenCount += enc.encode(JSON.stringify(tool.input_schema)).length;
56288
- }
56289
- });
56307
+ if (!model) {
56308
+ model = getUseModel(req, tokenCount, config);
56290
56309
  }
56291
- const model = getUseModel(req, tokenCount, config);
56292
56310
  req.body.model = model;
56293
56311
  } catch (error) {
56294
56312
  log("Error in router middleware:", error.message);