@fangyb/ahchat-bridge 0.1.33 → 0.1.35

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,1613 @@ 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/transports/console.ts
31959
+ init_cjs_shims();
31960
+ var protectedStreams = /* @__PURE__ */ new WeakSet();
31961
+ function defaultStream(kind) {
31962
+ const maybeGlobal = globalThis;
31963
+ return maybeGlobal.process?.[kind];
31964
+ }
31965
+ function safeWriteLine(stream, line, fallback) {
31966
+ if (!stream) {
31967
+ fallback(line);
31968
+ return;
31969
+ }
31970
+ if (stream.destroyed || stream.writableEnded) return;
31971
+ if (typeof stream === "object" && typeof stream.on === "function" && !protectedStreams.has(stream)) {
31972
+ protectedStreams.add(stream);
31973
+ stream.on("error", () => void 0);
31974
+ }
31975
+ try {
31976
+ stream.write(`${line}
31977
+ `, () => void 0);
31978
+ } catch {
31979
+ }
31980
+ }
31981
+ function consoleTransport(opts) {
31982
+ const fmt = opts?.formatter ?? jsonFormatter;
31983
+ return (entry) => {
31984
+ const line = fmt(entry);
31985
+ if (LOG_LEVEL_VALUE[entry.level] >= LOG_LEVEL_VALUE.ERROR) {
31986
+ safeWriteLine(opts?.stderr ?? defaultStream("stderr"), line, console.error);
31987
+ } else {
31988
+ safeWriteLine(opts?.stdout ?? defaultStream("stdout"), line, console.log);
31989
+ }
31990
+ };
31991
+ }
31992
+
31993
+ // ../logger/src/transports/file.ts
31994
+ init_cjs_shims();
31995
+ var import_node_path = __toESM(require("path"), 1);
31996
+
31997
+ // ../../node_modules/.pnpm/rotating-file-stream@3.2.9/node_modules/rotating-file-stream/dist/esm/index.js
31998
+ init_cjs_shims();
31999
+ var import_child_process = require("child_process");
32000
+ var import_zlib = require("zlib");
32001
+ var import_stream = require("stream");
32002
+ var import_fs = require("fs");
32003
+ var import_promises = require("fs/promises");
32004
+ var import_path = require("path");
32005
+ var import_util6 = require("util");
32006
+ var import_timers = require("timers");
32007
+ async function exists(filename) {
32008
+ return new Promise((resolve) => (0, import_fs.access)(filename, import_fs.constants.F_OK, (error51) => resolve(!error51)));
32009
+ }
32010
+ var RotatingFileStreamError = class extends Error {
32011
+ code = "RFS-TOO-MANY";
32012
+ constructor() {
32013
+ super("Too many destination file attempts");
32014
+ }
32015
+ };
32016
+ var RotatingFileStream = class extends import_stream.Writable {
32017
+ createGzip;
32018
+ exec;
32019
+ file;
32020
+ filename;
32021
+ finished;
32022
+ fsCreateReadStream;
32023
+ fsCreateWriteStream;
32024
+ fsOpen;
32025
+ fsReadFile;
32026
+ fsStat;
32027
+ fsUnlink;
32028
+ generator;
32029
+ initPromise;
32030
+ last;
32031
+ maxTimeout;
32032
+ next;
32033
+ options;
32034
+ prev;
32035
+ rotation;
32036
+ size;
32037
+ stdout;
32038
+ timeout;
32039
+ timeoutPromise;
32040
+ constructor(generator, options) {
32041
+ const { encoding, history, maxFiles, maxSize, path: path6 } = options;
32042
+ super({ decodeStrings: true, defaultEncoding: encoding });
32043
+ this.createGzip = import_zlib.createGzip;
32044
+ this.exec = import_child_process.exec;
32045
+ this.filename = path6 + generator(null);
32046
+ this.fsCreateReadStream = import_fs.createReadStream;
32047
+ this.fsCreateWriteStream = import_fs.createWriteStream;
32048
+ this.fsOpen = import_promises.open;
32049
+ this.fsReadFile = import_promises.readFile;
32050
+ this.fsStat = import_promises.stat;
32051
+ this.fsUnlink = import_promises.unlink;
32052
+ this.generator = generator;
32053
+ this.maxTimeout = 2147483640;
32054
+ this.options = options;
32055
+ this.stdout = process.stdout;
32056
+ if (maxFiles || maxSize)
32057
+ options.history = path6 + (history ? history : this.generator(null) + ".txt");
32058
+ this.on("close", () => this.finished ? null : this.emit("finish"));
32059
+ this.on("finish", () => this.finished = this.clear());
32060
+ (async () => {
32061
+ try {
32062
+ this.initPromise = this.init();
32063
+ await this.initPromise;
32064
+ delete this.initPromise;
32065
+ } catch (e) {
32066
+ }
32067
+ })();
32068
+ }
32069
+ _destroy(error51, callback) {
32070
+ this.refinal(error51, callback);
32071
+ }
32072
+ _final(callback) {
32073
+ this.refinal(void 0, callback);
32074
+ }
32075
+ _write(chunk, encoding, callback) {
32076
+ this.rewrite([{ chunk, encoding }], 0, callback);
32077
+ }
32078
+ _writev(chunks, callback) {
32079
+ this.rewrite(chunks, 0, callback);
32080
+ }
32081
+ async refinal(error51, callback) {
32082
+ try {
32083
+ this.clear();
32084
+ if (this.initPromise)
32085
+ await this.initPromise;
32086
+ if (this.timeoutPromise)
32087
+ await this.timeoutPromise;
32088
+ await this.reclose();
32089
+ } catch (e) {
32090
+ return callback(error51 || e);
32091
+ }
32092
+ callback(error51);
32093
+ }
32094
+ async rewrite(chunks, index, callback) {
32095
+ const { size, teeToStdout } = this.options;
32096
+ try {
32097
+ if (this.initPromise)
32098
+ await this.initPromise;
32099
+ for (let i = 0; i < chunks.length; ++i) {
32100
+ const { chunk } = chunks[i];
32101
+ this.size += chunk.length;
32102
+ if (this.timeoutPromise)
32103
+ await this.timeoutPromise;
32104
+ await this.file.write(chunk);
32105
+ if (teeToStdout && !this.stdout.destroyed)
32106
+ this.stdout.write(chunk);
32107
+ if (size && this.size >= size)
32108
+ await this.rotate();
32109
+ }
32110
+ } catch (e) {
32111
+ return callback(e);
32112
+ }
32113
+ callback();
32114
+ }
32115
+ async init() {
32116
+ const { immutable, initialRotation, interval, size } = this.options;
32117
+ if (immutable)
32118
+ return new Promise((resolve, reject) => process.nextTick(() => this.immutate(true).then(resolve).catch(reject)));
32119
+ let stats;
32120
+ try {
32121
+ stats = await (0, import_promises.stat)(this.filename);
32122
+ } catch (e) {
32123
+ if (e.code !== "ENOENT")
32124
+ throw e;
32125
+ return this.reopen(0);
32126
+ }
32127
+ if (!stats.isFile())
32128
+ throw new Error(`Can't write on: ${this.filename} (it is not a file)`);
32129
+ if (initialRotation) {
32130
+ this.intervalBounds(this.now());
32131
+ const prev = this.prev;
32132
+ this.intervalBounds(new Date(stats.mtime.getTime()));
32133
+ if (prev !== this.prev)
32134
+ return this.rotate();
32135
+ }
32136
+ this.size = stats.size;
32137
+ if (!size || stats.size < size)
32138
+ return this.reopen(stats.size);
32139
+ if (interval)
32140
+ this.intervalBounds(this.now());
32141
+ return this.rotate();
32142
+ }
32143
+ async makePath(name) {
32144
+ return (0, import_promises.mkdir)(name.split(import_path.sep).slice(0, -1).join(import_path.sep), { recursive: true });
32145
+ }
32146
+ async reopen(size) {
32147
+ let file2;
32148
+ try {
32149
+ file2 = await (0, import_promises.open)(this.filename, "a", this.options.mode);
32150
+ } catch (e) {
32151
+ if (e.code !== "ENOENT")
32152
+ throw e;
32153
+ await this.makePath(this.filename);
32154
+ file2 = await (0, import_promises.open)(this.filename, "a", this.options.mode);
32155
+ }
32156
+ this.file = file2;
32157
+ this.size = size;
32158
+ this.interval();
32159
+ this.emit("open", this.filename);
32160
+ }
32161
+ async reclose() {
32162
+ const { file: file2 } = this;
32163
+ if (!file2)
32164
+ return;
32165
+ delete this.file;
32166
+ return file2.close();
32167
+ }
32168
+ now() {
32169
+ return /* @__PURE__ */ new Date();
32170
+ }
32171
+ async rotate() {
32172
+ const { immutable, rotate } = this.options;
32173
+ this.size = 0;
32174
+ this.rotation = this.now();
32175
+ this.clear();
32176
+ this.emit("rotation");
32177
+ await this.reclose();
32178
+ if (rotate)
32179
+ return this.classical();
32180
+ if (immutable)
32181
+ return this.immutate(false);
32182
+ return this.move();
32183
+ }
32184
+ async findName() {
32185
+ const { interval, path: path6, intervalBoundary } = this.options;
32186
+ for (let index = 1; index < 1e3; ++index) {
32187
+ const filename = path6 + this.generator(interval && intervalBoundary ? new Date(this.prev) : this.rotation, index);
32188
+ if (!await exists(filename))
32189
+ return filename;
32190
+ }
32191
+ throw new RotatingFileStreamError();
32192
+ }
32193
+ async move() {
32194
+ const { compress } = this.options;
32195
+ const filename = await this.findName();
32196
+ await this.touch(filename);
32197
+ if (compress)
32198
+ await this.compress(filename);
32199
+ else
32200
+ await (0, import_promises.rename)(this.filename, filename);
32201
+ return this.rotated(filename);
32202
+ }
32203
+ async touch(filename) {
32204
+ let file2;
32205
+ try {
32206
+ file2 = await this.fsOpen(filename, "a");
32207
+ } catch (e) {
32208
+ if (e.code !== "ENOENT")
32209
+ throw e;
32210
+ await this.makePath(filename);
32211
+ file2 = await (0, import_promises.open)(filename, "a");
32212
+ }
32213
+ await file2.close();
32214
+ return this.unlink(filename);
32215
+ }
32216
+ async classical() {
32217
+ const { compress, path: path6, rotate } = this.options;
32218
+ let rotatedName = "";
32219
+ for (let count = rotate; count > 0; --count) {
32220
+ const currName = path6 + this.generator(count);
32221
+ const prevName = count === 1 ? this.filename : path6 + this.generator(count - 1);
32222
+ if (!await exists(prevName))
32223
+ continue;
32224
+ if (!rotatedName)
32225
+ rotatedName = currName;
32226
+ if (count === 1 && compress)
32227
+ await this.compress(currName);
32228
+ else {
32229
+ try {
32230
+ await (0, import_promises.rename)(prevName, currName);
32231
+ } catch (e) {
32232
+ if (e.code !== "ENOENT")
32233
+ throw e;
32234
+ await this.makePath(currName);
32235
+ await (0, import_promises.rename)(prevName, currName);
32236
+ }
32237
+ }
32238
+ }
32239
+ return this.rotated(rotatedName);
32240
+ }
32241
+ clear() {
32242
+ if (this.timeout) {
32243
+ clearTimeout(this.timeout);
32244
+ this.timeout = null;
32245
+ }
32246
+ return true;
32247
+ }
32248
+ intervalBoundsBig(now) {
32249
+ const year = this.options.intervalUTC ? now.getUTCFullYear() : now.getFullYear();
32250
+ let month = this.options.intervalUTC ? now.getUTCMonth() : now.getMonth();
32251
+ let day = this.options.intervalUTC ? now.getUTCDate() : now.getDate();
32252
+ let hours = this.options.intervalUTC ? now.getUTCHours() : now.getHours();
32253
+ const { num, unit } = this.options.interval;
32254
+ if (unit === "M") {
32255
+ day = 1;
32256
+ hours = 0;
32257
+ } else if (unit === "d")
32258
+ hours = 0;
32259
+ else
32260
+ hours = parseInt(hours / num, 10) * num;
32261
+ this.prev = new Date(year, month, day, hours, 0, 0, 0).getTime();
32262
+ if (unit === "M")
32263
+ month += num;
32264
+ else if (unit === "d")
32265
+ day += num;
32266
+ else
32267
+ hours += num;
32268
+ this.next = new Date(year, month, day, hours, 0, 0, 0).getTime();
32269
+ }
32270
+ intervalBounds(now) {
32271
+ const unit = this.options.interval.unit;
32272
+ if (unit === "M" || unit === "d" || unit === "h")
32273
+ this.intervalBoundsBig(now);
32274
+ else {
32275
+ let period = 1e3 * this.options.interval.num;
32276
+ if (unit === "m")
32277
+ period *= 60;
32278
+ this.prev = parseInt(now.getTime() / period, 10) * period;
32279
+ this.next = this.prev + period;
32280
+ }
32281
+ return new Date(this.prev);
32282
+ }
32283
+ interval() {
32284
+ if (!this.options.interval)
32285
+ return;
32286
+ this.intervalBounds(this.now());
32287
+ const set2 = async () => {
32288
+ const time3 = this.next - this.now().getTime();
32289
+ if (time3 <= 0) {
32290
+ try {
32291
+ this.timeoutPromise = this.rotate();
32292
+ await this.timeoutPromise;
32293
+ delete this.timeoutPromise;
32294
+ } catch (e) {
32295
+ }
32296
+ } else {
32297
+ this.timeout = (0, import_timers.setTimeout)(set2, time3 > this.maxTimeout ? this.maxTimeout : time3);
32298
+ this.timeout.unref();
32299
+ }
32300
+ };
32301
+ set2();
32302
+ }
32303
+ async compress(filename) {
32304
+ const { compress } = this.options;
32305
+ if (typeof compress === "function") {
32306
+ await new Promise((resolve, reject) => {
32307
+ this.exec(compress(this.filename, filename), (error51, stdout, stderr) => {
32308
+ this.emit("external", stdout, stderr);
32309
+ error51 ? reject(error51) : resolve();
32310
+ });
32311
+ });
32312
+ } else
32313
+ await this.gzip(filename);
32314
+ return this.unlink(this.filename);
32315
+ }
32316
+ async gzip(filename) {
32317
+ const { mode } = this.options;
32318
+ const options = mode ? { mode } : {};
32319
+ const inp = this.fsCreateReadStream(this.filename, {});
32320
+ const out = this.fsCreateWriteStream(filename, options);
32321
+ const zip = this.createGzip();
32322
+ await new Promise((resolve, reject) => {
32323
+ inp.once("error", reject);
32324
+ out.once("error", reject);
32325
+ zip.once("error", reject);
32326
+ out.once("finish", resolve);
32327
+ inp.pipe(zip).pipe(out);
32328
+ });
32329
+ await Promise.all([
32330
+ new Promise((resolve) => zip.close(resolve)),
32331
+ new Promise((resolve) => out.close((err) => {
32332
+ if (err)
32333
+ this.emit("warning", err);
32334
+ resolve();
32335
+ }))
32336
+ ]);
32337
+ }
32338
+ async rotated(filename) {
32339
+ const { maxFiles, maxSize } = this.options;
32340
+ if (maxFiles || maxSize)
32341
+ await this.history(filename);
32342
+ this.emit("rotated", filename);
32343
+ return this.reopen(0);
32344
+ }
32345
+ async history(filename) {
32346
+ const { history, maxFiles, maxSize } = this.options;
32347
+ const res = [];
32348
+ let files = [filename];
32349
+ try {
32350
+ const content = await this.fsReadFile(history, "utf8");
32351
+ files = [...content.toString().split("\n"), filename];
32352
+ } catch (e) {
32353
+ if (e.code !== "ENOENT")
32354
+ throw e;
32355
+ }
32356
+ for (const file2 of files) {
32357
+ if (file2) {
32358
+ try {
32359
+ const stats = await this.fsStat(file2);
32360
+ if (stats.isFile()) {
32361
+ res.push({
32362
+ name: file2,
32363
+ size: stats.size,
32364
+ time: stats.mtime.getTime()
32365
+ });
32366
+ } else
32367
+ this.emit("warning", new Error(`File '${file2}' contained in history is not a regular file`));
32368
+ } catch (e) {
32369
+ if (e.code !== "ENOENT")
32370
+ throw e;
32371
+ }
32372
+ }
32373
+ }
32374
+ res.sort((a, b) => a.time - b.time);
32375
+ if (maxFiles) {
32376
+ while (res.length > maxFiles) {
32377
+ const file2 = res.shift();
32378
+ await this.unlink(file2.name);
32379
+ this.emit("removed", file2.name, true);
32380
+ }
32381
+ }
32382
+ if (maxSize) {
32383
+ while (res.reduce((size, file2) => size + file2.size, 0) > maxSize) {
32384
+ const file2 = res.shift();
32385
+ await this.unlink(file2.name);
32386
+ this.emit("removed", file2.name, false);
32387
+ }
32388
+ }
32389
+ await (0, import_promises.writeFile)(history, res.map((e) => e.name).join("\n") + "\n", "utf-8");
32390
+ this.emit("history");
32391
+ }
32392
+ async immutate(first) {
32393
+ const { size } = this.options;
32394
+ const now = this.now();
32395
+ for (let index = 1; index < 1e3; ++index) {
32396
+ let fileSize = 0;
32397
+ let stats = void 0;
32398
+ this.filename = this.options.path + this.generator(now, index);
32399
+ try {
32400
+ stats = await this.fsStat(this.filename);
32401
+ } catch (e) {
32402
+ if (e.code !== "ENOENT")
32403
+ throw e;
32404
+ }
32405
+ if (stats) {
32406
+ fileSize = stats.size;
32407
+ if (!stats.isFile())
32408
+ throw new Error(`Can't write on: '${this.filename}' (it is not a file)`);
32409
+ if (size && fileSize >= size)
32410
+ continue;
32411
+ }
32412
+ if (first) {
32413
+ this.last = this.filename;
32414
+ return this.reopen(fileSize);
32415
+ }
32416
+ await this.rotated(this.last);
32417
+ this.last = this.filename;
32418
+ return;
32419
+ }
32420
+ throw new RotatingFileStreamError();
32421
+ }
32422
+ async unlink(filename) {
32423
+ try {
32424
+ await this.fsUnlink(filename);
32425
+ } catch (e) {
32426
+ if (e.code !== "ENOENT")
32427
+ throw e;
32428
+ this.emit("warning", e);
32429
+ }
32430
+ }
32431
+ };
32432
+ function buildNumberCheck(field) {
32433
+ return (type, options, value) => {
32434
+ const converted = parseInt(value, 10);
32435
+ if (type !== "number" || converted !== value || converted <= 0)
32436
+ throw new Error(`'${field}' option must be a positive integer number`);
32437
+ };
32438
+ }
32439
+ function buildStringCheck(field, check2) {
32440
+ return (type, options, value) => {
32441
+ if (type !== "string")
32442
+ throw new Error(`Don't know how to handle 'options.${field}' type: ${type}`);
32443
+ options[field] = check2(value);
32444
+ };
32445
+ }
32446
+ function checkMeasure(value, what, units) {
32447
+ const ret = {};
32448
+ ret.num = parseInt(value, 10);
32449
+ if (isNaN(ret.num))
32450
+ throw new Error(`Unknown 'options.${what}' format: ${value}`);
32451
+ if (ret.num <= 0)
32452
+ throw new Error(`A positive integer number is expected for 'options.${what}'`);
32453
+ ret.unit = value.replace(/^[ 0]*/g, "").substr((ret.num + "").length, 1);
32454
+ if (ret.unit.length === 0)
32455
+ throw new Error(`Missing unit for 'options.${what}'`);
32456
+ if (!units[ret.unit])
32457
+ throw new Error(`Unknown 'options.${what}' unit: ${ret.unit}`);
32458
+ return ret;
32459
+ }
32460
+ var intervalUnits = { M: true, d: true, h: true, m: true, s: true };
32461
+ function checkIntervalUnit(ret, unit, amount) {
32462
+ if (parseInt(amount / ret.num, 10) * ret.num !== amount)
32463
+ throw new Error(`An integer divider of ${amount} is expected as ${unit} for 'options.interval'`);
32464
+ }
32465
+ function checkInterval(value) {
32466
+ const ret = checkMeasure(value, "interval", intervalUnits);
32467
+ switch (ret.unit) {
32468
+ case "h":
32469
+ checkIntervalUnit(ret, "hours", 24);
32470
+ break;
32471
+ case "m":
32472
+ checkIntervalUnit(ret, "minutes", 60);
32473
+ break;
32474
+ case "s":
32475
+ checkIntervalUnit(ret, "seconds", 60);
32476
+ break;
32477
+ }
32478
+ return ret;
32479
+ }
32480
+ var sizeUnits = { B: true, G: true, K: true, M: true };
32481
+ function checkSize(value) {
32482
+ const ret = checkMeasure(value, "size", sizeUnits);
32483
+ if (ret.unit === "K")
32484
+ return ret.num * 1024;
32485
+ if (ret.unit === "M")
32486
+ return ret.num * 1048576;
32487
+ if (ret.unit === "G")
32488
+ return ret.num * 1073741824;
32489
+ return ret.num;
32490
+ }
32491
+ var checks = {
32492
+ encoding: (type, options, value) => new import_util6.TextDecoder(value),
32493
+ immutable: () => {
32494
+ },
32495
+ initialRotation: () => {
32496
+ },
32497
+ interval: buildStringCheck("interval", checkInterval),
32498
+ intervalBoundary: () => {
32499
+ },
32500
+ intervalUTC: () => {
32501
+ },
32502
+ maxFiles: buildNumberCheck("maxFiles"),
32503
+ maxSize: buildStringCheck("maxSize", checkSize),
32504
+ mode: () => {
32505
+ },
32506
+ omitExtension: () => {
32507
+ },
32508
+ rotate: buildNumberCheck("rotate"),
32509
+ size: buildStringCheck("size", checkSize),
32510
+ teeToStdout: () => {
32511
+ },
32512
+ ...{
32513
+ compress: (type, options, value) => {
32514
+ if (value === false)
32515
+ return;
32516
+ if (!value)
32517
+ throw new Error("A value for 'options.compress' must be specified");
32518
+ if (type === "boolean")
32519
+ return options.compress = (source, dest) => `cat ${source} | gzip -c9 > ${dest}`;
32520
+ if (type === "function")
32521
+ return;
32522
+ if (type !== "string")
32523
+ throw new Error(`Don't know how to handle 'options.compress' type: ${type}`);
32524
+ if (value !== "gzip")
32525
+ throw new Error(`Don't know how to handle compression method: ${value}`);
32526
+ },
32527
+ history: (type) => {
32528
+ if (type !== "string")
32529
+ throw new Error(`Don't know how to handle 'options.history' type: ${type}`);
32530
+ },
32531
+ path: (type, options, value) => {
32532
+ if (type !== "string")
32533
+ throw new Error(`Don't know how to handle 'options.path' type: ${type}`);
32534
+ if (value[value.length - 1] !== import_path.sep)
32535
+ options.path = value + import_path.sep;
32536
+ }
32537
+ }
32538
+ };
32539
+ function checkOpts(options) {
32540
+ const ret = {};
32541
+ let opt;
32542
+ for (opt in options) {
32543
+ const value = options[opt];
32544
+ const type = typeof value;
32545
+ if (!(opt in checks))
32546
+ throw new Error(`Unknown option: ${opt}`);
32547
+ ret[opt] = options[opt];
32548
+ checks[opt](type, ret, value);
32549
+ }
32550
+ if (!ret.path)
32551
+ ret.path = "";
32552
+ if (!ret.interval) {
32553
+ delete ret.immutable;
32554
+ delete ret.initialRotation;
32555
+ delete ret.intervalBoundary;
32556
+ delete ret.intervalUTC;
32557
+ }
32558
+ if (ret.rotate) {
32559
+ delete ret.history;
32560
+ delete ret.immutable;
32561
+ delete ret.maxFiles;
32562
+ delete ret.maxSize;
32563
+ delete ret.intervalBoundary;
32564
+ delete ret.intervalUTC;
32565
+ }
32566
+ if (ret.immutable)
32567
+ delete ret.compress;
32568
+ if (!ret.intervalBoundary)
32569
+ delete ret.initialRotation;
32570
+ return ret;
32571
+ }
32572
+ function createClassical(filename, compress, omitExtension) {
32573
+ return (index) => index ? `${filename}.${index}${compress && !omitExtension ? ".gz" : ""}` : filename;
32574
+ }
32575
+ function createGenerator(filename, compress, omitExtension) {
32576
+ const pad = (num) => (num > 9 ? "" : "0") + num;
32577
+ return (time3, index) => {
32578
+ if (!time3)
32579
+ return filename;
32580
+ const month = time3.getFullYear() + "" + pad(time3.getMonth() + 1);
32581
+ const day = pad(time3.getDate());
32582
+ const hour = pad(time3.getHours());
32583
+ const minute = pad(time3.getMinutes());
32584
+ return month + day + "-" + hour + minute + "-" + pad(index) + "-" + filename + (compress && !omitExtension ? ".gz" : "");
32585
+ };
32586
+ }
32587
+ function createStream(filename, options) {
32588
+ if (typeof options === "undefined")
32589
+ options = {};
32590
+ else if (typeof options !== "object")
32591
+ throw new Error(`The "options" argument must be of type object. Received type ${typeof options}`);
32592
+ const opts = checkOpts(options);
32593
+ const { compress, omitExtension } = opts;
32594
+ let generator;
32595
+ if (typeof filename === "string")
32596
+ generator = options.rotate ? createClassical(filename, !!compress, omitExtension) : createGenerator(filename, !!compress, omitExtension);
32597
+ else if (typeof filename === "function")
32598
+ generator = filename;
32599
+ else
32600
+ throw new Error(`The "filename" argument must be one of type string or function. Received type ${typeof filename}`);
32601
+ return new RotatingFileStream(generator, opts);
32602
+ }
32603
+
32604
+ // ../logger/src/transports/file.ts
32605
+ function parseSize(maxSize) {
32606
+ const trimmed = maxSize.trim().toUpperCase();
32607
+ if (trimmed.endsWith("MB")) {
32608
+ return `${trimmed.slice(0, -2)}M`;
32609
+ }
32610
+ return trimmed;
32611
+ }
32612
+ var streamCache = /* @__PURE__ */ new Map();
32613
+ function fileTransport(opts) {
32614
+ const fmt = opts.formatter ?? jsonFormatter;
32615
+ const resolved = import_node_path.default.resolve(opts.path);
32616
+ let cached2 = streamCache.get(resolved);
32617
+ if (!cached2) {
32618
+ cached2 = {
32619
+ stream: createStream(import_node_path.default.basename(resolved), {
32620
+ path: import_node_path.default.dirname(resolved),
32621
+ size: opts.rotate?.maxSize ? parseSize(opts.rotate.maxSize) : "50M",
32622
+ maxFiles: opts.rotate?.maxFiles ?? 7
32623
+ }),
32624
+ closed: false
32625
+ };
32626
+ streamCache.set(resolved, cached2);
32627
+ }
32628
+ return (entry) => {
32629
+ if (cached2.closed || cached2.stream.destroyed || cached2.stream.writableEnded) return;
32630
+ try {
32631
+ cached2.stream.write(`${fmt(entry)}
32632
+ `);
32633
+ } catch {
32634
+ }
32635
+ };
32636
+ }
32637
+
32638
+ // ../logger/src/index.ts
32639
+ function createLogger(config2) {
32640
+ return new Logger(config2);
32641
+ }
32642
+
32643
+ // src/config.ts
32644
+ init_cjs_shims();
32645
+ var import_node_crypto = __toESM(require("crypto"), 1);
32646
+ var import_node_fs = __toESM(require("fs"), 1);
32647
+ var import_node_os2 = __toESM(require("os"), 1);
32648
+ var import_node_path2 = __toESM(require("path"), 1);
32649
+ var DEFAULT_QUERY_CONFIG = {
32650
+ maxActive: 5040,
32651
+ idleTimeoutMs: 6e5,
32652
+ workingSilenceTimeoutMs: 12e5,
32653
+ evictionIntervalMs: 6e4,
32654
+ statusReportIntervalMs: 6e4,
32655
+ allowBuiltinWebSearch: false,
32656
+ 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",
32657
+ inboxQuietWindowMs: 15e3,
32658
+ inboxMaxLatencyMs: 18e4
32659
+ };
32660
+ function readEnvString(name, fallback) {
32661
+ const v = process.env[name];
32662
+ return v && v.length > 0 ? v : fallback;
32663
+ }
32664
+ function readEnvInt(name, fallback) {
32665
+ const v = process.env[name];
32666
+ if (!v || v.length === 0) return fallback;
32667
+ const n = Number.parseInt(v, 10);
32668
+ return Number.isFinite(n) && n > 0 ? n : fallback;
32669
+ }
32670
+ function readEnvBool(name, fallback) {
32671
+ const v = process.env[name];
32672
+ if (!v || v.length === 0) return fallback;
32673
+ const normalized = v.trim().toLowerCase();
32674
+ if (["1", "true", "yes", "on"].includes(normalized)) return true;
32675
+ if (["0", "false", "no", "off"].includes(normalized)) return false;
32676
+ return fallback;
32677
+ }
32678
+ function generateStableBridgeId(dataDir) {
32679
+ const raw = `${import_node_os2.default.hostname()}:${import_node_os2.default.userInfo().username}:${import_node_path2.default.resolve(dataDir)}`;
32680
+ const hash2 = import_node_crypto.default.createHash("sha256").update(raw).digest("hex").slice(0, 12);
32681
+ return `bridge_${hash2}`;
32682
+ }
32683
+ function generateStableBridgeToken() {
32684
+ const raw = `${import_node_os2.default.hostname()}:${import_node_os2.default.userInfo().username}:ahchat-bridge-token`;
32685
+ return import_node_crypto.default.createHash("sha256").update(raw).digest("hex").slice(0, 32);
32686
+ }
32687
+ function tryReadJsonConfig(filePath) {
32688
+ try {
32689
+ if (!import_node_fs.default.existsSync(filePath)) return {};
32690
+ const raw = import_node_fs.default.readFileSync(filePath, "utf-8");
32691
+ const parsed = JSON.parse(raw);
32692
+ if (typeof parsed !== "object" || parsed === null) return {};
32693
+ return parsed;
32694
+ } catch {
32695
+ return {};
32696
+ }
32697
+ }
32698
+ function mergeQueryConfig(file2) {
32699
+ const q = file2.queryConfig;
32700
+ return {
32701
+ maxActive: readEnvInt("AHCHAT_BRIDGE_MAX_ACTIVE", q?.maxActive ?? DEFAULT_QUERY_CONFIG.maxActive),
32702
+ idleTimeoutMs: readEnvInt(
32703
+ "AHCHAT_BRIDGE_IDLE_TIMEOUT_MS",
32704
+ q?.idleTimeoutMs ?? DEFAULT_QUERY_CONFIG.idleTimeoutMs
32705
+ ),
32706
+ workingSilenceTimeoutMs: readEnvInt(
32707
+ "AHCHAT_BRIDGE_WORKING_SILENCE_TIMEOUT_MS",
32708
+ q?.workingSilenceTimeoutMs ?? DEFAULT_QUERY_CONFIG.workingSilenceTimeoutMs
32709
+ ),
32710
+ evictionIntervalMs: readEnvInt(
32711
+ "AHCHAT_BRIDGE_EVICTION_INTERVAL_MS",
32712
+ q?.evictionIntervalMs ?? DEFAULT_QUERY_CONFIG.evictionIntervalMs
32713
+ ),
32714
+ statusReportIntervalMs: readEnvInt(
32715
+ "AHCHAT_BRIDGE_STATUS_REPORT_MS",
32716
+ q?.statusReportIntervalMs ?? DEFAULT_QUERY_CONFIG.statusReportIntervalMs
32717
+ ),
32718
+ allowBuiltinWebSearch: readEnvBool(
32719
+ "AHCHAT_BRIDGE_ALLOW_BUILTIN_WEBSEARCH",
32720
+ q?.allowBuiltinWebSearch ?? DEFAULT_QUERY_CONFIG.allowBuiltinWebSearch
32721
+ ),
32722
+ compactPromptTemplate: readEnvString(
32723
+ "AHCHAT_BRIDGE_COMPACT_PROMPT_TEMPLATE",
32724
+ q?.compactPromptTemplate ?? DEFAULT_QUERY_CONFIG.compactPromptTemplate
32725
+ ),
32726
+ inboxQuietWindowMs: readEnvInt(
32727
+ "AHCHAT_BRIDGE_INBOX_QUIET_WINDOW_MS",
32728
+ q?.inboxQuietWindowMs ?? DEFAULT_QUERY_CONFIG.inboxQuietWindowMs
32729
+ ),
32730
+ inboxMaxLatencyMs: readEnvInt(
32731
+ "AHCHAT_BRIDGE_INBOX_MAX_LATENCY_MS",
32732
+ q?.inboxMaxLatencyMs ?? DEFAULT_QUERY_CONFIG.inboxMaxLatencyMs
32733
+ )
32734
+ };
32735
+ }
32736
+ function resolveAgentConfigDir(dataDir) {
32737
+ const newPath = import_node_path2.default.join(dataDir, "agent-config");
32738
+ const oldPath = import_node_path2.default.join(dataDir, "claude-config");
32739
+ if (!import_node_fs.default.existsSync(newPath) && import_node_fs.default.existsSync(oldPath)) {
32740
+ try {
32741
+ import_node_fs.default.renameSync(oldPath, newPath);
32742
+ } catch {
32743
+ return oldPath;
32744
+ }
32745
+ }
32746
+ return newPath;
32747
+ }
32748
+ function loadBridgeConfig(opts) {
32749
+ const dataDir = opts?.dataDir ?? readEnvString(
32750
+ "AHCHAT_DATA_DIR",
32751
+ import_node_path2.default.join(import_node_os2.default.homedir(), ".ahchat")
32752
+ );
32753
+ const fileConfig = tryReadJsonConfig(import_node_path2.default.join(dataDir, "bridge.json"));
32754
+ return {
32755
+ serverUrl: readEnvString(
32756
+ "AHCHAT_BRIDGE_SERVER_URL",
32757
+ fileConfig.serverUrl ?? "ws://127.0.0.1:3001/ws/bridge"
32758
+ ),
32759
+ bridgeId: readEnvString(
32760
+ "AHCHAT_BRIDGE_ID",
32761
+ fileConfig.bridgeId ?? generateStableBridgeId(dataDir)
32762
+ ),
32763
+ bridgeToken: readEnvString(
32764
+ "AHCHAT_BRIDGE_TOKEN",
32765
+ fileConfig.bridgeToken ?? generateStableBridgeToken()
32766
+ ),
32767
+ logLevel: readEnvString(
32768
+ "AHCHAT_LOG_LEVEL",
32769
+ fileConfig.logLevel ?? "INFO"
32770
+ ),
32771
+ dataDir,
32772
+ dbPath: readEnvString(
32773
+ "AHCHAT_DB_PATH",
32774
+ fileConfig.dbPath ?? import_node_path2.default.join(dataDir, "data.db")
32775
+ ),
32776
+ serverApiUrl: readEnvString(
32777
+ "AHCHAT_SERVER_API_URL",
32778
+ fileConfig.serverApiUrl ?? "http://127.0.0.1:3001"
32779
+ ),
32780
+ agentConfigDir: readEnvString(
32781
+ "AHCHAT_AGENT_CONFIG_DIR",
32782
+ fileConfig.agentConfigDir ?? resolveAgentConfigDir(dataDir)
32783
+ ),
32784
+ defaultModel: readEnvString(
32785
+ "AHCHAT_DEFAULT_MODEL",
32786
+ fileConfig.defaultModel ?? ""
32787
+ ) || null,
32788
+ logUploadIntervalMs: readEnvInt(
32789
+ "AHCHAT_LOG_UPLOAD_INTERVAL_MS",
32790
+ fileConfig.logUploadIntervalMs ?? 24 * 60 * 60 * 1e3
32791
+ ),
32792
+ queryConfig: mergeQueryConfig(fileConfig)
32793
+ };
32794
+ }
32795
+ function ensureDir(dirPath) {
32796
+ import_node_fs.default.mkdirSync(dirPath, { recursive: true, mode: 448 });
32797
+ try {
32798
+ import_node_fs.default.chmodSync(dirPath, 448);
32799
+ } catch {
32800
+ }
32801
+ }
32802
+
32803
+ // src/logger.ts
32804
+ var bridgeConfig = loadBridgeConfig();
32805
+ var isTest = !!process.env["VITEST"];
32806
+ var activeDataDir = bridgeConfig.dataDir || import_node_path3.default.join(import_node_os3.default.homedir(), ".ahchat");
32807
+ var fileTransports = /* @__PURE__ */ new Map();
32808
+ function activeLogFile() {
32809
+ return import_node_path3.default.join(activeDataDir, "logs", "bridge.log");
32810
+ }
32811
+ if (!isTest) ensureDir(import_node_path3.default.dirname(activeLogFile()));
32812
+ function dynamicFileTransport() {
32813
+ return (entry) => {
32814
+ const logFile = activeLogFile();
32815
+ let transport = fileTransports.get(logFile);
32816
+ if (!transport) {
32817
+ transport = fileTransport({
32818
+ path: logFile,
32819
+ formatter: jsonFormatter,
32820
+ rotate: { maxSize: "20MB", maxFiles: 5 }
32821
+ });
32822
+ fileTransports.set(logFile, transport);
32823
+ }
32824
+ transport(entry);
32825
+ };
32826
+ }
32827
+ function createModuleLogger(module2) {
32828
+ const transports = [consoleTransport({ formatter: prettyFormatter })];
32829
+ if (!isTest) {
32830
+ transports.push(dynamicFileTransport());
32831
+ }
32832
+ return createLogger({
32833
+ source: "bridge",
32834
+ module: module2,
32835
+ level: parseLogLevel(bridgeConfig.logLevel),
32836
+ transports
32837
+ });
32838
+ }
32839
+
32840
+ // src/officialMcpQuota.ts
32841
+ var logger = createModuleLogger("officialMcp.quota");
31240
32842
  var OfficialMcpQuotaError = class extends Error {
31241
32843
  constructor(message) {
31242
32844
  super(message);
@@ -31257,7 +32859,8 @@ async function consumeOfficialMcpDailyQuota(serverName, toolName) {
31257
32859
  },
31258
32860
  body: JSON.stringify({ serverName, toolName })
31259
32861
  });
