@fangyb/ahchat-bridge 0.1.34 → 0.1.36

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.
@@ -420,11 +420,11 @@ var require_codegen = __commonJS({
420
420
  const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
421
421
  return `${varKind} ${this.name}${rhs};` + _n;
422
422
  }
423
- optimizeNames(names, constants) {
423
+ optimizeNames(names, constants2) {
424
424
  if (!names[this.name.str])
425
425
  return;
426
426
  if (this.rhs)
427
- this.rhs = optimizeExpr(this.rhs, names, constants);
427
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
428
428
  return this;
429
429
  }
430
430
  get names() {
@@ -441,10 +441,10 @@ var require_codegen = __commonJS({
441
441
  render({ _n }) {
442
442
  return `${this.lhs} = ${this.rhs};` + _n;
443
443
  }
444
- optimizeNames(names, constants) {
444
+ optimizeNames(names, constants2) {
445
445
  if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
446
446
  return;
447
- this.rhs = optimizeExpr(this.rhs, names, constants);
447
+ this.rhs = optimizeExpr(this.rhs, names, constants2);
448
448
  return this;
449
449
  }
450
450
  get names() {
@@ -505,8 +505,8 @@ var require_codegen = __commonJS({
505
505
  optimizeNodes() {
506
506
  return `${this.code}` ? this : void 0;
507
507
  }
508
- optimizeNames(names, constants) {
509
- this.code = optimizeExpr(this.code, names, constants);
508
+ optimizeNames(names, constants2) {
509
+ this.code = optimizeExpr(this.code, names, constants2);
510
510
  return this;
511
511
  }
512
512
  get names() {
@@ -535,12 +535,12 @@ var require_codegen = __commonJS({
535
535
  }
536
536
  return nodes.length > 0 ? this : void 0;
537
537
  }
538
- optimizeNames(names, constants) {
538
+ optimizeNames(names, constants2) {
539
539
  const { nodes } = this;
540
540
  let i = nodes.length;
541
541
  while (i--) {
542
542
  const n = nodes[i];
543
- if (n.optimizeNames(names, constants))
543
+ if (n.optimizeNames(names, constants2))
544
544
  continue;
545
545
  subtractNames(names, n.names);
546
546
  nodes.splice(i, 1);
@@ -593,12 +593,12 @@ var require_codegen = __commonJS({
593
593
  return void 0;
594
594
  return this;
595
595
  }
596
- optimizeNames(names, constants) {
596
+ optimizeNames(names, constants2) {
597
597
  var _a3;
598
- this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
599
- if (!(super.optimizeNames(names, constants) || this.else))
598
+ this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
599
+ if (!(super.optimizeNames(names, constants2) || this.else))
600
600
  return;
601
- this.condition = optimizeExpr(this.condition, names, constants);
601
+ this.condition = optimizeExpr(this.condition, names, constants2);
602
602
  return this;
603
603
  }
604
604
  get names() {
@@ -621,10 +621,10 @@ var require_codegen = __commonJS({
621
621
  render(opts) {
622
622
  return `for(${this.iteration})` + super.render(opts);
623
623
  }
624
- optimizeNames(names, constants) {
625
- if (!super.optimizeNames(names, constants))
624
+ optimizeNames(names, constants2) {
625
+ if (!super.optimizeNames(names, constants2))
626
626
  return;
627
- this.iteration = optimizeExpr(this.iteration, names, constants);
627
+ this.iteration = optimizeExpr(this.iteration, names, constants2);
628
628
  return this;
629
629
  }
630
630
  get names() {
@@ -660,10 +660,10 @@ var require_codegen = __commonJS({
660
660
  render(opts) {
661
661
  return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
662
662
  }
663
- optimizeNames(names, constants) {
664
- if (!super.optimizeNames(names, constants))
663
+ optimizeNames(names, constants2) {
664
+ if (!super.optimizeNames(names, constants2))
665
665
  return;
666
- this.iterable = optimizeExpr(this.iterable, names, constants);
666
+ this.iterable = optimizeExpr(this.iterable, names, constants2);
667
667
  return this;
668
668
  }
669
669
  get names() {
@@ -705,11 +705,11 @@ var require_codegen = __commonJS({
705
705
  (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNodes();
706
706
  return this;
707
707
  }
708
- optimizeNames(names, constants) {
708
+ optimizeNames(names, constants2) {
709
709
  var _a3, _b;
710
- super.optimizeNames(names, constants);
711
- (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
712
- (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants);
710
+ super.optimizeNames(names, constants2);
711
+ (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants2);
712
+ (_b = this.finally) === null || _b === void 0 ? void 0 : _b.optimizeNames(names, constants2);
713
713
  return this;
714
714
  }
715
715
  get names() {
@@ -1010,7 +1010,7 @@ var require_codegen = __commonJS({
1010
1010
  function addExprNames(names, from) {
1011
1011
  return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
1012
1012
  }
1013
- function optimizeExpr(expr, names, constants) {
1013
+ function optimizeExpr(expr, names, constants2) {
1014
1014
  if (expr instanceof code_1.Name)
1015
1015
  return replaceName(expr);
1016
1016
  if (!canOptimize(expr))
@@ -1025,14 +1025,14 @@ var require_codegen = __commonJS({
1025
1025
  return items;
1026
1026
  }, []));
1027
1027
  function replaceName(n) {
1028
- const c = constants[n.str];
1028
+ const c = constants2[n.str];
1029
1029
  if (c === void 0 || names[n.str] !== 1)
1030
1030
  return n;
1031
1031
  delete names[n.str];
1032
1032
  return c;
1033
1033
  }
1034
1034
  function canOptimize(e) {
1035
- return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
1035
+ return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants2[c.str] !== void 0);
1036
1036
  }
1037
1037
  }
1038
1038
  function subtractNames(names, from) {
@@ -2901,20 +2901,20 @@ var require_compile = __commonJS({
2901
2901
  var util_1 = require_util();
2902
2902
  var validate_1 = require_validate();
2903
2903
  var SchemaEnv = class {
2904
- constructor(env) {
2904
+ constructor(env2) {
2905
2905
  var _a3;
2906
2906
  this.refs = {};
2907
2907
  this.dynamicAnchors = {};
2908
2908
  let schema;
2909
- if (typeof env.schema == "object")
2910
- schema = env.schema;
2911
- this.schema = env.schema;
2912
- this.schemaId = env.schemaId;
2913
- this.root = env.root || this;
2914
- this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
2915
- this.schemaPath = env.schemaPath;
2916
- this.localRefs = env.localRefs;
2917
- this.meta = env.meta;
2909
+ if (typeof env2.schema == "object")
2910
+ schema = env2.schema;
2911
+ this.schema = env2.schema;
2912
+ this.schemaId = env2.schemaId;
2913
+ this.root = env2.root || this;
2914
+ this.baseId = (_a3 = env2.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]);
2915
+ this.schemaPath = env2.schemaPath;
2916
+ this.localRefs = env2.localRefs;
2917
+ this.meta = env2.meta;
2918
2918
  this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
2919
2919
  this.refs = {};
2920
2920
  }
@@ -3098,15 +3098,15 @@ var require_compile = __commonJS({
3098
3098
  baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
3099
3099
  }
3100
3100
  }
3101
- let env;
3101
+ let env2;
3102
3102
  if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
3103
3103
  const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
3104
- env = resolveSchema.call(this, root, $ref);
3104
+ env2 = resolveSchema.call(this, root, $ref);
3105
3105
  }
3106
3106
  const { schemaId } = this.opts;
3107
- env = env || new SchemaEnv({ schema, schemaId, root, baseId });
3108
- if (env.schema !== env.root.schema)
3109
- return env;
3107
+ env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId });
3108
+ if (env2.schema !== env2.root.schema)
3109
+ return env2;
3110
3110
  return void 0;
3111
3111
  }
3112
3112
  }
@@ -3258,8 +3258,8 @@ var require_utils = __commonJS({
3258
3258
  }
3259
3259
  return ind;
3260
3260
  }
3261
- function removeDotSegments(path3) {
3262
- let input = path3;
3261
+ function removeDotSegments(path6) {
3262
+ let input = path6;
3263
3263
  const output = [];
3264
3264
  let nextSlash = -1;
3265
3265
  let len = 0;
@@ -3512,8 +3512,8 @@ var require_schemes = __commonJS({
3512
3512
  wsComponent.secure = void 0;
3513
3513
  }
3514
3514
  if (wsComponent.resourceName) {
3515
- const [path3, query] = wsComponent.resourceName.split("?");
3516
- wsComponent.path = path3 && path3 !== "/" ? path3 : void 0;
3515
+ const [path6, query] = wsComponent.resourceName.split("?");
3516
+ wsComponent.path = path6 && path6 !== "/" ? path6 : void 0;
3517
3517
  wsComponent.query = query;
3518
3518
  wsComponent.resourceName = void 0;
3519
3519
  }
@@ -4437,11 +4437,11 @@ var require_core = __commonJS({
4437
4437
  Ajv2.ValidationError = validation_error_1.default;
4438
4438
  Ajv2.MissingRefError = ref_error_1.default;
4439
4439
  exports2.default = Ajv2;
4440
- function checkOptions(checkOpts, options, msg, log = "error") {
4441
- for (const key in checkOpts) {
4440
+ function checkOptions(checkOpts2, options, msg, log = "error") {
4441
+ for (const key in checkOpts2) {
4442
4442
  const opt = key;
4443
4443
  if (opt in options)
4444
- this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
4444
+ this.logger[log](`${msg}: option ${key}. ${checkOpts2[opt]}`);
4445
4445
  }
4446
4446
  }
4447
4447
  function getSchEnv(keyRef) {
@@ -4488,13 +4488,13 @@ var require_core = __commonJS({
4488
4488
  }, warn() {
4489
4489
  }, error() {
4490
4490
  } };
4491
- function getLogger(logger) {
4492
- if (logger === false)
4491
+ function getLogger(logger3) {
4492
+ if (logger3 === false)
4493
4493
  return noLogs;
4494
- if (logger === void 0)
4494
+ if (logger3 === void 0)
4495
4495
  return console;
4496
- if (logger.log && logger.warn && logger.error)
4497
- return logger;
4496
+ if (logger3.log && logger3.warn && logger3.error)
4497
+ return logger3;
4498
4498
  throw new Error("logger must implement log, warn and error methods");
4499
4499
  }
4500
4500
  var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
@@ -4601,8 +4601,8 @@ var require_ref = __commonJS({
4601
4601
  schemaType: "string",
4602
4602
  code(cxt) {
4603
4603
  const { gen, schema: $ref, it } = cxt;
4604
- const { baseId, schemaEnv: env, validateName, opts, self } = it;
4605
- const { root } = env;
4604
+ const { baseId, schemaEnv: env2, validateName, opts, self } = it;
4605
+ const { root } = env2;
4606
4606
  if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
4607
4607
  return callRootRef();
4608
4608
  const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref);
@@ -4612,8 +4612,8 @@ var require_ref = __commonJS({
4612
4612
  return callValidate(schOrEnv);
4613
4613
  return inlineRefSchema(schOrEnv);
4614
4614
  function callRootRef() {
4615
- if (env === root)
4616
- return callRef(cxt, validateName, env, env.$async);
4615
+ if (env2 === root)
4616
+ return callRef(cxt, validateName, env2, env2.$async);
4617
4617
  const rootName = gen.scopeValue("root", { ref: root });
4618
4618
  return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
4619
4619
  }
@@ -4643,14 +4643,14 @@ var require_ref = __commonJS({
4643
4643
  exports2.getValidate = getValidate;
4644
4644
  function callRef(cxt, v, sch, $async) {
4645
4645
  const { gen, it } = cxt;
4646
- const { allErrors, schemaEnv: env, opts } = it;
4646
+ const { allErrors, schemaEnv: env2, opts } = it;
4647
4647
  const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
4648
4648
  if ($async)
4649
4649
  callAsyncRef();
4650
4650
  else
4651
4651
  callSyncRef();
4652
4652
  function callAsyncRef() {
4653
- if (!env.$async)
4653
+ if (!env2.$async)
4654
4654
  throw new Error("async schema referenced by sync schema");
4655
4655
  const valid = gen.let("valid");
4656
4656
  gen.try(() => {
@@ -6952,12 +6952,12 @@ var require_dist = __commonJS({
6952
6952
  throw new Error(`Unknown format "${name}"`);
6953
6953
  return f;
6954
6954
  };
6955
- function addFormats(ajv, list, fs3, exportName) {
6955
+ function addFormats(ajv, list, fs4, exportName) {
6956
6956
  var _a3;
6957
6957
  var _b;
6958
6958
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
6959
6959
  for (const f of list)
6960
- ajv.addFormat(f, fs3[f]);
6960
+ ajv.addFormat(f, fs4[f]);
6961
6961
  }
6962
6962
  module2.exports = exports2 = formatsPlugin;
6963
6963
  Object.defineProperty(exports2, "__esModule", { value: true });
@@ -7350,8 +7350,8 @@ function getErrorMap() {
7350
7350
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/helpers/parseUtil.js
7351
7351
  init_cjs_shims();
7352
7352
  var makeIssue = (params) => {
7353
- const { data, path: path3, errorMaps, issueData } = params;
7354
- const fullPath = [...path3, ...issueData.path || []];
7353
+ const { data, path: path6, errorMaps, issueData } = params;
7354
+ const fullPath = [...path6, ...issueData.path || []];
7355
7355
  const fullIssue = {
7356
7356
  ...issueData,
7357
7357
  path: fullPath
@@ -7470,11 +7470,11 @@ var errorUtil;
7470
7470
 
7471
7471
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v3/types.js
7472
7472
  var ParseInputLazyPath = class {
7473
- constructor(parent, value, path3, key) {
7473
+ constructor(parent, value, path6, key) {
7474
7474
  this._cachedPath = [];
7475
7475
  this.parent = parent;
7476
7476
  this.data = value;
7477
- this._path = path3;
7477
+ this._path = path6;
7478
7478
  this._key = key;
7479
7479
  }
7480
7480
  get path() {
@@ -11178,12 +11178,12 @@ function $constructor(name, initializer3, params) {
11178
11178
  }
11179
11179
  inst._zod.traits.add(name);
11180
11180
  initializer3(inst, def);
11181
- const proto = _.prototype;
11182
- const keys = Object.keys(proto);
11181
+ const proto2 = _.prototype;
11182
+ const keys = Object.keys(proto2);
11183
11183
  for (let i = 0; i < keys.length; i++) {
11184
11184
  const k = keys[i];
11185
11185
  if (!(k in inst)) {
11186
- inst[k] = proto[k].bind(inst);
11186
+ inst[k] = proto2[k].bind(inst);
11187
11187
  }
11188
11188
  }
11189
11189
  }
@@ -11406,10 +11406,10 @@ function mergeDefs(...defs) {
11406
11406
  function cloneDef(schema) {
11407
11407
  return mergeDefs(schema._zod.def);
11408
11408
  }
11409
- function getElementAtPath(obj, path3) {
11410
- if (!path3)
11409
+ function getElementAtPath(obj, path6) {
11410
+ if (!path6)
11411
11411
  return obj;
11412
- return path3.reduce((acc, key) => acc?.[key], obj);
11412
+ return path6.reduce((acc, key) => acc?.[key], obj);
11413
11413
  }
11414
11414
  function promiseAllObject(promisesObj) {
11415
11415
  const keys = Object.keys(promisesObj);
@@ -11628,8 +11628,8 @@ var BIGINT_FORMAT_RANGES = {
11628
11628
  };
11629
11629
  function pick(schema, mask) {
11630
11630
  const currDef = schema._zod.def;
11631
- const checks = currDef.checks;
11632
- const hasChecks = checks && checks.length > 0;
11631
+ const checks2 = currDef.checks;
11632
+ const hasChecks = checks2 && checks2.length > 0;
11633
11633
  if (hasChecks) {
11634
11634
  throw new Error(".pick() cannot be used on object schemas containing refinements");
11635
11635
  }
@@ -11653,8 +11653,8 @@ function pick(schema, mask) {
11653
11653
  }
11654
11654
  function omit(schema, mask) {
11655
11655
  const currDef = schema._zod.def;
11656
- const checks = currDef.checks;
11657
- const hasChecks = checks && checks.length > 0;
11656
+ const checks2 = currDef.checks;
11657
+ const hasChecks = checks2 && checks2.length > 0;
11658
11658
  if (hasChecks) {
11659
11659
  throw new Error(".omit() cannot be used on object schemas containing refinements");
11660
11660
  }
@@ -11680,8 +11680,8 @@ function extend(schema, shape) {
11680
11680
  if (!isPlainObject(shape)) {
11681
11681
  throw new Error("Invalid input to extend: expected a plain object");
11682
11682
  }
11683
- const checks = schema._zod.def.checks;
11684
- const hasChecks = checks && checks.length > 0;
11683
+ const checks2 = schema._zod.def.checks;
11684
+ const hasChecks = checks2 && checks2.length > 0;
11685
11685
  if (hasChecks) {
11686
11686
  const existingShape = schema._zod.def.shape;
11687
11687
  for (const key in shape) {
@@ -11731,8 +11731,8 @@ function merge(a, b) {
11731
11731
  }
11732
11732
  function partial(Class2, schema, mask) {
11733
11733
  const currDef = schema._zod.def;
11734
- const checks = currDef.checks;
11735
- const hasChecks = checks && checks.length > 0;
11734
+ const checks2 = currDef.checks;
11735
+ const hasChecks = checks2 && checks2.length > 0;
11736
11736
  if (hasChecks) {
11737
11737
  throw new Error(".partial() cannot be used on object schemas containing refinements");
11738
11738
  }
@@ -11818,11 +11818,11 @@ function explicitlyAborted(x, startIndex = 0) {
11818
11818
  }
11819
11819
  return false;
11820
11820
  }
11821
- function prefixIssues(path3, issues) {
11821
+ function prefixIssues(path6, issues) {
11822
11822
  return issues.map((iss) => {
11823
11823
  var _a3;
11824
11824
  (_a3 = iss).path ?? (_a3.path = []);
11825
- iss.path.unshift(path3);
11825
+ iss.path.unshift(path6);
11826
11826
  return iss;
11827
11827
  });
11828
11828
  }
@@ -11969,16 +11969,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
11969
11969
  }
11970
11970
  function formatError(error51, mapper = (issue2) => issue2.message) {
11971
11971
  const fieldErrors = { _errors: [] };
11972
- const processError = (error52, path3 = []) => {
11972
+ const processError = (error52, path6 = []) => {
11973
11973
  for (const issue2 of error52.issues) {
11974
11974
  if (issue2.code === "invalid_union" && issue2.errors.length) {
11975
- issue2.errors.map((issues) => processError({ issues }, [...path3, ...issue2.path]));
11975
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
11976
11976
  } else if (issue2.code === "invalid_key") {
11977
- processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
11977
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
11978
11978
  } else if (issue2.code === "invalid_element") {
11979
- processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
11979
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
11980
11980
  } else {
11981
- const fullpath = [...path3, ...issue2.path];
11981
+ const fullpath = [...path6, ...issue2.path];
11982
11982
  if (fullpath.length === 0) {
11983
11983
  fieldErrors._errors.push(mapper(issue2));
11984
11984
  } else {
@@ -12005,17 +12005,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
12005
12005
  }
12006
12006
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
12007
12007
  const result = { errors: [] };
12008
- const processError = (error52, path3 = []) => {
12008
+ const processError = (error52, path6 = []) => {
12009
12009
  var _a3, _b;
12010
12010
  for (const issue2 of error52.issues) {
12011
12011
  if (issue2.code === "invalid_union" && issue2.errors.length) {
12012
- issue2.errors.map((issues) => processError({ issues }, [...path3, ...issue2.path]));
12012
+ issue2.errors.map((issues) => processError({ issues }, [...path6, ...issue2.path]));
12013
12013
  } else if (issue2.code === "invalid_key") {
12014
- processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
12014
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
12015
12015
  } else if (issue2.code === "invalid_element") {
12016
- processError({ issues: issue2.issues }, [...path3, ...issue2.path]);
12016
+ processError({ issues: issue2.issues }, [...path6, ...issue2.path]);
12017
12017
  } else {
12018
- const fullpath = [...path3, ...issue2.path];
12018
+ const fullpath = [...path6, ...issue2.path];
12019
12019
  if (fullpath.length === 0) {
12020
12020
  result.errors.push(mapper(issue2));
12021
12021
  continue;
@@ -12047,8 +12047,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
12047
12047
  }
12048
12048
  function toDotPath(_path) {
12049
12049
  const segs = [];
12050
- const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
12051
- for (const seg of path3) {
12050
+ const path6 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
12051
+ for (const seg of path6) {
12052
12052
  if (typeof seg === "number")
12053
12053
  segs.push(`[${seg}]`);
12054
12054
  else if (typeof seg === "symbol")
@@ -12928,25 +12928,25 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
12928
12928
  inst._zod.def = def;
12929
12929
  inst._zod.bag = inst._zod.bag || {};
12930
12930
  inst._zod.version = version;
12931
- const checks = [...inst._zod.def.checks ?? []];
12931
+ const checks2 = [...inst._zod.def.checks ?? []];
12932
12932
  if (inst._zod.traits.has("$ZodCheck")) {
12933
- checks.unshift(inst);
12933
+ checks2.unshift(inst);
12934
12934
  }
12935
- for (const ch of checks) {
12935
+ for (const ch of checks2) {
12936
12936
  for (const fn of ch._zod.onattach) {
12937
12937
  fn(inst);
12938
12938
  }
12939
12939
  }
12940
- if (checks.length === 0) {
12940
+ if (checks2.length === 0) {
12941
12941
  (_a3 = inst._zod).deferred ?? (_a3.deferred = []);
12942
12942
  inst._zod.deferred?.push(() => {
12943
12943
  inst._zod.run = inst._zod.parse;
12944
12944
  });
12945
12945
  } else {
12946
- const runChecks = (payload, checks2, ctx) => {
12946
+ const runChecks = (payload, checks3, ctx) => {
12947
12947
  let isAborted2 = aborted(payload);
12948
12948
  let asyncResult;
12949
- for (const ch of checks2) {
12949
+ for (const ch of checks3) {
12950
12950
  if (ch._zod.def.when) {
12951
12951
  if (explicitlyAborted(payload))
12952
12952
  continue;
@@ -12990,7 +12990,7 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
12990
12990
  canary.aborted = true;
12991
12991
  return canary;
12992
12992
  }
12993
- const checkResult = runChecks(payload, checks, ctx);
12993
+ const checkResult = runChecks(payload, checks2, ctx);
12994
12994
  if (checkResult instanceof Promise) {
12995
12995
  if (ctx.async === false)
12996
12996
  throw new $ZodAsyncError();
@@ -13015,9 +13015,9 @@ var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
13015
13015
  if (result instanceof Promise) {
13016
13016
  if (ctx.async === false)
13017
13017
  throw new $ZodAsyncError();
13018
- return result.then((result2) => runChecks(result2, checks, ctx));
13018
+ return result.then((result2) => runChecks(result2, checks2, ctx));
13019
13019
  }
13020
- return runChecks(result, checks, ctx);
13020
+ return runChecks(result, checks2, ctx);
13021
13021
  };
13022
13022
  }
13023
13023
  defineLazy(inst, "~standard", () => ({
@@ -23117,12 +23117,12 @@ var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
23117
23117
  inst.safeParse = (data, params) => safeParse(inst, data, params);
23118
23118
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
23119
23119
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
23120
- inst.check = (...checks) => {
23120
+ inst.check = (...checks2) => {
23121
23121
  return inst.clone({
23122
23122
  ...def,
23123
23123
  checks: [
23124
23124
  ...def.checks ?? [],
23125
- ...checks.map((ch) => typeof ch === "function" ? {
23125
+ ...checks2.map((ch) => typeof ch === "function" ? {
23126
23126
  _zod: { check: ch, def: { check: "custom" }, onattach: [] }
23127
23127
  } : ch)
23128
23128
  ]
@@ -23853,18 +23853,18 @@ var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
23853
23853
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js
23854
23854
  var _installedGroups = /* @__PURE__ */ new WeakMap();
23855
23855
  function _installLazyMethods(inst, group, methods) {
23856
- const proto = Object.getPrototypeOf(inst);
23857
- let installed = _installedGroups.get(proto);
23856
+ const proto2 = Object.getPrototypeOf(inst);
23857
+ let installed = _installedGroups.get(proto2);
23858
23858
  if (!installed) {
23859
23859
  installed = /* @__PURE__ */ new Set();
23860
- _installedGroups.set(proto, installed);
23860
+ _installedGroups.set(proto2, installed);
23861
23861
  }
23862
23862
  if (installed.has(group))
23863
23863
  return;
23864
23864
  installed.add(group);
23865
23865
  for (const key in methods) {
23866
23866
  const fn = methods[key];
23867
- Object.defineProperty(proto, key, {
23867
+ Object.defineProperty(proto2, key, {
23868
23868
  configurable: true,
23869
23869
  enumerable: false,
23870
23870
  get() {
@@ -25262,13 +25262,13 @@ function resolveRef(ref, ctx) {
25262
25262
  if (!ref.startsWith("#")) {
25263
25263
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
25264
25264
  }
25265
- const path3 = ref.slice(1).split("/").filter(Boolean);
25266
- if (path3.length === 0) {
25265
+ const path6 = ref.slice(1).split("/").filter(Boolean);
25266
+ if (path6.length === 0) {
25267
25267
  return ctx.rootSchema;
25268
25268
  }
25269
25269
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
25270
- if (path3[0] === defsKey) {
25271
- const key = path3[1];
25270
+ if (path6[0] === defsKey) {
25271
+ const key = path6[1];
25272
25272
  if (!key || !ctx.defs[key]) {
25273
25273
  throw new Error(`Reference not found: ${ref}`);
25274
25274
  }
@@ -31232,11 +31232,1659 @@ var StdioServerTransport = class {
31232
31232
  };
31233
31233
 
31234
31234
  // src/seedreamMcpCli.ts
31235
- var import_promises2 = __toESM(require("fs/promises"), 1);
31236
- var import_node_path2 = __toESM(require("path"), 1);
31235
+ var import_promises3 = __toESM(require("fs/promises"), 1);
31236
+ var import_node_path5 = __toESM(require("path"), 1);
31237
31237
 
31238
31238
  // src/officialMcpQuota.ts
31239
31239
  init_cjs_shims();
31240
+
31241
+ // src/logger.ts
31242
+ init_cjs_shims();
31243
+ var import_node_os3 = __toESM(require("os"), 1);
31244
+ var import_node_path3 = __toESM(require("path"), 1);
31245
+
31246
+ // ../logger/src/index.ts
31247
+ init_cjs_shims();
31248
+
31249
+ // ../logger/src/logger.ts
31250
+ init_cjs_shims();
31251
+
31252
+ // ../logger/src/types.ts
31253
+ init_cjs_shims();
31254
+ var LOG_LEVEL_VALUE = {
31255
+ TRACE: 0,
31256
+ DEBUG: 1,
31257
+ INFO: 2,
31258
+ WARN: 3,
31259
+ ERROR: 4,
31260
+ FATAL: 5
31261
+ };
31262
+ function parseLogLevel(value, fallback = "INFO") {
31263
+ const upper = value?.trim().toUpperCase();
31264
+ return upper && upper in LOG_LEVEL_VALUE ? upper : fallback;
31265
+ }
31266
+
31267
+ // ../logger/src/logger.ts
31268
+ var REDACTED = "***";
31269
+ var SENSITIVE_KEY_RE = /(token|apikey|authorization|password|secret|cookie)/i;
31270
+ function shouldRedactKey(key) {
31271
+ const normalized = key.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
31272
+ if (normalized.startsWith("has")) return false;
31273
+ if (normalized.endsWith("hash")) return false;
31274
+ return SENSITIVE_KEY_RE.test(normalized);
31275
+ }
31276
+ function redactString(value) {
31277
+ return value.replace(/([?&](?:token|api_?key|access_token|refresh_token)=)[^&#\s"']+/gi, `$1${REDACTED}`).replace(/("(?:apiKey|token|bridgeToken|authorization|password|secret|cookie|access_token|refresh_token)"\s*:\s*")[^"]*/gi, `$1${REDACTED}`).replace(/((?:apiKey|token|bridgeToken|authorization|password|secret|cookie|access_token|refresh_token)=)[^\s&"']+/gi, `$1${REDACTED}`).replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${REDACTED}`).replace(/\bsk-[A-Za-z0-9._-]{6,}\b/g, "sk-***");
31278
+ }
31279
+ function serializeError(err) {
31280
+ if (err instanceof Error) {
31281
+ return {
31282
+ name: err.name,
31283
+ message: redactString(err.message),
31284
+ ...err.stack ? { stack: redactString(err.stack) } : {}
31285
+ };
31286
+ }
31287
+ if (typeof err === "object" && err !== null && "message" in err) {
31288
+ const o = err;
31289
+ return {
31290
+ name: typeof o.name === "string" ? o.name : "Error",
31291
+ message: redactString(String(o.message)),
31292
+ ...typeof o.stack === "string" ? { stack: redactString(o.stack) } : {}
31293
+ };
31294
+ }
31295
+ return { name: "Error", message: redactString(String(err)) };
31296
+ }
31297
+ function isPlainObject3(value) {
31298
+ if (typeof value !== "object" || value === null) return false;
31299
+ const proto2 = Object.getPrototypeOf(value);
31300
+ return proto2 === Object.prototype || proto2 === null;
31301
+ }
31302
+ function redactValue(value, key, seen) {
31303
+ if (key && shouldRedactKey(key)) return REDACTED;
31304
+ if (typeof value === "string") return redactString(value);
31305
+ if (value instanceof Error) return serializeError(value);
31306
+ if (Array.isArray(value)) return value.map((item) => redactValue(item, void 0, seen));
31307
+ if (!isPlainObject3(value)) return value;
31308
+ if (seen.has(value)) return "[Circular]";
31309
+ seen.add(value);
31310
+ const out = {};
31311
+ for (const [childKey, childValue] of Object.entries(value)) {
31312
+ out[childKey] = redactValue(childValue, childKey, seen);
31313
+ }
31314
+ return out;
31315
+ }
31316
+ function stripReservedFields(data) {
31317
+ if (!data) return void 0;
31318
+ const rest = { ...data };
31319
+ delete rest.traceId;
31320
+ delete rest.error;
31321
+ if (Object.keys(rest).length === 0) return void 0;
31322
+ return redactValue(rest, void 0, /* @__PURE__ */ new WeakSet());
31323
+ }
31324
+ var Logger = class {
31325
+ config;
31326
+ levelValue;
31327
+ constructor(config2) {
31328
+ this.config = config2;
31329
+ this.levelValue = LOG_LEVEL_VALUE[config2.level] ?? LOG_LEVEL_VALUE.INFO;
31330
+ }
31331
+ trace(msg, data) {
31332
+ this.log("TRACE", msg, data);
31333
+ }
31334
+ debug(msg, data) {
31335
+ this.log("DEBUG", msg, data);
31336
+ }
31337
+ info(msg, data) {
31338
+ this.log("INFO", msg, data);
31339
+ }
31340
+ warn(msg, data) {
31341
+ this.log("WARN", msg, data);
31342
+ }
31343
+ error(msg, data) {
31344
+ this.log("ERROR", msg, data);
31345
+ }
31346
+ fatal(msg, data) {
31347
+ this.log("FATAL", msg, data);
31348
+ }
31349
+ log(level, msg, data) {
31350
+ if (LOG_LEVEL_VALUE[level] < this.levelValue) return;
31351
+ const traceId = typeof data?.traceId === "string" ? redactString(data.traceId) : void 0;
31352
+ const hasError = data && "error" in data && data.error !== void 0;
31353
+ const error51 = hasError ? serializeError(data.error) : void 0;
31354
+ const rest = stripReservedFields(data);
31355
+ const entry = {
31356
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
31357
+ level,
31358
+ source: this.config.source,
31359
+ module: this.config.module,
31360
+ msg,
31361
+ ...traceId ? { traceId } : {},
31362
+ ...error51 ? { error: error51 } : {},
31363
+ ...rest ? { data: rest } : {}
31364
+ };
31365
+ for (const transport of this.config.transports) {
31366
+ try {
31367
+ transport(entry);
31368
+ } catch (e) {
31369
+ console.error("[logger] transport failed", e);
31370
+ }
31371
+ }
31372
+ }
31373
+ };
31374
+
31375
+ // ../logger/src/formatters/json.ts
31376
+ init_cjs_shims();
31377
+ function safeReplacer() {
31378
+ const seen = /* @__PURE__ */ new WeakSet();
31379
+ return (_key, value) => {
31380
+ if (typeof value === "bigint") return value.toString();
31381
+ if (typeof value === "string") return toWellFormedString(value);
31382
+ if (typeof value === "object" && value !== null) {
31383
+ if (seen.has(value)) return "[Circular]";
31384
+ seen.add(value);
31385
+ }
31386
+ return value;
31387
+ };
31388
+ }
31389
+ function toWellFormedString(value) {
31390
+ let out = "";
31391
+ for (let i = 0; i < value.length; i += 1) {
31392
+ const code = value.charCodeAt(i);
31393
+ if (code >= 55296 && code <= 56319) {
31394
+ const next = value.charCodeAt(i + 1);
31395
+ if (next >= 56320 && next <= 57343) {
31396
+ out += value[i] + value[i + 1];
31397
+ i += 1;
31398
+ } else {
31399
+ out += "\uFFFD";
31400
+ }
31401
+ continue;
31402
+ }
31403
+ if (code >= 56320 && code <= 57343) {
31404
+ out += "\uFFFD";
31405
+ continue;
31406
+ }
31407
+ out += value[i];
31408
+ }
31409
+ return out;
31410
+ }
31411
+ var jsonFormatter = (entry) => {
31412
+ try {
31413
+ return JSON.stringify(entry, safeReplacer());
31414
+ } catch (e) {
31415
+ return JSON.stringify({
31416
+ ts: entry.ts,
31417
+ level: entry.level,
31418
+ source: entry.source,
31419
+ module: entry.module,
31420
+ msg: entry.msg,
31421
+ ...entry.traceId ? { traceId: entry.traceId } : {},
31422
+ data: { unserializable: e instanceof Error ? e.message : String(e) }
31423
+ });
31424
+ }
31425
+ };
31426
+
31427
+ // ../logger/src/formatters/pretty.ts
31428
+ init_cjs_shims();
31429
+
31430
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
31431
+ init_cjs_shims();
31432
+
31433
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js
31434
+ init_cjs_shims();
31435
+ var ANSI_BACKGROUND_OFFSET = 10;
31436
+ var wrapAnsi16 = (offset = 0) => (code) => `\x1B[${code + offset}m`;
31437
+ var wrapAnsi256 = (offset = 0) => (code) => `\x1B[${38 + offset};5;${code}m`;
31438
+ var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`;
31439
+ var styles = {
31440
+ modifier: {
31441
+ reset: [0, 0],
31442
+ // 21 isn't widely supported and 22 does the same thing
31443
+ bold: [1, 22],
31444
+ dim: [2, 22],
31445
+ italic: [3, 23],
31446
+ underline: [4, 24],
31447
+ overline: [53, 55],
31448
+ inverse: [7, 27],
31449
+ hidden: [8, 28],
31450
+ strikethrough: [9, 29]
31451
+ },
31452
+ color: {
31453
+ black: [30, 39],
31454
+ red: [31, 39],
31455
+ green: [32, 39],
31456
+ yellow: [33, 39],
31457
+ blue: [34, 39],
31458
+ magenta: [35, 39],
31459
+ cyan: [36, 39],
31460
+ white: [37, 39],
31461
+ // Bright color
31462
+ blackBright: [90, 39],
31463
+ gray: [90, 39],
31464
+ // Alias of `blackBright`
31465
+ grey: [90, 39],
31466
+ // Alias of `blackBright`
31467
+ redBright: [91, 39],
31468
+ greenBright: [92, 39],
31469
+ yellowBright: [93, 39],
31470
+ blueBright: [94, 39],
31471
+ magentaBright: [95, 39],
31472
+ cyanBright: [96, 39],
31473
+ whiteBright: [97, 39]
31474
+ },
31475
+ bgColor: {
31476
+ bgBlack: [40, 49],
31477
+ bgRed: [41, 49],
31478
+ bgGreen: [42, 49],
31479
+ bgYellow: [43, 49],
31480
+ bgBlue: [44, 49],
31481
+ bgMagenta: [45, 49],
31482
+ bgCyan: [46, 49],
31483
+ bgWhite: [47, 49],
31484
+ // Bright color
31485
+ bgBlackBright: [100, 49],
31486
+ bgGray: [100, 49],
31487
+ // Alias of `bgBlackBright`
31488
+ bgGrey: [100, 49],
31489
+ // Alias of `bgBlackBright`
31490
+ bgRedBright: [101, 49],
31491
+ bgGreenBright: [102, 49],
31492
+ bgYellowBright: [103, 49],
31493
+ bgBlueBright: [104, 49],
31494
+ bgMagentaBright: [105, 49],
31495
+ bgCyanBright: [106, 49],
31496
+ bgWhiteBright: [107, 49]
31497
+ }
31498
+ };
31499
+ var modifierNames = Object.keys(styles.modifier);
31500
+ var foregroundColorNames = Object.keys(styles.color);
31501
+ var backgroundColorNames = Object.keys(styles.bgColor);
31502
+ var colorNames = [...foregroundColorNames, ...backgroundColorNames];
31503
+ function assembleStyles() {
31504
+ const codes = /* @__PURE__ */ new Map();
31505
+ for (const [groupName, group] of Object.entries(styles)) {
31506
+ for (const [styleName, style] of Object.entries(group)) {
31507
+ styles[styleName] = {
31508
+ open: `\x1B[${style[0]}m`,
31509
+ close: `\x1B[${style[1]}m`
31510
+ };
31511
+ group[styleName] = styles[styleName];
31512
+ codes.set(style[0], style[1]);
31513
+ }
31514
+ Object.defineProperty(styles, groupName, {
31515
+ value: group,
31516
+ enumerable: false
31517
+ });
31518
+ }
31519
+ Object.defineProperty(styles, "codes", {
31520
+ value: codes,
31521
+ enumerable: false
31522
+ });
31523
+ styles.color.close = "\x1B[39m";
31524
+ styles.bgColor.close = "\x1B[49m";
31525
+ styles.color.ansi = wrapAnsi16();
31526
+ styles.color.ansi256 = wrapAnsi256();
31527
+ styles.color.ansi16m = wrapAnsi16m();
31528
+ styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
31529
+ styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
31530
+ styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
31531
+ Object.defineProperties(styles, {
31532
+ rgbToAnsi256: {
31533
+ value(red, green, blue) {
31534
+ if (red === green && green === blue) {
31535
+ if (red < 8) {
31536
+ return 16;
31537
+ }
31538
+ if (red > 248) {
31539
+ return 231;
31540
+ }
31541
+ return Math.round((red - 8) / 247 * 24) + 232;
31542
+ }
31543
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
31544
+ },
31545
+ enumerable: false
31546
+ },
31547
+ hexToRgb: {
31548
+ value(hex3) {
31549
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex3.toString(16));
31550
+ if (!matches) {
31551
+ return [0, 0, 0];
31552
+ }
31553
+ let [colorString] = matches;
31554
+ if (colorString.length === 3) {
31555
+ colorString = [...colorString].map((character) => character + character).join("");
31556
+ }
31557
+ const integer2 = Number.parseInt(colorString, 16);
31558
+ return [
31559
+ /* eslint-disable no-bitwise */
31560
+ integer2 >> 16 & 255,
31561
+ integer2 >> 8 & 255,
31562
+ integer2 & 255
31563
+ /* eslint-enable no-bitwise */
31564
+ ];
31565
+ },
31566
+ enumerable: false
31567
+ },
31568
+ hexToAnsi256: {
31569
+ value: (hex3) => styles.rgbToAnsi256(...styles.hexToRgb(hex3)),
31570
+ enumerable: false
31571
+ },
31572
+ ansi256ToAnsi: {
31573
+ value(code) {
31574
+ if (code < 8) {
31575
+ return 30 + code;
31576
+ }
31577
+ if (code < 16) {
31578
+ return 90 + (code - 8);
31579
+ }
31580
+ let red;
31581
+ let green;
31582
+ let blue;
31583
+ if (code >= 232) {
31584
+ red = ((code - 232) * 10 + 8) / 255;
31585
+ green = red;
31586
+ blue = red;
31587
+ } else {
31588
+ code -= 16;
31589
+ const remainder = code % 36;
31590
+ red = Math.floor(code / 36) / 5;
31591
+ green = Math.floor(remainder / 6) / 5;
31592
+ blue = remainder % 6 / 5;
31593
+ }
31594
+ const value = Math.max(red, green, blue) * 2;
31595
+ if (value === 0) {
31596
+ return 30;
31597
+ }
31598
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
31599
+ if (value === 2) {
31600
+ result += 60;
31601
+ }
31602
+ return result;
31603
+ },
31604
+ enumerable: false
31605
+ },
31606
+ rgbToAnsi: {
31607
+ value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),
31608
+ enumerable: false
31609
+ },
31610
+ hexToAnsi: {
31611
+ value: (hex3) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex3)),
31612
+ enumerable: false
31613
+ }
31614
+ });
31615
+ return styles;
31616
+ }
31617
+ var ansiStyles = assembleStyles();
31618
+ var ansi_styles_default = ansiStyles;
31619
+
31620
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js
31621
+ init_cjs_shims();
31622
+ var import_node_process2 = __toESM(require("process"), 1);
31623
+ var import_node_os = __toESM(require("os"), 1);
31624
+ var import_node_tty = __toESM(require("tty"), 1);
31625
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_node_process2.default.argv) {
31626
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
31627
+ const position = argv.indexOf(prefix + flag);
31628
+ const terminatorPosition = argv.indexOf("--");
31629
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
31630
+ }
31631
+ var { env } = import_node_process2.default;
31632
+ var flagForceColor;
31633
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
31634
+ flagForceColor = 0;
31635
+ } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
31636
+ flagForceColor = 1;
31637
+ }
31638
+ function envForceColor() {
31639
+ if ("FORCE_COLOR" in env) {
31640
+ if (env.FORCE_COLOR === "true") {
31641
+ return 1;
31642
+ }
31643
+ if (env.FORCE_COLOR === "false") {
31644
+ return 0;
31645
+ }
31646
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
31647
+ }
31648
+ }
31649
+ function translateLevel(level) {
31650
+ if (level === 0) {
31651
+ return false;
31652
+ }
31653
+ return {
31654
+ level,
31655
+ hasBasic: true,
31656
+ has256: level >= 2,
31657
+ has16m: level >= 3
31658
+ };
31659
+ }
31660
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
31661
+ const noFlagForceColor = envForceColor();
31662
+ if (noFlagForceColor !== void 0) {
31663
+ flagForceColor = noFlagForceColor;
31664
+ }
31665
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
31666
+ if (forceColor === 0) {
31667
+ return 0;
31668
+ }
31669
+ if (sniffFlags) {
31670
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
31671
+ return 3;
31672
+ }
31673
+ if (hasFlag("color=256")) {
31674
+ return 2;
31675
+ }
31676
+ }
31677
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) {
31678
+ return 1;
31679
+ }
31680
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
31681
+ return 0;
31682
+ }
31683
+ const min = forceColor || 0;
31684
+ if (env.TERM === "dumb") {
31685
+ return min;
31686
+ }
31687
+ if (import_node_process2.default.platform === "win32") {
31688
+ const osRelease = import_node_os.default.release().split(".");
31689
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
31690
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
31691
+ }
31692
+ return 1;
31693
+ }
31694
+ if ("CI" in env) {
31695
+ if (["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env)) {
31696
+ return 3;
31697
+ }
31698
+ if (["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
31699
+ return 1;
31700
+ }
31701
+ return min;
31702
+ }
31703
+ if ("TEAMCITY_VERSION" in env) {
31704
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
31705
+ }
31706
+ if (env.COLORTERM === "truecolor") {
31707
+ return 3;
31708
+ }
31709
+ if (env.TERM === "xterm-kitty") {
31710
+ return 3;
31711
+ }
31712
+ if (env.TERM === "xterm-ghostty") {
31713
+ return 3;
31714
+ }
31715
+ if (env.TERM === "wezterm") {
31716
+ return 3;
31717
+ }
31718
+ if ("TERM_PROGRAM" in env) {
31719
+ const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
31720
+ switch (env.TERM_PROGRAM) {
31721
+ case "iTerm.app": {
31722
+ return version2 >= 3 ? 3 : 2;
31723
+ }
31724
+ case "Apple_Terminal": {
31725
+ return 2;
31726
+ }
31727
+ }
31728
+ }
31729
+ if (/-256(color)?$/i.test(env.TERM)) {
31730
+ return 2;
31731
+ }
31732
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
31733
+ return 1;
31734
+ }
31735
+ if ("COLORTERM" in env) {
31736
+ return 1;
31737
+ }
31738
+ return min;
31739
+ }
31740
+ function createSupportsColor(stream, options = {}) {
31741
+ const level = _supportsColor(stream, {
31742
+ streamIsTTY: stream && stream.isTTY,
31743
+ ...options
31744
+ });
31745
+ return translateLevel(level);
31746
+ }
31747
+ var supportsColor = {
31748
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
31749
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
31750
+ };
31751
+ var supports_color_default = supportsColor;
31752
+
31753
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js
31754
+ init_cjs_shims();
31755
+ function stringReplaceAll(string4, substring, replacer) {
31756
+ let index = string4.indexOf(substring);
31757
+ if (index === -1) {
31758
+ return string4;
31759
+ }
31760
+ const substringLength = substring.length;
31761
+ let endIndex = 0;
31762
+ let returnValue = "";
31763
+ do {
31764
+ returnValue += string4.slice(endIndex, index) + substring + replacer;
31765
+ endIndex = index + substringLength;
31766
+ index = string4.indexOf(substring, endIndex);
31767
+ } while (index !== -1);
31768
+ returnValue += string4.slice(endIndex);
31769
+ return returnValue;
31770
+ }
31771
+ function stringEncaseCRLFWithFirstIndex(string4, prefix, postfix, index) {
31772
+ let endIndex = 0;
31773
+ let returnValue = "";
31774
+ do {
31775
+ const gotCR = string4[index - 1] === "\r";
31776
+ returnValue += string4.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? "\r\n" : "\n") + postfix;
31777
+ endIndex = index + 1;
31778
+ index = string4.indexOf("\n", endIndex);
31779
+ } while (index !== -1);
31780
+ returnValue += string4.slice(endIndex);
31781
+ return returnValue;
31782
+ }
31783
+
31784
+ // ../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js
31785
+ var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default;
31786
+ var GENERATOR = /* @__PURE__ */ Symbol("GENERATOR");
31787
+ var STYLER = /* @__PURE__ */ Symbol("STYLER");
31788
+ var IS_EMPTY = /* @__PURE__ */ Symbol("IS_EMPTY");
31789
+ var levelMapping = [
31790
+ "ansi",
31791
+ "ansi",
31792
+ "ansi256",
31793
+ "ansi16m"
31794
+ ];
31795
+ var styles2 = /* @__PURE__ */ Object.create(null);
31796
+ var applyOptions = (object3, options = {}) => {
31797
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
31798
+ throw new Error("The `level` option should be an integer from 0 to 3");
31799
+ }
31800
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
31801
+ object3.level = options.level === void 0 ? colorLevel : options.level;
31802
+ };
31803
+ var chalkFactory = (options) => {
31804
+ const chalk2 = (...strings) => strings.join(" ");
31805
+ applyOptions(chalk2, options);
31806
+ Object.setPrototypeOf(chalk2, createChalk.prototype);
31807
+ return chalk2;
31808
+ };
31809
+ function createChalk(options) {
31810
+ return chalkFactory(options);
31811
+ }
31812
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
31813
+ for (const [styleName, style] of Object.entries(ansi_styles_default)) {
31814
+ styles2[styleName] = {
31815
+ get() {
31816
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
31817
+ Object.defineProperty(this, styleName, { value: builder });
31818
+ return builder;
31819
+ }
31820
+ };
31821
+ }
31822
+ styles2.visible = {
31823
+ get() {
31824
+ const builder = createBuilder(this, this[STYLER], true);
31825
+ Object.defineProperty(this, "visible", { value: builder });
31826
+ return builder;
31827
+ }
31828
+ };
31829
+ var getModelAnsi = (model, level, type, ...arguments_) => {
31830
+ if (model === "rgb") {
31831
+ if (level === "ansi16m") {
31832
+ return ansi_styles_default[type].ansi16m(...arguments_);
31833
+ }
31834
+ if (level === "ansi256") {
31835
+ return ansi_styles_default[type].ansi256(ansi_styles_default.rgbToAnsi256(...arguments_));
31836
+ }
31837
+ return ansi_styles_default[type].ansi(ansi_styles_default.rgbToAnsi(...arguments_));
31838
+ }
31839
+ if (model === "hex") {
31840
+ return getModelAnsi("rgb", level, type, ...ansi_styles_default.hexToRgb(...arguments_));
31841
+ }
31842
+ return ansi_styles_default[type][model](...arguments_);
31843
+ };
31844
+ var usedModels = ["rgb", "hex", "ansi256"];
31845
+ for (const model of usedModels) {
31846
+ styles2[model] = {
31847
+ get() {
31848
+ const { level } = this;
31849
+ return function(...arguments_) {
31850
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "color", ...arguments_), ansi_styles_default.color.close, this[STYLER]);
31851
+ return createBuilder(this, styler, this[IS_EMPTY]);
31852
+ };
31853
+ }
31854
+ };
31855
+ const bgModel = "bg" + model[0].toUpperCase() + model.slice(1);
31856
+ styles2[bgModel] = {
31857
+ get() {
31858
+ const { level } = this;
31859
+ return function(...arguments_) {
31860
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), ansi_styles_default.bgColor.close, this[STYLER]);
31861
+ return createBuilder(this, styler, this[IS_EMPTY]);
31862
+ };
31863
+ }
31864
+ };
31865
+ }
31866
+ var proto = Object.defineProperties(() => {
31867
+ }, {
31868
+ ...styles2,
31869
+ level: {
31870
+ enumerable: true,
31871
+ get() {
31872
+ return this[GENERATOR].level;
31873
+ },
31874
+ set(level) {
31875
+ this[GENERATOR].level = level;
31876
+ }
31877
+ }
31878
+ });
31879
+ var createStyler = (open2, close, parent) => {
31880
+ let openAll;
31881
+ let closeAll;
31882
+ if (parent === void 0) {
31883
+ openAll = open2;
31884
+ closeAll = close;
31885
+ } else {
31886
+ openAll = parent.openAll + open2;
31887
+ closeAll = close + parent.closeAll;
31888
+ }
31889
+ return {
31890
+ open: open2,
31891
+ close,
31892
+ openAll,
31893
+ closeAll,
31894
+ parent
31895
+ };
31896
+ };
31897
+ var createBuilder = (self, _styler, _isEmpty) => {
31898
+ const builder = (...arguments_) => applyStyle(builder, arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "));
31899
+ Object.setPrototypeOf(builder, proto);
31900
+ builder[GENERATOR] = self;
31901
+ builder[STYLER] = _styler;
31902
+ builder[IS_EMPTY] = _isEmpty;
31903
+ return builder;
31904
+ };
31905
+ var applyStyle = (self, string4) => {
31906
+ if (self.level <= 0 || !string4) {
31907
+ return self[IS_EMPTY] ? "" : string4;
31908
+ }
31909
+ let styler = self[STYLER];
31910
+ if (styler === void 0) {
31911
+ return string4;
31912
+ }
31913
+ const { openAll, closeAll } = styler;
31914
+ if (string4.includes("\x1B")) {
31915
+ while (styler !== void 0) {
31916
+ string4 = stringReplaceAll(string4, styler.close, styler.open);
31917
+ styler = styler.parent;
31918
+ }
31919
+ }
31920
+ const lfIndex = string4.indexOf("\n");
31921
+ if (lfIndex !== -1) {
31922
+ string4 = stringEncaseCRLFWithFirstIndex(string4, closeAll, openAll, lfIndex);
31923
+ }
31924
+ return openAll + string4 + closeAll;
31925
+ };
31926
+ Object.defineProperties(createChalk.prototype, styles2);
31927
+ var chalk = createChalk();
31928
+ var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 });
31929
+ var source_default = chalk;
31930
+
31931
+ // ../logger/src/formatters/pretty.ts
31932
+ var LEVEL_COLOR = {
31933
+ TRACE: source_default.gray,
31934
+ DEBUG: source_default.cyan,
31935
+ INFO: source_default.green,
31936
+ WARN: source_default.yellow,
31937
+ ERROR: source_default.red,
31938
+ FATAL: source_default.bgRed.white
31939
+ };
31940
+ function formatLocalTs(iso) {
31941
+ const d = new Date(iso);
31942
+ const pad = (n, w = 2) => String(n).padStart(w, "0");
31943
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;
31944
+ }
31945
+ var prettyFormatter = (entry) => {
31946
+ const ts = formatLocalTs(entry.ts);
31947
+ const level = LEVEL_COLOR[entry.level](entry.level.padEnd(5));
31948
+ const scope = source_default.gray(`[${entry.source}:${entry.module}]`);
31949
+ const data = entry.data && Object.keys(entry.data).length > 0 ? ` ${source_default.gray(JSON.stringify(entry.data))}` : "";
31950
+ const trace = entry.traceId ? source_default.gray(` traceId=${entry.traceId}`) : "";
31951
+ const errPart = entry.error ? source_default.red(
31952
+ ` ${entry.error.name}: ${entry.error.message}${entry.error.stack ? `
31953
+ ${entry.error.stack}` : ""}`
31954
+ ) : "";
31955
+ return `${ts} ${level} ${scope} ${entry.msg}${data}${trace}${errPart}`;
31956
+ };
31957
+
31958
+ // ../logger/src/fallback.ts
31959
+ init_cjs_shims();
31960
+
31961
+ // ../logger/src/transports/console.ts
31962
+ init_cjs_shims();
31963
+ var protectedStreams = /* @__PURE__ */ new WeakSet();
31964
+ function ignoreWriteError(_error) {
31965
+ }
31966
+ function defaultStream(kind) {
31967
+ const maybeGlobal = globalThis;
31968
+ return maybeGlobal.process?.[kind];
31969
+ }
31970
+ function safeWriteLine(stream, line, fallback) {
31971
+ if (!stream) {
31972
+ fallback(line);
31973
+ return;
31974
+ }
31975
+ if (stream.destroyed || stream.writableEnded) return;
31976
+ if (typeof stream === "object" && typeof stream.on === "function" && !protectedStreams.has(stream)) {
31977
+ protectedStreams.add(stream);
31978
+ stream.on("error", ignoreWriteError);
31979
+ }
31980
+ try {
31981
+ stream.write(`${line}
31982
+ `, ignoreWriteError);
31983
+ } catch (e) {
31984
+ ignoreWriteError(e);
31985
+ }
31986
+ }
31987
+ function consoleTransport(opts) {
31988
+ const fmt = opts?.formatter ?? jsonFormatter;
31989
+ return (entry) => {
31990
+ const line = fmt(entry);
31991
+ if (LOG_LEVEL_VALUE[entry.level] >= LOG_LEVEL_VALUE.ERROR) {
31992
+ safeWriteLine(opts?.stderr ?? defaultStream("stderr"), line, console.error);
31993
+ } else {
31994
+ safeWriteLine(opts?.stdout ?? defaultStream("stdout"), line, console.log);
31995
+ }
31996
+ };
31997
+ }
31998
+
31999
+ // ../logger/src/transports/file.ts
32000
+ init_cjs_shims();
32001
+ var import_node_path = __toESM(require("path"), 1);
32002
+
32003
+ // ../../node_modules/.pnpm/rotating-file-stream@3.2.9/node_modules/rotating-file-stream/dist/esm/index.js
32004
+ init_cjs_shims();
32005
+ var import_child_process = require("child_process");
32006
+ var import_zlib = require("zlib");
32007
+ var import_stream = require("stream");
32008
+ var import_fs = require("fs");
32009
+ var import_promises = require("fs/promises");
32010
+ var import_path = require("path");
32011
+ var import_util6 = require("util");
32012
+ var import_timers = require("timers");
32013
+ async function exists(filename) {
32014
+ return new Promise((resolve) => (0, import_fs.access)(filename, import_fs.constants.F_OK, (error51) => resolve(!error51)));
32015
+ }
32016
+ var RotatingFileStreamError = class extends Error {
32017
+ code = "RFS-TOO-MANY";
32018
+ constructor() {
32019
+ super("Too many destination file attempts");
32020
+ }
32021
+ };
32022
+ var RotatingFileStream = class extends import_stream.Writable {
32023
+ createGzip;
32024
+ exec;
32025
+ file;
32026
+ filename;
32027
+ finished;
32028
+ fsCreateReadStream;
32029
+ fsCreateWriteStream;
32030
+ fsOpen;
32031
+ fsReadFile;
32032
+ fsStat;
32033
+ fsUnlink;
32034
+ generator;
32035
+ initPromise;
32036
+ last;
32037
+ maxTimeout;
32038
+ next;
32039
+ options;
32040
+ prev;
32041
+ rotation;
32042
+ size;
32043
+ stdout;
32044
+ timeout;
32045
+ timeoutPromise;
32046
+ constructor(generator, options) {
32047
+ const { encoding, history, maxFiles, maxSize, path: path6 } = options;
32048
+ super({ decodeStrings: true, defaultEncoding: encoding });
32049
+ this.createGzip = import_zlib.createGzip;
32050
+ this.exec = import_child_process.exec;
32051
+ this.filename = path6 + generator(null);
32052
+ this.fsCreateReadStream = import_fs.createReadStream;
32053
+ this.fsCreateWriteStream = import_fs.createWriteStream;
32054
+ this.fsOpen = import_promises.open;
32055
+ this.fsReadFile = import_promises.readFile;
32056
+ this.fsStat = import_promises.stat;
32057
+ this.fsUnlink = import_promises.unlink;
32058
+ this.generator = generator;
32059
+ this.maxTimeout = 2147483640;
32060
+ this.options = options;
32061
+ this.stdout = process.stdout;
32062
+ if (maxFiles || maxSize)
32063
+ options.history = path6 + (history ? history : this.generator(null) + ".txt");
32064
+ this.on("close", () => this.finished ? null : this.emit("finish"));
32065
+ this.on("finish", () => this.finished = this.clear());
32066
+ (async () => {
32067
+ try {
32068
+ this.initPromise = this.init();
32069
+ await this.initPromise;
32070
+ delete this.initPromise;
32071
+ } catch (e) {
32072
+ }
32073
+ })();
32074
+ }
32075
+ _destroy(error51, callback) {
32076
+ this.refinal(error51, callback);
32077
+ }
32078
+ _final(callback) {
32079
+ this.refinal(void 0, callback);
32080
+ }
32081
+ _write(chunk, encoding, callback) {
32082
+ this.rewrite([{ chunk, encoding }], 0, callback);
32083
+ }
32084
+ _writev(chunks, callback) {
32085
+ this.rewrite(chunks, 0, callback);
32086
+ }
32087
+ async refinal(error51, callback) {
32088
+ try {
32089
+ this.clear();
32090
+ if (this.initPromise)
32091
+ await this.initPromise;
32092
+ if (this.timeoutPromise)
32093
+ await this.timeoutPromise;
32094
+ await this.reclose();
32095
+ } catch (e) {
32096
+ return callback(error51 || e);
32097
+ }
32098
+ callback(error51);
32099
+ }
32100
+ async rewrite(chunks, index, callback) {
32101
+ const { size, teeToStdout } = this.options;
32102
+ try {
32103
+ if (this.initPromise)
32104
+ await this.initPromise;
32105
+ for (let i = 0; i < chunks.length; ++i) {
32106
+ const { chunk } = chunks[i];
32107
+ this.size += chunk.length;
32108
+ if (this.timeoutPromise)
32109
+ await this.timeoutPromise;
32110
+ await this.file.write(chunk);
32111
+ if (teeToStdout && !this.stdout.destroyed)
32112
+ this.stdout.write(chunk);
32113
+ if (size && this.size >= size)
32114
+ await this.rotate();
32115
+ }
32116
+ } catch (e) {
32117
+ return callback(e);
32118
+ }
32119
+ callback();
32120
+ }
32121
+ async init() {
32122
+ const { immutable, initialRotation, interval, size } = this.options;
32123
+ if (immutable)
32124
+ return new Promise((resolve, reject) => process.nextTick(() => this.immutate(true).then(resolve).catch(reject)));
32125
+ let stats;
32126
+ try {
32127
+ stats = await (0, import_promises.stat)(this.filename);
32128
+ } catch (e) {
32129
+ if (e.code !== "ENOENT")
32130
+ throw e;
32131
+ return this.reopen(0);
32132
+ }
32133
+ if (!stats.isFile())
32134
+ throw new Error(`Can't write on: ${this.filename} (it is not a file)`);
32135
+ if (initialRotation) {
32136
+ this.intervalBounds(this.now());
32137
+ const prev = this.prev;
32138
+ this.intervalBounds(new Date(stats.mtime.getTime()));
32139
+ if (prev !== this.prev)
32140
+ return this.rotate();
32141
+ }
32142
+ this.size = stats.size;
32143
+ if (!size || stats.size < size)
32144
+ return this.reopen(stats.size);
32145
+ if (interval)
32146
+ this.intervalBounds(this.now());
32147
+ return this.rotate();
32148
+ }
32149
+ async makePath(name) {
32150
+ return (0, import_promises.mkdir)(name.split(import_path.sep).slice(0, -1).join(import_path.sep), { recursive: true });
32151
+ }
32152
+ async reopen(size) {
32153
+ let file2;
32154
+ try {
32155
+ file2 = await (0, import_promises.open)(this.filename, "a", this.options.mode);
32156
+ } catch (e) {
32157
+ if (e.code !== "ENOENT")
32158
+ throw e;
32159
+ await this.makePath(this.filename);
32160
+ file2 = await (0, import_promises.open)(this.filename, "a", this.options.mode);
32161
+ }
32162
+ this.file = file2;
32163
+ this.size = size;
32164
+ this.interval();
32165
+ this.emit("open", this.filename);
32166
+ }
32167
+ async reclose() {
32168
+ const { file: file2 } = this;
32169
+ if (!file2)
32170
+ return;
32171
+ delete this.file;
32172
+ return file2.close();
32173
+ }
32174
+ now() {
32175
+ return /* @__PURE__ */ new Date();
32176
+ }
32177
+ async rotate() {
32178
+ const { immutable, rotate } = this.options;
32179
+ this.size = 0;
32180
+ this.rotation = this.now();
32181
+ this.clear();
32182
+ this.emit("rotation");
32183
+ await this.reclose();
32184
+ if (rotate)
32185
+ return this.classical();
32186
+ if (immutable)
32187
+ return this.immutate(false);
32188
+ return this.move();
32189
+ }
32190
+ async findName() {
32191
+ const { interval, path: path6, intervalBoundary } = this.options;
32192
+ for (let index = 1; index < 1e3; ++index) {
32193
+ const filename = path6 + this.generator(interval && intervalBoundary ? new Date(this.prev) : this.rotation, index);
32194
+ if (!await exists(filename))
32195
+ return filename;
32196
+ }
32197
+ throw new RotatingFileStreamError();
32198
+ }
32199
+ async move() {
32200
+ const { compress } = this.options;
32201
+ const filename = await this.findName();
32202
+ await this.touch(filename);
32203
+ if (compress)
32204
+ await this.compress(filename);
32205
+ else
32206
+ await (0, import_promises.rename)(this.filename, filename);
32207
+ return this.rotated(filename);
32208
+ }
32209
+ async touch(filename) {
32210
+ let file2;
32211
+ try {
32212
+ file2 = await this.fsOpen(filename, "a");
32213
+ } catch (e) {
32214
+ if (e.code !== "ENOENT")
32215
+ throw e;
32216
+ await this.makePath(filename);
32217
+ file2 = await (0, import_promises.open)(filename, "a");
32218
+ }
32219
+ await file2.close();
32220
+ return this.unlink(filename);
32221
+ }
32222
+ async classical() {
32223
+ const { compress, path: path6, rotate } = this.options;
32224
+ let rotatedName = "";
32225
+ for (let count = rotate; count > 0; --count) {
32226
+ const currName = path6 + this.generator(count);
32227
+ const prevName = count === 1 ? this.filename : path6 + this.generator(count - 1);
32228
+ if (!await exists(prevName))
32229
+ continue;
32230
+ if (!rotatedName)
32231
+ rotatedName = currName;
32232
+ if (count === 1 && compress)
32233
+ await this.compress(currName);
32234
+ else {
32235
+ try {
32236
+ await (0, import_promises.rename)(prevName, currName);
32237
+ } catch (e) {
32238
+ if (e.code !== "ENOENT")
32239
+ throw e;
32240
+ await this.makePath(currName);
32241
+ await (0, import_promises.rename)(prevName, currName);
32242
+ }
32243
+ }
32244
+ }
32245
+ return this.rotated(rotatedName);
32246
+ }
32247
+ clear() {
32248
+ if (this.timeout) {
32249
+ clearTimeout(this.timeout);
32250
+ this.timeout = null;
32251
+ }
32252
+ return true;
32253
+ }
32254
+ intervalBoundsBig(now) {
32255
+ const year = this.options.intervalUTC ? now.getUTCFullYear() : now.getFullYear();
32256
+ let month = this.options.intervalUTC ? now.getUTCMonth() : now.getMonth();
32257
+ let day = this.options.intervalUTC ? now.getUTCDate() : now.getDate();
32258
+ let hours = this.options.intervalUTC ? now.getUTCHours() : now.getHours();
32259
+ const { num, unit } = this.options.interval;
32260
+ if (unit === "M") {
32261
+ day = 1;
32262
+ hours = 0;
32263
+ } else if (unit === "d")
32264
+ hours = 0;
32265
+ else
32266
+ hours = parseInt(hours / num, 10) * num;
32267
+ this.prev = new Date(year, month, day, hours, 0, 0, 0).getTime();
32268
+ if (unit === "M")
32269
+ month += num;
32270
+ else if (unit === "d")
32271
+ day += num;
32272
+ else
32273
+ hours += num;
32274
+ this.next = new Date(year, month, day, hours, 0, 0, 0).getTime();
32275
+ }
32276
+ intervalBounds(now) {
32277
+ const unit = this.options.interval.unit;
32278
+ if (unit === "M" || unit === "d" || unit === "h")
32279
+ this.intervalBoundsBig(now);
32280
+ else {
32281
+ let period = 1e3 * this.options.interval.num;
32282
+ if (unit === "m")
32283
+ period *= 60;
32284
+ this.prev = parseInt(now.getTime() / period, 10) * period;
32285
+ this.next = this.prev + period;
32286
+ }
32287
+ return new Date(this.prev);
32288
+ }
32289
+ interval() {
32290
+ if (!this.options.interval)
32291
+ return;
32292
+ this.intervalBounds(this.now());
32293
+ const set2 = async () => {
32294
+ const time3 = this.next - this.now().getTime();
32295
+ if (time3 <= 0) {
32296
+ try {
32297
+ this.timeoutPromise = this.rotate();
32298
+ await this.timeoutPromise;
32299
+ delete this.timeoutPromise;
32300
+ } catch (e) {
32301
+ }
32302
+ } else {
32303
+ this.timeout = (0, import_timers.setTimeout)(set2, time3 > this.maxTimeout ? this.maxTimeout : time3);
32304
+ this.timeout.unref();
32305
+ }
32306
+ };
32307
+ set2();
32308
+ }
32309
+ async compress(filename) {
32310
+ const { compress } = this.options;
32311
+ if (typeof compress === "function") {
32312
+ await new Promise((resolve, reject) => {
32313
+ this.exec(compress(this.filename, filename), (error51, stdout, stderr) => {
32314
+ this.emit("external", stdout, stderr);
32315
+ error51 ? reject(error51) : resolve();
32316
+ });
32317
+ });
32318
+ } else
32319
+ await this.gzip(filename);
32320
+ return this.unlink(this.filename);
32321
+ }
32322
+ async gzip(filename) {
32323
+ const { mode } = this.options;
32324
+ const options = mode ? { mode } : {};
32325
+ const inp = this.fsCreateReadStream(this.filename, {});
32326
+ const out = this.fsCreateWriteStream(filename, options);
32327
+ const zip = this.createGzip();
32328
+ await new Promise((resolve, reject) => {
32329
+ inp.once("error", reject);
32330
+ out.once("error", reject);
32331
+ zip.once("error", reject);
32332
+ out.once("finish", resolve);
32333
+ inp.pipe(zip).pipe(out);
32334
+ });
32335
+ await Promise.all([
32336
+ new Promise((resolve) => zip.close(resolve)),
32337
+ new Promise((resolve) => out.close((err) => {
32338
+ if (err)
32339
+ this.emit("warning", err);
32340
+ resolve();
32341
+ }))
32342
+ ]);
32343
+ }
32344
+ async rotated(filename) {
32345
+ const { maxFiles, maxSize } = this.options;
32346
+ if (maxFiles || maxSize)
32347
+ await this.history(filename);
32348
+ this.emit("rotated", filename);
32349
+ return this.reopen(0);
32350
+ }
32351
+ async history(filename) {
32352
+ const { history, maxFiles, maxSize } = this.options;
32353
+ const res = [];
32354
+ let files = [filename];
32355
+ try {
32356
+ const content = await this.fsReadFile(history, "utf8");
32357
+ files = [...content.toString().split("\n"), filename];
32358
+ } catch (e) {
32359
+ if (e.code !== "ENOENT")
32360
+ throw e;
32361
+ }
32362
+ for (const file2 of files) {
32363
+ if (file2) {
32364
+ try {
32365
+ const stats = await this.fsStat(file2);
32366
+ if (stats.isFile()) {
32367
+ res.push({
32368
+ name: file2,
32369
+ size: stats.size,
32370
+ time: stats.mtime.getTime()
32371
+ });
32372
+ } else
32373
+ this.emit("warning", new Error(`File '${file2}' contained in history is not a regular file`));
32374
+ } catch (e) {
32375
+ if (e.code !== "ENOENT")
32376
+ throw e;
32377
+ }
32378
+ }
32379
+ }
32380
+ res.sort((a, b) => a.time - b.time);
32381
+ if (maxFiles) {
32382
+ while (res.length > maxFiles) {
32383
+ const file2 = res.shift();
32384
+ await this.unlink(file2.name);
32385
+ this.emit("removed", file2.name, true);
32386
+ }
32387
+ }
32388
+ if (maxSize) {
32389
+ while (res.reduce((size, file2) => size + file2.size, 0) > maxSize) {
32390
+ const file2 = res.shift();
32391
+ await this.unlink(file2.name);
32392
+ this.emit("removed", file2.name, false);
32393
+ }
32394
+ }
32395
+ await (0, import_promises.writeFile)(history, res.map((e) => e.name).join("\n") + "\n", "utf-8");
32396
+ this.emit("history");
32397
+ }
32398
+ async immutate(first) {
32399
+ const { size } = this.options;
32400
+ const now = this.now();
32401
+ for (let index = 1; index < 1e3; ++index) {
32402
+ let fileSize = 0;
32403
+ let stats = void 0;
32404
+ this.filename = this.options.path + this.generator(now, index);
32405
+ try {
32406
+ stats = await this.fsStat(this.filename);
32407
+ } catch (e) {
32408
+ if (e.code !== "ENOENT")
32409
+ throw e;
32410
+ }
32411
+ if (stats) {
32412
+ fileSize = stats.size;
32413
+ if (!stats.isFile())
32414
+ throw new Error(`Can't write on: '${this.filename}' (it is not a file)`);
32415
+ if (size && fileSize >= size)
32416
+ continue;
32417
+ }
32418
+ if (first) {
32419
+ this.last = this.filename;
32420
+ return this.reopen(fileSize);
32421
+ }
32422
+ await this.rotated(this.last);
32423
+ this.last = this.filename;
32424
+ return;
32425
+ }
32426
+ throw new RotatingFileStreamError();
32427
+ }
32428
+ async unlink(filename) {
32429
+ try {
32430
+ await this.fsUnlink(filename);
32431
+ } catch (e) {
32432
+ if (e.code !== "ENOENT")
32433
+ throw e;
32434
+ this.emit("warning", e);
32435
+ }
32436
+ }
32437
+ };
32438
+ function buildNumberCheck(field) {
32439
+ return (type, options, value) => {
32440
+ const converted = parseInt(value, 10);
32441
+ if (type !== "number" || converted !== value || converted <= 0)
32442
+ throw new Error(`'${field}' option must be a positive integer number`);
32443
+ };
32444
+ }
32445
+ function buildStringCheck(field, check2) {
32446
+ return (type, options, value) => {
32447
+ if (type !== "string")
32448
+ throw new Error(`Don't know how to handle 'options.${field}' type: ${type}`);
32449
+ options[field] = check2(value);
32450
+ };
32451
+ }
32452
+ function checkMeasure(value, what, units) {
32453
+ const ret = {};
32454
+ ret.num = parseInt(value, 10);
32455
+ if (isNaN(ret.num))
32456
+ throw new Error(`Unknown 'options.${what}' format: ${value}`);
32457
+ if (ret.num <= 0)
32458
+ throw new Error(`A positive integer number is expected for 'options.${what}'`);
32459
+ ret.unit = value.replace(/^[ 0]*/g, "").substr((ret.num + "").length, 1);
32460
+ if (ret.unit.length === 0)
32461
+ throw new Error(`Missing unit for 'options.${what}'`);
32462
+ if (!units[ret.unit])
32463
+ throw new Error(`Unknown 'options.${what}' unit: ${ret.unit}`);
32464
+ return ret;
32465
+ }
32466
+ var intervalUnits = { M: true, d: true, h: true, m: true, s: true };
32467
+ function checkIntervalUnit(ret, unit, amount) {
32468
+ if (parseInt(amount / ret.num, 10) * ret.num !== amount)
32469
+ throw new Error(`An integer divider of ${amount} is expected as ${unit} for 'options.interval'`);
32470
+ }
32471
+ function checkInterval(value) {
32472
+ const ret = checkMeasure(value, "interval", intervalUnits);
32473
+ switch (ret.unit) {
32474
+ case "h":
32475
+ checkIntervalUnit(ret, "hours", 24);
32476
+ break;
32477
+ case "m":
32478
+ checkIntervalUnit(ret, "minutes", 60);
32479
+ break;
32480
+ case "s":
32481
+ checkIntervalUnit(ret, "seconds", 60);
32482
+ break;
32483
+ }
32484
+ return ret;
32485
+ }
32486
+ var sizeUnits = { B: true, G: true, K: true, M: true };
32487
+ function checkSize(value) {
32488
+ const ret = checkMeasure(value, "size", sizeUnits);
32489
+ if (ret.unit === "K")
32490
+ return ret.num * 1024;
32491
+ if (ret.unit === "M")
32492
+ return ret.num * 1048576;
32493
+ if (ret.unit === "G")
32494
+ return ret.num * 1073741824;
32495
+ return ret.num;
32496
+ }
32497
+ var checks = {
32498
+ encoding: (type, options, value) => new import_util6.TextDecoder(value),
32499
+ immutable: () => {
32500
+ },
32501
+ initialRotation: () => {
32502
+ },
32503
+ interval: buildStringCheck("interval", checkInterval),
32504
+ intervalBoundary: () => {
32505
+ },
32506
+ intervalUTC: () => {
32507
+ },
32508
+ maxFiles: buildNumberCheck("maxFiles"),
32509
+ maxSize: buildStringCheck("maxSize", checkSize),
32510
+ mode: () => {
32511
+ },
32512
+ omitExtension: () => {
32513
+ },
32514
+ rotate: buildNumberCheck("rotate"),
32515
+ size: buildStringCheck("size", checkSize),
32516
+ teeToStdout: () => {
32517
+ },
32518
+ ...{
32519
+ compress: (type, options, value) => {
32520
+ if (value === false)
32521
+ return;
32522
+ if (!value)
32523
+ throw new Error("A value for 'options.compress' must be specified");
32524
+ if (type === "boolean")
32525
+ return options.compress = (source, dest) => `cat ${source} | gzip -c9 > ${dest}`;
32526
+ if (type === "function")
32527
+ return;
32528
+ if (type !== "string")
32529
+ throw new Error(`Don't know how to handle 'options.compress' type: ${type}`);
32530
+ if (value !== "gzip")
32531
+ throw new Error(`Don't know how to handle compression method: ${value}`);
32532
+ },
32533
+ history: (type) => {
32534
+ if (type !== "string")
32535
+ throw new Error(`Don't know how to handle 'options.history' type: ${type}`);
32536
+ },
32537
+ path: (type, options, value) => {
32538
+ if (type !== "string")
32539
+ throw new Error(`Don't know how to handle 'options.path' type: ${type}`);
32540
+ if (value[value.length - 1] !== import_path.sep)
32541
+ options.path = value + import_path.sep;
32542
+ }
32543
+ }
32544
+ };
32545
+ function checkOpts(options) {
32546
+ const ret = {};
32547
+ let opt;
32548
+ for (opt in options) {
32549
+ const value = options[opt];
32550
+ const type = typeof value;
32551
+ if (!(opt in checks))
32552
+ throw new Error(`Unknown option: ${opt}`);
32553
+ ret[opt] = options[opt];
32554
+ checks[opt](type, ret, value);
32555
+ }
32556
+ if (!ret.path)
32557
+ ret.path = "";
32558
+ if (!ret.interval) {
32559
+ delete ret.immutable;
32560
+ delete ret.initialRotation;
32561
+ delete ret.intervalBoundary;
32562
+ delete ret.intervalUTC;
32563
+ }
32564
+ if (ret.rotate) {
32565
+ delete ret.history;
32566
+ delete ret.immutable;
32567
+ delete ret.maxFiles;
32568
+ delete ret.maxSize;
32569
+ delete ret.intervalBoundary;
32570
+ delete ret.intervalUTC;
32571
+ }
32572
+ if (ret.immutable)
32573
+ delete ret.compress;
32574
+ if (!ret.intervalBoundary)
32575
+ delete ret.initialRotation;
32576
+ return ret;
32577
+ }
32578
+ function createClassical(filename, compress, omitExtension) {
32579
+ return (index) => index ? `${filename}.${index}${compress && !omitExtension ? ".gz" : ""}` : filename;
32580
+ }
32581
+ function createGenerator(filename, compress, omitExtension) {
32582
+ const pad = (num) => (num > 9 ? "" : "0") + num;
32583
+ return (time3, index) => {
32584
+ if (!time3)
32585
+ return filename;
32586
+ const month = time3.getFullYear() + "" + pad(time3.getMonth() + 1);
32587
+ const day = pad(time3.getDate());
32588
+ const hour = pad(time3.getHours());
32589
+ const minute = pad(time3.getMinutes());
32590
+ return month + day + "-" + hour + minute + "-" + pad(index) + "-" + filename + (compress && !omitExtension ? ".gz" : "");
32591
+ };
32592
+ }
32593
+ function createStream(filename, options) {
32594
+ if (typeof options === "undefined")
32595
+ options = {};
32596
+ else if (typeof options !== "object")
32597
+ throw new Error(`The "options" argument must be of type object. Received type ${typeof options}`);
32598
+ const opts = checkOpts(options);
32599
+ const { compress, omitExtension } = opts;
32600
+ let generator;
32601
+ if (typeof filename === "string")
32602
+ generator = options.rotate ? createClassical(filename, !!compress, omitExtension) : createGenerator(filename, !!compress, omitExtension);
32603
+ else if (typeof filename === "function")
32604
+ generator = filename;
32605
+ else
32606
+ throw new Error(`The "filename" argument must be one of type string or function. Received type ${typeof filename}`);
32607
+ return new RotatingFileStream(generator, opts);
32608
+ }
32609
+
32610
+ // ../logger/src/transports/file.ts
32611
+ function parseSize(maxSize) {
32612
+ const trimmed = maxSize.trim().toUpperCase();
32613
+ if (trimmed.endsWith("MB")) {
32614
+ return `${trimmed.slice(0, -2)}M`;
32615
+ }
32616
+ return trimmed;
32617
+ }
32618
+ var streamCache = /* @__PURE__ */ new Map();
32619
+ var droppedEntryCount = 0;
32620
+ var lastReportedDroppedTotal = 0;
32621
+ function buildLogDroppedSentinel(fmt, source, droppedTotal) {
32622
+ const entry = {
32623
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
32624
+ level: "WARN",
32625
+ source,
32626
+ module: "logger.file",
32627
+ msg: "log_dropped",
32628
+ data: { droppedTotal }
32629
+ };
32630
+ return fmt(entry);
32631
+ }
32632
+ function writeWithDroppedSentinel(stream, fmt, line, source) {
32633
+ stream.write(`${line}
32634
+ `);
32635
+ if (droppedEntryCount > lastReportedDroppedTotal) {
32636
+ lastReportedDroppedTotal = droppedEntryCount;
32637
+ stream.write(`${buildLogDroppedSentinel(fmt, source, droppedEntryCount)}
32638
+ `);
32639
+ }
32640
+ }
32641
+ function fileTransport(opts) {
32642
+ const fmt = opts.formatter ?? jsonFormatter;
32643
+ const logSource = opts.source ?? "server";
32644
+ const resolved = import_node_path.default.resolve(opts.path);
32645
+ let cached2 = streamCache.get(resolved);
32646
+ if (!cached2) {
32647
+ cached2 = {
32648
+ stream: createStream(import_node_path.default.basename(resolved), {
32649
+ path: import_node_path.default.dirname(resolved),
32650
+ size: opts.rotate?.maxSize ? parseSize(opts.rotate.maxSize) : "50M",
32651
+ maxFiles: opts.rotate?.maxFiles ?? 7
32652
+ }),
32653
+ closed: false
32654
+ };
32655
+ streamCache.set(resolved, cached2);
32656
+ }
32657
+ return (entry) => {
32658
+ if (cached2.closed || cached2.stream.destroyed || cached2.stream.writableEnded) {
32659
+ droppedEntryCount += 1;
32660
+ return;
32661
+ }
32662
+ try {
32663
+ writeWithDroppedSentinel(cached2.stream, fmt, fmt(entry), logSource);
32664
+ } catch {
32665
+ droppedEntryCount += 1;
32666
+ }
32667
+ };
32668
+ }
32669
+
32670
+ // ../logger/src/index.ts
32671
+ function createLogger(config2) {
32672
+ return new Logger(config2);
32673
+ }
32674
+
32675
+ // src/config.ts
32676
+ init_cjs_shims();
32677
+ var import_node_crypto = __toESM(require("crypto"), 1);
32678
+ var import_node_fs = __toESM(require("fs"), 1);
32679
+ var import_node_os2 = __toESM(require("os"), 1);
32680
+ var import_node_path2 = __toESM(require("path"), 1);
32681
+ var DEFAULT_QUERY_CONFIG = {
32682
+ maxActive: 5040,
32683
+ idleTimeoutMs: 6e5,
32684
+ workingSilenceTimeoutMs: 12e5,
32685
+ replyStallTimeoutMs: 3e5,
32686
+ busySilenceTimeoutMs: 18e5,
32687
+ evictionIntervalMs: 6e4,
32688
+ statusReportIntervalMs: 6e4,
32689
+ allowBuiltinWebSearch: false,
32690
+ compactPromptTemplate: "/compact \u6781\u81F4\u538B\u7F29\uFF1A\u53EA\u4FDD\u7559 1) \u7FA4\u91CC\u6210\u5458\u4E4B\u95F4\u7684\u5173\u952E\u5171\u8BC6\u4E0E\u51B3\u8BAE 2) \u8FDB\u884C\u4E2D\u7684\u4EFB\u52A1\u548C\u5F53\u524D\u72B6\u6001\uFF08\u542B\u8D1F\u8D23\u4EBA\uFF09 3) open blockers\u3002\u6BCF\u6761\u4E0D\u8D85\u8FC7 2 \u884C\uFF0C\u5176\u4ED6\u5168\u90E8\u7701\u7565\u3002",
32691
+ inboxQuietWindowMs: 15e3,
32692
+ inboxMaxLatencyMs: 18e4
32693
+ };
32694
+ function readEnvString(name, fallback) {
32695
+ const v = process.env[name];
32696
+ return v && v.length > 0 ? v : fallback;
32697
+ }
32698
+ function readEnvInt(name, fallback) {
32699
+ const v = process.env[name];
32700
+ if (!v || v.length === 0) return fallback;
32701
+ const n = Number.parseInt(v, 10);
32702
+ return Number.isFinite(n) && n > 0 ? n : fallback;
32703
+ }
32704
+ function readEnvBool(name, fallback) {
32705
+ const v = process.env[name];
32706
+ if (!v || v.length === 0) return fallback;
32707
+ const normalized = v.trim().toLowerCase();
32708
+ if (["1", "true", "yes", "on"].includes(normalized)) return true;
32709
+ if (["0", "false", "no", "off"].includes(normalized)) return false;
32710
+ return fallback;
32711
+ }
32712
+ function generateStableBridgeId(dataDir) {
32713
+ const raw = `${import_node_os2.default.hostname()}:${import_node_os2.default.userInfo().username}:${import_node_path2.default.resolve(dataDir)}`;
32714
+ const hash2 = import_node_crypto.default.createHash("sha256").update(raw).digest("hex").slice(0, 12);
32715
+ return `bridge_${hash2}`;
32716
+ }
32717
+ function generateStableBridgeToken() {
32718
+ const raw = `${import_node_os2.default.hostname()}:${import_node_os2.default.userInfo().username}:ahchat-bridge-token`;
32719
+ return import_node_crypto.default.createHash("sha256").update(raw).digest("hex").slice(0, 32);
32720
+ }
32721
+ function tryReadJsonConfig(filePath) {
32722
+ try {
32723
+ if (!import_node_fs.default.existsSync(filePath)) return {};
32724
+ const raw = import_node_fs.default.readFileSync(filePath, "utf-8");
32725
+ const parsed = JSON.parse(raw);
32726
+ if (typeof parsed !== "object" || parsed === null) return {};
32727
+ return parsed;
32728
+ } catch {
32729
+ return {};
32730
+ }
32731
+ }
32732
+ function mergeQueryConfig(file2) {
32733
+ const q = file2.queryConfig;
32734
+ return {
32735
+ maxActive: readEnvInt("AHCHAT_BRIDGE_MAX_ACTIVE", q?.maxActive ?? DEFAULT_QUERY_CONFIG.maxActive),
32736
+ idleTimeoutMs: readEnvInt(
32737
+ "AHCHAT_BRIDGE_IDLE_TIMEOUT_MS",
32738
+ q?.idleTimeoutMs ?? DEFAULT_QUERY_CONFIG.idleTimeoutMs
32739
+ ),
32740
+ workingSilenceTimeoutMs: readEnvInt(
32741
+ "AHCHAT_BRIDGE_WORKING_SILENCE_TIMEOUT_MS",
32742
+ q?.workingSilenceTimeoutMs ?? DEFAULT_QUERY_CONFIG.workingSilenceTimeoutMs
32743
+ ),
32744
+ replyStallTimeoutMs: readEnvInt(
32745
+ "AHCHAT_BRIDGE_REPLY_STALL_TIMEOUT_MS",
32746
+ q?.replyStallTimeoutMs ?? DEFAULT_QUERY_CONFIG.replyStallTimeoutMs
32747
+ ),
32748
+ busySilenceTimeoutMs: readEnvInt(
32749
+ "AHCHAT_BRIDGE_BUSY_SILENCE_TIMEOUT_MS",
32750
+ q?.busySilenceTimeoutMs ?? DEFAULT_QUERY_CONFIG.busySilenceTimeoutMs ?? 18e5
32751
+ ),
32752
+ evictionIntervalMs: readEnvInt(
32753
+ "AHCHAT_BRIDGE_EVICTION_INTERVAL_MS",
32754
+ q?.evictionIntervalMs ?? DEFAULT_QUERY_CONFIG.evictionIntervalMs
32755
+ ),
32756
+ statusReportIntervalMs: readEnvInt(
32757
+ "AHCHAT_BRIDGE_STATUS_REPORT_MS",
32758
+ q?.statusReportIntervalMs ?? DEFAULT_QUERY_CONFIG.statusReportIntervalMs
32759
+ ),
32760
+ allowBuiltinWebSearch: readEnvBool(
32761
+ "AHCHAT_BRIDGE_ALLOW_BUILTIN_WEBSEARCH",
32762
+ q?.allowBuiltinWebSearch ?? DEFAULT_QUERY_CONFIG.allowBuiltinWebSearch
32763
+ ),
32764
+ compactPromptTemplate: readEnvString(
32765
+ "AHCHAT_BRIDGE_COMPACT_PROMPT_TEMPLATE",
32766
+ q?.compactPromptTemplate ?? DEFAULT_QUERY_CONFIG.compactPromptTemplate
32767
+ ),
32768
+ inboxQuietWindowMs: readEnvInt(
32769
+ "AHCHAT_BRIDGE_INBOX_QUIET_WINDOW_MS",
32770
+ q?.inboxQuietWindowMs ?? DEFAULT_QUERY_CONFIG.inboxQuietWindowMs
32771
+ ),
32772
+ inboxMaxLatencyMs: readEnvInt(
32773
+ "AHCHAT_BRIDGE_INBOX_MAX_LATENCY_MS",
32774
+ q?.inboxMaxLatencyMs ?? DEFAULT_QUERY_CONFIG.inboxMaxLatencyMs
32775
+ )
32776
+ };
32777
+ }
32778
+ function resolveAgentConfigDir(dataDir) {
32779
+ const newPath = import_node_path2.default.join(dataDir, "agent-config");
32780
+ const oldPath = import_node_path2.default.join(dataDir, "claude-config");
32781
+ if (!import_node_fs.default.existsSync(newPath) && import_node_fs.default.existsSync(oldPath)) {
32782
+ try {
32783
+ import_node_fs.default.renameSync(oldPath, newPath);
32784
+ } catch {
32785
+ return oldPath;
32786
+ }
32787
+ }
32788
+ return newPath;
32789
+ }
32790
+ function loadBridgeConfig(opts) {
32791
+ const dataDir = opts?.dataDir ?? readEnvString(
32792
+ "AHCHAT_DATA_DIR",
32793
+ import_node_path2.default.join(import_node_os2.default.homedir(), ".ahchat")
32794
+ );
32795
+ const fileConfig = tryReadJsonConfig(import_node_path2.default.join(dataDir, "bridge.json"));
32796
+ return {
32797
+ serverUrl: readEnvString(
32798
+ "AHCHAT_BRIDGE_SERVER_URL",
32799
+ fileConfig.serverUrl ?? "ws://127.0.0.1:3001/ws/bridge"
32800
+ ),
32801
+ bridgeId: readEnvString(
32802
+ "AHCHAT_BRIDGE_ID",
32803
+ fileConfig.bridgeId ?? generateStableBridgeId(dataDir)
32804
+ ),
32805
+ bridgeToken: readEnvString(
32806
+ "AHCHAT_BRIDGE_TOKEN",
32807
+ fileConfig.bridgeToken ?? generateStableBridgeToken()
32808
+ ),
32809
+ logLevel: readEnvString(
32810
+ "AHCHAT_LOG_LEVEL",
32811
+ fileConfig.logLevel ?? "INFO"
32812
+ ),
32813
+ dataDir,
32814
+ dbPath: readEnvString(
32815
+ "AHCHAT_DB_PATH",
32816
+ fileConfig.dbPath ?? import_node_path2.default.join(dataDir, "data.db")
32817
+ ),
32818
+ serverApiUrl: readEnvString(
32819
+ "AHCHAT_SERVER_API_URL",
32820
+ fileConfig.serverApiUrl ?? "http://127.0.0.1:3001"
32821
+ ),
32822
+ agentConfigDir: readEnvString(
32823
+ "AHCHAT_AGENT_CONFIG_DIR",
32824
+ fileConfig.agentConfigDir ?? resolveAgentConfigDir(dataDir)
32825
+ ),
32826
+ defaultModel: readEnvString(
32827
+ "AHCHAT_DEFAULT_MODEL",
32828
+ fileConfig.defaultModel ?? ""
32829
+ ) || null,
32830
+ logUploadIntervalMs: readEnvInt(
32831
+ "AHCHAT_LOG_UPLOAD_INTERVAL_MS",
32832
+ // Flush every 60s instead of once a day. Daily flushing let logs pile up for hours,
32833
+ // then dumped tens of thousands of entries in one cycle on the next process start,
32834
+ // blowing past the server's per-minute upload quota (3000 entries / 3MB) and getting
32835
+ // 429'd. Small frequent batches stay well under that ceiling.
32836
+ fileConfig.logUploadIntervalMs ?? 6e4
32837
+ ),
32838
+ queryConfig: mergeQueryConfig(fileConfig)
32839
+ };
32840
+ }
32841
+ function ensureDir(dirPath) {
32842
+ import_node_fs.default.mkdirSync(dirPath, { recursive: true, mode: 448 });
32843
+ try {
32844
+ import_node_fs.default.chmodSync(dirPath, 448);
32845
+ } catch {
32846
+ }
32847
+ }
32848
+
32849
+ // src/logger.ts
32850
+ var bridgeConfig = loadBridgeConfig();
32851
+ var isTest = !!process.env["VITEST"];
32852
+ var activeDataDir = bridgeConfig.dataDir || import_node_path3.default.join(import_node_os3.default.homedir(), ".ahchat");
32853
+ var fileTransports = /* @__PURE__ */ new Map();
32854
+ function activeLogFile() {
32855
+ return import_node_path3.default.join(activeDataDir, "logs", "bridge.log");
32856
+ }
32857
+ if (!isTest) ensureDir(import_node_path3.default.dirname(activeLogFile()));
32858
+ function dynamicFileTransport() {
32859
+ return (entry) => {
32860
+ const logFile = activeLogFile();
32861
+ let transport = fileTransports.get(logFile);
32862
+ if (!transport) {
32863
+ transport = fileTransport({
32864
+ path: logFile,
32865
+ formatter: jsonFormatter,
32866
+ rotate: { maxSize: "20MB", maxFiles: 5 }
32867
+ });
32868
+ fileTransports.set(logFile, transport);
32869
+ }
32870
+ transport(entry);
32871
+ };
32872
+ }
32873
+ function createModuleLogger(module2) {
32874
+ const transports = [consoleTransport({ formatter: prettyFormatter })];
32875
+ if (!isTest) {
32876
+ transports.push(dynamicFileTransport());
32877
+ }
32878
+ return createLogger({
32879
+ source: "bridge",
32880
+ module: module2,
32881
+ level: parseLogLevel(bridgeConfig.logLevel),
32882
+ transports
32883
+ });
32884
+ }
32885
+
32886
+ // src/officialMcpQuota.ts
32887
+ var logger = createModuleLogger("officialMcp.quota");
31240
32888
  var OfficialMcpQuotaError = class extends Error {
31241
32889
  constructor(message) {
31242
32890
  super(message);
@@ -31257,7 +32905,8 @@ async function consumeOfficialMcpDailyQuota(serverName, toolName) {
31257
32905
  },
31258
32906
  body: JSON.stringify({ serverName, toolName })
31259
32907
  });
31260
- } catch {
32908
+ } catch (error51) {
32909
+ logger.error("Official MCP quota consume request failed", { error: error51, serverName, toolName });
31261
32910
  throw new OfficialMcpQuotaError("\u6682\u65F6\u65E0\u6CD5\u6821\u9A8C\u5B98\u65B9\u5A92\u4F53 MCP \u6BCF\u65E5\u989D\u5EA6\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002");
31262
32911
  }
31263
32912
  if (response.status === 404) return;
@@ -31275,7 +32924,8 @@ async function readQuotaResponse(response) {
31275
32924
  if (value && typeof value === "object" && !Array.isArray(value)) {
31276
32925
  return value;
31277
32926
  }
31278
- } catch {
32927
+ } catch (error51) {
32928
+ logger.error("Official MCP quota response was not JSON", { error: error51, status: response.status });
31279
32929
  }
31280
32930
  return {};
31281
32931
  }
@@ -31290,8 +32940,8 @@ function formatQuotaExceededMessage(serverName, body) {
31290
32940
 
31291
32941
  // src/seedreamValidation.ts
31292
32942
  init_cjs_shims();
31293
- var import_promises = __toESM(require("fs/promises"), 1);
31294
- var import_node_path = __toESM(require("path"), 1);
32943
+ var import_promises2 = __toESM(require("fs/promises"), 1);
32944
+ var import_node_path4 = __toESM(require("path"), 1);
31295
32945
  var import_node_url = require("url");
31296
32946
  var HTTP_IMAGE_URL_RE = /^https?:\/\/\S+$/i;
31297
32947
  var DATA_IMAGE_RE = /^data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+$/i;
@@ -31310,7 +32960,7 @@ function countSeedreamImageReferences(image) {
31310
32960
  return image ? 1 : 0;
31311
32961
  }
31312
32962
  async function resolveSeedreamImageReferences(image, options = {}) {
31313
- const cwd = import_node_path.default.resolve(options.cwd ?? process.cwd());
32963
+ const cwd = import_node_path4.default.resolve(options.cwd ?? process.cwd());
31314
32964
  if (!image) return { image: void 0, error: null };
31315
32965
  const refs = Array.isArray(image) ? image : [image];
31316
32966
  const resolved = [];
@@ -31354,36 +33004,37 @@ async function resolveLocalSeedreamImageReference(value, cwd) {
31354
33004
  error: `Seedream reference image must be a supported image file (jpg, png, webp, gif, or bmp). Unsupported path: "${formatImageReferenceSample(value)}".`
31355
33005
  };
31356
33006
  }
31357
- let stat;
33007
+ let stat2;
31358
33008
  try {
31359
- stat = await import_promises.default.stat(resolvedPath);
31360
- } catch {
33009
+ stat2 = await import_promises2.default.stat(resolvedPath);
33010
+ } catch (error51) {
33011
+ const code = error51 && typeof error51 === "object" && "code" in error51 ? String(error51.code) : "UNKNOWN";
31361
33012
  return {
31362
- error: `Seedream reference image was not found in the agent workspace: "${formatImageReferenceSample(value)}".`
33013
+ error: `Seedream reference image was not found in the agent workspace (${code}): "${formatImageReferenceSample(value)}".`
31363
33014
  };
31364
33015
  }
31365
- if (!stat.isFile()) {
33016
+ if (!stat2.isFile()) {
31366
33017
  return {
31367
33018
  error: `Seedream reference image must point to a file: "${formatImageReferenceSample(value)}".`
31368
33019
  };
31369
33020
  }
31370
- const bytes = await import_promises.default.readFile(resolvedPath);
33021
+ const bytes = await import_promises2.default.readFile(resolvedPath);
31371
33022
  return {
31372
33023
  image: `data:${mimeType};base64,${bytes.toString("base64")}`,
31373
33024
  error: null
31374
33025
  };
31375
33026
  }
31376
33027
  function resolveLocalPath(value, cwd) {
31377
- if (/^file:/i.test(value)) return import_node_path.default.resolve((0, import_node_url.fileURLToPath)(value));
31378
- if (import_node_path.default.isAbsolute(value)) return import_node_path.default.resolve(value);
31379
- return import_node_path.default.resolve(cwd, value);
33028
+ if (/^file:/i.test(value)) return import_node_path4.default.resolve((0, import_node_url.fileURLToPath)(value));
33029
+ if (import_node_path4.default.isAbsolute(value)) return import_node_path4.default.resolve(value);
33030
+ return import_node_path4.default.resolve(cwd, value);
31380
33031
  }
31381
33032
  function mimeTypeForImagePath(filePath) {
31382
- return SUPPORTED_IMAGE_MIME_BY_EXT[import_node_path.default.extname(filePath).toLowerCase()] ?? null;
33033
+ return SUPPORTED_IMAGE_MIME_BY_EXT[import_node_path4.default.extname(filePath).toLowerCase()] ?? null;
31383
33034
  }
31384
33035
  function isPathInside(filePath, basePath) {
31385
- const relative = import_node_path.default.relative(import_node_path.default.resolve(basePath), import_node_path.default.resolve(filePath));
31386
- return relative === "" || !relative.startsWith("..") && !import_node_path.default.isAbsolute(relative);
33036
+ const relative = import_node_path4.default.relative(import_node_path4.default.resolve(basePath), import_node_path4.default.resolve(filePath));
33037
+ return relative === "" || !relative.startsWith("..") && !import_node_path4.default.isAbsolute(relative);
31387
33038
  }
31388
33039
  function formatImageReferenceSample(value) {
31389
33040
  const trimmed = value.trim();
@@ -31395,6 +33046,7 @@ function formatImageReferenceSample(value) {
31395
33046
  var SERVER_NAME = "ahchat-seedream-mcp";
31396
33047
  var SERVER_VERSION = "0.1.0";
31397
33048
  var DEFAULT_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
33049
+ var logger2 = createModuleLogger("seedream.mcpCli");
31398
33050
  var SEEDREAM_MODELS = [
31399
33051
  "doubao-seedream-5-0-lite-260128",
31400
33052
  "doubao-seedream-4-0-250828",
@@ -31709,8 +33361,8 @@ async function saveGeneratedImagesToWorkdir(images) {
31709
33361
  try {
31710
33362
  const downloaded = await downloadGeneratedImage(image.url);
31711
33363
  const fileName = await uniqueGeneratedImageFileName(downloaded.extension, index);
31712
- const filePath = import_node_path2.default.join(process.cwd(), fileName);
31713
- await import_promises2.default.writeFile(filePath, downloaded.buffer, { flag: "wx" });
33364
+ const filePath = import_node_path5.default.join(process.cwd(), fileName);
33365
+ await import_promises3.default.writeFile(filePath, downloaded.buffer, { flag: "wx" });
31714
33366
  saved.push({
31715
33367
  ...image,
31716
33368
  local_path: filePath,
@@ -31765,14 +33417,10 @@ function imageMimeTypeFromContentType(contentType) {
31765
33417
  return normalizeImageMimeType(contentType.split(";")[0]?.trim() ?? "");
31766
33418
  }
31767
33419
  function imageMimeTypeFromUrl(url2) {
31768
- try {
31769
- return imageMimeTypeFromPath(new URL(url2).pathname);
31770
- } catch {
31771
- return imageMimeTypeFromPath(url2);
31772
- }
33420
+ return imageMimeTypeFromPath(URL.canParse(url2) ? new URL(url2).pathname : url2);
31773
33421
  }
31774
33422
  function imageMimeTypeFromPath(filePath) {
31775
- switch (import_node_path2.default.extname(filePath).toLowerCase()) {
33423
+ switch (import_node_path5.default.extname(filePath).toLowerCase()) {
31776
33424
  case ".bmp":
31777
33425
  return "image/bmp";
31778
33426
  case ".gif":
@@ -31816,8 +33464,11 @@ async function uniqueGeneratedImageFileName(extension, imageIndex) {
31816
33464
  const suffix = attempt === 0 ? "" : `-${attempt + 1}`;
31817
33465
  const fileName = `${baseName}${suffix}${extension}`;
31818
33466
  try {
31819
- await import_promises2.default.access(import_node_path2.default.join(process.cwd(), fileName));
31820
- } catch {
33467
+ await import_promises3.default.access(import_node_path5.default.join(process.cwd(), fileName));
33468
+ } catch (error51) {
33469
+ if (!isFileNotFoundError(error51)) {
33470
+ logger2.error("Seedream generated image filename access check failed", { error: error51 });
33471
+ }
31821
33472
  return fileName;
31822
33473
  }
31823
33474
  }
@@ -31828,7 +33479,12 @@ async function parseJsonSafe(response) {
31828
33479
  if (!text) return void 0;
31829
33480
  try {
31830
33481
  return JSON.parse(text);
31831
- } catch {
33482
+ } catch (error51) {
33483
+ logger2.error("Seedream ARK API returned non-JSON response body", {
33484
+ error: error51,
33485
+ status: response.status,
33486
+ bodyLength: text.length
33487
+ });
31832
33488
  return text;
31833
33489
  }
31834
33490
  }
@@ -31891,14 +33547,15 @@ function errorResult(message) {
31891
33547
  isError: true
31892
33548
  };
31893
33549
  }
33550
+ function isFileNotFoundError(error51) {
33551
+ return Boolean(error51 && typeof error51 === "object" && error51.code === "ENOENT");
33552
+ }
31894
33553
  async function main() {
31895
33554
  const server = createServer();
31896
33555
  const transport = new StdioServerTransport();
31897
33556
  await server.connect(transport);
31898
- console.error(`${SERVER_NAME} v${SERVER_VERSION} running on stdio`);
31899
33557
  }
31900
33558
  main().catch((error51) => {
31901
- const message = error51 instanceof Error ? error51.stack ?? error51.message : String(error51);
31902
- console.error(`Fatal error in ${SERVER_NAME}: ${message}`);
33559
+ logger2.error(`Fatal error in ${SERVER_NAME}`, { error: error51 });
31903
33560
  process.exit(1);
31904
33561
  });