@musistudio/claude-code-router 1.0.18 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +96 -2
  2. package/dist/cli.js +450 -409
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -270,7 +270,7 @@ var require_queue = __commonJS({
270
270
  queue.drained = drained;
271
271
  return queue;
272
272
  function push(value) {
273
- var p2 = new Promise(function(resolve, reject) {
273
+ var p = new Promise(function(resolve, reject) {
274
274
  pushCb(value, function(err, result) {
275
275
  if (err) {
276
276
  reject(err);
@@ -279,11 +279,11 @@ var require_queue = __commonJS({
279
279
  resolve(result);
280
280
  });
281
281
  });
282
- p2.catch(noop);
283
- return p2;
282
+ p.catch(noop);
283
+ return p;
284
284
  }
285
285
  function unshift(value) {
286
- var p2 = new Promise(function(resolve, reject) {
286
+ var p = new Promise(function(resolve, reject) {
287
287
  unshiftCb(value, function(err, result) {
288
288
  if (err) {
289
289
  reject(err);
@@ -292,11 +292,11 @@ var require_queue = __commonJS({
292
292
  resolve(result);
293
293
  });
294
294
  });
295
- p2.catch(noop);
296
- return p2;
295
+ p.catch(noop);
296
+ return p;
297
297
  }
298
298
  function drained() {
299
- var p2 = new Promise(function(resolve) {
299
+ var p = new Promise(function(resolve) {
300
300
  process.nextTick(function() {
301
301
  if (queue.idle()) {
302
302
  resolve();
@@ -310,7 +310,7 @@ var require_queue = __commonJS({
310
310
  }
311
311
  });
312
312
  });
313
- return p2;
313
+ return p;
314
314
  }
315
315
  }
316
316
  module2.exports = fastqueue;
@@ -918,8 +918,8 @@ var require_thenify = __commonJS({
918
918
  }
919
919
  debug("thenify");
920
920
  return (resolve, reject) => {
921
- const p2 = this._loadRegistered();
922
- return p2.then(() => {
921
+ const p = this._loadRegistered();
922
+ return p.then(() => {
923
923
  this[kThenifyDoNotWrap] = true;
924
924
  return resolve(this._server);
925
925
  }, reject);
@@ -2150,20 +2150,20 @@ var require_hooks = __commonJS({
2150
2150
  this.validate(hook, fn);
2151
2151
  this[hook].push(fn);
2152
2152
  };
2153
- function buildHooks(h) {
2153
+ function buildHooks(h2) {
2154
2154
  const hooks = new Hooks();
2155
- hooks.onRequest = h.onRequest.slice();
2156
- hooks.preParsing = h.preParsing.slice();
2157
- hooks.preValidation = h.preValidation.slice();
2158
- hooks.preSerialization = h.preSerialization.slice();
2159
- hooks.preHandler = h.preHandler.slice();
2160
- hooks.onSend = h.onSend.slice();
2161
- hooks.onResponse = h.onResponse.slice();
2162
- hooks.onError = h.onError.slice();
2163
- hooks.onRoute = h.onRoute.slice();
2164
- hooks.onRegister = h.onRegister.slice();
2165
- hooks.onTimeout = h.onTimeout.slice();
2166
- hooks.onRequestAbort = h.onRequestAbort.slice();
2155
+ hooks.onRequest = h2.onRequest.slice();
2156
+ hooks.preParsing = h2.preParsing.slice();
2157
+ hooks.preValidation = h2.preValidation.slice();
2158
+ hooks.preSerialization = h2.preSerialization.slice();
2159
+ hooks.preHandler = h2.preHandler.slice();
2160
+ hooks.onSend = h2.onSend.slice();
2161
+ hooks.onResponse = h2.onResponse.slice();
2162
+ hooks.onError = h2.onError.slice();
2163
+ hooks.onRoute = h2.onRoute.slice();
2164
+ hooks.onRegister = h2.onRegister.slice();
2165
+ hooks.onTimeout = h2.onTimeout.slice();
2166
+ hooks.onRequestAbort = h2.onRequestAbort.slice();
2167
2167
  hooks.onReady = [];
2168
2168
  hooks.onListen = [];
2169
2169
  hooks.preClose = [];
@@ -2782,7 +2782,7 @@ var require_validation = __commonJS({
2782
2782
  headersSchemaLowerCase[k] = headers[k];
2783
2783
  });
2784
2784
  if (headersSchemaLowerCase.required instanceof Array) {
2785
- headersSchemaLowerCase.required = headersSchemaLowerCase.required.map((h) => h.toLowerCase());
2785
+ headersSchemaLowerCase.required = headersSchemaLowerCase.required.map((h2) => h2.toLowerCase());
2786
2786
  }
2787
2787
  if (headers.properties) {
2788
2788
  headersSchemaLowerCase.properties = {};
@@ -3644,11 +3644,11 @@ var require_parse = __commonJS({
3644
3644
  const wildcards = [];
3645
3645
  var wcLen = 0;
3646
3646
  const secret = paths.reduce(function(o, strPath, ix) {
3647
- var path3 = strPath.match(rx).map((p2) => p2.replace(/'|"|`/g, ""));
3647
+ var path3 = strPath.match(rx).map((p) => p.replace(/'|"|`/g, ""));
3648
3648
  const leadingBracket = strPath[0] === "[";
3649
- path3 = path3.map((p2) => {
3650
- if (p2[0] === "[") return p2.substr(1, p2.length - 2);
3651
- else return p2;
3649
+ path3 = path3.map((p) => {
3650
+ if (p[0] === "[") return p.substr(1, p.length - 2);
3651
+ else return p;
3652
3652
  });
3653
3653
  const star = path3.indexOf("*");
3654
3654
  if (star > -1) {
@@ -3722,14 +3722,14 @@ var require_redactor = __commonJS({
3722
3722
  const { index, input } = match;
3723
3723
  if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1)));
3724
3724
  }
3725
- var existence = hops.map((p2) => `o${delim}${p2}`).join(" && ");
3725
+ var existence = hops.map((p) => `o${delim}${p}`).join(" && ");
3726
3726
  if (existence.length === 0) existence += `o${delim}${path3} != null`;
3727
3727
  else existence += ` && o${delim}${path3} != null`;
3728
3728
  const circularDetection = `
3729
3729
  switch (true) {
3730
- ${hops.reverse().map((p2) => `
3731
- case o${delim}${p2} === censor:
3732
- secret[${escPath}].circle = ${JSON.stringify(p2)}
3730
+ ${hops.reverse().map((p) => `
3731
+ case o${delim}${p} === censor:
3732
+ secret[${escPath}].circle = ${JSON.stringify(p)}
3733
3733
  break
3734
3734
  `).join("\n")}
3735
3735
  }
@@ -3928,12 +3928,12 @@ var require_modifiers = __commonJS({
3928
3928
  }
3929
3929
  }
3930
3930
  }
3931
- function get(o, p2) {
3931
+ function get(o, p) {
3932
3932
  var i = -1;
3933
- var l = p2.length;
3933
+ var l = p.length;
3934
3934
  var n = o;
3935
3935
  while (n != null && ++i < l) {
3936
- n = n[p2[i]];
3936
+ n = n[p[i]];
3937
3937
  }
3938
3938
  return n;
3939
3939
  }
@@ -13236,7 +13236,7 @@ var require_util = __commonJS({
13236
13236
  }
13237
13237
  exports2.evaluatedPropsToName = evaluatedPropsToName;
13238
13238
  function setEvaluated(gen, props, ps) {
13239
- Object.keys(ps).forEach((p2) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p2)}`, true));
13239
+ Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
13240
13240
  }
13241
13241
  exports2.setEvaluated = setEvaluated;
13242
13242
  var snippets = {};
@@ -13809,11 +13809,11 @@ var require_code2 = __commonJS({
13809
13809
  }
13810
13810
  exports2.noPropertyInData = noPropertyInData;
13811
13811
  function allSchemaProperties(schemaMap) {
13812
- return schemaMap ? Object.keys(schemaMap).filter((p2) => p2 !== "__proto__") : [];
13812
+ return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
13813
13813
  }
13814
13814
  exports2.allSchemaProperties = allSchemaProperties;
13815
13815
  function schemaProperties(it, schemaMap) {
13816
- return allSchemaProperties(schemaMap).filter((p2) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p2]));
13816
+ return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
13817
13817
  }
13818
13818
  exports2.schemaProperties = schemaProperties;
13819
13819
  function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
@@ -14291,12 +14291,12 @@ var require_resolve = __commonJS({
14291
14291
  function getFullPath(resolver, id2 = "", normalize) {
14292
14292
  if (normalize !== false)
14293
14293
  id2 = normalizeId(id2);
14294
- const p2 = resolver.parse(id2);
14295
- return _getFullPath(resolver, p2);
14294
+ const p = resolver.parse(id2);
14295
+ return _getFullPath(resolver, p);
14296
14296
  }
14297
14297
  exports2.getFullPath = getFullPath;
14298
- function _getFullPath(resolver, p2) {
14299
- const serialized = resolver.serialize(p2);
14298
+ function _getFullPath(resolver, p) {
14299
+ const serialized = resolver.serialize(p);
14300
14300
  return serialized.split("#")[0] + "#";
14301
14301
  }
14302
14302
  exports2._getFullPath = _getFullPath;
@@ -15071,11 +15071,11 @@ var require_compile = __commonJS({
15071
15071
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
15072
15072
  }
15073
15073
  function resolveSchema(root, ref) {
15074
- const p2 = this.opts.uriResolver.parse(ref);
15075
- const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p2);
15074
+ const p = this.opts.uriResolver.parse(ref);
15075
+ const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
15076
15076
  let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
15077
15077
  if (Object.keys(root.schema).length > 0 && refPath === baseId) {
15078
- return getJsonPointer.call(this, p2, root);
15078
+ return getJsonPointer.call(this, p, root);
15079
15079
  }
15080
15080
  const id2 = (0, resolve_1.normalizeId)(refPath);
15081
15081
  const schOrRef = this.refs[id2] || this.schemas[id2];
@@ -15083,7 +15083,7 @@ var require_compile = __commonJS({
15083
15083
  const sch = resolveSchema.call(this, root, schOrRef);
15084
15084
  if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
15085
15085
  return;
15086
- return getJsonPointer.call(this, p2, sch);
15086
+ return getJsonPointer.call(this, p, sch);
15087
15087
  }
15088
15088
  if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
15089
15089
  return;
@@ -15097,7 +15097,7 @@ var require_compile = __commonJS({
15097
15097
  baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
15098
15098
  return new SchemaEnv({ schema, schemaId, root, baseId });
15099
15099
  }
15100
- return getJsonPointer.call(this, p2, schOrRef);
15100
+ return getJsonPointer.call(this, p, schOrRef);
15101
15101
  }
15102
15102
  exports2.resolveSchema = resolveSchema;
15103
15103
  var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
@@ -16048,9 +16048,9 @@ var require_core = __commonJS({
16048
16048
  this.addSchema(_schema, ref, meta);
16049
16049
  }
16050
16050
  async function _loadSchema(ref) {
16051
- const p2 = this._loading[ref];
16052
- if (p2)
16053
- return p2;
16051
+ const p = this._loading[ref];
16052
+ if (p)
16053
+ return p;
16054
16054
  try {
16055
16055
  return await (this._loading[ref] = loadSchema(ref));
16056
16056
  } finally {
@@ -17523,12 +17523,12 @@ var require_additionalProperties = __commonJS({
17523
17523
  const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
17524
17524
  definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
17525
17525
  } else if (props.length) {
17526
- definedProp = (0, codegen_1.or)(...props.map((p2) => (0, codegen_1._)`${key} === ${p2}`));
17526
+ definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
17527
17527
  } else {
17528
17528
  definedProp = codegen_1.nil;
17529
17529
  }
17530
17530
  if (patProps.length) {
17531
- definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p2) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p2)}.test(${key})`));
17531
+ definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
17532
17532
  }
17533
17533
  return (0, codegen_1.not)(definedProp);
17534
17534
  }
@@ -17608,7 +17608,7 @@ var require_properties = __commonJS({
17608
17608
  if (it.opts.unevaluated && allProps.length && it.props !== true) {
17609
17609
  it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
17610
17610
  }
17611
- const properties = allProps.filter((p2) => !(0, util_1.alwaysValidSchema)(it, schema[p2]));
17611
+ const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
17612
17612
  if (properties.length === 0)
17613
17613
  return;
17614
17614
  const valid = gen.name("valid");
@@ -17658,7 +17658,7 @@ var require_patternProperties = __commonJS({
17658
17658
  const { gen, schema, data, parentSchema, it } = cxt;
17659
17659
  const { opts } = it;
17660
17660
  const patterns = (0, code_1.allSchemaProperties)(schema);
17661
- const alwaysValidPatterns = patterns.filter((p2) => (0, util_1.alwaysValidSchema)(it, schema[p2]));
17661
+ const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
17662
17662
  if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
17663
17663
  return;
17664
17664
  }
@@ -21778,8 +21778,8 @@ var require_properties2 = __commonJS({
21778
21778
  const optProps = parentSchema.optionalProperties;
21779
21779
  if (!(props && optProps))
21780
21780
  return false;
21781
- for (const p2 in props) {
21782
- if (Object.prototype.hasOwnProperty.call(optProps, p2))
21781
+ for (const p in props) {
21782
+ if (Object.prototype.hasOwnProperty.call(optProps, p))
21783
21783
  return true;
21784
21784
  }
21785
21785
  return false;
@@ -21787,10 +21787,10 @@ var require_properties2 = __commonJS({
21787
21787
  function schemaProperties(keyword) {
21788
21788
  const schema = parentSchema[keyword];
21789
21789
  const allPs = schema ? (0, code_1.allSchemaProperties)(schema) : [];
21790
- if (it.jtdDiscriminator && allPs.some((p2) => p2 === it.jtdDiscriminator)) {
21790
+ if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
21791
21791
  throw new Error(`JTD: discriminator tag used in ${keyword}`);
21792
21792
  }
21793
- const ps = allPs.filter((p2) => !(0, util_1.alwaysValidSchema)(it, schema[p2]));
21793
+ const ps = allPs.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
21794
21794
  return [allPs, ps];
21795
21795
  }
21796
21796
  function validateProps(props, keyword, required) {
@@ -21841,7 +21841,7 @@ var require_properties2 = __commonJS({
21841
21841
  }
21842
21842
  } else if (props.length || jtdDiscriminator !== void 0) {
21843
21843
  const ps = jtdDiscriminator === void 0 ? props : [jtdDiscriminator].concat(props);
21844
- additional = (0, codegen_1.and)(...ps.map((p2) => (0, codegen_1._)`${key} !== ${p2}`));
21844
+ additional = (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`));
21845
21845
  } else {
21846
21846
  additional = true;
21847
21847
  }
@@ -22397,7 +22397,7 @@ var require_serialize = __commonJS({
22397
22397
  serializeCode({ ...cxt, schema: propSchema, data: value });
22398
22398
  }
22399
22399
  function isAdditional(key, ps) {
22400
- return ps.length ? (0, codegen_1.and)(...ps.map((p2) => (0, codegen_1._)`${key} !== ${p2}`)) : true;
22400
+ return ps.length ? (0, codegen_1.and)(...ps.map((p) => (0, codegen_1._)`${key} !== ${p}`)) : true;
22401
22401
  }
22402
22402
  }
22403
22403
  function serializeType(cxt) {
@@ -22839,7 +22839,7 @@ var require_parse2 = __commonJS({
22839
22839
  });
22840
22840
  if (properties) {
22841
22841
  const hasProp = (0, code_1.hasPropFunc)(gen);
22842
- const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p2) => (0, codegen_1._)`${hasProp}.call(${data}, ${p2})`));
22842
+ const allProps = (0, codegen_1.and)(...Object.keys(properties).map((p) => (0, codegen_1._)`${hasProp}.call(${data}, ${p})`));
22843
22843
  gen.if((0, codegen_1.not)(allProps), () => parsingError(cxt, (0, codegen_1.str)`missing required properties`));
22844
22844
  }
22845
22845
  }
@@ -24490,20 +24490,20 @@ var require_range = __commonJS({
24490
24490
  };
24491
24491
  var replaceTilde = (comp, options) => {
24492
24492
  const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE];
24493
- return comp.replace(r, (_, M, m, p2, pr) => {
24494
- debug("tilde", comp, _, M, m, p2, pr);
24493
+ return comp.replace(r, (_, M, m, p, pr) => {
24494
+ debug("tilde", comp, _, M, m, p, pr);
24495
24495
  let ret;
24496
24496
  if (isX(M)) {
24497
24497
  ret = "";
24498
24498
  } else if (isX(m)) {
24499
24499
  ret = `>=${M}.0.0 <${+M + 1}.0.0-0`;
24500
- } else if (isX(p2)) {
24500
+ } else if (isX(p)) {
24501
24501
  ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`;
24502
24502
  } else if (pr) {
24503
24503
  debug("replaceTilde pr", pr);
24504
- ret = `>=${M}.${m}.${p2}-${pr} <${M}.${+m + 1}.0-0`;
24504
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
24505
24505
  } else {
24506
- ret = `>=${M}.${m}.${p2} <${M}.${+m + 1}.0-0`;
24506
+ ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`;
24507
24507
  }
24508
24508
  debug("tilde return", ret);
24509
24509
  return ret;
@@ -24516,14 +24516,14 @@ var require_range = __commonJS({
24516
24516
  debug("caret", comp, options);
24517
24517
  const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET];
24518
24518
  const z = options.includePrerelease ? "-0" : "";
24519
- return comp.replace(r, (_, M, m, p2, pr) => {
24520
- debug("caret", comp, _, M, m, p2, pr);
24519
+ return comp.replace(r, (_, M, m, p, pr) => {
24520
+ debug("caret", comp, _, M, m, p, pr);
24521
24521
  let ret;
24522
24522
  if (isX(M)) {
24523
24523
  ret = "";
24524
24524
  } else if (isX(m)) {
24525
24525
  ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`;
24526
- } else if (isX(p2)) {
24526
+ } else if (isX(p)) {
24527
24527
  if (M === "0") {
24528
24528
  ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`;
24529
24529
  } else {
@@ -24533,23 +24533,23 @@ var require_range = __commonJS({
24533
24533
  debug("replaceCaret pr", pr);
24534
24534
  if (M === "0") {
24535
24535
  if (m === "0") {
24536
- ret = `>=${M}.${m}.${p2}-${pr} <${M}.${m}.${+p2 + 1}-0`;
24536
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`;
24537
24537
  } else {
24538
- ret = `>=${M}.${m}.${p2}-${pr} <${M}.${+m + 1}.0-0`;
24538
+ ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`;
24539
24539
  }
24540
24540
  } else {
24541
- ret = `>=${M}.${m}.${p2}-${pr} <${+M + 1}.0.0-0`;
24541
+ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`;
24542
24542
  }
24543
24543
  } else {
24544
24544
  debug("no pr");
24545
24545
  if (M === "0") {
24546
24546
  if (m === "0") {
24547
- ret = `>=${M}.${m}.${p2}${z} <${M}.${m}.${+p2 + 1}-0`;
24547
+ ret = `>=${M}.${m}.${p}${z} <${M}.${m}.${+p + 1}-0`;
24548
24548
  } else {
24549
- ret = `>=${M}.${m}.${p2}${z} <${M}.${+m + 1}.0-0`;
24549
+ ret = `>=${M}.${m}.${p}${z} <${M}.${+m + 1}.0-0`;
24550
24550
  }
24551
24551
  } else {
24552
- ret = `>=${M}.${m}.${p2} <${+M + 1}.0.0-0`;
24552
+ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`;
24553
24553
  }
24554
24554
  }
24555
24555
  debug("caret return", ret);
@@ -24563,11 +24563,11 @@ var require_range = __commonJS({
24563
24563
  var replaceXRange = (comp, options) => {
24564
24564
  comp = comp.trim();
24565
24565
  const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE];
24566
- return comp.replace(r, (ret, gtlt, M, m, p2, pr) => {
24567
- debug("xRange", comp, ret, gtlt, M, m, p2, pr);
24566
+ return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
24567
+ debug("xRange", comp, ret, gtlt, M, m, p, pr);
24568
24568
  const xM = isX(M);
24569
24569
  const xm = xM || isX(m);
24570
- const xp = xm || isX(p2);
24570
+ const xp = xm || isX(p);
24571
24571
  const anyX = xp;
24572
24572
  if (gtlt === "=" && anyX) {
24573
24573
  gtlt = "";
@@ -24583,16 +24583,16 @@ var require_range = __commonJS({
24583
24583
  if (xm) {
24584
24584
  m = 0;
24585
24585
  }
24586
- p2 = 0;
24586
+ p = 0;
24587
24587
  if (gtlt === ">") {
24588
24588
  gtlt = ">=";
24589
24589
  if (xm) {
24590
24590
  M = +M + 1;
24591
24591
  m = 0;
24592
- p2 = 0;
24592
+ p = 0;
24593
24593
  } else {
24594
24594
  m = +m + 1;
24595
- p2 = 0;
24595
+ p = 0;
24596
24596
  }
24597
24597
  } else if (gtlt === "<=") {
24598
24598
  gtlt = "<";
@@ -24605,7 +24605,7 @@ var require_range = __commonJS({
24605
24605
  if (gtlt === "<") {
24606
24606
  pr = "-0";
24607
24607
  }
24608
- ret = `${gtlt + M}.${m}.${p2}${pr}`;
24608
+ ret = `${gtlt + M}.${m}.${p}${pr}`;
24609
24609
  } else if (xm) {
24610
24610
  ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`;
24611
24611
  } else if (xp) {
@@ -26387,7 +26387,7 @@ var require_types4 = __commonJS({
26387
26387
  o[k2] = m[k];
26388
26388
  });
26389
26389
  var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
26390
- for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m, p2);
26390
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
26391
26391
  };
26392
26392
  Object.defineProperty(exports2, "__esModule", { value: true });
26393
26393
  __exportStar(require_tokens(), exports2);
@@ -26498,13 +26498,13 @@ var require_util2 = __commonJS({
26498
26498
  let tokens = [], rs, c;
26499
26499
  const regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(((?:\\)])|(((?:\\)?([^\]])))))|(\])|(?:\\)?([^])/g;
26500
26500
  while ((rs = regexp.exec(str)) !== null) {
26501
- const p2 = (_g = (_f = (_e = (_d = (_c = (_b = (_a = rs[1] && sets.words()) !== null && _a !== void 0 ? _a : rs[2] && sets.ints()) !== null && _b !== void 0 ? _b : rs[3] && sets.whitespace()) !== null && _c !== void 0 ? _c : rs[4] && sets.notWords()) !== null && _d !== void 0 ? _d : rs[5] && sets.notInts()) !== null && _e !== void 0 ? _e : rs[6] && sets.notWhitespace()) !== null && _f !== void 0 ? _f : rs[7] && {
26501
+ const p = (_g = (_f = (_e = (_d = (_c = (_b = (_a = rs[1] && sets.words()) !== null && _a !== void 0 ? _a : rs[2] && sets.ints()) !== null && _b !== void 0 ? _b : rs[3] && sets.whitespace()) !== null && _c !== void 0 ? _c : rs[4] && sets.notWords()) !== null && _d !== void 0 ? _d : rs[5] && sets.notInts()) !== null && _e !== void 0 ? _e : rs[6] && sets.notWhitespace()) !== null && _f !== void 0 ? _f : rs[7] && {
26502
26502
  type: types_1.types.RANGE,
26503
26503
  from: (rs[8] || rs[9]).charCodeAt(0),
26504
26504
  to: (c = rs[10]).charCodeAt(c.length - 1)
26505
26505
  }) !== null && _g !== void 0 ? _g : (c = rs[16]) && { type: types_1.types.CHAR, value: c.charCodeAt(0) };
26506
- if (p2) {
26507
- tokens.push(p2);
26506
+ if (p) {
26507
+ tokens.push(p);
26508
26508
  } else {
26509
26509
  return [tokens, regexp.lastIndex];
26510
26510
  }
@@ -27037,7 +27037,7 @@ var require_dist3 = __commonJS({
27037
27037
  o[k2] = m[k];
27038
27038
  });
27039
27039
  var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) {
27040
- for (var p2 in m) if (p2 !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p2)) __createBinding(exports3, m, p2);
27040
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
27041
27041
  };
27042
27042
  Object.defineProperty(exports2, "__esModule", { value: true });
27043
27043
  exports2.types = void 0;
@@ -28943,7 +28943,7 @@ var require_route = __commonJS({
28943
28943
  context.schemaErrorFormatter = opts.schemaErrorFormatter || this[kSchemaErrorFormatter] || context.schemaErrorFormatter;
28944
28944
  avvio.once("preReady", () => {
28945
28945
  for (const hook of lifecycleHooks) {
28946
- const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this));
28946
+ const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h2) => h2.bind(this));
28947
28947
  context[hook] = toSet.length ? toSet : null;
28948
28948
  }
28949
28949
  while (!context.Request[kHasBeenDecorated] && context.Request.parent) {
@@ -29231,7 +29231,7 @@ var require_fourOhFour = __commonJS({
29231
29231
  avvio.once("preReady", () => {
29232
29232
  const context2 = this[kFourOhFourContext];
29233
29233
  for (const hook of lifecycleHooks) {
29234
- const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h) => h.bind(this));
29234
+ const toSet = this[kHooks][hook].concat(opts[hook] || []).map((h2) => h2.bind(this));
29235
29235
  context2[hook] = toSet.length ? toSet : null;
29236
29236
  }
29237
29237
  context2.errorHandler = opts.errorHandler ? buildErrorHandler(this[kErrorHandler], opts.errorHandler) : this[kErrorHandler];
@@ -38306,11 +38306,11 @@ var require_util4 = __commonJS({
38306
38306
  }
38307
38307
  function tryUpgradeRequestToAPotentiallyTrustworthyURL(request) {
38308
38308
  }
38309
- function sameOrigin(A2, B) {
38310
- if (A2.origin === B.origin && A2.origin === "null") {
38309
+ function sameOrigin(A, B2) {
38310
+ if (A.origin === B2.origin && A.origin === "null") {
38311
38311
  return true;
38312
38312
  }
38313
- if (A2.protocol === B.protocol && A2.hostname === B.hostname && A2.port === B.port) {
38313
+ if (A.protocol === B2.protocol && A.hostname === B2.hostname && A.port === B2.port) {
38314
38314
  return true;
38315
38315
  }
38316
38316
  return false;
@@ -39607,7 +39607,7 @@ var require_client_h1 = __commonJS({
39607
39607
  * @param {number} len
39608
39608
  * @returns {number}
39609
39609
  */
39610
- wasm_on_url: (p2, at, len) => {
39610
+ wasm_on_url: (p, at, len) => {
39611
39611
  return 0;
39612
39612
  },
39613
39613
  /**
@@ -39616,8 +39616,8 @@ var require_client_h1 = __commonJS({
39616
39616
  * @param {number} len
39617
39617
  * @returns {number}
39618
39618
  */
39619
- wasm_on_status: (p2, at, len) => {
39620
- assert(currentParser.ptr === p2);
39619
+ wasm_on_status: (p, at, len) => {
39620
+ assert(currentParser.ptr === p);
39621
39621
  const start = at - currentBufferPtr + currentBufferRef.byteOffset;
39622
39622
  return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len));
39623
39623
  },
@@ -39625,8 +39625,8 @@ var require_client_h1 = __commonJS({
39625
39625
  * @param {number} p
39626
39626
  * @returns {number}
39627
39627
  */
39628
- wasm_on_message_begin: (p2) => {
39629
- assert(currentParser.ptr === p2);
39628
+ wasm_on_message_begin: (p) => {
39629
+ assert(currentParser.ptr === p);
39630
39630
  return currentParser.onMessageBegin();
39631
39631
  },
39632
39632
  /**
@@ -39635,8 +39635,8 @@ var require_client_h1 = __commonJS({
39635
39635
  * @param {number} len
39636
39636
  * @returns {number}
39637
39637
  */
39638
- wasm_on_header_field: (p2, at, len) => {
39639
- assert(currentParser.ptr === p2);
39638
+ wasm_on_header_field: (p, at, len) => {
39639
+ assert(currentParser.ptr === p);
39640
39640
  const start = at - currentBufferPtr + currentBufferRef.byteOffset;
39641
39641
  return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len));
39642
39642
  },
@@ -39646,8 +39646,8 @@ var require_client_h1 = __commonJS({
39646
39646
  * @param {number} len
39647
39647
  * @returns {number}
39648
39648
  */
39649
- wasm_on_header_value: (p2, at, len) => {
39650
- assert(currentParser.ptr === p2);
39649
+ wasm_on_header_value: (p, at, len) => {
39650
+ assert(currentParser.ptr === p);
39651
39651
  const start = at - currentBufferPtr + currentBufferRef.byteOffset;
39652
39652
  return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len));
39653
39653
  },
@@ -39658,8 +39658,8 @@ var require_client_h1 = __commonJS({
39658
39658
  * @param {0|1} shouldKeepAlive
39659
39659
  * @returns {number}
39660
39660
  */
39661
- wasm_on_headers_complete: (p2, statusCode, upgrade, shouldKeepAlive) => {
39662
- assert(currentParser.ptr === p2);
39661
+ wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => {
39662
+ assert(currentParser.ptr === p);
39663
39663
  return currentParser.onHeadersComplete(statusCode, upgrade === 1, shouldKeepAlive === 1);
39664
39664
  },
39665
39665
  /**
@@ -39668,8 +39668,8 @@ var require_client_h1 = __commonJS({
39668
39668
  * @param {number} len
39669
39669
  * @returns {number}
39670
39670
  */
39671
- wasm_on_body: (p2, at, len) => {
39672
- assert(currentParser.ptr === p2);
39671
+ wasm_on_body: (p, at, len) => {
39672
+ assert(currentParser.ptr === p);
39673
39673
  const start = at - currentBufferPtr + currentBufferRef.byteOffset;
39674
39674
  return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len));
39675
39675
  },
@@ -39677,8 +39677,8 @@ var require_client_h1 = __commonJS({
39677
39677
  * @param {number} p
39678
39678
  * @returns {number}
39679
39679
  */
39680
- wasm_on_message_complete: (p2) => {
39681
- assert(currentParser.ptr === p2);
39680
+ wasm_on_message_complete: (p) => {
39681
+ assert(currentParser.ptr === p);
39682
39682
  return currentParser.onMessageComplete();
39683
39683
  }
39684
39684
  }
@@ -42207,7 +42207,7 @@ var require_balanced_pool = __commonJS({
42207
42207
  return this;
42208
42208
  }
42209
42209
  get upstreams() {
42210
- return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p2) => p2[kUrl].origin);
42210
+ return this[kClients].filter((dispatcher) => dispatcher.closed !== true && dispatcher.destroyed !== true).map((p) => p[kUrl].origin);
42211
42211
  }
42212
42212
  [kGetDispatcher]() {
42213
42213
  if (this[kClients].length === 0) {
@@ -48573,12 +48573,12 @@ var require_response2 = __commonJS({
48573
48573
  ...state
48574
48574
  };
48575
48575
  return new Proxy(response, {
48576
- get(target, p2) {
48577
- return p2 in state ? state[p2] : target[p2];
48576
+ get(target, p) {
48577
+ return p in state ? state[p] : target[p];
48578
48578
  },
48579
- set(target, p2, value) {
48580
- assert(!(p2 in state));
48581
- target[p2] = value;
48579
+ set(target, p, value) {
48580
+ assert(!(p in state));
48581
+ target[p] = value;
48582
48582
  return true;
48583
48583
  }
48584
48584
  });
@@ -49581,18 +49581,18 @@ var require_fetch = __commonJS({
49581
49581
  }
49582
49582
  function fetch2(input, init = void 0) {
49583
49583
  webidl.argumentLengthCheck(arguments, 1, "globalThis.fetch");
49584
- let p2 = createDeferredPromise();
49584
+ let p = createDeferredPromise();
49585
49585
  let requestObject;
49586
49586
  try {
49587
49587
  requestObject = new Request(input, init);
49588
49588
  } catch (e) {
49589
- p2.reject(e);
49590
- return p2.promise;
49589
+ p.reject(e);
49590
+ return p.promise;
49591
49591
  }
49592
49592
  const request = getRequestState(requestObject);
49593
49593
  if (requestObject.signal.aborted) {
49594
- abortFetch(p2, request, null, requestObject.signal.reason);
49595
- return p2.promise;
49594
+ abortFetch(p, request, null, requestObject.signal.reason);
49595
+ return p.promise;
49596
49596
  }
49597
49597
  const globalObject = request.client.globalObject;
49598
49598
  if (globalObject?.constructor?.name === "ServiceWorkerGlobalScope") {
@@ -49608,7 +49608,7 @@ var require_fetch = __commonJS({
49608
49608
  assert(controller != null);
49609
49609
  controller.abort(requestObject.signal.reason);
49610
49610
  const realResponse = responseObject?.deref();
49611
- abortFetch(p2, request, realResponse, requestObject.signal.reason);
49611
+ abortFetch(p, request, realResponse, requestObject.signal.reason);
49612
49612
  }
49613
49613
  );
49614
49614
  const processResponse = (response) => {
@@ -49616,16 +49616,16 @@ var require_fetch = __commonJS({
49616
49616
  return;
49617
49617
  }
49618
49618
  if (response.aborted) {
49619
- abortFetch(p2, request, responseObject, controller.serializedAbortReason);
49619
+ abortFetch(p, request, responseObject, controller.serializedAbortReason);
49620
49620
  return;
49621
49621
  }
49622
49622
  if (response.type === "error") {
49623
- p2.reject(new TypeError("fetch failed", { cause: response.error }));
49623
+ p.reject(new TypeError("fetch failed", { cause: response.error }));
49624
49624
  return;
49625
49625
  }
49626
49626
  responseObject = new WeakRef(fromInnerResponse(response, "immutable"));
49627
- p2.resolve(responseObject.deref());
49628
- p2 = null;
49627
+ p.resolve(responseObject.deref());
49628
+ p = null;
49629
49629
  };
49630
49630
  controller = fetching({
49631
49631
  request,
@@ -49634,7 +49634,7 @@ var require_fetch = __commonJS({
49634
49634
  dispatcher: getRequestDispatcher(requestObject)
49635
49635
  // undici
49636
49636
  });
49637
- return p2.promise;
49637
+ return p.promise;
49638
49638
  }
49639
49639
  function finalizeAndReportTiming(response, initiatorType = "other") {
49640
49640
  if (response.type === "error" && response.aborted) {
@@ -49672,9 +49672,9 @@ var require_fetch = __commonJS({
49672
49672
  );
49673
49673
  }
49674
49674
  var markResourceTiming = performance.markResourceTiming;
49675
- function abortFetch(p2, request, responseObject, error) {
49676
- if (p2) {
49677
- p2.reject(error);
49675
+ function abortFetch(p, request, responseObject, error) {
49676
+ if (p) {
49677
+ p.reject(error);
49678
49678
  }
49679
49679
  if (request.body?.stream != null && isReadable(request.body.stream)) {
49680
49680
  request.body.stream.cancel(error).catch((err) => {
@@ -50552,9 +50552,9 @@ var require_util5 = __commonJS({
50552
50552
  var assert = require("node:assert");
50553
50553
  var { URLSerializer } = require_data_url();
50554
50554
  var { isValidHeaderName } = require_util4();
50555
- function urlEquals(A2, B, excludeFragment = false) {
50556
- const serializedA = URLSerializer(A2, excludeFragment);
50557
- const serializedB = URLSerializer(B, excludeFragment);
50555
+ function urlEquals(A, B2, excludeFragment = false) {
50556
+ const serializedA = URLSerializer(A, excludeFragment);
50557
+ const serializedB = URLSerializer(B2, excludeFragment);
50558
50558
  return serializedA === serializedB;
50559
50559
  }
50560
50560
  function getFieldValues(header) {
@@ -50607,11 +50607,11 @@ var require_cache3 = __commonJS({
50607
50607
  webidl.argumentLengthCheck(arguments, 1, prefix);
50608
50608
  request = webidl.converters.RequestInfo(request, prefix, "request");
50609
50609
  options = webidl.converters.CacheQueryOptions(options, prefix, "options");
50610
- const p2 = this.#internalMatchAll(request, options, 1);
50611
- if (p2.length === 0) {
50610
+ const p = this.#internalMatchAll(request, options, 1);
50611
+ if (p.length === 0) {
50612
50612
  return;
50613
50613
  }
50614
- return p2[0];
50614
+ return p[0];
50615
50615
  }
50616
50616
  async matchAll(request = void 0, options = {}) {
50617
50617
  webidl.brandCheck(this, _Cache);
@@ -50702,8 +50702,8 @@ var require_cache3 = __commonJS({
50702
50702
  }));
50703
50703
  responsePromises.push(responsePromise.promise);
50704
50704
  }
50705
- const p2 = Promise.all(responsePromises);
50706
- const responses = await p2;
50705
+ const p = Promise.all(responsePromises);
50706
+ const responses = await p;
50707
50707
  const operations = [];
50708
50708
  let index = 0;
50709
50709
  for (const response of responses) {
@@ -53005,10 +53005,10 @@ var require_websocket = __commonJS({
53005
53005
  if (typeof protocols === "string") {
53006
53006
  protocols = [protocols];
53007
53007
  }
53008
- if (protocols.length !== new Set(protocols.map((p2) => p2.toLowerCase())).size) {
53008
+ if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
53009
53009
  throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
53010
53010
  }
53011
- if (protocols.length > 0 && !protocols.every((p2) => isValidSubprotocol(p2))) {
53011
+ if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
53012
53012
  throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
53013
53013
  }
53014
53014
  this.#url = new URL(urlRecord.href);
@@ -53496,10 +53496,10 @@ var require_websocketstream = __commonJS({
53496
53496
  const baseURL = environmentSettingsObject.settingsObject.baseUrl;
53497
53497
  const urlRecord = getURLRecord(url, baseURL);
53498
53498
  const protocols = options.protocols;
53499
- if (protocols.length !== new Set(protocols.map((p2) => p2.toLowerCase())).size) {
53499
+ if (protocols.length !== new Set(protocols.map((p) => p.toLowerCase())).size) {
53500
53500
  throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
53501
53501
  }
53502
- if (protocols.length > 0 && !protocols.every((p2) => isValidSubprotocol(p2))) {
53502
+ if (protocols.length > 0 && !protocols.every((p) => isValidSubprotocol(p))) {
53503
53503
  throw new DOMException("Invalid Sec-WebSocket-Protocol value", "SyntaxError");
53504
53504
  }
53505
53505
  this.#url = urlRecord.toString();
@@ -54958,7 +54958,7 @@ var initConfig = async () => {
54958
54958
  return config;
54959
54959
  };
54960
54960
 
54961
- // node_modules/.pnpm/@musistudio+llms@1.0.5_ws@8.18.3_zod@3.25.67/node_modules/@musistudio/llms/dist/esm/server.mjs
54961
+ // node_modules/.pnpm/@musistudio+llms@1.0.6_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");
@@ -55035,13 +55035,13 @@ var N = class {
55035
55035
  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(", ")}`;
55036
55036
  }
55037
55037
  };
55038
- function p(...a) {
55038
+ function h(...a) {
55039
55039
  if (console.log(...a), !(process.env.LOG === "true")) return;
55040
55040
  let n = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${Array.isArray(a) ? a.map((r) => typeof r == "object" ? JSON.stringify(r) : String(r)).join(" ") : ""}
55041
55041
  `, o = process.env.LOG_FILE || "app.log";
55042
55042
  import_node_fs.default.appendFileSync(o, n, "utf8");
55043
55043
  }
55044
- function A(a, e = 500, t = "internal_error", n = "api_error") {
55044
+ function L(a, e = 500, t = "internal_error", n = "api_error") {
55045
55045
  let o = new Error(a);
55046
55046
  return o.statusCode = e, o.code = t, o.type = n, o;
55047
55047
  }
@@ -55052,51 +55052,51 @@ async function Z(a, e, t) {
55052
55052
  }
55053
55053
  function ee(a, e, t) {
55054
55054
  let n = new Headers({ "Content-Type": "application/json" });
55055
- t.headers && Object.entries(t.headers).forEach(([u, d]) => {
55056
- n.set(u, d);
55055
+ t.headers && Object.entries(t.headers).forEach(([d, u]) => {
55056
+ n.set(d, u);
55057
55057
  });
55058
55058
  let o, r = AbortSignal.timeout(t.TIMEOUT ?? 60 * 1e3 * 60);
55059
55059
  if (t.signal) {
55060
- let u = new AbortController(), d = () => u.abort();
55061
- t.signal.addEventListener("abort", d), r.addEventListener("abort", d), o = u.signal;
55060
+ let d = new AbortController(), u = () => d.abort();
55061
+ t.signal.addEventListener("abort", u), r.addEventListener("abort", u), o = d.signal;
55062
55062
  } else o = r;
55063
55063
  let l = { method: "POST", headers: n, body: JSON.stringify(e), signal: o };
55064
- return t.httpsProxy && (l.dispatcher = new import_undici.ProxyAgent(new URL(t.httpsProxy).toString())), p("final request:", typeof a == "string" ? a : a.toString(), t.httpsProxy, l), fetch(typeof a == "string" ? a : a.toString(), l);
55064
+ return t.httpsProxy && (l.dispatcher = new import_undici.ProxyAgent(new URL(t.httpsProxy).toString())), h("final request:", typeof a == "string" ? a : a.toString(), t.httpsProxy, l), fetch(typeof a == "string" ? a : a.toString(), l);
55065
55065
  }
55066
55066
  var te = async (a) => {
55067
55067
  a.get("/", async (t, n) => ({ message: "LLMs API", version: "1.0.0" })), a.get("/health", async (t, n) => ({ status: "ok", timestamp: (/* @__PURE__ */ new Date()).toISOString() }));
55068
55068
  let e = a._server.transformerService.getTransformersWithEndpoint();
55069
55069
  for (let { name: t, transformer: n } of e) n.endPoint && a.post(n.endPoint, async (o, r) => {
55070
- let l = o.body, u = o.provider, d = a._server.providerService.getProvider(u);
55071
- if (!d) throw A(`Provider '${u}' not found`, 404, "provider_not_found");
55070
+ let l = o.body, d = o.provider, u = a._server.providerService.getProvider(d);
55071
+ if (!u) throw L(`Provider '${d}' not found`, 404, "provider_not_found");
55072
55072
  let i = l, c = {};
55073
55073
  if (typeof n.transformRequestOut == "function") {
55074
55074
  let s = await n.transformRequestOut(l);
55075
55075
  s.body ? (i = s.body, c = s.config || {}) : i = s;
55076
55076
  }
55077
- if (p("use transformers:", d.transformer?.use), d.transformer?.use?.length) for (let s of d.transformer.use) {
55077
+ if (h("use transformers:", u.transformer?.use), u.transformer?.use?.length) for (let s of u.transformer.use) {
55078
55078
  if (!s || typeof s.transformRequestIn != "function") continue;
55079
- let _ = await s.transformRequestIn(i, d);
55080
- _.body ? (i = _.body, c = { ...c, ..._.config }) : i = _;
55081
- }
55082
- if (d.transformer?.[o.body.model]?.use?.length) for (let s of d.transformer[o.body.model].use) !s || typeof s.transformRequestIn != "function" || (i = await s.transformRequestIn(i, d));
55083
- let h = c.url || new URL(d.baseUrl), g = await ee(h, i, { httpsProxy: a._server.configService.getHttpsProxy(), ...c, headers: { Authorization: `Bearer ${d.apiKey}`, ...c?.headers || {} } });
55084
- if (!g.ok) {
55085
- let s = await g.text();
55086
- throw p(`Error response from ${h}: ${s}`), A(`Error from provider: ${s}`, g.status, "provider_response_error");
55087
- }
55088
- let m = g;
55089
- if (d.transformer?.use?.length) for (let s of d.transformer.use) !s || typeof s.transformResponseOut != "function" || (m = await s.transformResponseOut(m));
55090
- if (d.transformer?.[o.body.model]?.use?.length) for (let s of d.transformer[o.body.model].use) !s || typeof s.transformResponseOut != "function" || (m = await s.transformResponseOut(m));
55079
+ let y = await s.transformRequestIn(i, u);
55080
+ y.body ? (i = y.body, c = { ...c, ...y.config }) : i = y;
55081
+ }
55082
+ if (u.transformer?.[o.body.model]?.use?.length) for (let s of u.transformer[o.body.model].use) !s || typeof s.transformRequestIn != "function" || (i = await s.transformRequestIn(i, u));
55083
+ let k = c.url || new URL(u.baseUrl), v = await ee(k, i, { httpsProxy: a._server.configService.getHttpsProxy(), ...c, headers: { Authorization: `Bearer ${u.apiKey}`, ...c?.headers || {} } });
55084
+ if (!v.ok) {
55085
+ let s = await v.text();
55086
+ throw h(`Error response from ${k}: ${s}`), L(`Error from provider: ${s}`, v.status, "provider_response_error");
55087
+ }
55088
+ let m = v;
55089
+ if (u.transformer?.use?.length) for (let s of u.transformer.use) !s || typeof s.transformResponseOut != "function" || (m = await s.transformResponseOut(m));
55090
+ if (u.transformer?.[o.body.model]?.use?.length) for (let s of u.transformer[o.body.model].use) !s || typeof s.transformResponseOut != "function" || (m = await s.transformResponseOut(m));
55091
55091
  return n.transformResponseIn && (m = await n.transformResponseIn(m)), m.ok || r.code(m.status), l?.stream === true ? (r.header("Content-Type", "text/event-stream"), r.header("Cache-Control", "no-cache"), r.header("Connection", "keep-alive"), r.send(m.body)) : m.json();
55092
55092
  });
55093
55093
  a.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) => {
55094
- let { name: o, type: r, baseUrl: l, apiKey: u, models: d } = t.body;
55095
- if (!o?.trim()) throw A("Provider name is required", 400, "invalid_request");
55096
- if (!l || !le(l)) throw A("Valid base URL is required", 400, "invalid_request");
55097
- if (!u?.trim()) throw A("API key is required", 400, "invalid_request");
55098
- if (!d || !Array.isArray(d) || d.length === 0) throw A("At least one model is required", 400, "invalid_request");
55099
- if (a._server.providerService.getProvider(id)) throw A(`Provider with ID '${id}' already exists`, 400, "provider_exists");
55094
+ let { name: o, type: r, baseUrl: l, apiKey: d, models: u } = t.body;
55095
+ if (!o?.trim()) throw L("Provider name is required", 400, "invalid_request");
55096
+ if (!l || !de(l)) throw L("Valid base URL is required", 400, "invalid_request");
55097
+ if (!d?.trim()) throw L("API key is required", 400, "invalid_request");
55098
+ if (!u || !Array.isArray(u) || u.length === 0) throw L("At least one model is required", 400, "invalid_request");
55099
+ if (a._server.providerService.getProvider(id)) throw L(`Provider with ID '${id}' already exists`, 400, "provider_exists");
55100
55100
  return a._server.providerService.registerProvider(t.body);
55101
55101
  }), a.get("/providers", async (t, n) => a._server.providerService.getProviders()), a.get("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => {
55102
55102
  let o = a._server.providerService.getProvider(t.params.id);
@@ -55106,14 +55106,14 @@ var te = async (a) => {
55106
55106
  return o || n.code(404).send({ error: "Provider not found" });
55107
55107
  }), a.delete("/providers/:id", { schema: { params: { type: "object", properties: { id: { type: "string" } }, required: ["id"] } } }, async (t, n) => a._server.providerService.deleteProvider(t.params.id) ? { message: "Provider deleted successfully" } : n.code(404).send({ error: "Provider not found" })), a.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) => a._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" }));
55108
55108
  };
55109
- function le(a) {
55109
+ function de(a) {
55110
55110
  try {
55111
55111
  return new URL(a), true;
55112
55112
  } catch {
55113
55113
  return false;
55114
55114
  }
55115
55115
  }
55116
- var H = class {
55116
+ var $ = class {
55117
55117
  constructor(e) {
55118
55118
  this.providerService = e;
55119
55119
  }
@@ -55150,7 +55150,7 @@ var H = class {
55150
55150
  return this.providerService.getModelRoutes();
55151
55151
  }
55152
55152
  };
55153
- var $ = class {
55153
+ var F = class {
55154
55154
  constructor(e, t) {
55155
55155
  this.configService = e;
55156
55156
  this.transformerService = t;
@@ -55184,9 +55184,9 @@ var $ = class {
55184
55184
  }
55185
55185
  if (typeof r == "string") return this.transformerService.getTransformer(r);
55186
55186
  }).filter((r) => typeof r < "u") });
55187
- }), console.log("providerConfig: ", t.name, n.use), this.registerProvider({ name: t.name, baseUrl: t.api_base_url, apiKey: t.api_key, models: t.models || [], transformer: t.transformer ? n : void 0 }), p(`${t.name} provider registered`);
55187
+ }), console.log("providerConfig: ", t.name, n.use), this.registerProvider({ name: t.name, baseUrl: t.api_base_url, apiKey: t.api_key, models: t.models || [], transformer: t.transformer ? n : void 0 }), h(`${t.name} provider registered`);
55188
55188
  } catch (n) {
55189
- p(`${t.name} provider registered error: ${n}`);
55189
+ h(`${t.name} provider registered error: ${n}`);
55190
55190
  }
55191
55191
  });
55192
55192
  }
@@ -55211,8 +55211,8 @@ var $ = class {
55211
55211
  let l = `${n.id},${r}`;
55212
55212
  this.modelRoutes.delete(l), this.modelRoutes.delete(r);
55213
55213
  }), t.models.forEach((r) => {
55214
- let l = `${n.name},${r}`, u = { provider: n.name, model: r, fullModel: l };
55215
- this.modelRoutes.set(l, u), this.modelRoutes.has(r) || this.modelRoutes.set(r, u);
55214
+ let l = `${n.name},${r}`, d = { provider: n.name, model: r, fullModel: l };
55215
+ this.modelRoutes.set(l, d), this.modelRoutes.has(r) || this.modelRoutes.set(r, d);
55216
55216
  })), o;
55217
55217
  }
55218
55218
  deleteProvider(e) {
@@ -55260,11 +55260,11 @@ var $ = class {
55260
55260
  }), { object: "list", data: e };
55261
55261
  }
55262
55262
  };
55263
- var F = class {
55263
+ var I = class {
55264
55264
  name = "Anthropic";
55265
55265
  endPoint = "/v1/messages";
55266
55266
  transformRequestOut(e) {
55267
- p("Anthropic Request:", JSON.stringify(e, null, 2));
55267
+ h("Anthropic Request:", JSON.stringify(e, null, 2));
55268
55268
  let t = [];
55269
55269
  if (e.system) {
55270
55270
  if (typeof e.system == "string") t.push({ role: "system", content: e.system });
@@ -55275,20 +55275,20 @@ var F = class {
55275
55275
  }
55276
55276
  return JSON.parse(JSON.stringify(e.messages || []))?.forEach((r, l) => {
55277
55277
  if (r.role === "user" || r.role === "assistant") {
55278
- let u = { role: r.role, content: null };
55278
+ let d = { role: r.role, content: null };
55279
55279
  if (typeof r.content == "string") t.push({ role: r.role, content: r.content });
55280
55280
  else if (Array.isArray(r.content)) {
55281
55281
  if (r.role === "user") {
55282
- let d = r.content.filter((c) => c.type === "tool_result" && c.tool_use_id);
55283
- d.length && d.forEach((c, h) => {
55284
- let g = { role: "tool", content: typeof c.content == "string" ? c.content : JSON.stringify(c.content), tool_call_id: c.tool_use_id, cache_control: c.cache_control };
55285
- t.push(g);
55282
+ let u = r.content.filter((c) => c.type === "tool_result" && c.tool_use_id);
55283
+ u.length && u.forEach((c, k) => {
55284
+ let v = { role: "tool", content: typeof c.content == "string" ? c.content : JSON.stringify(c.content), tool_call_id: c.tool_use_id, cache_control: c.cache_control };
55285
+ t.push(v);
55286
55286
  });
55287
55287
  let i = r.content.filter((c) => c.type === "text" && c.text);
55288
55288
  i.length && t.push({ role: "user", content: i });
55289
55289
  } else if (r.role === "assistant") {
55290
- let d = r.content.filter((c) => c.type === "text" && c.text);
55291
- d.length && t.push(...d.map((c) => ({ role: "assistant", content: c.text })));
55290
+ let u = r.content.filter((c) => c.type === "text" && c.text);
55291
+ u.length && t.push(...u.map((c) => ({ role: "assistant", content: c.text })));
55292
55292
  let i = r.content.filter((c) => c.type === "tool_use" && c.id);
55293
55293
  i.length && t.push({ role: "assistant", content: null, tool_calls: i.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.input || {}) } })) });
55294
55294
  }
@@ -55312,226 +55312,226 @@ var F = class {
55312
55312
  }
55313
55313
  async convertOpenAIStreamToAnthropic(e) {
55314
55314
  return new ReadableStream({ async start(n) {
55315
- let o = new TextEncoder(), r = `msg_${Date.now()}`, l = "unknown", u = false, d = false, i = false, c = /* @__PURE__ */ new Map(), h = /* @__PURE__ */ new Map(), g = 0, m = 0, f = 0, s = false, _ = false, y = 0, v = (x) => {
55315
+ let o = new TextEncoder(), r = `msg_${Date.now()}`, l = "unknown", d = false, u = false, i = false, c = /* @__PURE__ */ new Map(), k = /* @__PURE__ */ new Map(), v = 0, m = 0, f = 0, s = false, y = false, g = 0, p = (_) => {
55316
55316
  if (!s) try {
55317
- n.enqueue(x);
55318
- let C = new TextDecoder().decode(x);
55319
- p("send data:", C.trim());
55320
- } catch (C) {
55321
- if (C instanceof TypeError && C.message.includes("Controller is already closed")) s = true;
55322
- else throw p(`send data error: ${C.message}`), C;
55323
- }
55324
- }, z = () => {
55317
+ n.enqueue(_);
55318
+ let R = new TextDecoder().decode(_);
55319
+ h("send data:", R.trim());
55320
+ } catch (R) {
55321
+ if (R instanceof TypeError && R.message.includes("Controller is already closed")) s = true;
55322
+ else throw h(`send data error: ${R.message}`), R;
55323
+ }
55324
+ }, S = () => {
55325
55325
  if (!s) try {
55326
55326
  n.close(), s = true;
55327
- } catch (x) {
55328
- if (x instanceof TypeError && x.message.includes("Controller is already closed")) s = true;
55329
- else throw x;
55327
+ } catch (_) {
55328
+ if (_ instanceof TypeError && _.message.includes("Controller is already closed")) s = true;
55329
+ else throw _;
55330
55330
  }
55331
- }, M = null;
55331
+ }, P = null;
55332
55332
  try {
55333
- M = e.getReader();
55334
- let x = new TextDecoder(), C = "";
55333
+ P = e.getReader();
55334
+ let _ = new TextDecoder(), R = "";
55335
55335
  for (; !s; ) {
55336
- let { done: oe, value: re } = await M.read();
55336
+ let { done: oe, value: re } = await P.read();
55337
55337
  if (oe) break;
55338
- C += x.decode(re, { stream: true });
55339
- let K = C.split(`
55338
+ R += _.decode(re, { stream: true });
55339
+ let K = R.split(`
55340
55340
  `);
55341
- C = K.pop() || "";
55341
+ R = K.pop() || "";
55342
55342
  for (let Y of K) {
55343
55343
  if (s || i) break;
55344
55344
  if (!Y.startsWith("data: ")) continue;
55345
- let B = Y.slice(6);
55346
- if (B !== "[DONE]") try {
55347
- let P = JSON.parse(B);
55348
- if (g++, p("Original Response:", JSON.stringify(P, null, 2)), l = P.model || l, !u && !s && !i) {
55349
- u = true;
55350
- let k = { type: "message_start", message: { id: r, type: "message", role: "assistant", content: [], model: l, stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } } };
55351
- v(o.encode(`event: message_start
55352
- data: ${JSON.stringify(k)}
55345
+ let z = Y.slice(6);
55346
+ if (z !== "[DONE]") try {
55347
+ let w = JSON.parse(z);
55348
+ if (v++, h("Original Response:", JSON.stringify(w, null, 2)), l = w.model || l, !d && !s && !i) {
55349
+ d = true;
55350
+ let b = { type: "message_start", message: { id: r, type: "message", role: "assistant", content: [], model: l, stop_reason: null, stop_sequence: null, usage: { input_tokens: 1, output_tokens: 1 } } };
55351
+ p(o.encode(`event: message_start
55352
+ data: ${JSON.stringify(b)}
55353
55353
 
55354
55354
  `));
55355
55355
  }
55356
- let S = P.choices?.[0];
55357
- if (!S) continue;
55358
- if (S?.delta?.thinking && !s && !i) {
55359
- if (!_) {
55360
- let k = { type: "content_block_start", index: y, content_block: { type: "thinking", thinking: "" } };
55361
- v(o.encode(`event: content_block_start
55362
- data: ${JSON.stringify(k)}
55363
-
55364
- `)), _ = true;
55356
+ let T = w.choices?.[0];
55357
+ if (!T) continue;
55358
+ if (T?.delta?.thinking && !s && !i) {
55359
+ if (!y) {
55360
+ let b = { type: "content_block_start", index: g, content_block: { type: "thinking", thinking: "" } };
55361
+ p(o.encode(`event: content_block_start
55362
+ data: ${JSON.stringify(b)}
55363
+
55364
+ `)), y = true;
55365
55365
  }
55366
- if (S.delta.thinking.signature) {
55367
- let k = { type: "content_block_delta", index: y, delta: { type: "signature_delta", signature: S.delta.thinking.signature } };
55368
- v(o.encode(`event: content_block_delta
55369
- data: ${JSON.stringify(k)}
55366
+ if (T.delta.thinking.signature) {
55367
+ let b = { type: "content_block_delta", index: g, delta: { type: "signature_delta", signature: T.delta.thinking.signature } };
55368
+ p(o.encode(`event: content_block_delta
55369
+ data: ${JSON.stringify(b)}
55370
55370
 
55371
55371
  `));
55372
- let b = { type: "content_block_stop", index: y };
55373
- v(o.encode(`event: content_block_stop
55372
+ let C = { type: "content_block_stop", index: g };
55373
+ p(o.encode(`event: content_block_stop
55374
+ data: ${JSON.stringify(C)}
55375
+
55376
+ `)), g++;
55377
+ } else if (T.delta.thinking.content) {
55378
+ let b = { type: "content_block_delta", index: g, delta: { type: "thinking_delta", thinking: T.delta.thinking.content || "" } };
55379
+ p(o.encode(`event: content_block_delta
55374
55380
  data: ${JSON.stringify(b)}
55375
55381
 
55376
- `)), y++;
55377
- } else if (S.delta.thinking.content) {
55378
- let k = { type: "content_block_delta", index: y, delta: { type: "thinking_delta", thinking: S.delta.thinking.content || "" } };
55379
- v(o.encode(`event: content_block_delta
55380
- data: ${JSON.stringify(k)}
55381
-
55382
55382
  `));
55383
55383
  }
55384
55384
  }
55385
- if (S?.delta?.content && !s && !i) {
55386
- if (m++, !d && !i) {
55387
- d = true;
55388
- let k = { type: "content_block_start", index: y, content_block: { type: "text", text: "" } };
55389
- v(o.encode(`event: content_block_start
55390
- data: ${JSON.stringify(k)}
55385
+ if (T?.delta?.content && !s && !i) {
55386
+ if (m++, !u && !i) {
55387
+ u = true;
55388
+ let b = { type: "content_block_start", index: g, content_block: { type: "text", text: "" } };
55389
+ p(o.encode(`event: content_block_start
55390
+ data: ${JSON.stringify(b)}
55391
55391
 
55392
55392
  `));
55393
55393
  }
55394
55394
  if (!s && !i) {
55395
- let k = { type: "content_block_delta", index: y, delta: { type: "text_delta", text: S.delta.content } };
55396
- v(o.encode(`event: content_block_delta
55397
- data: ${JSON.stringify(k)}
55395
+ let b = { type: "content_block_delta", index: g, delta: { type: "text_delta", text: T.delta.content } };
55396
+ p(o.encode(`event: content_block_delta
55397
+ data: ${JSON.stringify(b)}
55398
55398
 
55399
55399
  `));
55400
55400
  }
55401
55401
  }
55402
- if (S?.delta?.tool_calls && !s && !i) {
55402
+ if (T?.delta?.tool_calls && !s && !i) {
55403
55403
  f++;
55404
- let k = /* @__PURE__ */ new Set();
55405
- for (let b of S.delta.tool_calls) {
55404
+ let b = /* @__PURE__ */ new Set();
55405
+ for (let C of T.delta.tool_calls) {
55406
55406
  if (s) break;
55407
- let R = b.index ?? 0;
55408
- if (k.has(R)) continue;
55409
- if (k.add(R), !h.has(R)) {
55410
- let T = d ? h.size + 1 : h.size;
55411
- if (T !== 0) {
55412
- p("content_block_stop2");
55413
- let se = { type: "content_block_stop", index: y };
55414
- v(o.encode(`event: content_block_stop
55407
+ let x = C.index ?? 0;
55408
+ if (b.has(x)) continue;
55409
+ if (b.add(x), !k.has(x)) {
55410
+ let O = u ? k.size + 1 : k.size;
55411
+ if (O !== 0) {
55412
+ h("content_block_stop2");
55413
+ let se = { type: "content_block_stop", index: g };
55414
+ p(o.encode(`event: content_block_stop
55415
55415
  data: ${JSON.stringify(se)}
55416
55416
 
55417
- `)), y++;
55417
+ `)), g++;
55418
55418
  }
55419
- h.set(R, T);
55420
- let E = b.id || `call_${Date.now()}_${R}`, w = b.function?.name || `tool_${R}`, O = { type: "content_block_start", index: y, content_block: { type: "tool_use", id: E, name: w, input: {} } };
55421
- v(o.encode(`event: content_block_start
55422
- data: ${JSON.stringify(O)}
55419
+ k.set(x, O);
55420
+ let H = C.id || `call_${Date.now()}_${x}`, A = C.function?.name || `tool_${x}`, E = { type: "content_block_start", index: g, content_block: { type: "tool_use", id: H, name: A, input: {} } };
55421
+ p(o.encode(`event: content_block_start
55422
+ data: ${JSON.stringify(E)}
55423
55423
 
55424
55424
  `));
55425
- let L = { id: E, name: w, arguments: "", contentBlockIndex: T };
55426
- c.set(R, L);
55427
- } else if (b.id && b.function?.name) {
55428
- let T = c.get(R);
55429
- T.id.startsWith("call_") && T.name.startsWith("tool_") && (T.id = b.id, T.name = b.function.name);
55425
+ let M = { id: H, name: A, arguments: "", contentBlockIndex: O };
55426
+ c.set(x, M);
55427
+ } else if (C.id && C.function?.name) {
55428
+ let O = c.get(x);
55429
+ O.id.startsWith("call_") && O.name.startsWith("tool_") && (O.id = C.id, O.name = C.function.name);
55430
55430
  }
55431
- if (b.function?.arguments && !s && !i) {
55432
- if (h.get(R) === void 0) continue;
55433
- let E = c.get(R);
55434
- if (E) {
55435
- E.arguments += b.function.arguments;
55431
+ if (C.function?.arguments && !s && !i) {
55432
+ if (k.get(x) === void 0) continue;
55433
+ let H = c.get(x);
55434
+ if (H) {
55435
+ H.arguments += C.function.arguments;
55436
55436
  try {
55437
- let w = null, O = E.arguments.trim();
55438
- if (O.startsWith("{") && O.endsWith("}")) try {
55439
- w = JSON.parse(O);
55440
- } catch (L) {
55441
- p("Tool call index:", R, "error", L.message);
55437
+ let A = null, E = H.arguments.trim();
55438
+ if (E.startsWith("{") && E.endsWith("}")) try {
55439
+ A = JSON.parse(E);
55440
+ } catch (M) {
55441
+ h("Tool call index:", x, "error", M.message);
55442
55442
  }
55443
- } catch (w) {
55444
- p("Tool call index:", R, "error", w.message);
55443
+ } catch (A) {
55444
+ h("Tool call index:", x, "error", A.message);
55445
55445
  }
55446
55446
  }
55447
55447
  try {
55448
- let w = { type: "content_block_delta", index: y, delta: { type: "input_json_delta", partial_json: b.function.arguments } };
55449
- v(o.encode(`event: content_block_delta
55450
- data: ${JSON.stringify(w)}
55448
+ let A = { type: "content_block_delta", index: g, delta: { type: "input_json_delta", partial_json: C.function.arguments } };
55449
+ p(o.encode(`event: content_block_delta
55450
+ data: ${JSON.stringify(A)}
55451
55451
 
55452
55452
  `));
55453
55453
  } catch {
55454
55454
  try {
55455
- let O = b.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"'), L = { type: "content_block_delta", index: y, delta: { type: "input_json_delta", partial_json: O } };
55456
- v(o.encode(`event: content_block_delta
55457
- data: ${JSON.stringify(L)}
55455
+ let E = C.function.arguments.replace(/[\x00-\x1F\x7F-\x9F]/g, "").replace(/\\/g, "\\\\").replace(/"/g, '\\"'), M = { type: "content_block_delta", index: g, delta: { type: "input_json_delta", partial_json: E } };
55456
+ p(o.encode(`event: content_block_delta
55457
+ data: ${JSON.stringify(M)}
55458
55458
 
55459
55459
  `));
55460
- } catch (O) {
55461
- console.error(O);
55460
+ } catch (E) {
55461
+ console.error(E);
55462
55462
  }
55463
55463
  }
55464
55464
  }
55465
55465
  }
55466
55466
  }
55467
- if (S?.finish_reason && !s && !i) {
55468
- if (i = true, m === 0 && f === 0 && console.error("Warning: No content in the stream response!"), (d || f > 0) && !s) {
55469
- p("content_block_stop hasTextContentStarted");
55470
- let k = { type: "content_block_stop", index: y };
55471
- v(o.encode(`event: content_block_stop
55472
- data: ${JSON.stringify(k)}
55467
+ if (T?.finish_reason && !s && !i) {
55468
+ if (i = true, m === 0 && f === 0 && console.error("Warning: No content in the stream response!"), (u || f > 0) && !s) {
55469
+ h("content_block_stop hasTextContentStarted");
55470
+ let b = { type: "content_block_stop", index: g };
55471
+ p(o.encode(`event: content_block_stop
55472
+ data: ${JSON.stringify(b)}
55473
55473
 
55474
55474
  `));
55475
55475
  }
55476
55476
  if (!s) {
55477
- let R = { type: "message_delta", delta: { stop_reason: { stop: "end_turn", length: "max_tokens", tool_calls: "tool_use", content_filter: "stop_sequence" }[S.finish_reason] || "end_turn", stop_sequence: null }, usage: { input_tokens: P.usage?.prompt_tokens || 0, output_tokens: P.usage?.completion_tokens || 0 } };
55478
- v(o.encode(`event: message_delta
55479
- data: ${JSON.stringify(R)}
55477
+ let x = { type: "message_delta", delta: { stop_reason: { stop: "end_turn", length: "max_tokens", tool_calls: "tool_use", content_filter: "stop_sequence" }[T.finish_reason] || "end_turn", stop_sequence: null }, usage: { input_tokens: w.usage?.prompt_tokens || 0, output_tokens: w.usage?.completion_tokens || 0 } };
55478
+ p(o.encode(`event: message_delta
55479
+ data: ${JSON.stringify(x)}
55480
55480
 
55481
55481
  `));
55482
55482
  }
55483
55483
  if (!s) {
55484
- let k = { type: "message_stop" };
55485
- v(o.encode(`event: message_stop
55486
- data: ${JSON.stringify(k)}
55484
+ let b = { type: "message_stop" };
55485
+ p(o.encode(`event: message_stop
55486
+ data: ${JSON.stringify(b)}
55487
55487
 
55488
55488
  `));
55489
55489
  }
55490
55490
  break;
55491
55491
  }
55492
- } catch (P) {
55493
- p(`parseError: ${P.name} message: ${P.message} stack: ${P.stack} data: ${B}`);
55492
+ } catch (w) {
55493
+ h(`parseError: ${w.name} message: ${w.message} stack: ${w.stack} data: ${z}`);
55494
55494
  }
55495
55495
  }
55496
55496
  }
55497
- z();
55498
- } catch (x) {
55497
+ S();
55498
+ } catch (_) {
55499
55499
  if (!s) try {
55500
- n.error(x);
55501
- } catch (C) {
55502
- console.error(C);
55500
+ n.error(_);
55501
+ } catch (R) {
55502
+ console.error(R);
55503
55503
  }
55504
55504
  } finally {
55505
- if (M) try {
55506
- M.releaseLock();
55507
- } catch (x) {
55508
- console.error(x);
55505
+ if (P) try {
55506
+ P.releaseLock();
55507
+ } catch (_) {
55508
+ console.error(_);
55509
55509
  }
55510
55510
  }
55511
55511
  }, cancel(n) {
55512
- p("cancle stream:", n);
55512
+ h("cancle stream:", n);
55513
55513
  } });
55514
55514
  }
55515
55515
  convertOpenAIResponseToAnthropic(e) {
55516
- p("Original OpenAI response:", JSON.stringify(e, null, 2));
55516
+ h("Original OpenAI response:", JSON.stringify(e, null, 2));
55517
55517
  let t = e.choices[0];
55518
55518
  if (!t) throw new Error("No choices found in OpenAI response");
55519
55519
  let n = [];
55520
55520
  t.message.content && n.push({ type: "text", text: t.message.content }), t.message.tool_calls && t.message.tool_calls.length > 0 && t.message.tool_calls.forEach((r, l) => {
55521
- let u = {};
55521
+ let d = {};
55522
55522
  try {
55523
- let d = r.function.arguments || "{}";
55524
- typeof d == "object" ? u = d : typeof d == "string" && (u = JSON.parse(d));
55523
+ let u = r.function.arguments || "{}";
55524
+ typeof u == "object" ? d = u : typeof u == "string" && (d = JSON.parse(u));
55525
55525
  } catch {
55526
- u = { text: r.function.arguments || "" };
55526
+ d = { text: r.function.arguments || "" };
55527
55527
  }
55528
- n.push({ type: "tool_use", id: r.id, name: r.function.name, input: u });
55528
+ n.push({ type: "tool_use", id: r.id, name: r.function.name, input: d });
55529
55529
  });
55530
55530
  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 } };
55531
- return p("Conversion complete, final Anthropic response:", JSON.stringify(o, null, 2)), o;
55531
+ return h("Conversion complete, final Anthropic response:", JSON.stringify(o, null, 2)), o;
55532
55532
  }
55533
55533
  };
55534
- var I = class {
55534
+ var q = class {
55535
55535
  name = "gemini";
55536
55536
  endPoint = "/v1beta/models/:modelAndAction";
55537
55537
  transformRequestIn(e, t) {
@@ -55547,12 +55547,12 @@ var I = class {
55547
55547
  }), { name: n.function.name, description: n.function.description, parameters: n.function.parameters })) || [] }] }, config: { url: new URL(`./${e.model}:${e.stream ? "streamGenerateContent?alt=sse" : "generateContent"}`, t.baseUrl), headers: { "x-goog-api-key": t.apiKey, Authorization: void 0 } } };
55548
55548
  }
55549
55549
  transformRequestOut(e) {
55550
- let t = e.contents, n = e.tools, o = e.model, r = e.max_tokens, l = e.temperature, u = e.stream, d = e.tool_choice, i = { messages: [], model: o, max_tokens: r, temperature: l, stream: u, tool_choice: d };
55550
+ let t = e.contents, n = e.tools, o = e.model, r = e.max_tokens, l = e.temperature, d = e.stream, u = e.tool_choice, i = { messages: [], model: o, max_tokens: r, temperature: l, stream: d, tool_choice: u };
55551
55551
  return Array.isArray(t) && t.forEach((c) => {
55552
- typeof c == "string" ? i.messages.push({ role: "user", content: c }) : typeof c.text == "string" ? i.messages.push({ role: "user", content: c.text || null }) : c.role === "user" ? i.messages.push({ role: "user", content: c?.parts?.map((h) => ({ type: "text", text: h.text || "" })) || [] }) : c.role === "model" && i.messages.push({ role: "assistant", content: c?.parts?.map((h) => ({ type: "text", text: h.text || "" })) || [] });
55552
+ typeof c == "string" ? i.messages.push({ role: "user", content: c }) : typeof c.text == "string" ? i.messages.push({ role: "user", content: c.text || null }) : c.role === "user" ? i.messages.push({ role: "user", content: c?.parts?.map((k) => ({ type: "text", text: k.text || "" })) || [] }) : c.role === "model" && i.messages.push({ role: "assistant", content: c?.parts?.map((k) => ({ type: "text", text: k.text || "" })) || [] });
55553
55553
  }), Array.isArray(n) && (i.tools = [], n.forEach((c) => {
55554
- Array.isArray(c.functionDeclarations) && c.functionDeclarations.forEach((h) => {
55555
- i.tools.push({ type: "function", function: { name: h.name, description: h.description, parameters: h.parameters } });
55554
+ Array.isArray(c.functionDeclarations) && c.functionDeclarations.forEach((k) => {
55555
+ i.tools.push({ type: "function", function: { name: k.name, description: k.description, parameters: k.parameters } });
55556
55556
  });
55557
55557
  })), i;
55558
55558
  }
@@ -55567,20 +55567,20 @@ var I = class {
55567
55567
  let l = e.body.getReader();
55568
55568
  try {
55569
55569
  for (; ; ) {
55570
- let { done: u, value: d } = await l.read();
55571
- if (u) break;
55572
- let i = t.decode(d, { stream: true });
55570
+ let { done: d, value: u } = await l.read();
55571
+ if (d) break;
55572
+ let i = t.decode(u, { stream: true });
55573
55573
  if (i.startsWith("data: ")) i = i.slice(6).trim();
55574
55574
  else break;
55575
- p("gemini chunk:", i), i = JSON.parse(i);
55576
- let c = i.candidates[0].content.parts.filter((g) => g.functionCall).map((g) => ({ id: g.functionCall?.id || `tool_${Math.random().toString(36).substring(2, 15)}`, type: "function", function: { name: g.functionCall?.name, arguments: JSON.stringify(g.functionCall?.args || {}) } })), h = { choices: [{ delta: { role: "assistant", content: i.candidates[0].content.parts.filter((g) => g.text).map((g) => g.text).join(`
55575
+ h("gemini chunk:", i), i = JSON.parse(i);
55576
+ let c = i.candidates[0].content.parts.filter((v) => v.functionCall).map((v) => ({ id: v.functionCall?.id || `tool_${Math.random().toString(36).substring(2, 15)}`, type: "function", function: { name: v.functionCall?.name, arguments: JSON.stringify(v.functionCall?.args || {}) } })), k = { choices: [{ delta: { role: "assistant", content: i.candidates[0].content.parts.filter((v) => v.text).map((v) => v.text).join(`
55577
55577
  `), tool_calls: c.length > 0 ? c : void 0 }, finish_reason: i.candidates[0].finishReason?.toLowerCase() || null, index: i.candidates[0].index || c.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" };
55578
- p("gemini response:", JSON.stringify(h, null, 2)), r.enqueue(n.encode(`data: ${JSON.stringify(h)}
55578
+ h("gemini response:", JSON.stringify(k, null, 2)), r.enqueue(n.encode(`data: ${JSON.stringify(k)}
55579
55579
 
55580
55580
  `));
55581
55581
  }
55582
- } catch (u) {
55583
- r.error(u);
55582
+ } catch (d) {
55583
+ r.error(d);
55584
55584
  } finally {
55585
55585
  r.close();
55586
55586
  }
@@ -55601,58 +55601,58 @@ var j = class {
55601
55601
  return new Response(JSON.stringify(t), { status: e.status, statusText: e.statusText, headers: e.headers });
55602
55602
  } else if (e.headers.get("Content-Type")?.includes("stream")) {
55603
55603
  if (!e.body) return e;
55604
- let t = new TextDecoder(), n = new TextEncoder(), o = "", r = false, l = new ReadableStream({ async start(u) {
55605
- let d = e.body.getReader();
55604
+ let t = new TextDecoder(), n = new TextEncoder(), o = "", r = false, l = new ReadableStream({ async start(d) {
55605
+ let u = e.body.getReader();
55606
55606
  try {
55607
55607
  for (; ; ) {
55608
- let { done: i, value: c } = await d.read();
55608
+ let { done: i, value: c } = await u.read();
55609
55609
  if (i) break;
55610
- let g = t.decode(c, { stream: true }).split(`
55610
+ let v = t.decode(c, { stream: true }).split(`
55611
55611
  `);
55612
- for (let m of g) if (m.startsWith("data: ") && m.trim() !== "data: [DONE]") try {
55612
+ for (let m of v) if (m.startsWith("data: ") && m.trim() !== "data: [DONE]") try {
55613
55613
  let f = JSON.parse(m.slice(6));
55614
55614
  if (f.choices?.[0]?.delta?.reasoning_content) {
55615
55615
  o += f.choices[0].delta.reasoning_content;
55616
55616
  let s = { ...f, choices: [{ ...f.choices[0], delta: { ...f.choices[0].delta, thinking: { content: f.choices[0].delta.reasoning_content } } }] };
55617
55617
  delete s.choices[0].delta.reasoning_content;
55618
- let _ = `data: ${JSON.stringify(s)}
55618
+ let y = `data: ${JSON.stringify(s)}
55619
55619
 
55620
55620
  `;
55621
- u.enqueue(n.encode(_));
55621
+ d.enqueue(n.encode(y));
55622
55622
  continue;
55623
55623
  }
55624
55624
  if (f.choices?.[0]?.delta?.content && o && !r) {
55625
55625
  r = true;
55626
- let s = Date.now().toString(), _ = { ...f, choices: [{ ...f.choices[0], delta: { ...f.choices[0].delta, content: null, thinking: { content: o, signature: s } } }] };
55627
- delete _.choices[0].delta.reasoning_content;
55628
- let y = `data: ${JSON.stringify(_)}
55626
+ let s = Date.now().toString(), y = { ...f, choices: [{ ...f.choices[0], delta: { ...f.choices[0].delta, content: null, thinking: { content: o, signature: s } } }] };
55627
+ delete y.choices[0].delta.reasoning_content;
55628
+ let g = `data: ${JSON.stringify(y)}
55629
55629
 
55630
55630
  `;
55631
- u.enqueue(n.encode(y));
55631
+ d.enqueue(n.encode(g));
55632
55632
  }
55633
55633
  if (f.choices[0]?.delta?.reasoning_content && delete f.choices[0].delta.reasoning_content, f.choices?.[0]?.delta && Object.keys(f.choices[0].delta).length > 0) {
55634
55634
  r && f.choices[0].index++;
55635
55635
  let s = `data: ${JSON.stringify(f)}
55636
55636
 
55637
55637
  `;
55638
- u.enqueue(n.encode(s));
55638
+ d.enqueue(n.encode(s));
55639
55639
  }
55640
55640
  } catch {
55641
- u.enqueue(n.encode(m + `
55641
+ d.enqueue(n.encode(m + `
55642
55642
  `));
55643
55643
  }
55644
- else u.enqueue(n.encode(m + `
55644
+ else d.enqueue(n.encode(m + `
55645
55645
  `));
55646
55646
  }
55647
55647
  } catch (i) {
55648
- u.error(i);
55648
+ d.error(i);
55649
55649
  } finally {
55650
55650
  try {
55651
- d.releaseLock();
55651
+ u.releaseLock();
55652
55652
  } catch (i) {
55653
55653
  console.error("Error releasing reader lock:", i);
55654
55654
  }
55655
- u.close();
55655
+ d.close();
55656
55656
  }
55657
55657
  } });
55658
55658
  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" } });
@@ -55660,7 +55660,7 @@ var j = class {
55660
55660
  return e;
55661
55661
  }
55662
55662
  };
55663
- var q = class {
55663
+ var J = class {
55664
55664
  name = "tooluse";
55665
55665
  transformRequestIn(e) {
55666
55666
  return e.messages.push({ role: "system", content: "<system-reminder>Tool mode is active. The user expects you to proactively execute the most suitable tool to help complete the task. \nBefore invoking a tool, you must carefully evaluate whether it matches the current task. If no available tool is appropriate for the task, you MUST call the `ExitTool` to exit tool mode \u2014 this is the only valid way to terminate tool mode.\nAlways prioritize completing the user's task effectively and efficiently by using tools whenever appropriate.</system-reminder>" }), e.tools?.length && (e.tool_choice = "required", e.tools.unshift({ type: "function", function: { name: "ExitTool", description: `Use this tool when you are in tool mode and have completed the task. This is the only valid way to exit tool mode.
@@ -55679,15 +55679,15 @@ Examples:
55679
55679
  return new Response(JSON.stringify(t), { status: e.status, statusText: e.statusText, headers: e.headers });
55680
55680
  } else if (e.headers.get("Content-Type")?.includes("stream")) {
55681
55681
  if (!e.body) return e;
55682
- let t = new TextDecoder(), n = new TextEncoder(), o = -1, r = "", l = new ReadableStream({ async start(u) {
55683
- let d = e.body.getReader();
55682
+ let t = new TextDecoder(), n = new TextEncoder(), o = -1, r = "", l = new ReadableStream({ async start(d) {
55683
+ let u = e.body.getReader();
55684
55684
  try {
55685
55685
  for (; ; ) {
55686
- let { done: i, value: c } = await d.read();
55686
+ let { done: i, value: c } = await u.read();
55687
55687
  if (i) break;
55688
- let g = t.decode(c, { stream: true }).split(`
55688
+ let v = t.decode(c, { stream: true }).split(`
55689
55689
  `);
55690
- for (let m of g) if (m.startsWith("data: ") && m.trim() !== "data: [DONE]") try {
55690
+ for (let m of v) if (m.startsWith("data: ") && m.trim() !== "data: [DONE]") try {
55691
55691
  let f = JSON.parse(m.slice(6));
55692
55692
  if (f.choices[0]?.delta?.tool_calls?.length) {
55693
55693
  let s = f.choices[0].delta.tool_calls[0];
@@ -55697,12 +55697,12 @@ Examples:
55697
55697
  } else if (o > -1 && s.index === o && s.function.arguments) {
55698
55698
  r += s.function.arguments;
55699
55699
  try {
55700
- let _ = JSON.parse(r);
55701
- f.choices = [{ delta: { role: "assistant", content: _.response || "" } }];
55702
- let y = `data: ${JSON.stringify(f)}
55700
+ let y = JSON.parse(r);
55701
+ f.choices = [{ delta: { role: "assistant", content: y.response || "" } }];
55702
+ let g = `data: ${JSON.stringify(f)}
55703
55703
 
55704
55704
  `;
55705
- u.enqueue(n.encode(y));
55705
+ d.enqueue(n.encode(g));
55706
55706
  } catch {
55707
55707
  }
55708
55708
  continue;
@@ -55712,24 +55712,24 @@ Examples:
55712
55712
  let s = `data: ${JSON.stringify(f)}
55713
55713
 
55714
55714
  `;
55715
- u.enqueue(n.encode(s));
55715
+ d.enqueue(n.encode(s));
55716
55716
  }
55717
55717
  } catch {
55718
- u.enqueue(n.encode(m + `
55718
+ d.enqueue(n.encode(m + `
55719
55719
  `));
55720
55720
  }
55721
- else u.enqueue(n.encode(m + `
55721
+ else d.enqueue(n.encode(m + `
55722
55722
  `));
55723
55723
  }
55724
55724
  } catch (i) {
55725
- u.error(i);
55725
+ d.error(i);
55726
55726
  } finally {
55727
55727
  try {
55728
- d.releaseLock();
55728
+ u.releaseLock();
55729
55729
  } catch (i) {
55730
55730
  console.error("Error releasing reader lock:", i);
55731
55731
  }
55732
- u.close();
55732
+ d.close();
55733
55733
  }
55734
55734
  } });
55735
55735
  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" } });
@@ -55737,7 +55737,7 @@ Examples:
55737
55737
  return e;
55738
55738
  }
55739
55739
  };
55740
- var J = class {
55740
+ var U = class {
55741
55741
  name = "openrouter";
55742
55742
  transformRequestIn(e) {
55743
55743
  return e.model.includes("claude") || e.messages.forEach((t) => {
@@ -55752,56 +55752,97 @@ var J = class {
55752
55752
  return new Response(JSON.stringify(t), { status: e.status, statusText: e.statusText, headers: e.headers });
55753
55753
  } else if (e.headers.get("Content-Type")?.includes("stream")) {
55754
55754
  if (!e.body) return e;
55755
- let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", l = false, u = new ReadableStream({ async start(d) {
55756
- let i = e.body.getReader();
55757
- try {
55758
- for (; ; ) {
55759
- let { done: c, value: h } = await i.read();
55760
- if (c) break;
55761
- let m = t.decode(h, { stream: true }).split(`
55755
+ let t = new TextDecoder(), n = new TextEncoder(), o = false, r = "", l = false, d = "", u = new ReadableStream({ async start(i) {
55756
+ let c = e.body.getReader(), k = (m, f, s) => {
55757
+ let y = m.split(`
55762
55758
  `);
55763
- for (let f of m) if (f.startsWith("data: ") && f.trim() !== "data: [DONE]") try {
55764
- let s = JSON.parse(f.slice(6));
55765
- if (s.choices[0]?.delta?.content && !o && (o = true), s.choices?.[0]?.delta?.reasoning) {
55766
- r += s.choices[0].delta.reasoning;
55767
- let y = { ...s, choices: [{ ...s.choices[0], delta: { ...s.choices[0].delta, thinking: { content: s.choices[0].delta.reasoning } } }] };
55768
- delete y.choices[0].delta.reasoning;
55769
- let v = `data: ${JSON.stringify(y)}
55759
+ for (let g of y) g.trim() && f.enqueue(s.encode(g + `
55760
+ `));
55761
+ }, v = (m, f) => {
55762
+ let { controller: s, encoder: y } = f;
55763
+ if (m.startsWith("data: ") && m.trim() !== "data: [DONE]") {
55764
+ let g = m.slice(6);
55765
+ try {
55766
+ let p = JSON.parse(g);
55767
+ if (p.choices?.[0]?.delta?.content && !f.hasTextContent() && f.setHasTextContent(true), p.choices?.[0]?.delta?.reasoning) {
55768
+ f.appendReasoningContent(p.choices[0].delta.reasoning);
55769
+ let P = { ...p, choices: [{ ...p.choices?.[0], delta: { ...p.choices[0].delta, thinking: { content: p.choices[0].delta.reasoning } } }] };
55770
+ P.choices?.[0]?.delta && delete P.choices[0].delta.reasoning;
55771
+ let _ = `data: ${JSON.stringify(P)}
55770
55772
 
55771
55773
  `;
55772
- d.enqueue(n.encode(v));
55773
- continue;
55774
+ s.enqueue(y.encode(_));
55775
+ return;
55774
55776
  }
55775
- if (s.choices?.[0]?.delta?.content && r && !l) {
55776
- l = true;
55777
- let y = Date.now().toString(), v = { ...s, choices: [{ ...s.choices[0], delta: { ...s.choices[0].delta, content: null, thinking: { content: r, signature: y } } }] };
55778
- delete v.choices[0].delta.reasoning;
55779
- let z = `data: ${JSON.stringify(v)}
55777
+ if (p.choices?.[0]?.delta?.content && f.reasoningContent() && !f.isReasoningComplete()) {
55778
+ f.setReasoningComplete(true);
55779
+ let P = Date.now().toString(), _ = { ...p, choices: [{ ...p.choices?.[0], delta: { ...p.choices[0].delta, content: null, thinking: { content: f.reasoningContent(), signature: P } } }] };
55780
+ _.choices?.[0]?.delta && delete _.choices[0].delta.reasoning;
55781
+ let R = `data: ${JSON.stringify(_)}
55780
55782
 
55781
55783
  `;
55782
- d.enqueue(n.encode(z));
55784
+ s.enqueue(y.encode(R));
55783
55785
  }
55784
- s.choices[0]?.delta?.reasoning && delete s.choices[0].delta.reasoning, s.choices[0]?.delta?.tool_calls?.length && o && (s.choices[0].index += 1);
55785
- let _ = `data: ${JSON.stringify(s)}
55786
+ p.choices?.[0]?.delta?.reasoning && delete p.choices[0].delta.reasoning, p.choices?.[0]?.delta?.tool_calls?.length && f.hasTextContent() && (typeof p.choices[0].index == "number" ? p.choices[0].index += 1 : p.choices[0].index = 1);
55787
+ let S = `data: ${JSON.stringify(p)}
55786
55788
 
55787
55789
  `;
55788
- d.enqueue(n.encode(_));
55790
+ s.enqueue(y.encode(S));
55789
55791
  } catch {
55790
- d.enqueue(n.encode(f + `
55792
+ s.enqueue(y.encode(m + `
55793
+ `));
55794
+ }
55795
+ } else s.enqueue(y.encode(m + `
55796
+ `));
55797
+ };
55798
+ try {
55799
+ for (; ; ) {
55800
+ let { done: m, value: f } = await c.read();
55801
+ if (m) {
55802
+ d.trim() && k(d, i, n);
55803
+ break;
55804
+ }
55805
+ if (!f || f.length === 0) continue;
55806
+ let s;
55807
+ try {
55808
+ s = t.decode(f, { stream: true });
55809
+ } catch (g) {
55810
+ console.warn("Failed to decode chunk", g);
55811
+ continue;
55812
+ }
55813
+ if (s.length === 0) continue;
55814
+ if (d += s, d.length > 1e6) {
55815
+ console.warn("Buffer size exceeds limit, processing partial data");
55816
+ let g = d.split(`
55817
+ `);
55818
+ d = g.pop() || "";
55819
+ for (let p of g) if (p.trim()) try {
55820
+ v(p, { controller: i, encoder: n, hasTextContent: () => o, setHasTextContent: (S) => o = S, reasoningContent: () => r, appendReasoningContent: (S) => r += S, isReasoningComplete: () => l, setReasoningComplete: (S) => l = S });
55821
+ } catch (S) {
55822
+ console.error("Error processing line:", p, S), i.enqueue(n.encode(p + `
55791
55823
  `));
55824
+ }
55825
+ continue;
55792
55826
  }
55793
- else d.enqueue(n.encode(f + `
55827
+ let y = d.split(`
55828
+ `);
55829
+ d = y.pop() || "";
55830
+ for (let g of y) if (g.trim()) try {
55831
+ v(g, { controller: i, encoder: n, hasTextContent: () => o, setHasTextContent: (p) => o = p, reasoningContent: () => r, appendReasoningContent: (p) => r += p, isReasoningComplete: () => l, setReasoningComplete: (p) => l = p });
55832
+ } catch (p) {
55833
+ console.error("Error processing line:", g, p), i.enqueue(n.encode(g + `
55794
55834
  `));
55835
+ }
55795
55836
  }
55796
- } catch (c) {
55797
- d.error(c);
55837
+ } catch (m) {
55838
+ console.error("Stream error:", m), i.error(m);
55798
55839
  } finally {
55799
55840
  try {
55800
- i.releaseLock();
55801
- } catch (c) {
55802
- console.error("Error releasing reader lock:", c);
55841
+ c.releaseLock();
55842
+ } catch (m) {
55843
+ console.error("Error releasing reader lock:", m);
55803
55844
  }
55804
- d.close();
55845
+ i.close();
55805
55846
  }
55806
55847
  } });
55807
55848
  return new Response(u, { status: e.status, statusText: e.statusText, headers: { "Content-Type": e.headers.get("Content-Type") || "text/plain", "Cache-Control": "no-cache", Connection: "keep-alive" } });
@@ -55809,7 +55850,7 @@ var J = class {
55809
55850
  return e;
55810
55851
  }
55811
55852
  };
55812
- var U = class {
55853
+ var D = class {
55813
55854
  constructor(e) {
55814
55855
  this.options = e;
55815
55856
  this.max_tokens = this.options?.max_tokens;
@@ -55820,14 +55861,14 @@ var U = class {
55820
55861
  return e.max_tokens && e.max_tokens > this.max_tokens && (e.max_tokens = this.max_tokens), e;
55821
55862
  }
55822
55863
  };
55823
- var ne = { AnthropicTransformer: F, GeminiTransformer: I, DeepseekTransformer: j, TooluseTransformer: q, OpenrouterTransformer: J, MaxTokenTransformer: U };
55824
- var D = class {
55864
+ var ne = { AnthropicTransformer: I, GeminiTransformer: q, DeepseekTransformer: j, TooluseTransformer: J, OpenrouterTransformer: U, MaxTokenTransformer: D };
55865
+ var B = class {
55825
55866
  constructor(e) {
55826
55867
  this.configService = e;
55827
55868
  }
55828
55869
  transformers = /* @__PURE__ */ new Map();
55829
55870
  registerTransformer(e, t) {
55830
- this.transformers.set(e, t), p(`register transformer: ${e}${t.endPoint ? ` (endpoint: ${t.endPoint})` : " (no endpoint)"}`);
55871
+ this.transformers.set(e, t), h(`register transformer: ${e}${t.endPoint ? ` (endpoint: ${t.endPoint})` : " (no endpoint)"}`);
55831
55872
  }
55832
55873
  getTransformer(e) {
55833
55874
  return this.transformers.get(e);
@@ -55857,7 +55898,7 @@ var D = class {
55857
55898
  try {
55858
55899
  let t = import_node_module.default._load;
55859
55900
  if (import_node_module.default._load = function(n, o, r) {
55860
- return n === "claude-code-router" ? { log: p } : t.apply(import_node_module.default, arguments);
55901
+ return n === "claude-code-router" ? { log: h } : t.apply(import_node_module.default, arguments);
55861
55902
  }, e.path) {
55862
55903
  let n = W(W.resolve(e.path));
55863
55904
  if (n) {
@@ -55868,14 +55909,14 @@ var D = class {
55868
55909
  }
55869
55910
  return false;
55870
55911
  } catch (t) {
55871
- return p(`load transformer (${e.path}) error:`, t.message, t.stack), false;
55912
+ return h(`load transformer (${e.path}) error:`, t.message, t.stack), false;
55872
55913
  }
55873
55914
  }
55874
55915
  async initialize() {
55875
55916
  try {
55876
55917
  await this.registerDefaultTransformersInternal(), await this.loadFromConfig();
55877
55918
  } catch (e) {
55878
- p("TransformerService init error:", e);
55919
+ h("TransformerService init error:", e);
55879
55920
  }
55880
55921
  }
55881
55922
  async registerDefaultTransformersInternal() {
@@ -55888,7 +55929,7 @@ var D = class {
55888
55929
  }
55889
55930
  });
55890
55931
  } catch (e) {
55891
- p("transformer regist error:", e);
55932
+ h("transformer regist error:", e);
55892
55933
  }
55893
55934
  }
55894
55935
  async loadFromConfig() {
@@ -55907,8 +55948,8 @@ var G = class {
55907
55948
  providerService;
55908
55949
  transformerService;
55909
55950
  constructor(e = {}) {
55910
- this.configService = new N(e), this.transformerService = new D(this.configService), this.transformerService.initialize().finally(() => {
55911
- this.providerService = new $(this.configService, this.transformerService), this.llmService = new H(this.providerService);
55951
+ this.configService = new N(e), this.transformerService = new B(this.configService), this.transformerService.initialize().finally(() => {
55952
+ this.providerService = new F(this.configService, this.transformerService), this.llmService = new $(this.providerService);
55912
55953
  }), this.app = pe();
55913
55954
  }
55914
55955
  async register(e, t) {
@@ -55923,21 +55964,21 @@ var G = class {
55923
55964
  try {
55924
55965
  let r = n.body;
55925
55966
  if (!r || !r.model) return o.code(400).send({ error: "Missing model in request body" });
55926
- let [l, u] = r.model.split(",");
55927
- r.model = u, n.provider = l;
55967
+ let [l, d] = r.model.split(",");
55968
+ r.model = d, n.provider = l;
55928
55969
  return;
55929
55970
  } catch (r) {
55930
55971
  return n.log.error("Error in modelProviderMiddleware:", r), o.code(500).send({ error: "Internal server error" });
55931
55972
  }
55932
55973
  }), this.app.register(te);
55933
55974
  let e = await this.app.listen({ port: parseInt(this.configService.get("PORT") || "3000", 10), host: this.configService.get("HOST") || "127.0.0.1" });
55934
- p(`\u{1F680} LLMs API server listening on ${e}`);
55975
+ h(`\u{1F680} LLMs API server listening on ${e}`);
55935
55976
  let t = async (n) => {
55936
- p(`Received ${n}, shutting down gracefully...`), await this.app.close(), process.exit(0);
55977
+ h(`Received ${n}, shutting down gracefully...`), await this.app.close(), process.exit(0);
55937
55978
  };
55938
55979
  process.on("SIGINT", () => t("SIGINT")), process.on("SIGTERM", () => t("SIGTERM"));
55939
55980
  } catch (e) {
55940
- p(`Error starting server: ${e}`), process.exit(1);
55981
+ h(`Error starting server: ${e}`), process.exit(1);
55941
55982
  }
55942
55983
  }
55943
55984
  };
@@ -56264,7 +56305,7 @@ async function executeCodeCommand(args = []) {
56264
56305
  }
56265
56306
 
56266
56307
  // package.json
56267
- var version = "1.0.18";
56308
+ var version = "1.0.19";
56268
56309
 
56269
56310
  // src/cli.ts
56270
56311
  var import_child_process2 = require("child_process");