31260
- } catch {
32862
+ } catch (error51) {
32863
+ logger.error("Official MCP quota consume request failed", { error: error51, serverName, toolName });
31261
32864
  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
32865
  }
31263
32866
  if (response.status === 404) return;
@@ -31275,7 +32878,8 @@ async function readQuotaResponse(response) {
31275
32878
  if (value && typeof value === "object" && !Array.isArray(value)) {
31276
32879
  return value;
31277
32880
  }
31278
- } catch {
32881
+ } catch (error51) {
32882
+ logger.error("Official MCP quota response was not JSON", { error: error51, status: response.status });
31279
32883
  }
31280
32884
  return {};
31281
32885
  }
@@ -31290,8 +32894,8 @@ function formatQuotaExceededMessage(serverName, body) {
31290
32894
 
31291
32895
  // src/seedreamValidation.ts
31292
32896
  init_cjs_shims();
31293
- var import_promises = __toESM(require("fs/promises"), 1);
31294
- var import_node_path = __toESM(require("path"), 1);
32897
+ var import_promises2 = __toESM(require("fs/promises"), 1);
32898
+ var import_node_path4 = __toESM(require("path"), 1);
31295
32899
  var import_node_url = require("url");
31296
32900
  var HTTP_IMAGE_URL_RE = /^https?:\/\/\S+$/i;
31297
32901
  var DATA_IMAGE_RE = /^data:image\/[a-z0-9.+-]+;base64,[a-z0-9+/=\s]+$/i;
@@ -31310,7 +32914,7 @@ function countSeedreamImageReferences(image) {
31310
32914
  return image ? 1 : 0;
31311
32915
  }
31312
32916
  async function resolveSeedreamImageReferences(image, options = {}) {
31313
- const cwd = import_node_path.default.resolve(options.cwd ?? process.cwd());
32917
+ const cwd = import_node_path4.default.resolve(options.cwd ?? process.cwd());
31314
32918
  if (!image) return { image: void 0, error: null };
31315
32919
  const refs = Array.isArray(image) ? image : [image];
31316
32920
  const resolved = [];
@@ -31354,36 +32958,37 @@ async function resolveLocalSeedreamImageReference(value, cwd) {
31354
32958
  error: `Seedream reference image must be a supported image file (jpg, png, webp, gif, or bmp). Unsupported path: "${formatImageReferenceSample(value)}".`
31355
32959
  };
31356
32960
  }
31357
- let stat;
32961
+ let stat2;
31358
32962
  try {
31359
- stat = await import_promises.default.stat(resolvedPath);
31360
- } catch {
32963
+ stat2 = await import_promises2.default.stat(resolvedPath);
32964
+ } catch (error51) {
32965
+ const code = error51 && typeof error51 === "object" && "code" in error51 ? String(error51.code) : "UNKNOWN";
31361
32966
  return {
31362
- error: `Seedream reference image was not found in the agent workspace: "${formatImageReferenceSample(value)}".`
32967
+ error: `Seedream reference image was not found in the agent workspace (${code}): "${formatImageReferenceSample(value)}".`
31363
32968
  };
31364
32969
  }
31365
- if (!stat.isFile()) {
32970
+ if (!stat2.isFile()) {
31366
32971
  return {
31367
32972
  error: `Seedream reference image must point to a file: "${formatImageReferenceSample(value)}".`
31368
32973
  };
31369
32974
  }
31370
- const bytes = await import_promises.default.readFile(resolvedPath);
32975
+ const bytes = await import_promises2.default.readFile(resolvedPath);
31371
32976
  return {
31372
32977
  image: `data:${mimeType};base64,${bytes.toString("base64")}`,
31373
32978
  error: null
31374
32979
  };
31375
32980
  }
31376
32981
  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);
