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