@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.
package/dist/index.cjs.js CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
+ var os = require('os');
6
+ var path = require('path');
7
+ var util = require('util');
8
+ var uuid = require('uuid');
9
+
5
10
  const VERSION$1 = '0.33.1'; // x-release-please-version
6
11
 
7
12
  let auto$1 = false;
@@ -2714,7 +2719,7 @@ class ClaudeProvider {
2714
2719
  if (typeof window !== 'undefined' &&
2715
2720
  typeof document !== 'undefined' &&
2716
2721
  (typeof param == 'string' || param.apiKey)) {
2717
- console.warn(`
2722
+ logger.warn(`
2718
2723
  ⚠️ Security Warning:
2719
2724
  DO NOT use API Keys in browser/frontend code!
2720
2725
  This will expose your credentials and may lead to unauthorized usage.
@@ -8782,6 +8787,630 @@ OpenAI.BatchesPage = BatchesPage;
8782
8787
  OpenAI.Uploads = Uploads;
8783
8788
  OpenAI.Responses = Responses;
8784
8789
 
8790
+ const prettyLogStyles = {
8791
+ reset: [0, 0],
8792
+ bold: [1, 22],
8793
+ dim: [2, 22],
8794
+ italic: [3, 23],
8795
+ underline: [4, 24],
8796
+ overline: [53, 55],
8797
+ inverse: [7, 27],
8798
+ hidden: [8, 28],
8799
+ strikethrough: [9, 29],
8800
+ black: [30, 39],
8801
+ red: [31, 39],
8802
+ green: [32, 39],
8803
+ yellow: [33, 39],
8804
+ blue: [34, 39],
8805
+ magenta: [35, 39],
8806
+ cyan: [36, 39],
8807
+ white: [37, 39],
8808
+ blackBright: [90, 39],
8809
+ redBright: [91, 39],
8810
+ greenBright: [92, 39],
8811
+ yellowBright: [93, 39],
8812
+ blueBright: [94, 39],
8813
+ magentaBright: [95, 39],
8814
+ cyanBright: [96, 39],
8815
+ whiteBright: [97, 39],
8816
+ bgBlack: [40, 49],
8817
+ bgRed: [41, 49],
8818
+ bgGreen: [42, 49],
8819
+ bgYellow: [43, 49],
8820
+ bgBlue: [44, 49],
8821
+ bgMagenta: [45, 49],
8822
+ bgCyan: [46, 49],
8823
+ bgWhite: [47, 49],
8824
+ bgBlackBright: [100, 49],
8825
+ bgRedBright: [101, 49],
8826
+ bgGreenBright: [102, 49],
8827
+ bgYellowBright: [103, 49],
8828
+ bgBlueBright: [104, 49],
8829
+ bgMagentaBright: [105, 49],
8830
+ bgCyanBright: [106, 49],
8831
+ bgWhiteBright: [107, 49],
8832
+ };
8833
+
8834
+ function formatTemplate(settings, template, values, hideUnsetPlaceholder = false) {
8835
+ const templateString = String(template);
8836
+ const ansiColorWrap = (placeholderValue, code) => `\u001b[${code[0]}m${placeholderValue}\u001b[${code[1]}m`;
8837
+ const styleWrap = (value, style) => {
8838
+ if (style != null && typeof style === "string") {
8839
+ return ansiColorWrap(value, prettyLogStyles[style]);
8840
+ }
8841
+ else if (style != null && Array.isArray(style)) {
8842
+ return style.reduce((prevValue, thisStyle) => styleWrap(prevValue, thisStyle), value);
8843
+ }
8844
+ else {
8845
+ if (style != null && style[value.trim()] != null) {
8846
+ return styleWrap(value, style[value.trim()]);
8847
+ }
8848
+ else if (style != null && style["*"] != null) {
8849
+ return styleWrap(value, style["*"]);
8850
+ }
8851
+ else {
8852
+ return value;
8853
+ }
8854
+ }
8855
+ };
8856
+ const defaultStyle = null;
8857
+ return templateString.replace(/{{(.+?)}}/g, (_, placeholder) => {
8858
+ const value = values[placeholder] != null ? String(values[placeholder]) : hideUnsetPlaceholder ? "" : _;
8859
+ return settings.stylePrettyLogs
8860
+ ? styleWrap(value, settings?.prettyLogStyles?.[placeholder] ?? defaultStyle) + ansiColorWrap("", prettyLogStyles.reset)
8861
+ : value;
8862
+ });
8863
+ }
8864
+
8865
+ function formatNumberAddZeros(value, digits = 2, addNumber = 0) {
8866
+ if (value != null && isNaN(value)) {
8867
+ return "";
8868
+ }
8869
+ value = value != null ? value + addNumber : value;
8870
+ return digits === 2
8871
+ ? value == null
8872
+ ? "--"
8873
+ : value < 10
8874
+ ? "0" + value
8875
+ : value.toString()
8876
+ : value == null
8877
+ ? "---"
8878
+ : value < 10
8879
+ ? "00" + value
8880
+ : value < 100
8881
+ ? "0" + value
8882
+ : value.toString();
8883
+ }
8884
+
8885
+ function urlToObject(url) {
8886
+ return {
8887
+ href: url.href,
8888
+ protocol: url.protocol,
8889
+ username: url.username,
8890
+ password: url.password,
8891
+ host: url.host,
8892
+ hostname: url.hostname,
8893
+ port: url.port,
8894
+ pathname: url.pathname,
8895
+ search: url.search,
8896
+ searchParams: [...url.searchParams].map(([key, value]) => ({ key, value })),
8897
+ hash: url.hash,
8898
+ origin: url.origin,
8899
+ };
8900
+ }
8901
+
8902
+ var Runtime = {
8903
+ getCallerStackFrame,
8904
+ getErrorTrace,
8905
+ getMeta,
8906
+ transportJSON,
8907
+ transportFormatted: transportFormatted$1,
8908
+ isBuffer,
8909
+ isError,
8910
+ prettyFormatLogObj,
8911
+ prettyFormatErrorObj,
8912
+ };
8913
+ const meta = {
8914
+ runtime: "Nodejs",
8915
+ runtimeVersion: process?.version,
8916
+ hostname: os.hostname ? os.hostname() : undefined,
8917
+ };
8918
+ function getMeta(logLevelId, logLevelName, stackDepthLevel, hideLogPositionForPerformance, name, parentNames) {
8919
+ return Object.assign({}, meta, {
8920
+ name,
8921
+ parentNames,
8922
+ date: new Date(),
8923
+ logLevelId,
8924
+ logLevelName,
8925
+ path: !hideLogPositionForPerformance ? getCallerStackFrame(stackDepthLevel) : undefined,
8926
+ });
8927
+ }
8928
+ function getCallerStackFrame(stackDepthLevel, error = Error()) {
8929
+ return stackLineToStackFrame(error?.stack?.split("\n")?.filter((thisLine) => thisLine.includes(" at "))?.[stackDepthLevel]);
8930
+ }
8931
+ function getErrorTrace(error) {
8932
+ return error?.stack?.split("\n")?.reduce((result, line) => {
8933
+ if (line.includes(" at ")) {
8934
+ result.push(stackLineToStackFrame(line));
8935
+ }
8936
+ return result;
8937
+ }, []);
8938
+ }
8939
+ function stackLineToStackFrame(line) {
8940
+ const pathResult = {
8941
+ fullFilePath: undefined,
8942
+ fileName: undefined,
8943
+ fileNameWithLine: undefined,
8944
+ fileColumn: undefined,
8945
+ fileLine: undefined,
8946
+ filePath: undefined,
8947
+ filePathWithLine: undefined,
8948
+ method: undefined,
8949
+ };
8950
+ if (line != null && line.includes(" at ")) {
8951
+ line = line.replace(/^\s+at\s+/gm, "");
8952
+ const errorStackLine = line.split(" (");
8953
+ const fullFilePath = line?.slice(-1) === ")" ? line?.match(/\(([^)]+)\)/)?.[1] : line;
8954
+ const pathArray = fullFilePath?.includes(":") ? fullFilePath?.replace("file://", "")?.replace(process.cwd(), "")?.split(":") : undefined;
8955
+ const fileColumn = pathArray?.pop();
8956
+ const fileLine = pathArray?.pop();
8957
+ const filePath = pathArray?.pop();
8958
+ const filePathWithLine = path.normalize(`${filePath}:${fileLine}`);
8959
+ const fileName = filePath?.split("/")?.pop();
8960
+ const fileNameWithLine = `${fileName}:${fileLine}`;
8961
+ if (filePath != null && filePath.length > 0) {
8962
+ pathResult.fullFilePath = fullFilePath;
8963
+ pathResult.fileName = fileName;
8964
+ pathResult.fileNameWithLine = fileNameWithLine;
8965
+ pathResult.fileColumn = fileColumn;
8966
+ pathResult.fileLine = fileLine;
8967
+ pathResult.filePath = filePath;
8968
+ pathResult.filePathWithLine = filePathWithLine;
8969
+ pathResult.method = errorStackLine?.[1] != null ? errorStackLine?.[0] : undefined;
8970
+ }
8971
+ }
8972
+ return pathResult;
8973
+ }
8974
+ function isError(e) {
8975
+ return util.types?.isNativeError != null ? util.types.isNativeError(e) : e instanceof Error;
8976
+ }
8977
+ function prettyFormatLogObj(maskedArgs, settings) {
8978
+ return maskedArgs.reduce((result, arg) => {
8979
+ isError(arg) ? result.errors.push(prettyFormatErrorObj(arg, settings)) : result.args.push(arg);
8980
+ return result;
8981
+ }, { args: [], errors: [] });
8982
+ }
8983
+ function prettyFormatErrorObj(error, settings) {
8984
+ const errorStackStr = getErrorTrace(error).map((stackFrame) => {
8985
+ return formatTemplate(settings, settings.prettyErrorStackTemplate, { ...stackFrame }, true);
8986
+ });
8987
+ const placeholderValuesError = {
8988
+ errorName: ` ${error.name} `,
8989
+ errorMessage: Object.getOwnPropertyNames(error)
8990
+ .reduce((result, key) => {
8991
+ if (key !== "stack") {
8992
+ result.push(error[key]);
8993
+ }
8994
+ return result;
8995
+ }, [])
8996
+ .join(", "),
8997
+ errorStack: errorStackStr.join("\n"),
8998
+ };
8999
+ return formatTemplate(settings, settings.prettyErrorTemplate, placeholderValuesError);
9000
+ }
9001
+ function transportFormatted$1(logMetaMarkup, logArgs, logErrors, settings) {
9002
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
9003
+ settings.prettyInspectOptions.colors = settings.stylePrettyLogs;
9004
+ console.log(logMetaMarkup + util.formatWithOptions(settings.prettyInspectOptions, ...logArgs) + logErrorsStr);
9005
+ }
9006
+ function transportJSON(json) {
9007
+ console.log(jsonStringifyRecursive(json));
9008
+ function jsonStringifyRecursive(obj) {
9009
+ const cache = new Set();
9010
+ return JSON.stringify(obj, (key, value) => {
9011
+ if (typeof value === "object" && value !== null) {
9012
+ if (cache.has(value)) {
9013
+ return "[Circular]";
9014
+ }
9015
+ cache.add(value);
9016
+ }
9017
+ if (typeof value === "bigint") {
9018
+ return `${value}`;
9019
+ }
9020
+ if (typeof value === "undefined") {
9021
+ return "[undefined]";
9022
+ }
9023
+ return value;
9024
+ });
9025
+ }
9026
+ }
9027
+ function isBuffer(arg) {
9028
+ return Buffer.isBuffer(arg);
9029
+ }
9030
+
9031
+ class BaseLogger {
9032
+ constructor(settings, logObj, stackDepthLevel = 4) {
9033
+ this.logObj = logObj;
9034
+ this.stackDepthLevel = stackDepthLevel;
9035
+ this.runtime = Runtime;
9036
+ this.settings = {
9037
+ type: settings?.type ?? "pretty",
9038
+ name: settings?.name,
9039
+ parentNames: settings?.parentNames,
9040
+ minLevel: settings?.minLevel ?? 0,
9041
+ argumentsArrayName: settings?.argumentsArrayName,
9042
+ hideLogPositionForProduction: settings?.hideLogPositionForProduction ?? false,
9043
+ prettyLogTemplate: settings?.prettyLogTemplate ??
9044
+ "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}\t{{logLevelName}}\t{{filePathWithLine}}{{nameWithDelimiterPrefix}}\t",
9045
+ prettyErrorTemplate: settings?.prettyErrorTemplate ?? "\n{{errorName}} {{errorMessage}}\nerror stack:\n{{errorStack}}",
9046
+ prettyErrorStackTemplate: settings?.prettyErrorStackTemplate ?? " • {{fileName}}\t{{method}}\n\t{{filePathWithLine}}",
9047
+ prettyErrorParentNamesSeparator: settings?.prettyErrorParentNamesSeparator ?? ":",
9048
+ prettyErrorLoggerNameDelimiter: settings?.prettyErrorLoggerNameDelimiter ?? "\t",
9049
+ stylePrettyLogs: settings?.stylePrettyLogs ?? true,
9050
+ prettyLogTimeZone: settings?.prettyLogTimeZone ?? "UTC",
9051
+ prettyLogStyles: settings?.prettyLogStyles ?? {
9052
+ logLevelName: {
9053
+ "*": ["bold", "black", "bgWhiteBright", "dim"],
9054
+ SILLY: ["bold", "white"],
9055
+ TRACE: ["bold", "whiteBright"],
9056
+ DEBUG: ["bold", "green"],
9057
+ INFO: ["bold", "blue"],
9058
+ WARN: ["bold", "yellow"],
9059
+ ERROR: ["bold", "red"],
9060
+ FATAL: ["bold", "redBright"],
9061
+ },
9062
+ dateIsoStr: "white",
9063
+ filePathWithLine: "white",
9064
+ name: ["white", "bold"],
9065
+ nameWithDelimiterPrefix: ["white", "bold"],
9066
+ nameWithDelimiterSuffix: ["white", "bold"],
9067
+ errorName: ["bold", "bgRedBright", "whiteBright"],
9068
+ fileName: ["yellow"],
9069
+ fileNameWithLine: "white",
9070
+ },
9071
+ prettyInspectOptions: settings?.prettyInspectOptions ?? {
9072
+ colors: true,
9073
+ compact: false,
9074
+ depth: Infinity,
9075
+ },
9076
+ metaProperty: settings?.metaProperty ?? "_meta",
9077
+ maskPlaceholder: settings?.maskPlaceholder ?? "[***]",
9078
+ maskValuesOfKeys: settings?.maskValuesOfKeys ?? ["password"],
9079
+ maskValuesOfKeysCaseInsensitive: settings?.maskValuesOfKeysCaseInsensitive ?? false,
9080
+ maskValuesRegEx: settings?.maskValuesRegEx,
9081
+ prefix: [...(settings?.prefix ?? [])],
9082
+ attachedTransports: [...(settings?.attachedTransports ?? [])],
9083
+ overwrite: {
9084
+ mask: settings?.overwrite?.mask,
9085
+ toLogObj: settings?.overwrite?.toLogObj,
9086
+ addMeta: settings?.overwrite?.addMeta,
9087
+ addPlaceholders: settings?.overwrite?.addPlaceholders,
9088
+ formatMeta: settings?.overwrite?.formatMeta,
9089
+ formatLogObj: settings?.overwrite?.formatLogObj,
9090
+ transportFormatted: settings?.overwrite?.transportFormatted,
9091
+ transportJSON: settings?.overwrite?.transportJSON,
9092
+ },
9093
+ };
9094
+ }
9095
+ log(logLevelId, logLevelName, ...args) {
9096
+ if (logLevelId < this.settings.minLevel) {
9097
+ return;
9098
+ }
9099
+ const logArgs = [...this.settings.prefix, ...args];
9100
+ const maskedArgs = this.settings.overwrite?.mask != null
9101
+ ? this.settings.overwrite?.mask(logArgs)
9102
+ : this.settings.maskValuesOfKeys != null && this.settings.maskValuesOfKeys.length > 0
9103
+ ? this._mask(logArgs)
9104
+ : logArgs;
9105
+ const thisLogObj = this.logObj != null ? this._recursiveCloneAndExecuteFunctions(this.logObj) : undefined;
9106
+ const logObj = this.settings.overwrite?.toLogObj != null ? this.settings.overwrite?.toLogObj(maskedArgs, thisLogObj) : this._toLogObj(maskedArgs, thisLogObj);
9107
+ const logObjWithMeta = this.settings.overwrite?.addMeta != null
9108
+ ? this.settings.overwrite?.addMeta(logObj, logLevelId, logLevelName)
9109
+ : this._addMetaToLogObj(logObj, logLevelId, logLevelName);
9110
+ let logMetaMarkup;
9111
+ let logArgsAndErrorsMarkup = undefined;
9112
+ if (this.settings.overwrite?.formatMeta != null) {
9113
+ logMetaMarkup = this.settings.overwrite?.formatMeta(logObjWithMeta?.[this.settings.metaProperty]);
9114
+ }
9115
+ if (this.settings.overwrite?.formatLogObj != null) {
9116
+ logArgsAndErrorsMarkup = this.settings.overwrite?.formatLogObj(maskedArgs, this.settings);
9117
+ }
9118
+ if (this.settings.type === "pretty") {
9119
+ logMetaMarkup = logMetaMarkup ?? this._prettyFormatLogObjMeta(logObjWithMeta?.[this.settings.metaProperty]);
9120
+ logArgsAndErrorsMarkup = logArgsAndErrorsMarkup ?? this.runtime.prettyFormatLogObj(maskedArgs, this.settings);
9121
+ }
9122
+ if (logMetaMarkup != null && logArgsAndErrorsMarkup != null) {
9123
+ this.settings.overwrite?.transportFormatted != null
9124
+ ? this.settings.overwrite?.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings)
9125
+ : this.runtime.transportFormatted(logMetaMarkup, logArgsAndErrorsMarkup.args, logArgsAndErrorsMarkup.errors, this.settings);
9126
+ }
9127
+ else {
9128
+ this.settings.overwrite?.transportJSON != null
9129
+ ? this.settings.overwrite?.transportJSON(logObjWithMeta)
9130
+ : this.settings.type !== "hidden"
9131
+ ? this.runtime.transportJSON(logObjWithMeta)
9132
+ : undefined;
9133
+ }
9134
+ if (this.settings.attachedTransports != null && this.settings.attachedTransports.length > 0) {
9135
+ this.settings.attachedTransports.forEach((transportLogger) => {
9136
+ transportLogger(logObjWithMeta);
9137
+ });
9138
+ }
9139
+ return logObjWithMeta;
9140
+ }
9141
+ attachTransport(transportLogger) {
9142
+ this.settings.attachedTransports.push(transportLogger);
9143
+ }
9144
+ getSubLogger(settings, logObj) {
9145
+ const subLoggerSettings = {
9146
+ ...this.settings,
9147
+ ...settings,
9148
+ parentNames: this.settings?.parentNames != null && this.settings?.name != null
9149
+ ? [...this.settings.parentNames, this.settings.name]
9150
+ : this.settings?.name != null
9151
+ ? [this.settings.name]
9152
+ : undefined,
9153
+ prefix: [...this.settings.prefix, ...(settings?.prefix ?? [])],
9154
+ };
9155
+ const subLogger = new this.constructor(subLoggerSettings, logObj ?? this.logObj, this.stackDepthLevel);
9156
+ return subLogger;
9157
+ }
9158
+ _mask(args) {
9159
+ const maskValuesOfKeys = this.settings.maskValuesOfKeysCaseInsensitive !== true ? this.settings.maskValuesOfKeys : this.settings.maskValuesOfKeys.map((key) => key.toLowerCase());
9160
+ return args?.map((arg) => {
9161
+ return this._recursiveCloneAndMaskValuesOfKeys(arg, maskValuesOfKeys);
9162
+ });
9163
+ }
9164
+ _recursiveCloneAndMaskValuesOfKeys(source, keys, seen = []) {
9165
+ if (seen.includes(source)) {
9166
+ return { ...source };
9167
+ }
9168
+ if (typeof source === "object" && source !== null) {
9169
+ seen.push(source);
9170
+ }
9171
+ if (this.runtime.isError(source) || this.runtime.isBuffer(source)) {
9172
+ return source;
9173
+ }
9174
+ else if (source instanceof Map) {
9175
+ return new Map(source);
9176
+ }
9177
+ else if (source instanceof Set) {
9178
+ return new Set(source);
9179
+ }
9180
+ else if (Array.isArray(source)) {
9181
+ return source.map((item) => this._recursiveCloneAndMaskValuesOfKeys(item, keys, seen));
9182
+ }
9183
+ else if (source instanceof Date) {
9184
+ return new Date(source.getTime());
9185
+ }
9186
+ else if (source instanceof URL) {
9187
+ return urlToObject(source);
9188
+ }
9189
+ else if (source !== null && typeof source === "object") {
9190
+ const baseObject = this.runtime.isError(source) ? this._cloneError(source) : Object.create(Object.getPrototypeOf(source));
9191
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
9192
+ o[prop] = keys.includes(this.settings?.maskValuesOfKeysCaseInsensitive !== true ? prop : prop.toLowerCase())
9193
+ ? this.settings.maskPlaceholder
9194
+ : (() => {
9195
+ try {
9196
+ return this._recursiveCloneAndMaskValuesOfKeys(source[prop], keys, seen);
9197
+ }
9198
+ catch (e) {
9199
+ return null;
9200
+ }
9201
+ })();
9202
+ return o;
9203
+ }, baseObject);
9204
+ }
9205
+ else {
9206
+ if (typeof source === "string") {
9207
+ let modifiedSource = source;
9208
+ for (const regEx of this.settings?.maskValuesRegEx || []) {
9209
+ modifiedSource = modifiedSource.replace(regEx, this.settings?.maskPlaceholder || "");
9210
+ }
9211
+ return modifiedSource;
9212
+ }
9213
+ return source;
9214
+ }
9215
+ }
9216
+ _recursiveCloneAndExecuteFunctions(source, seen = []) {
9217
+ if (this.isObjectOrArray(source) && seen.includes(source)) {
9218
+ return this.shallowCopy(source);
9219
+ }
9220
+ if (this.isObjectOrArray(source)) {
9221
+ seen.push(source);
9222
+ }
9223
+ if (Array.isArray(source)) {
9224
+ return source.map((item) => this._recursiveCloneAndExecuteFunctions(item, seen));
9225
+ }
9226
+ else if (source instanceof Date) {
9227
+ return new Date(source.getTime());
9228
+ }
9229
+ else if (this.isObject(source)) {
9230
+ return Object.getOwnPropertyNames(source).reduce((o, prop) => {
9231
+ const descriptor = Object.getOwnPropertyDescriptor(source, prop);
9232
+ if (descriptor) {
9233
+ Object.defineProperty(o, prop, descriptor);
9234
+ const value = source[prop];
9235
+ o[prop] = typeof value === "function" ? value() : this._recursiveCloneAndExecuteFunctions(value, seen);
9236
+ }
9237
+ return o;
9238
+ }, Object.create(Object.getPrototypeOf(source)));
9239
+ }
9240
+ else {
9241
+ return source;
9242
+ }
9243
+ }
9244
+ isObjectOrArray(value) {
9245
+ return typeof value === "object" && value !== null;
9246
+ }
9247
+ isObject(value) {
9248
+ return typeof value === "object" && !Array.isArray(value) && value !== null;
9249
+ }
9250
+ shallowCopy(source) {
9251
+ if (Array.isArray(source)) {
9252
+ return [...source];
9253
+ }
9254
+ else {
9255
+ return { ...source };
9256
+ }
9257
+ }
9258
+ _toLogObj(args, clonedLogObj = {}) {
9259
+ args = args?.map((arg) => (this.runtime.isError(arg) ? this._toErrorObject(arg) : arg));
9260
+ if (this.settings.argumentsArrayName == null) {
9261
+ if (args.length === 1 && !Array.isArray(args[0]) && this.runtime.isBuffer(args[0]) !== true && !(args[0] instanceof Date)) {
9262
+ clonedLogObj = typeof args[0] === "object" && args[0] != null ? { ...args[0], ...clonedLogObj } : { 0: args[0], ...clonedLogObj };
9263
+ }
9264
+ else {
9265
+ clonedLogObj = { ...clonedLogObj, ...args };
9266
+ }
9267
+ }
9268
+ else {
9269
+ clonedLogObj = {
9270
+ ...clonedLogObj,
9271
+ [this.settings.argumentsArrayName]: args,
9272
+ };
9273
+ }
9274
+ return clonedLogObj;
9275
+ }
9276
+ _cloneError(error) {
9277
+ const cloned = new error.constructor();
9278
+ Object.getOwnPropertyNames(error).forEach((key) => {
9279
+ cloned[key] = error[key];
9280
+ });
9281
+ return cloned;
9282
+ }
9283
+ _toErrorObject(error) {
9284
+ return {
9285
+ nativeError: error,
9286
+ name: error.name ?? "Error",
9287
+ message: error.message,
9288
+ stack: this.runtime.getErrorTrace(error),
9289
+ };
9290
+ }
9291
+ _addMetaToLogObj(logObj, logLevelId, logLevelName) {
9292
+ return {
9293
+ ...logObj,
9294
+ [this.settings.metaProperty]: this.runtime.getMeta(logLevelId, logLevelName, this.stackDepthLevel, this.settings.hideLogPositionForProduction, this.settings.name, this.settings.parentNames),
9295
+ };
9296
+ }
9297
+ _prettyFormatLogObjMeta(logObjMeta) {
9298
+ if (logObjMeta == null) {
9299
+ return "";
9300
+ }
9301
+ let template = this.settings.prettyLogTemplate;
9302
+ const placeholderValues = {};
9303
+ if (template.includes("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}")) {
9304
+ template = template.replace("{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}}:{{ms}}", "{{dateIsoStr}}");
9305
+ }
9306
+ else {
9307
+ if (this.settings.prettyLogTimeZone === "UTC") {
9308
+ placeholderValues["yyyy"] = logObjMeta?.date?.getUTCFullYear() ?? "----";
9309
+ placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMonth(), 2, 1);
9310
+ placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getUTCDate(), 2);
9311
+ placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getUTCHours(), 2);
9312
+ placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMinutes(), 2);
9313
+ placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getUTCSeconds(), 2);
9314
+ placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getUTCMilliseconds(), 3);
9315
+ }
9316
+ else {
9317
+ placeholderValues["yyyy"] = logObjMeta?.date?.getFullYear() ?? "----";
9318
+ placeholderValues["mm"] = formatNumberAddZeros(logObjMeta?.date?.getMonth(), 2, 1);
9319
+ placeholderValues["dd"] = formatNumberAddZeros(logObjMeta?.date?.getDate(), 2);
9320
+ placeholderValues["hh"] = formatNumberAddZeros(logObjMeta?.date?.getHours(), 2);
9321
+ placeholderValues["MM"] = formatNumberAddZeros(logObjMeta?.date?.getMinutes(), 2);
9322
+ placeholderValues["ss"] = formatNumberAddZeros(logObjMeta?.date?.getSeconds(), 2);
9323
+ placeholderValues["ms"] = formatNumberAddZeros(logObjMeta?.date?.getMilliseconds(), 3);
9324
+ }
9325
+ }
9326
+ const dateInSettingsTimeZone = this.settings.prettyLogTimeZone === "UTC" ? logObjMeta?.date : new Date(logObjMeta?.date?.getTime() - logObjMeta?.date?.getTimezoneOffset() * 60000);
9327
+ placeholderValues["rawIsoStr"] = dateInSettingsTimeZone?.toISOString();
9328
+ placeholderValues["dateIsoStr"] = dateInSettingsTimeZone?.toISOString().replace("T", " ").replace("Z", "");
9329
+ placeholderValues["logLevelName"] = logObjMeta?.logLevelName;
9330
+ placeholderValues["fileNameWithLine"] = logObjMeta?.path?.fileNameWithLine ?? "";
9331
+ placeholderValues["filePathWithLine"] = logObjMeta?.path?.filePathWithLine ?? "";
9332
+ placeholderValues["fullFilePath"] = logObjMeta?.path?.fullFilePath ?? "";
9333
+ let parentNamesString = this.settings.parentNames?.join(this.settings.prettyErrorParentNamesSeparator);
9334
+ parentNamesString = parentNamesString != null && logObjMeta?.name != null ? parentNamesString + this.settings.prettyErrorParentNamesSeparator : undefined;
9335
+ placeholderValues["name"] = logObjMeta?.name != null || parentNamesString != null ? (parentNamesString ?? "") + logObjMeta?.name ?? "" : "";
9336
+ placeholderValues["nameWithDelimiterPrefix"] =
9337
+ placeholderValues["name"].length > 0 ? this.settings.prettyErrorLoggerNameDelimiter + placeholderValues["name"] : "";
9338
+ placeholderValues["nameWithDelimiterSuffix"] =
9339
+ placeholderValues["name"].length > 0 ? placeholderValues["name"] + this.settings.prettyErrorLoggerNameDelimiter : "";
9340
+ if (this.settings.overwrite?.addPlaceholders != null) {
9341
+ this.settings.overwrite?.addPlaceholders(logObjMeta, placeholderValues);
9342
+ }
9343
+ return formatTemplate(this.settings, template, placeholderValues);
9344
+ }
9345
+ }
9346
+
9347
+ class Logger extends BaseLogger {
9348
+ constructor(settings, logObj) {
9349
+ const isBrowser = typeof window !== "undefined" && typeof document !== "undefined";
9350
+ const isBrowserBlinkEngine = isBrowser ? window.chrome !== undefined && window.CSS !== undefined && window.CSS.supports("color", "green") : false;
9351
+ const isSafari = isBrowser ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false;
9352
+ settings = settings || {};
9353
+ settings.stylePrettyLogs = settings.stylePrettyLogs && isBrowser && !isBrowserBlinkEngine ? false : settings.stylePrettyLogs;
9354
+ super(settings, logObj, isSafari ? 4 : 5);
9355
+ }
9356
+ log(logLevelId, logLevelName, ...args) {
9357
+ return super.log(logLevelId, logLevelName, ...args);
9358
+ }
9359
+ silly(...args) {
9360
+ return super.log(0, "SILLY", ...args);
9361
+ }
9362
+ trace(...args) {
9363
+ return super.log(1, "TRACE", ...args);
9364
+ }
9365
+ debug(...args) {
9366
+ return super.log(2, "DEBUG", ...args);
9367
+ }
9368
+ info(...args) {
9369
+ return super.log(3, "INFO", ...args);
9370
+ }
9371
+ warn(...args) {
9372
+ return super.log(4, "WARN", ...args);
9373
+ }
9374
+ error(...args) {
9375
+ return super.log(5, "ERROR", ...args);
9376
+ }
9377
+ fatal(...args) {
9378
+ return super.log(6, "FATAL", ...args);
9379
+ }
9380
+ getSubLogger(settings, logObj) {
9381
+ return super.getSubLogger(settings, logObj);
9382
+ }
9383
+ }
9384
+
9385
+ function transportFormatted(logMetaMarkup, logArgs, logErrors, settings) {
9386
+ const logErrorsStr = (logErrors.length > 0 && logArgs.length > 0 ? "\n" : "") + logErrors.join("\n");
9387
+ settings.prettyInspectOptions.colors = settings.stylePrettyLogs;
9388
+ console.log(logMetaMarkup, ...logArgs, logErrorsStr);
9389
+ }
9390
+ function formatMeta(logObjMeta) {
9391
+ if (!logObjMeta) {
9392
+ return '';
9393
+ }
9394
+ const { date, logLevelName } = logObjMeta;
9395
+ const year = date.getFullYear();
9396
+ const month = String(date.getMonth() + 1).padStart(2, '0');
9397
+ const day = String(date.getDate()).padStart(2, '0');
9398
+ const hours = String(date.getHours()).padStart(2, '0');
9399
+ const minutes = String(date.getMinutes()).padStart(2, '0');
9400
+ const seconds = String(date.getSeconds()).padStart(2, '0');
9401
+ const milliseconds = String(date.getMilliseconds()).padStart(3, '0');
9402
+ const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
9403
+ const loggerName = logObjMeta.name;
9404
+ return `${formattedDate} ${logLevelName} ${loggerName}`;
9405
+ }
9406
+ const logger$1 = new Logger({
9407
+ name: "ekoLogger",
9408
+ overwrite: {
9409
+ transportFormatted,
9410
+ formatMeta,
9411
+ }
9412
+ });
9413
+
8785
9414
  class OpenaiProvider {
8786
9415
  constructor(param, defaultModel, options) {
8787
9416
  this.defaultModel = 'gpt-4o';
@@ -8791,7 +9420,7 @@ class OpenaiProvider {
8791
9420
  if (typeof window !== 'undefined' &&
8792
9421
  typeof document !== 'undefined' &&
8793
9422
  (typeof param == 'string' || param.apiKey)) {
8794
- console.warn(`
9423
+ logger$1.warn(`
8795
9424
  ⚠️ Security Warning:
8796
9425
  DO NOT use API Keys in browser/frontend code!
8797
9426
  This will expose your credentials and may lead to unauthorized usage.
@@ -9065,7 +9694,7 @@ class OpenaiProvider {
9065
9694
  if (choice.finish_reason) {
9066
9695
  stop_reason = choice.finish_reason;
9067
9696
  if (currentToolUse) {
9068
- console.log("currentToolUse.accumulatedJson=", currentToolUse.accumulatedJson);
9697
+ logger$1.debug("currentToolUse.accumulatedJson=", currentToolUse.accumulatedJson);
9069
9698
  const toolCall = {
9070
9699
  id: currentToolUse.id,
9071
9700
  name: currentToolUse.name,
@@ -9159,7 +9788,7 @@ class ExecutionLogger {
9159
9788
  if (this.shouldLog(level)) {
9160
9789
  const timestamp = this.includeTimestamp ? new Date().toISOString() : '';
9161
9790
  const contextSummary = this.summarizeContext(context);
9162
- console.log(`${timestamp} [${level.toUpperCase()}] ${message}${contextSummary}`);
9791
+ logger$1.debug(`${timestamp} [${level.toUpperCase()}] ${message}${contextSummary}`);
9163
9792
  }
9164
9793
  }
9165
9794
  /**
@@ -9227,7 +9856,7 @@ class ExecutionLogger {
9227
9856
  * Logs an error that occurred during execution
9228
9857
  */
9229
9858
  logError(error, context) {
9230
- console.error(error);
9859
+ logger$1.error(error);
9231
9860
  try {
9232
9861
  this.log('error', `Error occurred: ${error.message}`, context);
9233
9862
  if (error.stack) {
@@ -9235,8 +9864,8 @@ class ExecutionLogger {
9235
9864
  }
9236
9865
  }
9237
9866
  catch (error) {
9238
- console.error("An error occurs when trying to log another error:");
9239
- console.error(error);
9867
+ logger$1.error("An error occurs when trying to log another error:");
9868
+ logger$1.error(error);
9240
9869
  }
9241
9870
  }
9242
9871
  extractFromDataUrl(dataUrl) {
@@ -9289,7 +9918,7 @@ class ExecutionLogger {
9289
9918
  return '[image]';
9290
9919
  }
9291
9920
  catch (error) {
9292
- console.warn('Failed to save debug image:', error);
9921
+ logger$1.warn('Failed to save debug image:', error);
9293
9922
  return '[image]';
9294
9923
  }
9295
9924
  }
@@ -9328,7 +9957,7 @@ class ExecutionLogger {
9328
9957
  const timestamp = this.includeTimestamp ? new Date().toISOString() : '';
9329
9958
  const contextSummary = this.summarizeContext(context);
9330
9959
  const formattedResult = await this.formatToolResult(result);
9331
- console.log(`${timestamp} [INFO] Tool executed: ${toolName}\n` +
9960
+ logger$1.debug(`${timestamp} [INFO] Tool executed: ${toolName}\n` +
9332
9961
  `${timestamp} [INFO] Tool result: ${formattedResult}${contextSummary}`);
9333
9962
  }
9334
9963
  }
@@ -9361,7 +9990,7 @@ ${JSON.stringify(nodeOutputs)}
9361
9990
  `,
9362
9991
  },
9363
9992
  ];
9364
- console.log(messages);
9993
+ logger$1.debug(messages);
9365
9994
  const params = {
9366
9995
  temperature: 0.7,
9367
9996
  maxTokens: 8192,
@@ -9392,9 +10021,9 @@ ${JSON.stringify(nodeOutputs)}
9392
10021
  }],
9393
10022
  toolChoice: { type: 'tool', name: 'summarize_workflow' },
9394
10023
  };
9395
- console.log(params);
10024
+ logger$1.debug(params);
9396
10025
  const response = await llmProvider.generateText(messages, params);
9397
- console.log(response);
10026
+ logger$1.debug(response);
9398
10027
  return {
9399
10028
  isSuccessful: contextVariables.get("__isSuccessful__"),
9400
10029
  summary: response.toolCalls[0].input.summary,
@@ -9493,9 +10122,7 @@ class WorkflowImpl {
9493
10122
  const action_executing_result = await node.action.execute(node.input, node.output, context);
9494
10123
  node.output.value = action_executing_result.nodeOutput;
9495
10124
  const action_reacts = action_executing_result.reacts;
9496
- console.log("debug `action_reacts`...");
9497
- console.log(action_reacts);
9498
- console.log("debug `action_reacts`...done");
10125
+ logger$1.debug("debug `action_reacts`...", action_reacts);
9499
10126
  executing.delete(nodeId);
9500
10127
  executed.add(nodeId);
9501
10128
  callback && await ((_d = (_c = callback.hooks).afterSubtask) === null || _d === void 0 ? void 0 : _d.call(_c, node, context, (_e = node.output) === null || _e === void 0 ? void 0 : _e.value));
@@ -9511,12 +10138,10 @@ class WorkflowImpl {
9511
10138
  workflowSummary = await summarizeWorkflow(this.llmProvider, this, this.variables, node_outputs);
9512
10139
  }
9513
10140
  else {
9514
- console.warn("WorkflowImpl.llmProvider is undefined, cannot generate workflow summary");
10141
+ logger$1.warn("WorkflowImpl.llmProvider is undefined, cannot generate workflow summary");
9515
10142
  }
9516
- // Special context variables
9517
- console.log("debug special context variables...");
9518
10143
  let workflowPayload = this.variables.get("workflow_transcript");
9519
- console.log(workflowPayload);
10144
+ logger$1.debug("workflowPayload", workflowPayload);
9520
10145
  if (!workflowPayload) {
9521
10146
  workflowPayload = workflowSummary === null || workflowSummary === void 0 ? void 0 : workflowSummary.payload;
9522
10147
  }
@@ -9639,13 +10264,11 @@ function createReturnTool(actionName, outputDescription, outputSchema) {
9639
10264
  description: 'The output value. Only provide a value if the previous tool result is not suitable for the output description. Otherwise, leave this as null.',
9640
10265
  },
9641
10266
  },
9642
- required: ['use_tool_result', 'value'],
10267
+ required: ['isSuccessful', 'use_tool_result', 'value'],
9643
10268
  },
9644
10269
  async execute(context, params) {
9645
10270
  context.variables.set(`__action_${actionName}_output`, params);
9646
- console.info('debug the output...');
9647
- console.log(params);
9648
- console.info('debug the output...done');
10271
+ console.debug('debug the output...', params);
9649
10272
  context.variables.set("__isSuccessful__", params.isSuccessful);
9650
10273
  return { success: true };
9651
10274
  },
@@ -9678,7 +10301,6 @@ class ActionImpl {
9678
10301
  let params_copy = JSON.parse(JSON.stringify(params));
9679
10302
  params_copy.tools = (_a = params_copy.tools) === null || _a === void 0 ? void 0 : _a.map(this.wrapToolInputSchema);
9680
10303
  while (!((_b = context.signal) === null || _b === void 0 ? void 0 : _b.aborted)) {
9681
- this.logger = context.logger;
9682
10304
  roundMessages = [];
9683
10305
  hasToolUse = false;
9684
10306
  response = null;
@@ -9701,8 +10323,13 @@ class ActionImpl {
9701
10323
  }
9702
10324
  },
9703
10325
  onToolUse: async (toolCall) => {
9704
- this.logger.log('info', `Assistant: ${assistantTextMessage}`);
9705
- this.logger.logToolExecution(toolCall.name, toolCall.input, context);
10326
+ logger$1.info("toolCall start", {
10327
+ assistant: assistantTextMessage,
10328
+ toolCall: {
10329
+ name: toolCall.name,
10330
+ input: toolCall.input,
10331
+ },
10332
+ });
9706
10333
  hasToolUse = true;
9707
10334
  const tool = toolMap.get(toolCall.name);
9708
10335
  if (!tool) {
@@ -9742,7 +10369,7 @@ class ActionImpl {
9742
10369
  };
9743
10370
  // Store the promise of tool execution
9744
10371
  toolExecutionPromise = (async () => {
9745
- var _a, _b, _c, _d;
10372
+ var _a, _b, _c, _d, _e, _f, _g;
9746
10373
  try {
9747
10374
  // beforeToolUse
9748
10375
  context.__skip = false;
@@ -9768,12 +10395,18 @@ class ActionImpl {
9768
10395
  // unwrap the toolCall
9769
10396
  let unwrapped = this.unwrapToolCall(toolCall);
9770
10397
  let input = unwrapped.toolCall.input;
9771
- console.log("unwrapped", unwrapped);
10398
+ logger$1.debug("unwrapped", unwrapped);
10399
+ if (unwrapped.thinking) {
10400
+ (_d = (_b = context.callback) === null || _b === void 0 ? void 0 : (_c = _b.hooks).onLlmMessage) === null || _d === void 0 ? void 0 : _d.call(_c, unwrapped.thinking);
10401
+ }
10402
+ else {
10403
+ logger$1.warn("LLM returns without `userSidePrompt`");
10404
+ }
9772
10405
  if (unwrapped.userSidePrompt) {
9773
- (_d = (_b = context.callback) === null || _b === void 0 ? void 0 : (_c = _b.hooks).onLlmMessageUserSidePrompt) === null || _d === void 0 ? void 0 : _d.call(_c, unwrapped.userSidePrompt, toolCall.name);
10406
+ (_g = (_e = context.callback) === null || _e === void 0 ? void 0 : (_f = _e.hooks).onLlmMessageUserSidePrompt) === null || _g === void 0 ? void 0 : _g.call(_f, unwrapped.userSidePrompt, toolCall.name);
9774
10407
  }
9775
10408
  else {
9776
- console.warn("LLM returns without `userSidePrompt`");
10409
+ logger$1.warn("LLM returns without `userSidePrompt`");
9777
10410
  }
9778
10411
  // Execute the tool
9779
10412
  let result = await tool.execute(context, input);
@@ -9811,15 +10444,30 @@ class ActionImpl {
9811
10444
  content: [resultContent],
9812
10445
  };
9813
10446
  toolResultMessage = resultMessage;
9814
- this.logger.logToolResult(tool.name, result, context);
10447
+ const truncate = (x) => {
10448
+ const s = JSON.stringify(x);
10449
+ const maxLength = 1000;
10450
+ if (s.length < maxLength) {
10451
+ return x;
10452
+ }
10453
+ else {
10454
+ return s.slice(0, maxLength) + "...(truncated)";
10455
+ }
10456
+ };
10457
+ logger$1.info("toolCall done", {
10458
+ toolCall: {
10459
+ name: tool.name,
10460
+ result: truncate(result),
10461
+ },
10462
+ });
9815
10463
  // Store tool results except for the return_output tool
9816
10464
  if (tool.name !== 'return_output') {
9817
10465
  this.toolResults.set(toolCall.id, resultContentText);
9818
10466
  }
9819
10467
  }
9820
10468
  catch (err) {
9821
- console.log('An error occurred when calling tool:');
9822
- console.log(err);
10469
+ logger$1.error('An error occurred when calling tool:');
10470
+ logger$1.error(err);
9823
10471
  const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';
9824
10472
  const errorResult = {
9825
10473
  role: 'user',
@@ -9833,7 +10481,6 @@ class ActionImpl {
9833
10481
  ],
9834
10482
  };
9835
10483
  toolResultMessage = errorResult;
9836
- this.logger.logError(err, context);
9837
10484
  }
9838
10485
  })();
9839
10486
  },
@@ -9841,8 +10488,8 @@ class ActionImpl {
9841
10488
  response = llmResponse;
9842
10489
  },
9843
10490
  onError: (error) => {
9844
- // console.error('Stream Error:', error);
9845
- // console.log('Last message array sent to LLM:', JSON.stringify(messages, null, 2));
10491
+ logger$1.error('Stream Error:', error);
10492
+ logger$1.debug('Last message array sent to LLM:', JSON.stringify(messages, null, 2));
9846
10493
  throw error;
9847
10494
  },
9848
10495
  };
@@ -9855,8 +10502,7 @@ class ActionImpl {
9855
10502
  await this.llmProvider.generateStream(messages, params_copy, handler);
9856
10503
  }
9857
10504
  catch (e) {
9858
- console.warn("an error occurs when LLM generate response");
9859
- console.warn(e);
10505
+ logger$1.warn("an error occurs when LLM generate response, retry...", e);
9860
10506
  continue;
9861
10507
  }
9862
10508
  // Wait for tool execution to complete if it was started
@@ -9911,7 +10557,7 @@ class ActionImpl {
9911
10557
  }
9912
10558
  const finalImageCount = this.countImages(messages);
9913
10559
  if (initialImageCount !== finalImageCount) {
9914
- this.logger.log('info', `Removed ${initialImageCount - finalImageCount} images from history`);
10560
+ logger$1.debug(`Removed ${initialImageCount - finalImageCount} images from history`);
9915
10561
  }
9916
10562
  }
9917
10563
  countImages(messages) {
@@ -9928,9 +10574,8 @@ class ActionImpl {
9928
10574
  return count;
9929
10575
  }
9930
10576
  async execute(input, output, context, outputSchema) {
9931
- var _a, _b, _c, _d, _e;
9932
- this.logger = context.logger;
9933
- console.log(`Executing action started: ${this.name}`);
10577
+ var _a, _b;
10578
+ logger$1.debug(`Executing action started: ${this.name}`);
9934
10579
  // Create return tool with output schema
9935
10580
  const returnTool = createReturnTool(this.name, output.description, outputSchema);
9936
10581
  // Create tool map combining context tools, action tools, and return tool
@@ -9956,7 +10601,12 @@ class ActionImpl {
9956
10601
  content: this.formatUserPrompt(this.name, this.description, this.tabs, existingTabs, patchs),
9957
10602
  },
9958
10603
  ];
9959
- this.logger.logActionStart(this.name, input, context);
10604
+ logger$1.info("action start", {
10605
+ action: {
10606
+ name: this.name,
10607
+ input,
10608
+ },
10609
+ });
9960
10610
  // Configure tool parameters
9961
10611
  const params = {
9962
10612
  ...this.llmConfig,
@@ -9973,19 +10623,15 @@ class ActionImpl {
9973
10623
  throw new Error('Workflow cancelled');
9974
10624
  }
9975
10625
  roundCount++;
9976
- this.logger.log('info', `Starting round ${roundCount} of ${this.maxRounds}`, context);
10626
+ logger$1.info(`Starting round ${roundCount} of ${this.maxRounds}`);
9977
10627
  const { response, hasToolUse, roundMessages } = await this.executeSingleRound(messages, params, toolMap, context);
9978
- if (response === null || response === void 0 ? void 0 : response.textContent) {
9979
- (_e = (_d = (_c = context.callback) === null || _c === void 0 ? void 0 : _c.hooks) === null || _d === void 0 ? void 0 : _d.onLlmMessage) === null || _e === void 0 ? void 0 : _e.call(_d, response.textContent);
9980
- }
9981
10628
  // Add round messages to conversation history
9982
10629
  messages.push(...roundMessages);
9983
- this.logger.log('debug', `Round ${roundCount} messages: ${JSON.stringify(roundMessages)}`, context);
9984
10630
  // Check termination conditions
9985
10631
  if (!hasToolUse && response) {
9986
10632
  // LLM sent a message without using tools - request explicit return
9987
- this.logger.log('info', `Assistant: ${response.textContent}`);
9988
- this.logger.log('warn', 'LLM sent a message without using tools; requesting explicit return');
10633
+ logger$1.info(`Assistant: ${response.textContent}`);
10634
+ logger$1.warn('LLM sent a message without using tools; requesting explicit return');
9989
10635
  const returnOnlyParams = {
9990
10636
  ...params,
9991
10637
  tools: [
@@ -10009,7 +10655,7 @@ class ActionImpl {
10009
10655
  }
10010
10656
  // If this is the last round, force an explicit return
10011
10657
  if (roundCount === this.maxRounds) {
10012
- this.logger.log('warn', 'Max rounds reached, requesting explicit return');
10658
+ logger$1.warn('Max rounds reached, requesting explicit return');
10013
10659
  const returnOnlyParams = {
10014
10660
  ...params,
10015
10661
  tools: [
@@ -10032,7 +10678,7 @@ class ActionImpl {
10032
10678
  const outputKey = `__action_${this.name}_output`;
10033
10679
  const outputParams = context.variables.get(outputKey);
10034
10680
  if (!outputParams) {
10035
- console.warn('outputParams is `undefined`, action return `{}`');
10681
+ logger$1.warn('outputParams is `undefined`, action return `{}`');
10036
10682
  return { nodeOutput: {}, reacts: messages };
10037
10683
  }
10038
10684
  context.variables.delete(outputKey);
@@ -10041,7 +10687,7 @@ class ActionImpl {
10041
10687
  ? Array.from(this.toolResults.values()).pop()
10042
10688
  : outputParams === null || outputParams === void 0 ? void 0 : outputParams.value;
10043
10689
  if (outputValue === undefined) {
10044
- console.warn('Action completed without returning a value');
10690
+ logger$1.warn('Action completed without returning a value');
10045
10691
  return { nodeOutput: {}, reacts: messages };
10046
10692
  }
10047
10693
  return { nodeOutput: outputValue, reacts: messages };
@@ -10049,7 +10695,7 @@ class ActionImpl {
10049
10695
  formatSystemPrompt() {
10050
10696
  const now = new Date();
10051
10697
  const formattedTime = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
10052
- console.log('Now is ' + formattedTime);
10698
+ logger$1.debug('Now is ' + formattedTime);
10053
10699
  return `You are an AI agent designed to automate browser tasks. Your goal is to accomplish the ultimate task following the rules. Now is ${formattedTime}.
10054
10700
 
10055
10701
  ## GENERIC:
@@ -10166,7 +10812,7 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10166
10812
  return data.map((entryWithScore) => entryWithScore.entry);
10167
10813
  }
10168
10814
  catch (error) {
10169
- console.error('Failed to fetch patches:', error);
10815
+ logger$1.error('Failed to fetch patches:', error);
10170
10816
  return [];
10171
10817
  }
10172
10818
  }
@@ -10183,10 +10829,10 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10183
10829
  // "type": "string",
10184
10830
  // "description": 'Your observation of the previous steps. Should start with "In the previous step, I\'ve ...".',
10185
10831
  // },
10186
- // thinking: {
10187
- // "type": "string",
10188
- // "description": 'Your thinking draft. Should start with "As observation before, now I should ...".',
10189
- // },
10832
+ thinking: {
10833
+ "type": "string",
10834
+ "description": 'Your thinking draft.',
10835
+ },
10190
10836
  userSidePrompt: {
10191
10837
  "type": "string",
10192
10838
  "description": 'The user-side prompt, showing why calling this tool. Should start with "I\'m calling the ...(tool) to ...(target)". Rememeber to keep the same language of the ultimate task.',
@@ -10196,7 +10842,7 @@ Navigation Bar or Menu Changes: After logging in, the navigation bar will includ
10196
10842
  required: [
10197
10843
  // comment for backup
10198
10844
  // "observation",
10199
- // "thinking",
10845
+ "thinking",
10200
10846
  "userSidePrompt",
10201
10847
  "toolCall",
10202
10848
  ],
@@ -10251,62 +10897,6 @@ The workflow must ensure proper dependencies between nodes.`,
10251
10897
  };
10252
10898
  }
10253
10899
 
10254
- const byteToHex = [];
10255
- for (let i = 0; i < 256; ++i) {
10256
- byteToHex.push((i + 0x100).toString(16).slice(1));
10257
- }
10258
- function unsafeStringify(arr, offset = 0) {
10259
- return (byteToHex[arr[offset + 0]] +
10260
- byteToHex[arr[offset + 1]] +
10261
- byteToHex[arr[offset + 2]] +
10262
- byteToHex[arr[offset + 3]] +
10263
- '-' +
10264
- byteToHex[arr[offset + 4]] +
10265
- byteToHex[arr[offset + 5]] +
10266
- '-' +
10267
- byteToHex[arr[offset + 6]] +
10268
- byteToHex[arr[offset + 7]] +
10269
- '-' +
10270
- byteToHex[arr[offset + 8]] +
10271
- byteToHex[arr[offset + 9]] +
10272
- '-' +
10273
- byteToHex[arr[offset + 10]] +
10274
- byteToHex[arr[offset + 11]] +
10275
- byteToHex[arr[offset + 12]] +
10276
- byteToHex[arr[offset + 13]] +
10277
- byteToHex[arr[offset + 14]] +
10278
- byteToHex[arr[offset + 15]]).toLowerCase();
10279
- }
10280
-
10281
- let getRandomValues;
10282
- const rnds8 = new Uint8Array(16);
10283
- function rng() {
10284
- if (!getRandomValues) {
10285
- if (typeof crypto === 'undefined' || !crypto.getRandomValues) {
10286
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
10287
- }
10288
- getRandomValues = crypto.getRandomValues.bind(crypto);
10289
- }
10290
- return getRandomValues(rnds8);
10291
- }
10292
-
10293
- const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
10294
- var native = { randomUUID };
10295
-
10296
- function v4(options, buf, offset) {
10297
- if (native.randomUUID && true && !options) {
10298
- return native.randomUUID();
10299
- }
10300
- options = options || {};
10301
- const rnds = options.random ?? options.rng?.() ?? rng();
10302
- if (rnds.length < 16) {
10303
- throw new Error('Random bytes length must be >= 16');
10304
- }
10305
- rnds[6] = (rnds[6] & 0x0f) | 0x40;
10306
- rnds[8] = (rnds[8] & 0x3f) | 0x80;
10307
- return unsafeStringify(rnds);
10308
- }
10309
-
10310
10900
  class WorkflowGenerator {
10311
10901
  constructor(llmProvider, toolRegistry) {
10312
10902
  this.llmProvider = llmProvider;
@@ -10380,12 +10970,10 @@ class WorkflowGenerator {
10380
10970
  });
10381
10971
  const workflowData = response.toolCalls[0].input.workflow;
10382
10972
  // debug
10383
- console.log("Debug the workflow...");
10384
- console.log({ ...workflowData });
10385
- console.log("Debug the workflow...Done");
10973
+ logger$1.debug("Debug the workflow...", { ...workflowData });
10386
10974
  // Generate a new UUID if not provided
10387
10975
  if (!workflowData.id) {
10388
- workflowData.id = v4();
10976
+ workflowData.id = uuid.v4();
10389
10977
  }
10390
10978
  return this.createFastWorkflowFromData(workflowData, ekoConfig);
10391
10979
  }
@@ -10400,7 +10988,7 @@ class WorkflowGenerator {
10400
10988
  const tools = nodeData.action.tools.filter((toolName) => {
10401
10989
  let hasTool = this.toolRegistry.hasTools([toolName]);
10402
10990
  if (!hasTool) {
10403
- console.warn(`The [${toolName}] tool does not exist.`);
10991
+ logger$1.warn(`The [${toolName}] tool does not exist.`);
10404
10992
  }
10405
10993
  return hasTool;
10406
10994
  }).map((toolName) => this.toolRegistry.getTool(toolName));
@@ -10554,15 +11142,17 @@ class Eko {
10554
11142
  this.prompt = "";
10555
11143
  this.tabs = [];
10556
11144
  this.workflow = undefined;
10557
- console.info("using Eko@" + "ffed3dcfde4a8b89072e1c33ad98532f7522fe47");
10558
- console.warn("this version is POC, should not used for production");
10559
11145
  this.llmProvider = LLMProviderFactory.buildLLMProvider(llmConfig);
10560
11146
  this.ekoConfig = this.buildEkoConfig(ekoConfig);
10561
11147
  this.registerTools();
11148
+ logger$1.info("using Eko@" + "eccb3dbbb41a09c67cd27351fbe1dd7491793d2b");
11149
+ }
11150
+ static getLogger() {
11151
+ return logger$1;
10562
11152
  }
10563
11153
  buildEkoConfig(ekoConfig) {
10564
11154
  if (!ekoConfig) {
10565
- console.warn("`ekoConfig` is missing when construct `Eko` instance");
11155
+ logger$1.warn("`ekoConfig` is missing when construct `Eko` instance");
10566
11156
  }
10567
11157
  const defaultEkoConfig = {
10568
11158
  workingWindowId: undefined,
@@ -10599,11 +11189,12 @@ class Eko {
10599
11189
  });
10600
11190
  }
10601
11191
  else {
10602
- console.warn("`ekoConfig.callback` is missing when construct `Eko` instance.");
11192
+ logger$1.warn("`ekoConfig.callback` is missing when construct `Eko` instance.");
10603
11193
  }
10604
11194
  tools.forEach(tool => this.toolRegistry.registerTool(tool));
10605
11195
  }
10606
11196
  async generate(prompt, tabs = [], param) {
11197
+ logger$1.info("workflow generating...");
10607
11198
  this.prompt = prompt;
10608
11199
  this.tabs = tabs;
10609
11200
  let toolRegistry = this.toolRegistry;
@@ -10622,12 +11213,12 @@ class Eko {
10622
11213
  const generator = new WorkflowGenerator(this.llmProvider, toolRegistry);
10623
11214
  const workflow = await generator.generateWorkflow(prompt, this.ekoConfig);
10624
11215
  this.workflowGeneratorMap.set(workflow, generator);
10625
- console.log("the workflow returned by generate");
10626
- console.log(workflow);
10627
11216
  this.workflow = workflow;
11217
+ logger$1.info("workflow generating...done");
10628
11218
  return workflow;
10629
11219
  }
10630
11220
  async execute(workflow) {
11221
+ logger$1.info("workflow executing...");
10631
11222
  let prompt = this.prompt;
10632
11223
  let description = "";
10633
11224
  workflow.nodes.forEach(node => {
@@ -10663,12 +11254,11 @@ class Eko {
10663
11254
  },
10664
11255
  ],
10665
11256
  };
10666
- console.log("debug the workflow...");
10667
- console.log(json);
10668
- console.log("debug the workflow...done");
10669
- console.log("debug the LLMProvider...");
10670
- console.log(this.llmProvider);
10671
- console.log("debug the LLMProvider...done");
11257
+ logger$1.debug("workflow", json);
11258
+ logger$1.debug("LLMProvider", {
11259
+ client: (typeof this.llmProvider.client),
11260
+ defaultModel: this.llmProvider.defaultModel,
11261
+ });
10672
11262
  const generator = new WorkflowGenerator(this.llmProvider, this.toolRegistry);
10673
11263
  workflow = await generator.generateWorkflowFromJson(json, this.ekoConfig);
10674
11264
  this.workflow = workflow;
@@ -10689,7 +11279,8 @@ class Eko {
10689
11279
  }
10690
11280
  }
10691
11281
  const result = await workflow.execute(this.ekoConfig.callback);
10692
- console.log(result);
11282
+ logger$1.debug(result);
11283
+ logger$1.info("workflow executing...done");
10693
11284
  return result;
10694
11285
  }
10695
11286
  async cancel() {
@@ -10966,8 +11557,6 @@ class WorkflowParser {
10966
11557
  * In this example, `tabs_get` is a mock implementation that logs the `tabId` before calling the original `chrome.tabs.get` method, and the same as `chrome.windows.create` method.
10967
11558
  */
10968
11559
  function createChromeApiProxy(mockClass) {
10969
- console.log("debug mockClass:");
10970
- console.log(mockClass);
10971
11560
  // Helper function to recursively create nested proxies
10972
11561
  function createNestedProxy(target, path) {
10973
11562
  return new Proxy(target, {