32982
+ if (/^file:/i.test(value)) return import_node_path4.default.resolve((0, import_node_url.fileURLToPath)(value));
32983
+ if (import_node_path4.default.isAbsolute(value)) return import_node_path4.default.resolve(value);
32984
+ return import_node_path4.default.resolve(cwd, value);
31380
32985
  }
31381
32986
  function mimeTypeForImagePath(filePath) {
31382
- return SUPPORTED_IMAGE_MIME_BY_EXT[import_node_path.default.extname(filePath).toLowerCase()] ?? null;
32987
+ return SUPPORTED_IMAGE_MIME_BY_EXT[import_node_path4.default.extname(filePath).toLowerCase()] ?? null;
31383
32988
  }
31384
32989
  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);
32990
+ const relative = import_node_path4.default.relative(import_node_path4.default.resolve(basePath), import_node_path4.default.resolve(filePath));
32991
+ return relative === "" || !relative.startsWith("..") && !import_node_path4.default.isAbsolute(relative);
31387
32992
  }
31388
32993
  function formatImageReferenceSample(value) {
31389
32994
  const trimmed = value.trim();
@@ -31395,6 +33000,7 @@ function formatImageReferenceSample(value) {
31395
33000
  var SERVER_NAME = "ahchat-seedream-mcp";
31396
33001
  var SERVER_VERSION = "0.1.0";
31397
33002
  var DEFAULT_BASE_URL = "https://ark.cn-beijing.volces.com/api/v3";
33003
+ var logger2 = createModuleLogger("seedream.mcpCli");
31398
33004
  var SEEDREAM_MODELS = [
31399
33005
  "doubao-seedream-5-0-lite-260128",
31400
33006
  "doubao-seedream-4-0-250828",
@@ -31709,8 +33315,8 @@ async function saveGeneratedImagesToWorkdir(images) {
31709
33315
  try {
31710
33316
  const downloaded = await downloadGeneratedImage(image.url);
31711
33317
  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" });
33318
+ const filePath = import_node_path5.default.join(process.cwd(), fileName);
33319
+ await import_promises3.default.writeFile(filePath, downloaded.buffer, { flag: "wx" });
31714
33320
  saved.push({
31715
33321
  ...image,
31716
33322
  local_path: filePath,
@@ -31765,14 +33371,10 @@ function imageMimeTypeFromContentType(contentType) {
31765
33371
  return normalizeImageMimeType(contentType.split(";")[0]?.trim() ?? "");
31766
33372
  }
31767
33373
  function imageMimeTypeFromUrl(url2) {
31768
- try {
31769
- return imageMimeTypeFromPath(new URL(url2).pathname);
31770
- } catch {
31771
- return imageMimeTypeFromPath(url2);
31772
- }
33374
+ return imageMimeTypeFromPath(URL.canParse(url2) ? new URL(url2).pathname : url2);
31773
33375
  }
31774
33376
  function imageMimeTypeFromPath(filePath) {
31775
- switch (import_node_path2.default.extname(filePath).toLowerCase()) {
33377
+ switch (import_node_path5.default.extname(filePath).toLowerCase()) {
31776
33378
  case ".bmp":
31777
33379
  return "image/bmp";
31778
33380
  case ".gif":
@@ -31816,8 +33418,11 @@ async function uniqueGeneratedImageFileName(extension, imageIndex) {
31816
33418
  const suffix = attempt === 0 ? "" : `-${attempt + 1}`;
31817
33419
  const fileName = `${baseName}${suffix}${extension}`;
31818
33420
  try {
31819
- await import_promises2.default.access(import_node_path2.default.join(process.cwd(), fileName));
31820
- } catch {
33421
+ await import_promises3.default.access(import_node_path5.default.join(process.cwd(), fileName));
33422
+ } catch (error51) {
33423
+ if (!isFileNotFoundError(error51)) {
33424
+ logger2.error("Seedream generated image filename access check failed", { error: error51 });
33425
+ }
31821
33426
  return fileName;
31822
33427
  }
31823
33428
  }
@@ -31828,7 +33433,12 @@ async function parseJsonSafe(response) {
31828
33433
  if (!text) return void 0;
31829
33434
  try {
31830
33435
  return JSON.parse(text);
31831
- } catch {
33436
+ } catch (error51) {
33437
+ logger2.error("Seedream ARK API returned non-JSON response body", {
33438
+ error: error51,
33439
+ status: response.status,
33440
+ bodyLength: text.length
33441
+ });
31832
33442
  return text;
31833
33443
  }
31834
33444
  }
@@ -31891,14 +33501,15 @@ function errorResult(message) {
31891
33501
  isError: true
31892
33502
  };
31893
33503
  }
33504
+ function isFileNotFoundError(error51) {
33505
+ return Boolean(error51 && typeof error51 === "object" && error51.code === "ENOENT");
33506
+ }
31894
33507
  async function main() {
31895
33508
  const server = createServer();
31896
33509
  const transport = new StdioServerTransport();
31897
33510
  await server.connect(transport);
31898
- console.error(`${SERVER_NAME} v${SERVER_VERSION} running on stdio`);
31899
33511
  }
31900
33512
  main().catch((error51) => {
31901
- const message = error51 instanceof Error ? error51.stack ?? error51.message : String(error51);
31902
- console.error(`Fatal error in ${SERVER_NAME}: ${message}`);
33513
+ logger2.error(`Fatal error in ${SERVER_NAME}`, { error: error51 });
31903
33514
  process.exit(1);
31904
33515
  });