@eko-ai/eko 1.2.0 → 1.2.2

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.
@@ -1,5 +1,633 @@
1
1
  'use strict';
2
2
 
3
+ var os = require('os');
4
+ var path = require('path');
5
+ var util = require('util');
6
+
7
+ const prettyLogStyles = {
8
+ reset: [0, 0],
9
+ bold: [1, 22],
10
+ dim: [2, 22],
11
+ italic: [3, 23],
12
+ underline: [4, 24],
13
+ overline: [53, 55],
14
+ inverse: [7, 27],
15
+ hidden: [8, 28],
16
+ strikethrough: [9, 29],
17
+ black: [30, 39],
18
+ red: [31, 39],
19
+ green: [32, 39],
20
+ yellow: [33, 39],
21
+ blue: [34, 39],
22
+ magenta: [35, 39],
23
+ cyan: [36, 39],
24
+ white: [37, 39],
25
+ blackBright: [90, 39],
26
+ redBright: [91, 39],
27
+ greenBright: [92, 39],
28
+ yellowBright: [93, 39],
29
+ blueBright: [94, 39],
30
+ magentaBright: [95, 39],
31
+ cyanBright: [96, 39],
32
+ whiteBright: [97, 39],
33
+ bgBlack: [40, 49],
34
+ bgRed: [41, 49],
35
+ bgGreen: [42, 49],
36
+ bgYellow: [43, 49],
37
+ bgBlue: [44, 49],
38
+ bgMagenta: [45, 49],
39
+ bgCyan: [46, 49],
40
+ bgWhite: [47, 49],
41
+ bgBlackBright: [100, 49],
42
+ bgRedBright: [101, 49],
43
+ bgGreenBright: [102, 49],
44
+ bgYellowBright: [103, 49],
45
+ bgBlueBright: [104, 49],
46
+ bgMagentaBright: [105, 49],
47
+ bgCyanBright: [106, 49],
48
+ bgWhiteBright: [107, 49],
49
+ };
50
+
51
+ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
52
+ const templateString = String(template);
53
+ const ansiColorWrap = (placeholderValue, code) => `\u001b[${code[0]}m${placeholderValue}\u001b[${code[1]}m`;
54
+ const styleWrap = (value, style) => {
55
+ if (style != null && typeof style === "string") {
56
+ return ansiColorWrap(value, prettyLogStyles[style]);
57
+ }
58
+ else if (style != null && Array.isArray(style)) {
59
+ return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
60
+ }
61
+ else {
62
+ if (style != null && style[value.trim()] != null) {
63
+ return styleWrap(value, style[value.trim()]);
64
+ }
65
+ else if (style != null && style["*"] != null) {
66
+ return styleWrap(value, style["*"]);
67
+ }
68
+ else {
69
+ return value;
70
+ }
71
+ }
72
+ };
73
+ const defaultStyle = null;
74
+ return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
75
+ const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
76
+ return settings.stylePrettyLogs
77
+ ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset)
78
+ : value;
79
+ });
80
+ }
81
+
82
+ function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
83
+ if (value != null && isNaN(value)) {
84
+ return "";
85
+ }
86
+ value = value != null ? value + addNumber : value;
87
+ return digits === 2
88
+ ? value == null
89
+ ? "--"
90
+ : value < 10
91
+ ? "0" + value
92
+ : value.toString()
93
+ : value == null
94
+ ? "---"
95
+ : value < 10
96
+ ? "00" + value
97
+ : value < 100
98
+ ? "0" + value
99
+ : value.toString();
100
+ }
101
+
102
+ function urlToObject(url) {
103
+ return {
104
+ href: url.href,
105
+ protocol: url.protocol,
106
+ username: url.username,
107
+ password: url.password,
108
+ host: url.host,
109
+ hostname: url.hostname,
110
+ port: url.port,
111
+ pathname: url.pathname,
112
+ search: url.search,
113
+ searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
114
+ hash: url.hash,
115
+ origin: url.origin,
116
+ };
117
+ }
118
+
119
+ var Runtime = {
120
+ getCallerStackFrame,
121
+ getErrorTrace,
122
+ getMeta,
123
+ transportJSON,
124
+ transportFormatted: transportFormatted$1,
125
+ isBuffer,
126
+ isError,
127
+ prettyFormatLogObj,
128
+ prettyFormatErrorObj,
129
+ };
130
+ const meta = {
131
+ runtime: "Nodejs",
132
+ runtimeVersion: process?.version,
133
+ hostname: os.hostname ? os.hostname() : undefined,
134
+ };
135
+ function getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
136
+ return Object.assign({}, meta, {
137
+ name,
138
+ parentNames,
139
+ date: new Date(),
140
+ logLevelId,
141
+ logLevelName,
142
+ path: !hideLogPositionForPerformance ? getCallerStackFrame(stackDepthLevel) : undefined,
143
+ });
144
+ }
145
+ function getCallerStackFrame(stackDepthLevel, error = Error()) {
146
+ return stackLineToStackFrame(error?.stack?.split("\n")?.filter((thisLine) => thisLine.includes(" at "))?.[stackDepthLevel]);
147
+ }
148
+ function getErrorTrace(error) {
149
+ return error?.stack?.split("\n")?.reduce((result, line) => {
150
+ if (line.includes(" at ")) {
151
+ result.push(stackLineToStackFrame(line));
152
+ }
153
+ return result;
154
+ }, []);
155
+ }
156
+ function stackLineToStackFrame(line) {
157
+ const pathResult = {
158
+ fullFilePath: undefined,
159
+ fileName: undefined,
160
+ fileNameWithLine: undefined,
161
+ fileColumn: undefined,
162
+ fileLine: undefined,
163
+ filePath: undefined,
164
+ filePathWithLine: undefined,
165
+ method: undefined,
166
+ };
167
+ if (line != null && line.includes(" at ")) {
168
+ line = line.replace(/^\s+at\s+/gm, "");
169
+ const errorStackLine = line.split(" (");
170
+ const fullFilePath = line?.slice(-1) === ")" ? line?.match(/\(([^)]+)\)/)?.[1] : line;
171
+ const pathArray = fullFilePath?.includes(":") ? fullFilePath?.replace("file://", "")?.replace(process.cwd(), "")?.split(":") : undefined;
172
+ const fileColumn = pathArray?.pop();
173
+ const fileLine = pathArray?.pop();
174
+ const filePath = pathArray?.pop();
175
+ const filePathWithLine = path.normalize(`${filePath}:${fileLine}`);
176
+ const fileName = filePath?.split("/")?.pop();
177
+ const fileNameWithLine = `${fileName}:${fileLine}`;
178
+ if (filePath != null && filePath.length > 0) {
179
+ pathResult.fullFilePath = fullFilePath;
180
+ pathResult.fileName = fileName;
181
+ pathResult.fileNameWithLine = fileNameWithLine;
182
+ pathResult.fileColumn = fileColumn;
183
+ pathResult.fileLine = fileLine;
184
+ pathResult.filePath = filePath;
185
+ pathResult.filePathWithLine = filePathWithLine;
186
+ pathResult.method = errorStackLine?.[1] != null ? errorStackLine?.[0] : undefined;
187
+ }
188
+ }
189
+ return pathResult;
190
+ }
191
+ function isError(e) {
192
+ return util.types?.isNativeError != null ? util.types.isNativeError(e) : e instanceof Error;
193
+ }
194
+ function prettyFormatLogObj(maskedArgs, settings) {
195
+ return maskedArgs.reduce((result, arg) => {
196
+ isError(arg) ? result.errors.push(prettyFormatErrorObj(arg, settings)) : result.args.push(arg);
197
+ return result;
198
+ }, { args: [], errors: [] });
199
+ }
200
+ function prettyFormatErrorObj(error, settings) {
201
+ const errorStackStr = getErrorTrace(error).map((stackFrame) => {
202
+ return formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true);
203
+ });
204
+ const placeholderValuesError = {
205
+ errorName: ` ${error.name} `,
206
+ errorMessage: Object.getOwnPropertyNames(error)
207
+ .reduce((result, key) => {
208
+ if (key !== "stack") {
209
+ result.push(error[key]);
210
+ }
211
+ return result;
212
+ }, [])
213
+ .join(", "),
214
+ errorStack: errorStackStr.join("\n"),
215
+ };
216
+ return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
217
+ }
218
+ function transportFormatted$1(logMetaMarkup, logArgs, logErrors, settings) {
219
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
220
+ settings.prettyInspectOptions.colors = settings.stylePrettyLogs;
221
+ console.log(logMetaMarkup + util.formatWithOptions(settings.prettyInspectOptions, ...logArgs) + logErrorsStr);
222
+ }
223
+ function transportJSON(json) {
224
+ console.log(jsonStringifyRecursive(json));
225
+ function jsonStringifyRecursive(obj) {
226
+ const cache = new Set();
227
+ return JSON.stringify(obj, (key, value) => {
228
+ if (typeof value === "object" && value !== null) {
229
+ if (cache.has(value)) {
230
+ return "[Circular]";
231
+ }
232
+ cache.add(value);
233
+ }
234
+ if (typeof value === "bigint") {
235
+ return `${value}`;
236
+ }
237
+ if (typeof value === "undefined") {
238
+ return "[undefined]";
239
+ }
240
+ return value;
241
+ });
242
+ }
243
+ }
244
+ function isBuffer(arg) {
245
+ return Buffer.isBuffer(arg);
246
+ }
247
+
248
+ class BaseLogger {
249
+ constructor(settings, logObj, stackDepthLevel = 4) {
250
+ this.logObj = logObj;
251
+ this.stackDepthLevel = stackDepthLevel;
252
+ this.runtime = Runtime;
253
+ this.settings = {
254
+ type: settings?.type ?? "pretty",
255
+ name: settings?.name,
256
+ parentNames: settings?.parentNames,
257
+ minLevel: settings?.minLevel ?? 0,
258
+ argumentsArrayName: settings?.argumentsArrayName,
259
+ hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
260
+ prettyLogTemplate: settings?.prettyLogTemplate ??
261
+ "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t",
262
+ prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
263
+ prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
264
+ prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
265
+ prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? "\t",
266
+ stylePrettyLogs: settings?.stylePrettyLogs ?? true,
267
+ prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
268
+ prettyLogStyles: settings?.prettyLogStyles ?? {
269
+ logLevelName: {
270
+ "*": ["bold", "black", "bgWhiteBright", "dim"],
271
+ SILLY: ["bold", "white"],
272
+ TRACE: ["bold", "whiteBright"],
273
+ DEBUG: ["bold", "green"],
274
+ INFO: ["bold", "blue"],
275
+ WARN: ["bold", "yellow"],
276
+ ERROR: ["bold", "red"],
277
+ FATAL: ["bold", "redBright"],
278
+ },
279
+ dateIsoStr: "white",
280
+ filePathWithLine: "white",
281
+ name: ["white", "bold"],
282
+ nameWithDelimiterPrefix: ["white", "bold"],
283
+ nameWithDelimiterSuffix: ["white", "bold"],
284
+ errorName: ["bold", "bgRedBright", "whiteBright"],
285
+ fileName: ["yellow"],
286
+ fileNameWithLine: "white",
287
+ },
288
+ prettyInspectOptions: settings?.prettyInspectOptions ?? {
289
+ colors: true,
290
+ compact: false,
291
+ depth: Infinity,
292
+ },
293
+ metaProperty: settings?.metaProperty ?? "_meta",
294
+ maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
295
+ maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
296
+ maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
297
+ maskValuesRegEx: settings?.maskValuesRegEx,
298
+ prefix: [...(settings?.prefix ?? [])],
299
+ attachedTransports: [...(settings?.attachedTransports ?? [])],
300
+ overwrite: {
301
+ mask: settings?.overwrite?.mask,
302
+ toLogObj: settings?.overwrite?.toLogObj,
303
+ addMeta: settings?.overwrite?.addMeta,
304
+ addPlaceholders: settings?.overwrite?.addPlaceholders,
305
+ formatMeta: settings?.overwrite?.formatMeta,
306
+ formatLogObj: settings?.overwrite?.formatLogObj,
307
+ transportFormatted: settings?.overwrite?.transportFormatted,
308
+ transportJSON: settings?.overwrite?.transportJSON,
309
+ },
310
+ };
311
+ }
312
+ log(logLevelId, logLevelName, ...args) {
313
+ if (logLevelId < this.settings.minLevel) {
314
+ return;
315
+ }
316
+ const logArgs = [...this.settings.prefix, ...args];
317
+ const maskedArgs = this.settings.overwrite?.mask != null
318
+ ? this.settings.overwrite?.mask(logArgs)
319
+ : this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0
320
+ ? this._mask(logArgs)
321
+ : logArgs;
322
+ const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : undefined;
323
+ const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
324
+ const logObjWithMeta = this.settings.overwrite?.addMeta != null
325
+ ? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName)
326
+ : this._addMetaToLogObj(logObj, logLevelId, logLevelName);
327
+ let logMetaMarkup;
328
+ let logArgsAndErrorsMarkup = undefined;
329
+ if (this.settings.overwrite?.formatMeta != null) {
330
+ logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
331
+ }
332
+ if (this.settings.overwrite?.formatLogObj != null) {
333
+ logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
334
+ }
335
+ if (this.settings.type === "pretty") {
336
+ logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
337
+ logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? this.runtime.prettyFormatLogObj(maskedArgs, this.settings);
338
+ }
339
+ if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
340
+ this.settings.overwrite?.transportFormatted != null
341
+ ? this.settings.overwrite?.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings)
342
+ : this.runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings);
343
+ }
344
+ else {
345
+ this.settings.overwrite?.transportJSON != null
346
+ ? this.settings.overwrite?.transportJSON(logObjWithMeta)
347
+ : this.settings.type !== "hidden"
348
+ ? this.runtime.transportJSON(logObjWithMeta)
349
+ : undefined;
350
+ }
351
+ if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
352
+ this.settings.attachedTransports.forEach((transportLogger) => {
353
+ transportLogger(logObjWithMeta);
354
+ });
355
+ }
356
+ return logObjWithMeta;
357
+ }
358
+ attachTransport(transportLogger) {
359
+ this.settings.attachedTransports.push(transportLogger);
360
+ }
361
+ getSubLogger(settings, logObj) {
362
+ const subLoggerSettings = {
363
+ ...this.settings,
364
+ ...settings,
365
+ parentNames: this.settings?.parentNames != null && this.settings?.name != null
366
+ ? [...this.settings.parentNames, this.settings.name]
367
+ : this.settings?.name != null
368
+ ? [this.settings.name]
369
+ : undefined,
370
+ prefix: [...this.settings.prefix, ...(settings?.prefix ?? [])],
371
+ };
372
+ const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
373
+ return subLogger;
374
+ }
375
+ _mask(args) {
376
+ const maskValuesOfKeys = this.settings.maskValuesOfKeysCaseInsensitive !== true ? this.settings.maskValuesOfKeys : this.settings.maskValuesOfKeys.map((key) => key.toLowerCase());
377
+ return args?.map((arg) => {
378
+ return this._recursiveCloneAndMaskValuesOfKeys(arg, maskValuesOfKeys);
379
+ });
380
+ }
381
+ _recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
382
+ if (seen.includes(source)) {
383
+ return { ...source };
384
+ }
385
+ if (typeof source === "object" && source !== null) {
386
+ seen.push(source);
387
+ }
388
+ if (this.runtime.isError(source) || this.runtime.isBuffer(source)) {
389
+ return source;
390
+ }
391
+ else if (source instanceof Map) {
392
+ return new Map(source);
393
+ }
394
+ else if (source instanceof Set) {
395
+ return new Set(source);
396
+ }
397
+ else if (Array.isArray(source)) {
398
+ return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
399
+ }
400
+ else if (source instanceof Date) {
401
+ return new Date(source.getTime());
402
+ }
403
+ else if (source instanceof URL) {
404
+ return urlToObject(source);
405
+ }
406
+ else if (source !== null && typeof source === "object") {
407
+ const baseObject = this.runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
408
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
409
+ o[prop] = keys.includes(this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : prop.toLowerCase())
410
+ ? this.settings.maskPlaceholder
411
+ : (() => {
412
+ try {
413
+ return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
414
+ }
415
+ catch (e) {
416
+ return null;
417
+ }
418
+ })();
419
+ return o;
420
+ }, baseObject);
421
+ }
422
+ else {
423
+ if (typeof source === "string") {
424
+ let modifiedSource = source;
425
+ for (const regEx of this.settings?.maskValuesRegEx || []) {
426
+ modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
427
+ }
428
+ return modifiedSource;
429
+ }
430
+ return source;
431
+ }
432
+ }
433
+ _recursiveCloneAndExecuteFunctions(source, seen = []) {
434
+ if (this.isObjectOrArray(source) && seen.includes(source)) {
435
+ return this.shallowCopy(source);
436
+ }
437
+ if (this.isObjectOrArray(source)) {
438
+ seen.push(source);
439
+ }
440
+ if (Array.isArray(source)) {
441
+ return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
442
+ }
443
+ else if (source instanceof Date) {
444
+ return new Date(source.getTime());
445
+ }
446
+ else if (this.isObject(source)) {
447
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
448
+ const descriptor = Object.getOwnPropertyDescriptor(source, prop);
449
+ if (descriptor) {
450
+ Object.defineProperty(o, prop, descriptor);
451
+ const value = source[prop];
452
+ o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
453
+ }
454
+ return o;
455
+ }, Object.create(Object.getPrototypeOf(source)));
456
+ }
457
+ else {
458
+ return source;
459
+ }
460
+ }
461
+ isObjectOrArray(value) {
462
+ return typeof value === "object" && value !== null;
463
+ }
464
+ isObject(value) {
465
+ return typeof value === "object" && !Array.isArray(value) && value !== null;
466
+ }
467
+ shallowCopy(source) {
468
+ if (Array.isArray(source)) {
469
+ return [...source];
470
+ }
471
+ else {
472
+ return { ...source };
473
+ }
474
+ }
475
+ _toLogObj(args, clonedLogObj = {}) {
476
+ args = args?.map((arg) => (this.runtime.isError(arg) ? this._toErrorObject(arg) : arg));
477
+ if (this.settings.argumentsArrayName == null) {
478
+ if (args.length === 1 && !Array.isArray(args[0]) && this.runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
479
+ clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
480
+ }
481
+ else {
482
+ clonedLogObj = { ...clonedLogObj, ...args };
483
+ }
484
+ }
485
+ else {
486
+ clonedLogObj = {
487
+ ...clonedLogObj,
488
+ [this.settings.argumentsArrayName]: args,
489
+ };
490
+ }
491
+ return clonedLogObj;
492
+ }
493
+ _cloneError(error) {
494
+ const cloned = new error.constructor();
495
+ Object.getOwnPropertyNames(error).forEach((key) => {
496
+ cloned[key] = error[key];
497
+ });
498
+ return cloned;
499
+ }
500
+ _toErrorObject(error) {
501
+ return {
502
+ nativeError: error,
503
+ name: error.name ?? "Error",
504
+ message: error.message,
505
+ stack: this.runtime.getErrorTrace(error),
506
+ };
507
+ }
508
+ _addMetaToLogObj(logObj, logLevelId, logLevelName) {
509
+ return {
510
+ ...logObj,
511
+ [this.settings.metaProperty]: this.runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, this.settings.hideLogPositionForProduction, this.settings.name, this.settings.parentNames),
512
+ };
513
+ }
514
+ _prettyFormatLogObjMeta(logObjMeta) {
515
+ if (logObjMeta == null) {
516
+ return "";
517
+ }
518
+ let template = this.settings.prettyLogTemplate;
519
+ const placeholderValues = {};
520
+ if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
521
+ template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
522
+ }
523
+ else {
524
+ if (this.settings.prettyLogTimeZone === "UTC") {
525
+ placeholderValues["yyyy"] = logObjMeta?.date?.getUTCFullYear() ?? "----";
526
+ placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMonth(), 2, 1);
527
+ placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getUTCDate(), 2);
528
+ placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getUTCHours(), 2);
529
+ placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMinutes(), 2);
530
+ placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getUTCSeconds(), 2);
531
+ placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMilliseconds(), 3);
532
+ }
533
+ else {
534
+ placeholderValues["yyyy"] = logObjMeta?.date?.getFullYear() ?? "----";
535
+ placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getMonth(), 2, 1);
536
+ placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getDate(), 2);
537
+ placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getHours(), 2);
538
+ placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getMinutes(), 2);
539
+ placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getSeconds(), 2);
540
+ placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getMilliseconds(), 3);
541
+ }
542
+ }
543
+ const dateInSettingsTimeZone = this.settings.prettyLogTimeZone === "UTC" ? logObjMeta?.date : new Date(logObjMeta?.date?.getTime() - logObjMeta?.date?.getTimezoneOffset() * 60000);
544
+ placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString();
545
+ placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "");
546
+ placeholderValues["logLevelName"] = logObjMeta?.logLevelName;
547
+ placeholderValues["fileNameWithLine"] = logObjMeta?.path?.fileNameWithLine ?? "";
548
+ placeholderValues["filePathWithLine"] = logObjMeta?.path?.filePathWithLine ?? "";
549
+ placeholderValues["fullFilePath"] = logObjMeta?.path?.fullFilePath ?? "";
550
+ let parentNamesString = this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);
551
+ parentNamesString = parentNamesString != null && logObjMeta?.name != null ? parentNamesString + this.settings.prettyErrorParentNamesSeparator : undefined;
552
+ placeholderValues["name"] = logObjMeta?.name != null || parentNamesString != null ? (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
553
+ placeholderValues["nameWithDelimiterPrefix"] =
554
+ placeholderValues["name"].length > 0 ? this.settings.prettyErrorLoggerNameDelimiter + placeholderValues["name"] : "";
555
+ placeholderValues["nameWithDelimiterSuffix"] =
556
+ placeholderValues["name"].length > 0 ? placeholderValues["name"] + this.settings.prettyErrorLoggerNameDelimiter : "";
557
+ if (this.settings.overwrite?.addPlaceholders != null) {
558
+ this.settings.overwrite?.addPlaceholders(logObjMeta, placeholderValues);
559
+ }
560
+ return formatTemplate(this.settings, template, placeholderValues);
561
+ }
562
+ }
563
+
564
+ class Logger extends BaseLogger {
565
+ constructor(settings, logObj) {
566
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
567
+ const isBrowserBlinkEngine = isBrowser ? window.chrome !== undefined && window.CSS !== undefined && window.CSS.supports("color", "green") : false;
568
+ const isSafari = isBrowser ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
569
+ settings = settings || {};
570
+ settings.stylePrettyLogs = settings.stylePrettyLogs && isBrowser && !isBrowserBlinkEngine ? false : settings.stylePrettyLogs;
571
+ super(settings, logObj, isSafari ? 4 : 5);
572
+ }
573
+ log(logLevelId, logLevelName, ...args) {
574
+ return super.log(logLevelId, logLevelName, ...args);
575
+ }
576
+ silly(...args) {
577
+ return super.log(0, "SILLY", ...args);
578
+ }
579
+ trace(...args) {
580
+ return super.log(1, "TRACE", ...args);
581
+ }
582
+ debug(...args) {
583
+ return super.log(2, "DEBUG", ...args);
584
+ }
585
+ info(...args) {
586
+ return super.log(3, "INFO", ...args);
587
+ }
588
+ warn(...args) {
589
+ return super.log(4, "WARN", ...args);
590
+ }
591
+ error(...args) {
592
+ return super.log(5, "ERROR", ...args);
593
+ }
594
+ fatal(...args) {
595
+ return super.log(6, "FATAL", ...args);
596
+ }
597
+ getSubLogger(settings, logObj) {
598
+ return super.getSubLogger(settings, logObj);
599
+ }
600
+ }
601
+
602
+ function transportFormatted(logMetaMarkup, logArgs, logErrors, settings) {
603
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
604
+ settings.prettyInspectOptions.colors = settings.stylePrettyLogs;
605
+ console.log(logMetaMarkup, ...logArgs, logErrorsStr);
606
+ }
607
+ function formatMeta(logObjMeta) {
608
+ if (!logObjMeta) {
609
+ return '';
610
+ }
611
+ const { date, logLevelName } = logObjMeta;
612
+ const year = date.getFullYear();
613
+ const month = String(date.getMonth() + 1).padStart(2, '0');
614
+ const day = String(date.getDate()).padStart(2, '0');
615
+ const hours = String(date.getHours()).padStart(2, '0');
616
+ const minutes = String(date.getMinutes()).padStart(2, '0');
617
+ const seconds = String(date.getSeconds()).padStart(2, '0');
618
+ const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
619
+ const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
620
+ const loggerName = logObjMeta.name;
621
+ return `${formattedDate} ${logLevelName} ${loggerName}`;
622
+ }
623
+ const logger = new Logger({
624
+ name: "ekoLogger",
625
+ overwrite: {
626
+ transportFormatted,
627
+ formatMeta,
628
+ }
629
+ });
630
+
3
631
  async function getWindowId(context) {
4
632
  let windowId = context.variables.get('windowId');
5
633
  if (windowId) {
@@ -30,11 +658,12 @@ async function getWindowId(context) {
30
658
  windowId = window.FELLOU_WINDOW_ID;
31
659
  }
32
660
  if (!windowId) {
33
- console.warn("`getWindowId()` returns " + windowId);
661
+ logger.warn("`getWindowId()` returns " + windowId);
34
662
  }
35
663
  return windowId;
36
664
  }
37
665
  async function getTabId(context) {
666
+ logger.debug("debug the getTabId()...");
38
667
  let tabId = context.variables.get('tabId');
39
668
  if (tabId) {
40
669
  try {
@@ -46,56 +675,58 @@ async function getTabId(context) {
46
675
  }
47
676
  }
48
677
  if (!tabId) {
49
- console.log("tabId is empty");
678
+ logger.debug("tabId is empty");
50
679
  let windowId = await getWindowId(context);
51
- console.log(`windowId=${windowId}`);
680
+ logger.debug(`windowId=${windowId}`);
52
681
  if (windowId) {
53
682
  try {
54
683
  tabId = await getCurrentTabId(context.ekoConfig.chromeProxy, windowId);
55
- console.log("getCurrentTabId(context.ekoConfig.chromeProxy, windowId) returns " + tabId);
684
+ logger.debug("getCurrentTabId(context.ekoConfig.chromeProxy, windowId) returns " + tabId);
56
685
  }
57
686
  catch (e) {
58
687
  tabId = await getCurrentTabId(context.ekoConfig.chromeProxy);
59
- console.log("getCurrentTabId(context.ekoConfig.chromeProxy, windowId) throws an error");
60
- console.log("getCurrentTabId(context.ekoConfig.chromeProxy) returns " + tabId);
688
+ logger.debug("getCurrentTabId(context.ekoConfig.chromeProxy, windowId) throws an error");
689
+ logger.debug("getCurrentTabId(context.ekoConfig.chromeProxy) returns " + tabId);
61
690
  context.variables.delete('windowId');
62
691
  }
63
692
  }
64
693
  else {
65
694
  tabId = await getCurrentTabId(context.ekoConfig.chromeProxy);
66
- console.log("getCurrentTabId(context.ekoConfig.chromeProxy) #2 returns " + tabId);
695
+ logger.debug("getCurrentTabId(context.ekoConfig.chromeProxy) #2 returns " + tabId);
67
696
  }
68
697
  if (!tabId) {
69
698
  throw new Error('Could not find a valid tab');
70
699
  }
71
700
  context.variables.set('tabId', tabId);
72
701
  }
702
+ logger.debug(`debug the getTabId()...returns ${tabId}`);
73
703
  return tabId;
74
704
  }
75
705
  function getCurrentTabId(chromeProxy, windowId) {
76
706
  return new Promise((resolve, reject) => {
77
- console.debug("[getCurrentTabId] get the active tabId on: ", { windowId });
707
+ logger.debug("debug the Promise in getCurrentTabId()...");
708
+ logger.debug("get the active tabId on: ", { windowId });
78
709
  let queryInfo;
79
710
  if (windowId !== undefined) {
80
- console.debug(`[getCurrentTabId] get the active tab in window (windowId=${windowId})...`);
711
+ logger.debug(`get the active tab in window (windowId=${windowId})...`);
81
712
  queryInfo = { windowId, active: true };
82
713
  }
83
714
  else {
84
- console.debug(`[getCurrentTabId] get the active tabId on current window`);
715
+ logger.debug(`get the active tabId on current window`);
85
716
  queryInfo = { active: true, currentWindow: true };
86
717
  }
87
718
  chrome.tabs.query(queryInfo, (tabs) => {
88
719
  if (chromeProxy.runtime.lastError) {
89
- console.error(`[getCurrentTabId] failed to get: `, chromeProxy.runtime.lastError);
720
+ logger.error(`failed to get: `, chromeProxy.runtime.lastError);
90
721
  reject(chromeProxy.runtime.lastError);
91
722
  return;
92
723
  }
93
724
  if (tabs.length > 0) {
94
- console.debug(`[getCurrentTabId] found the tab, ID=${tabs[0].id}`);
725
+ logger.debug(`found the tab, ID=${tabs[0].id}`);
95
726
  resolve(tabs[0].id);
96
727
  }
97
728
  else {
98
- console.debug(`[getCurrentTabId] cannot find the tab, returns undefined`);
729
+ logger.debug(`cannot find the tab, returns undefined`);
99
730
  resolve(undefined);
100
731
  }
101
732
  });
@@ -106,17 +737,17 @@ async function open_new_tab(chromeProxy, url, windowId) {
106
737
  const window = await chromeProxy.windows.getCurrent();
107
738
  windowId = window.id;
108
739
  }
109
- console.log("windowId: " + windowId);
740
+ logger.debug("windowId: " + windowId);
110
741
  let tab = await chromeProxy.tabs.create({
111
742
  url: url,
112
743
  windowId: windowId,
113
744
  });
114
- console.log("chromeProxy.tabs.create() done");
745
+ logger.debug("chromeProxy.tabs.create() done");
115
746
  let tabId = tab.id;
116
747
  let completedTab = await waitForTabComplete(chromeProxy, tabId);
117
- console.log("waitForTabComplete() done");
748
+ logger.debug("waitForTabComplete() done");
118
749
  await sleep(200);
119
- console.log("sleep() done");
750
+ logger.debug("sleep() done");
120
751
  return completedTab;
121
752
  }
122
753
  async function executeScript(chromeProxy, tabId, func, args) {
@@ -129,41 +760,43 @@ async function executeScript(chromeProxy, tabId, func, args) {
129
760
  }
130
761
  async function waitForTabComplete(chromeProxy, tabId, timeout = 30000) {
131
762
  return new Promise(async (resolve, reject) => {
763
+ logger.debug("debug waitForTabComplete()...");
132
764
  const time = setTimeout(async () => {
133
- console.log("listener(#1)=", listener);
765
+ logger.debug("listener(#1)=", listener);
134
766
  chromeProxy.tabs.onUpdated.removeListener(listener);
135
- console.log("tabId(#1)=", tabId);
767
+ logger.debug("tabId(#1)=", tabId);
136
768
  let tab = await chromeProxy.tabs.get(tabId);
137
- console.log("tab(#1)=", tab);
769
+ logger.debug("tab(#1)=", tab);
138
770
  if (tab.status === 'complete') {
139
- console.warn('Timeout: waitForTabComplete, but tab is already complete.');
771
+ logger.warn('Timeout: waitForTabComplete, but tab is already complete.');
140
772
  resolve(tab);
141
773
  }
142
774
  else {
143
- console.warn("Timeout: waitForTabComplete, and tab is not complete");
775
+ logger.warn("Timeout: waitForTabComplete, and tab is not complete");
144
776
  resolve(tab);
145
777
  }
146
778
  }, timeout);
147
- console.log("setTimeout done");
779
+ logger.debug("setTimeout done");
148
780
  const listener = async (updatedTabId, changeInfo, tab) => {
149
- console.log("listener start...");
781
+ logger.debug("listener start...");
150
782
  if (updatedTabId === tabId && changeInfo.status === 'complete') {
151
- console.log("listener(#2)=", listener);
783
+ logger.debug("listener(#2)=", listener);
152
784
  chromeProxy.tabs.onUpdated.removeListener(listener);
153
785
  clearTimeout(time);
154
786
  resolve(tab);
155
787
  }
156
788
  };
157
- console.log("tabId(#2)=", tabId);
789
+ logger.debug("tabId(#2)=", tabId);
158
790
  let tab = await chromeProxy.tabs.get(tabId);
159
- console.log("tab(#2)=", tab);
791
+ logger.debug("tab(#2)=", tab);
160
792
  if (tab.status === 'complete') {
161
793
  resolve(tab);
162
794
  clearTimeout(time);
163
795
  return;
164
796
  }
165
- console.log("listener(#3)=", listener);
797
+ logger.debug("listener(#3)=", listener);
166
798
  chromeProxy.tabs.onUpdated.addListener(listener);
799
+ logger.debug("debug waitForTabComplete()...done");
167
800
  });
168
801
  }
169
802
  async function doesTabExists(chromeProxy, tabId) {
@@ -229,7 +862,7 @@ class MsgEvent {
229
862
  }
230
863
  }
231
864
  catch (e) {
232
- console.error(e);
865
+ logger.error(e);
233
866
  }
234
867
  }
235
868
  }
@@ -291,12 +924,12 @@ var utils = /*#__PURE__*/Object.freeze({
291
924
 
292
925
  function isFellouBrowser(chromeProxy) {
293
926
  const result = typeof chromeProxy.browseruse == 'object';
294
- console.log("isFellouBrowser", result);
927
+ logger.debug("isFellouBrowser", result);
295
928
  return result;
296
929
  }
297
930
  async function type(chromeProxy, tabId, text, coordinate) {
298
931
  const isFellou = isFellouBrowser(chromeProxy);
299
- console.log('Sending type message to tab:', tabId, { text, coordinate }, isFellou ? ' > fellou' : '');
932
+ logger.debug('Sending type message to tab:', tabId, { text, coordinate }, isFellou ? ' > fellou' : '');
300
933
  try {
301
934
  if (!coordinate) {
302
935
  coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
@@ -321,17 +954,17 @@ async function type(chromeProxy, tabId, text, coordinate) {
321
954
  coordinate,
322
955
  });
323
956
  }
324
- console.log('type Got response:', response);
957
+ logger.debug('type Got response:', response);
325
958
  return response;
326
959
  }
327
960
  catch (e) {
328
- console.error('Failed to send type message:', e);
961
+ logger.error('Failed to send type message:', e);
329
962
  throw e;
330
963
  }
331
964
  }
332
965
  async function type_by(chromeProxy, tabId, text, xpath, highlightIndex) {
333
966
  const isFellou = isFellouBrowser(chromeProxy);
334
- console.log('Sending type_by message to tab:', tabId, { text, xpath, highlightIndex }, isFellou ? ' > fellou' : '');
967
+ logger.debug('Sending type_by message to tab:', tabId, { text, xpath, highlightIndex }, isFellou ? ' > fellou' : '');
335
968
  try {
336
969
  let response;
337
970
  if (isFellou) {
@@ -353,17 +986,17 @@ async function type_by(chromeProxy, tabId, text, xpath, highlightIndex) {
353
986
  highlightIndex,
354
987
  });
355
988
  }
356
- console.log('type_by Got response:', response);
989
+ logger.debug('type_by Got response:', response);
357
990
  return response;
358
991
  }
359
992
  catch (e) {
360
- console.error('Failed to send type message:', e);
993
+ logger.error('Failed to send type message:', e);
361
994
  throw e;
362
995
  }
363
996
  }
364
997
  async function enter_by(chromeProxy, tabId, xpath, highlightIndex) {
365
998
  const isFellou = isFellouBrowser(chromeProxy);
366
- console.log('Sending enter_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
999
+ logger.debug('Sending enter_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
367
1000
  try {
368
1001
  let response;
369
1002
  if (isFellou) {
@@ -377,17 +1010,17 @@ async function enter_by(chromeProxy, tabId, xpath, highlightIndex) {
377
1010
  highlightIndex,
378
1011
  });
379
1012
  }
380
- console.log('enter_by Got response:', response);
1013
+ logger.debug('enter_by Got response:', response);
381
1014
  return response;
382
1015
  }
383
1016
  catch (e) {
384
- console.error('Failed to send enter_by message:', e);
1017
+ logger.error('Failed to send enter_by message:', e);
385
1018
  throw e;
386
1019
  }
387
1020
  }
388
1021
  async function clear_input(chromeProxy, tabId, coordinate) {
389
1022
  const isFellou = isFellouBrowser(chromeProxy);
390
- console.log('Sending clear_input message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
1023
+ logger.debug('Sending clear_input message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
391
1024
  try {
392
1025
  if (!coordinate) {
393
1026
  coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
@@ -405,17 +1038,17 @@ async function clear_input(chromeProxy, tabId, coordinate) {
405
1038
  coordinate,
406
1039
  });
407
1040
  }
408
- console.log('clear_input Got response:', response);
1041
+ logger.debug('clear_input Got response:', response);
409
1042
  return response;
410
1043
  }
411
1044
  catch (e) {
412
- console.error('Failed to send clear_input message:', e);
1045
+ logger.error('Failed to send clear_input message:', e);
413
1046
  throw e;
414
1047
  }
415
1048
  }
416
1049
  async function clear_input_by(chromeProxy, tabId, xpath, highlightIndex) {
417
1050
  const isFellou = isFellouBrowser(chromeProxy);
418
- console.log('Sending clear_input_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
1051
+ logger.debug('Sending clear_input_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
419
1052
  try {
420
1053
  let response;
421
1054
  if (isFellou) {
@@ -430,17 +1063,17 @@ async function clear_input_by(chromeProxy, tabId, xpath, highlightIndex) {
430
1063
  highlightIndex,
431
1064
  });
432
1065
  }
433
- console.log('clear_input_by Got response:', response);
1066
+ logger.debug('clear_input_by Got response:', response);
434
1067
  return response;
435
1068
  }
436
1069
  catch (e) {
437
- console.error('Failed to send clear_input_by message:', e);
1070
+ logger.error('Failed to send clear_input_by message:', e);
438
1071
  throw e;
439
1072
  }
440
1073
  }
441
1074
  async function mouse_move(chromeProxy, tabId, coordinate) {
442
1075
  const isFellou = isFellouBrowser(chromeProxy);
443
- console.log('Sending mouse_move message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
1076
+ logger.debug('Sending mouse_move message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
444
1077
  let response;
445
1078
  if (isFellou) {
446
1079
  response = await chromeProxy.browseruse.mouse.move(tabId, coordinate[0], coordinate[1]);
@@ -451,12 +1084,12 @@ async function mouse_move(chromeProxy, tabId, coordinate) {
451
1084
  coordinate,
452
1085
  });
453
1086
  }
454
- console.log('mouse_move Got response:', response);
1087
+ logger.debug('mouse_move Got response:', response);
455
1088
  return response;
456
1089
  }
457
1090
  async function left_click(chromeProxy, tabId, coordinate) {
458
1091
  const isFellou = isFellouBrowser(chromeProxy);
459
- console.log('Sending left_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
1092
+ logger.debug('Sending left_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
460
1093
  if (!coordinate) {
461
1094
  coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
462
1095
  }
@@ -470,12 +1103,12 @@ async function left_click(chromeProxy, tabId, coordinate) {
470
1103
  coordinate,
471
1104
  });
472
1105
  }
473
- console.log('left_click Got response:', response);
1106
+ logger.debug('left_click Got response:', response);
474
1107
  return response;
475
1108
  }
476
1109
  async function left_click_by(chromeProxy, tabId, xpath, highlightIndex) {
477
1110
  const isFellou = isFellouBrowser(chromeProxy);
478
- console.log('Sending left_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
1111
+ logger.debug('Sending left_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
479
1112
  let response;
480
1113
  if (isFellou) {
481
1114
  response = await chromeProxy.browseruse.handle.click(tabId, build_fellou_handle_js(xpath, highlightIndex));
@@ -487,12 +1120,12 @@ async function left_click_by(chromeProxy, tabId, xpath, highlightIndex) {
487
1120
  highlightIndex,
488
1121
  });
489
1122
  }
490
- console.log('left_click_by Got response:', response);
1123
+ logger.debug('left_click_by Got response:', response);
491
1124
  return response;
492
1125
  }
493
1126
  async function right_click(chromeProxy, tabId, coordinate) {
494
1127
  const isFellou = isFellouBrowser(chromeProxy);
495
- console.log('Sending right_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
1128
+ logger.debug('Sending right_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
496
1129
  if (!coordinate) {
497
1130
  coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
498
1131
  }
@@ -506,12 +1139,12 @@ async function right_click(chromeProxy, tabId, coordinate) {
506
1139
  coordinate,
507
1140
  });
508
1141
  }
509
- console.log('right_click Got response:', response);
1142
+ logger.debug('right_click Got response:', response);
510
1143
  return response;
511
1144
  }
512
1145
  async function right_click_by(chromeProxy, tabId, xpath, highlightIndex) {
513
1146
  const isFellou = isFellouBrowser(chromeProxy);
514
- console.log('Sending right_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
1147
+ logger.debug('Sending right_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
515
1148
  let response;
516
1149
  if (isFellou) {
517
1150
  response = await chromeProxy.browseruse.handle.click(tabId, build_fellou_handle_js(xpath, highlightIndex), { button: 'right' });
@@ -523,12 +1156,12 @@ async function right_click_by(chromeProxy, tabId, xpath, highlightIndex) {
523
1156
  highlightIndex,
524
1157
  });
525
1158
  }
526
- console.log('right_click_by Got response:', response);
1159
+ logger.debug('right_click_by Got response:', response);
527
1160
  return response;
528
1161
  }
529
1162
  async function double_click(chromeProxy, tabId, coordinate) {
530
1163
  const isFellou = isFellouBrowser(chromeProxy);
531
- console.log('Sending double_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
1164
+ logger.debug('Sending double_click message to tab:', tabId, { coordinate }, isFellou ? ' > fellou' : '');
532
1165
  if (!coordinate) {
533
1166
  coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
534
1167
  }
@@ -542,12 +1175,12 @@ async function double_click(chromeProxy, tabId, coordinate) {
542
1175
  coordinate,
543
1176
  });
544
1177
  }
545
- console.log('double_click Got response:', response);
1178
+ logger.debug('double_click Got response:', response);
546
1179
  return response;
547
1180
  }
548
1181
  async function double_click_by(chromeProxy, tabId, xpath, highlightIndex) {
549
1182
  const isFellou = isFellouBrowser(chromeProxy);
550
- console.log('Sending double_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
1183
+ logger.debug('Sending double_click_by message to tab:', tabId, { xpath, highlightIndex }, isFellou ? ' > fellou' : '');
551
1184
  let response;
552
1185
  if (isFellou) {
553
1186
  response = await chromeProxy.browseruse.mouse.click(tabId, build_fellou_handle_js(xpath, highlightIndex), { count: 2 });
@@ -559,11 +1192,11 @@ async function double_click_by(chromeProxy, tabId, xpath, highlightIndex) {
559
1192
  highlightIndex,
560
1193
  });
561
1194
  }
562
- console.log('double_click_by Got response:', response);
1195
+ logger.debug('double_click_by Got response:', response);
563
1196
  return response;
564
1197
  }
565
1198
  async function screenshot(chromeProxy, windowId, compress) {
566
- console.log('Taking screenshot of window:', windowId, { compress });
1199
+ logger.debug('Taking screenshot of window:', windowId, { compress });
567
1200
  try {
568
1201
  let dataUrl;
569
1202
  if (compress) {
@@ -587,12 +1220,12 @@ async function screenshot(chromeProxy, windowId, compress) {
587
1220
  data: data,
588
1221
  },
589
1222
  };
590
- console.log('screenshot Got screenshot result:', result);
1223
+ logger.debug('screenshot Got screenshot result:', result);
591
1224
  return result;
592
1225
  }
593
1226
  catch (e) {
594
1227
  if (isFellouBrowser(chromeProxy)) {
595
- console.log('Failed to take screenshot, try fellou...');
1228
+ logger.debug('Failed to take screenshot, try fellou...');
596
1229
  const tabId = await getCurrentTabId(chromeProxy, windowId);
597
1230
  const base64 = await chromeProxy.browseruse.screenshot(tabId, {
598
1231
  type: 'jpeg',
@@ -606,15 +1239,15 @@ async function screenshot(chromeProxy, windowId, compress) {
606
1239
  data: base64,
607
1240
  },
608
1241
  };
609
- console.log('screenshot Got screenshot result, try fellou:', result);
1242
+ logger.debug('screenshot Got screenshot result, try fellou:', result);
610
1243
  return result;
611
1244
  }
612
- console.error('Failed to take screenshot:', e);
1245
+ logger.error('Failed to take screenshot:', e);
613
1246
  throw e;
614
1247
  }
615
1248
  }
616
1249
  async function compress_image(dataUrl, scale = 0.8, quality = 0.8) {
617
- console.log('Compressing image', { scale, quality });
1250
+ logger.debug('Compressing image', { scale, quality });
618
1251
  try {
619
1252
  const bitmap = await createImageBitmap(await (await fetch(dataUrl)).blob());
620
1253
  let width = bitmap.width * scale;
@@ -630,56 +1263,56 @@ async function compress_image(dataUrl, scale = 0.8, quality = 0.8) {
630
1263
  const reader = new FileReader();
631
1264
  reader.onloadend = () => {
632
1265
  const result = reader.result;
633
- console.log('Got compressed image result:', result);
1266
+ logger.debug('Got compressed image result (sliced):', result.slice(0, 200));
634
1267
  resolve(result);
635
1268
  };
636
1269
  reader.readAsDataURL(blob);
637
1270
  });
638
1271
  }
639
1272
  catch (e) {
640
- console.error('Failed to compress image:', e);
1273
+ logger.error('Failed to compress image:', e);
641
1274
  return dataUrl;
642
1275
  }
643
1276
  }
644
1277
  async function scroll_to(chromeProxy, tabId, coordinate) {
645
- console.log('Sending scroll_to message to tab:', tabId, { coordinate });
1278
+ logger.debug('Sending scroll_to message to tab:', tabId, { coordinate });
646
1279
  let from_coordinate = (await cursor_position(chromeProxy, tabId)).coordinate;
647
1280
  const response = await chromeProxy.tabs.sendMessage(tabId, {
648
1281
  type: 'computer:scroll_to',
649
1282
  from_coordinate,
650
1283
  to_coordinate: coordinate,
651
1284
  });
652
- console.log('scroll_to Got response:', response);
1285
+ logger.debug('scroll_to Got response:', response);
653
1286
  return response;
654
1287
  }
655
1288
  async function scroll_to_by(chromeProxy, tabId, xpath, highlightIndex) {
656
- console.log('Sending scroll_to_by message to tab:', tabId, { xpath, highlightIndex });
1289
+ logger.debug('Sending scroll_to_by message to tab:', tabId, { xpath, highlightIndex });
657
1290
  const response = await chromeProxy.tabs.sendMessage(tabId, {
658
1291
  type: 'computer:scroll_to',
659
1292
  xpath,
660
1293
  highlightIndex,
661
1294
  });
662
- console.log('scroll_to_by Got response:', response);
1295
+ logger.debug('scroll_to_by Got response:', response);
663
1296
  return response;
664
1297
  }
665
1298
  async function get_dropdown_options(chromeProxy, tabId, xpath, highlightIndex) {
666
- console.log('Sending get_dropdown_options message to tab:', tabId, { xpath, highlightIndex });
1299
+ logger.debug('Sending get_dropdown_options message to tab:', tabId, { xpath, highlightIndex });
667
1300
  try {
668
1301
  const response = await chromeProxy.tabs.sendMessage(tabId, {
669
1302
  type: 'computer:get_dropdown_options',
670
1303
  xpath,
671
1304
  highlightIndex,
672
1305
  });
673
- console.log('get_dropdown_options Got response:', response);
1306
+ logger.debug('get_dropdown_options Got response:', response);
674
1307
  return response;
675
1308
  }
676
1309
  catch (e) {
677
- console.error('Failed to send get_dropdown_options message:', e);
1310
+ logger.error('Failed to send get_dropdown_options message:', e);
678
1311
  throw e;
679
1312
  }
680
1313
  }
681
1314
  async function select_dropdown_option(chromeProxy, tabId, text, xpath, highlightIndex) {
682
- console.log('Sending select_dropdown_option message to tab:', tabId, { text, xpath, highlightIndex });
1315
+ logger.debug('Sending select_dropdown_option message to tab:', tabId, { text, xpath, highlightIndex });
683
1316
  try {
684
1317
  const response = await chromeProxy.tabs.sendMessage(tabId, {
685
1318
  type: 'computer:select_dropdown_option',
@@ -687,37 +1320,37 @@ async function select_dropdown_option(chromeProxy, tabId, text, xpath, highlight
687
1320
  xpath,
688
1321
  highlightIndex,
689
1322
  });
690
- console.log('select_dropdown_option Got response:', response);
1323
+ logger.debug('select_dropdown_option Got response:', response);
691
1324
  return response;
692
1325
  }
693
1326
  catch (e) {
694
- console.error('Failed to send select_dropdown_option message:', e);
1327
+ logger.error('Failed to send select_dropdown_option message:', e);
695
1328
  throw e;
696
1329
  }
697
1330
  }
698
1331
  async function cursor_position(chromeProxy, tabId) {
699
- console.log('Sending cursor_position message to tab:', tabId);
1332
+ logger.debug('Sending cursor_position message to tab:', tabId);
700
1333
  try {
701
1334
  let result = await chromeProxy.tabs.sendMessage(tabId, {
702
1335
  type: 'computer:cursor_position',
703
1336
  });
704
- console.log('Got cursor position:', result.coordinate);
1337
+ logger.debug('Got cursor position:', result.coordinate);
705
1338
  return { coordinate: result.coordinate };
706
1339
  }
707
1340
  catch (e) {
708
- console.error('Failed to send cursor_position message:', e);
1341
+ logger.error('Failed to send cursor_position message:', e);
709
1342
  throw e;
710
1343
  }
711
1344
  }
712
1345
  async function size(chromeProxy, tabId) {
713
- console.log('Getting page size for tab:', tabId);
1346
+ logger.debug('Getting page size for tab:', tabId);
714
1347
  try {
715
1348
  const pageSize = await getPageSize(chromeProxy, tabId);
716
- console.log('Got page size:', pageSize);
1349
+ logger.debug('Got page size:', pageSize);
717
1350
  return pageSize;
718
1351
  }
719
1352
  catch (e) {
720
- console.error('Failed to get page size:', e);
1353
+ logger.error('Failed to get page size:', e);
721
1354
  throw e;
722
1355
  }
723
1356
  }
@@ -757,7 +1390,8 @@ var browser = /*#__PURE__*/Object.freeze({
757
1390
  class ToolReturnsScreenshot {
758
1391
  async execute(context, params) {
759
1392
  const realResult = await this.realExecute(context, params);
760
- console.log("debug realResult...", realResult);
1393
+ logger.debug("debug realResult...");
1394
+ logger.debug(realResult);
761
1395
  let instance = new BrowserUse();
762
1396
  const image = await instance.realExecute(context, { action: "screenshot_extract_element" });
763
1397
  return image;
@@ -834,22 +1468,22 @@ class BrowserUse extends ToolReturnsScreenshot {
834
1468
  */
835
1469
  async realExecute(context, params) {
836
1470
  var _a;
837
- console.log("execute 'browser_use'...");
1471
+ logger.debug("debug 'browser_use'...");
1472
+ logger.debug(params);
838
1473
  try {
839
1474
  if (params === null || !params.action) {
840
1475
  throw new Error('Invalid parameters. Expected an object with a "action" property.');
841
1476
  }
842
1477
  let tabId;
843
1478
  try {
844
- console.log("getTabId(context)...");
845
1479
  tabId = await getTabId(context);
846
- console.log("getTabId(context)...done");
1480
+ logger.debug(tabId);
847
1481
  if (!tabId || !Number.isInteger(tabId)) {
848
1482
  throw new Error('Could not get valid tab ID');
849
1483
  }
850
1484
  }
851
1485
  catch (e) {
852
- console.error('Tab ID error:', e);
1486
+ logger.error('Tab ID error:', e);
853
1487
  return { success: false, error: 'Could not access browser tab' };
854
1488
  }
855
1489
  let windowId = await getWindowId(context);
@@ -862,7 +1496,7 @@ class BrowserUse extends ToolReturnsScreenshot {
862
1496
  }
863
1497
  }
864
1498
  let result;
865
- console.log("switch cases...");
1499
+ logger.debug("switch cases...");
866
1500
  switch (params.action) {
867
1501
  case 'input_text':
868
1502
  if (params.index == null) {
@@ -932,38 +1566,37 @@ class BrowserUse extends ToolReturnsScreenshot {
932
1566
  result = await select_dropdown_option(context.ekoConfig.chromeProxy, tabId, params.text, selector_xpath, params.index);
933
1567
  break;
934
1568
  case 'screenshot_extract_element':
935
- console.log("execute 'screenshot_extract_element'...");
1569
+ logger.debug("execute 'screenshot_extract_element'...");
936
1570
  await sleep(100);
937
- console.log("injectScript...");
1571
+ logger.debug("injectScript...");
938
1572
  await injectScript(context.ekoConfig.chromeProxy, tabId, 'build_dom_tree.js');
939
1573
  await sleep(100);
940
1574
  try {
941
- console.log("executeScript...");
1575
+ logger.debug("executeScript...");
942
1576
  let element_result = await executeScript(context.ekoConfig.chromeProxy, tabId, () => {
943
1577
  return window.get_clickable_elements(true);
944
1578
  }, []);
945
1579
  context.selector_map = element_result.selector_map;
946
- console.log("browser.screenshot...");
1580
+ logger.debug("browser.screenshot...");
947
1581
  let screenshot$1 = await screenshot(context.ekoConfig.chromeProxy, windowId, true);
948
1582
  result = { image: screenshot$1.image, text: element_result.element_str };
949
1583
  }
950
1584
  finally {
951
- console.log("executeScript #2...");
1585
+ logger.debug("executeScript #2...");
952
1586
  await executeScript(context.ekoConfig.chromeProxy, tabId, () => {
953
1587
  return window.remove_highlight();
954
1588
  }, []);
955
1589
  }
956
- console.log("execute 'screenshot_extract_element'...done");
1590
+ logger.debug("execute 'screenshot_extract_element'...done");
957
1591
  break;
958
1592
  default:
959
1593
  throw Error(`Invalid parameters. The "${params.action}" value is not included in the "action" enumeration.`);
960
1594
  }
961
- console.log("execute 'browser_use'...done, result=");
962
- console.log(result);
1595
+ logger.debug(`execute 'browser_use'...done, result=${result}`);
963
1596
  return result;
964
1597
  }
965
1598
  catch (e) {
966
- console.error('Browser use error:', e);
1599
+ logger.error('Browser use error:', e);
967
1600
  return { success: false, error: e === null || e === void 0 ? void 0 : e.message };
968
1601
  }
969
1602
  }
@@ -1137,7 +1770,7 @@ class GetAllTabs {
1137
1770
  const tabsInfo = [];
1138
1771
  for (const tab of tabs) {
1139
1772
  if (tab.id === undefined) {
1140
- console.warn(`Tab ID is undefined for tab with URL: ${tab.url}`);
1773
+ logger.warn(`Tab ID is undefined for tab with URL: ${tab.url}`);
1141
1774
  continue;
1142
1775
  }
1143
1776
  await injectScript(context.ekoConfig.chromeProxy, tab.id);
@@ -1154,9 +1787,7 @@ class GetAllTabs {
1154
1787
  content: content,
1155
1788
  description: description,
1156
1789
  };
1157
- console.log("url: " + tab.url);
1158
- console.log("title: " + tab.title);
1159
- console.log("description: " + description);
1790
+ logger.debug(tabInfo);
1160
1791
  tabsInfo.push(tabInfo);
1161
1792
  }
1162
1793
  return tabsInfo;
@@ -1194,69 +1825,67 @@ class OpenUrl extends ToolReturnsScreenshot {
1194
1825
  */
1195
1826
  async realExecute(context, params) {
1196
1827
  var _a, _b, _c, _d, _e, _f;
1197
- console.log('Starting execute function with context:', context, 'and params:', params);
1198
1828
  // 参数验证
1199
1829
  if (typeof params !== 'object' || params === null || !params.url) {
1200
- console.error('Invalid parameters. Expected an object with a "url" property.');
1830
+ logger.error('Invalid parameters. Expected an object with a "url" property.');
1201
1831
  throw new Error('Invalid parameters. Expected an object with a "url" property.');
1202
1832
  }
1203
1833
  // 提取参数
1204
1834
  let url = params.url.trim();
1205
1835
  let newWindow = params.newWindow;
1206
- console.log('URL to open:', url);
1207
- console.log('Initial newWindow value:', newWindow);
1836
+ logger.debug('URL to open:', url);
1837
+ logger.debug('Initial newWindow value:', newWindow);
1208
1838
  // 根据上下文调整 newWindow 的值
1209
1839
  if (context.ekoConfig.workingWindowId) {
1210
- console.log('Working window ID exists in context, setting newWindow to false.');
1840
+ logger.debug('Working window ID exists in context, setting newWindow to false.');
1211
1841
  newWindow = false;
1212
1842
  }
1213
1843
  else if (!newWindow && !context.variables.get('windowId') && !context.variables.get('tabId')) {
1214
1844
  // First mandatory opening of a new window
1215
- console.log('No existing window or tab ID found, forcing newWindow to true.');
1845
+ logger.debug('No existing window or tab ID found, forcing newWindow to true.');
1216
1846
  newWindow = true;
1217
1847
  }
1218
- console.log('Final newWindow value:', newWindow);
1848
+ logger.debug('Final newWindow value:', newWindow);
1219
1849
  // 打开新标签页
1220
1850
  let tab;
1221
1851
  if (newWindow) {
1222
- console.log('Opening new tab in a new window.');
1852
+ logger.debug('Opening new tab in a new window.');
1223
1853
  tab = await open_new_tab(context.ekoConfig.chromeProxy, url);
1224
1854
  (_c = (_b = (_a = context.callback) === null || _a === void 0 ? void 0 : _a.hooks) === null || _b === void 0 ? void 0 : _b.onTabCreated) === null || _c === void 0 ? void 0 : _c.call(_b, tab.id);
1225
- console.log('New tab created in a new window:', tab);
1855
+ logger.debug('New tab created in a new window:', tab.id);
1226
1856
  }
1227
1857
  else {
1228
1858
  let windowId = context.ekoConfig.workingWindowId ? context.ekoConfig.workingWindowId : await getWindowId(context);
1229
- console.log('Using existing window with ID:', windowId);
1859
+ logger.debug('Using existing window with ID:', windowId);
1230
1860
  try {
1231
1861
  tab = await open_new_tab(context.ekoConfig.chromeProxy, url, windowId);
1232
- console.log("Calling hook...");
1862
+ logger.debug("Calling hook...");
1233
1863
  (_f = (_e = (_d = context.callback) === null || _d === void 0 ? void 0 : _d.hooks) === null || _e === void 0 ? void 0 : _e.onTabCreated) === null || _f === void 0 ? void 0 : _f.call(_e, tab.id);
1234
- console.log('New tab created in existing window:', tab);
1864
+ logger.debug('New tab created in existing window:', tab.id);
1235
1865
  }
1236
1866
  catch (e) {
1237
- console.error("An error occurs when `open_url`");
1238
- console.error(e);
1867
+ logger.error("An error occurs when `open_url`", e);
1239
1868
  throw e;
1240
1869
  }
1241
1870
  }
1242
1871
  // 获取窗口和标签 ID
1243
1872
  let windowId = tab.windowId;
1244
1873
  let tabId = tab.id;
1245
- console.log('Tab ID:', tabId, 'Window ID:', windowId);
1874
+ logger.debug('Tab ID:', tabId, 'Window ID:', windowId);
1246
1875
  // 更新上下文变量
1247
1876
  context.variables.set('windowId', windowId);
1248
1877
  context.variables.set('tabId', tabId);
1249
- console.log('Updated context variables:', context.variables);
1878
+ logger.debug('Updated context variables:', context.variables);
1250
1879
  // 处理新窗口的 windowIds
1251
1880
  if (newWindow) {
1252
1881
  let windowIds = context.variables.get('windowIds');
1253
1882
  if (windowIds) {
1254
- console.log('Existing window IDs:', windowIds);
1883
+ logger.debug('Existing window IDs:', windowIds);
1255
1884
  windowIds.push(windowId);
1256
- console.log('Updated window IDs:', windowIds);
1885
+ logger.debug('Updated window IDs:', windowIds);
1257
1886
  }
1258
1887
  else {
1259
- console.log('No existing window IDs found, creating new array.');
1888
+ logger.debug('No existing window IDs found, creating new array.');
1260
1889
  context.variables.set('windowIds', [windowId]);
1261
1890
  }
1262
1891
  }
@@ -1266,7 +1895,7 @@ class OpenUrl extends ToolReturnsScreenshot {
1266
1895
  windowId,
1267
1896
  title: tab.title,
1268
1897
  };
1269
- console.log('Returning result:', result);
1898
+ logger.debug('Returning result:', result);
1270
1899
  return result;
1271
1900
  }
1272
1901
  }
@@ -1565,7 +2194,7 @@ async function deepSearch(context, taskId, searchs, detailsMaxNum, windowId) {
1565
2194
  let detailLinkGroups = await doDetailLinkGroups(context, taskId, searchs, detailsMaxNum, windowId);
1566
2195
  // crawler all details page content and comments
1567
2196
  let searchInfo = await doPageContent(context, taskId, detailLinkGroups, windowId);
1568
- console.log('searchInfo: ', searchInfo);
2197
+ logger.debug('searchInfo: ', searchInfo);
1569
2198
  // close window
1570
2199
  closeWindow && context.ekoConfig.chromeProxy.windows.remove(windowId);
1571
2200
  return searchInfo;
@@ -1610,9 +2239,9 @@ async function doDetailLinkGroups(context, taskId, searchs, detailsMaxNum, windo
1610
2239
  type: 'page:getDetailLinks',
1611
2240
  keyword: searchs[i].keyword,
1612
2241
  });
1613
- console.log('detailLinks: ', detailLinks);
2242
+ logger.debug('detailLinks: ', detailLinks);
1614
2243
  if (!detailLinks || !detailLinks.links) {
1615
- console.error("detailLinks is empty");
2244
+ logger.error("detailLinks is empty");
1616
2245
  throw new Error("An error occurs when calling `web_search`, please try again.");
1617
2246
  }
1618
2247
  let links = detailLinks.links.slice(0, detailsMaxNum);
@@ -1628,7 +2257,7 @@ async function doDetailLinkGroups(context, taskId, searchs, detailsMaxNum, windo
1628
2257
  }, eventId);
1629
2258
  }
1630
2259
  catch (e) {
1631
- console.error(e);
2260
+ logger.error(e);
1632
2261
  countDownLatch.countDown();
1633
2262
  }
1634
2263
  }
@@ -1722,7 +2351,7 @@ async function doPageContent(context, taskId, detailLinkGroups, windowId) {
1722
2351
  await Promise.race([monitorTabPromise, timeoutPromise]);
1723
2352
  }
1724
2353
  catch (e) {
1725
- console.error(`${link.title} failed:`, e);
2354
+ logger.error(`${link.title} failed:`, e);
1726
2355
  searchInfo.running--;
1727
2356
  searchInfo.failed++;
1728
2357
  searchInfo.failedLinks.push(link);
@@ -1841,7 +2470,7 @@ class CancelWorkflow {
1841
2470
  throw new Error('Invalid parameters. Expected an object with a "reason" property.');
1842
2471
  }
1843
2472
  const reason = params.reason;
1844
- console.log("The workflow has been cancelled because: " + reason);
2473
+ logger.info("The workflow has been cancelled because: " + reason);
1845
2474
  await ((_a = context.workflow) === null || _a === void 0 ? void 0 : _a.cancel());
1846
2475
  return;
1847
2476
  }
@@ -1868,7 +2497,7 @@ class HumanInputText {
1868
2497
  throw new Error('Invalid parameters. Expected an object with a "question" property.');
1869
2498
  }
1870
2499
  const question = params.question;
1871
- console.log("question: " + question);
2500
+ logger.debug("question: " + question);
1872
2501
  let onHumanInputText = (_a = context.callback) === null || _a === void 0 ? void 0 : _a.hooks.onHumanInputText;
1873
2502
  if (onHumanInputText) {
1874
2503
  let answer;
@@ -1876,14 +2505,14 @@ class HumanInputText {
1876
2505
  answer = await onHumanInputText(question);
1877
2506
  }
1878
2507
  catch (e) {
1879
- console.error(e);
2508
+ logger.warn(e);
1880
2509
  return { status: "Error: Cannot get user's answer.", answer: "" };
1881
2510
  }
1882
- console.log("answer: " + answer);
2511
+ logger.debug("answer: " + answer);
1883
2512
  return { status: "OK", answer: answer };
1884
2513
  }
1885
2514
  else {
1886
- console.error("`onHumanInputText` not implemented");
2515
+ logger.error("`onHumanInputText` not implemented");
1887
2516
  return { status: "Error: Cannot get user's answer.", answer: "" };
1888
2517
  }
1889
2518
  }
@@ -1922,8 +2551,8 @@ class HumanInputSingleChoice {
1922
2551
  }
1923
2552
  const question = params.question;
1924
2553
  const choices = params.choices.map((e) => e.choice);
1925
- console.log("question: " + question);
1926
- console.log("choices: " + choices);
2554
+ logger.debug("question: " + question);
2555
+ logger.debug("choices: " + choices);
1927
2556
  let onHumanInputSingleChoice = (_a = context.callback) === null || _a === void 0 ? void 0 : _a.hooks.onHumanInputSingleChoice;
1928
2557
  if (onHumanInputSingleChoice) {
1929
2558
  let answer;
@@ -1931,14 +2560,14 @@ class HumanInputSingleChoice {
1931
2560
  answer = await onHumanInputSingleChoice(question, choices);
1932
2561
  }
1933
2562
  catch (e) {
1934
- console.error(e);
2563
+ logger.warn(e);
1935
2564
  return { status: "Error: Cannot get user's answer.", answer: "" };
1936
2565
  }
1937
- console.log("answer: " + answer);
2566
+ logger.debug("answer: " + answer);
1938
2567
  return { status: "OK", answer: answer };
1939
2568
  }
1940
2569
  else {
1941
- console.error("`onHumanInputSingleChoice` not implemented");
2570
+ logger.error("`onHumanInputSingleChoice` not implemented");
1942
2571
  return { status: "Error: Cannot get user's answer.", answer: "" };
1943
2572
  }
1944
2573
  }
@@ -1977,8 +2606,8 @@ class HumanInputMultipleChoice {
1977
2606
  }
1978
2607
  const question = params.question;
1979
2608
  const choices = params.choices.map((e) => e.choice);
1980
- console.log("question: " + question);
1981
- console.log("choices: " + choices);
2609
+ logger.debug("question: " + question);
2610
+ logger.debug("choices: " + choices);
1982
2611
  let onHumanInputMultipleChoice = (_a = context.callback) === null || _a === void 0 ? void 0 : _a.hooks.onHumanInputMultipleChoice;
1983
2612
  if (onHumanInputMultipleChoice) {
1984
2613
  let answer;
@@ -1986,14 +2615,14 @@ class HumanInputMultipleChoice {
1986
2615
  answer = await onHumanInputMultipleChoice(question, choices);
1987
2616
  }
1988
2617
  catch (e) {
1989
- console.error(e);
1990
- return { status: "`onHumanInputMultipleChoice` not implemented", answer: [] };
2618
+ logger.warn(e);
2619
+ return { status: "Error: Cannot get user's answer.", answer: [] };
1991
2620
  }
1992
- console.log("answer: " + answer);
2621
+ logger.debug("answer: " + answer);
1993
2622
  return { status: "OK", answer: answer };
1994
2623
  }
1995
2624
  else {
1996
- console.error("Cannot get user's answer.");
2625
+ logger.error("`onHumanInputMultipleChoice` not implemented");
1997
2626
  return { status: "Error: Cannot get user's answer.", answer: [] };
1998
2627
  }
1999
2628
  }
@@ -2027,7 +2656,7 @@ When calling this tool to transfer control to the user, please explain in detail
2027
2656
  throw new Error('Invalid parameters. Expected an object with a "reason" property.');
2028
2657
  }
2029
2658
  const reason = params.reason;
2030
- console.log("reason: " + reason);
2659
+ logger.debug("reason: " + reason);
2031
2660
  let onHumanOperate = (_a = context.callback) === null || _a === void 0 ? void 0 : _a.hooks.onHumanOperate;
2032
2661
  if (onHumanOperate) {
2033
2662
  let userOperation;
@@ -2035,10 +2664,10 @@ When calling this tool to transfer control to the user, please explain in detail
2035
2664
  userOperation = await onHumanOperate(reason);
2036
2665
  }
2037
2666
  catch (e) {
2038
- console.error(e);
2039
- return { status: "`onHumanOperate` not implemented", userOperation: "" };
2667
+ logger.warn(e);
2668
+ return { status: "Error: Cannot get user's operation.", userOperation: "" };
2040
2669
  }
2041
- console.log("userOperation: " + userOperation);
2670
+ logger.debug("userOperation: " + userOperation);
2042
2671
  if (userOperation == "") {
2043
2672
  return { status: "OK", userOperation: "Done. Please take a screenshot to ensure the result." };
2044
2673
  }
@@ -2047,7 +2676,7 @@ When calling this tool to transfer control to the user, please explain in detail
2047
2676
  }
2048
2677
  }
2049
2678
  else {
2050
- console.error("Cannot get user's operation.");
2679
+ logger.error("`onHumanOperate` not implemented");
2051
2680
  return { status: "Error: Cannot get user's operation.", userOperation: "" };
2052
2681
  }
2053
2682
  }
@@ -2144,7 +2773,7 @@ function loadTools() {
2144
2773
  toolsMap.set(instance.name || key, instance);
2145
2774
  }
2146
2775
  catch (e) {
2147
- console.error(`Failed to instantiate ${key}:`, e);
2776
+ logger.error(`Failed to instantiate ${key}:`, e);
2148
2777
  }
2149
2778
  }
2150
2779
  }