@elizaos/core 1.6.5-alpha.8 → 1.6.5-beta.0

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.
@@ -1438,295 +1438,6 @@ var require_dist2 = __commonJS((exports) => {
1438
1438
  }
1439
1439
  });
1440
1440
 
1441
- // ../../node_modules/retry/lib/retry_operation.js
1442
- var require_retry_operation = __commonJS((exports, module) => {
1443
- function RetryOperation(timeouts, options) {
1444
- if (typeof options === "boolean") {
1445
- options = { forever: options };
1446
- }
1447
- this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
1448
- this._timeouts = timeouts;
1449
- this._options = options || {};
1450
- this._maxRetryTime = options && options.maxRetryTime || Infinity;
1451
- this._fn = null;
1452
- this._errors = [];
1453
- this._attempts = 1;
1454
- this._operationTimeout = null;
1455
- this._operationTimeoutCb = null;
1456
- this._timeout = null;
1457
- this._operationStart = null;
1458
- this._timer = null;
1459
- if (this._options.forever) {
1460
- this._cachedTimeouts = this._timeouts.slice(0);
1461
- }
1462
- }
1463
- module.exports = RetryOperation;
1464
- RetryOperation.prototype.reset = function() {
1465
- this._attempts = 1;
1466
- this._timeouts = this._originalTimeouts.slice(0);
1467
- };
1468
- RetryOperation.prototype.stop = function() {
1469
- if (this._timeout) {
1470
- clearTimeout(this._timeout);
1471
- }
1472
- if (this._timer) {
1473
- clearTimeout(this._timer);
1474
- }
1475
- this._timeouts = [];
1476
- this._cachedTimeouts = null;
1477
- };
1478
- RetryOperation.prototype.retry = function(err) {
1479
- if (this._timeout) {
1480
- clearTimeout(this._timeout);
1481
- }
1482
- if (!err) {
1483
- return false;
1484
- }
1485
- var currentTime = new Date().getTime();
1486
- if (err && currentTime - this._operationStart >= this._maxRetryTime) {
1487
- this._errors.push(err);
1488
- this._errors.unshift(new Error("RetryOperation timeout occurred"));
1489
- return false;
1490
- }
1491
- this._errors.push(err);
1492
- var timeout = this._timeouts.shift();
1493
- if (timeout === undefined) {
1494
- if (this._cachedTimeouts) {
1495
- this._errors.splice(0, this._errors.length - 1);
1496
- timeout = this._cachedTimeouts.slice(-1);
1497
- } else {
1498
- return false;
1499
- }
1500
- }
1501
- var self2 = this;
1502
- this._timer = setTimeout(function() {
1503
- self2._attempts++;
1504
- if (self2._operationTimeoutCb) {
1505
- self2._timeout = setTimeout(function() {
1506
- self2._operationTimeoutCb(self2._attempts);
1507
- }, self2._operationTimeout);
1508
- if (self2._options.unref) {
1509
- self2._timeout.unref();
1510
- }
1511
- }
1512
- self2._fn(self2._attempts);
1513
- }, timeout);
1514
- if (this._options.unref) {
1515
- this._timer.unref();
1516
- }
1517
- return true;
1518
- };
1519
- RetryOperation.prototype.attempt = function(fn, timeoutOps) {
1520
- this._fn = fn;
1521
- if (timeoutOps) {
1522
- if (timeoutOps.timeout) {
1523
- this._operationTimeout = timeoutOps.timeout;
1524
- }
1525
- if (timeoutOps.cb) {
1526
- this._operationTimeoutCb = timeoutOps.cb;
1527
- }
1528
- }
1529
- var self2 = this;
1530
- if (this._operationTimeoutCb) {
1531
- this._timeout = setTimeout(function() {
1532
- self2._operationTimeoutCb();
1533
- }, self2._operationTimeout);
1534
- }
1535
- this._operationStart = new Date().getTime();
1536
- this._fn(this._attempts);
1537
- };
1538
- RetryOperation.prototype.try = function(fn) {
1539
- console.log("Using RetryOperation.try() is deprecated");
1540
- this.attempt(fn);
1541
- };
1542
- RetryOperation.prototype.start = function(fn) {
1543
- console.log("Using RetryOperation.start() is deprecated");
1544
- this.attempt(fn);
1545
- };
1546
- RetryOperation.prototype.start = RetryOperation.prototype.try;
1547
- RetryOperation.prototype.errors = function() {
1548
- return this._errors;
1549
- };
1550
- RetryOperation.prototype.attempts = function() {
1551
- return this._attempts;
1552
- };
1553
- RetryOperation.prototype.mainError = function() {
1554
- if (this._errors.length === 0) {
1555
- return null;
1556
- }
1557
- var counts = {};
1558
- var mainError = null;
1559
- var mainErrorCount = 0;
1560
- for (var i = 0;i < this._errors.length; i++) {
1561
- var error = this._errors[i];
1562
- var message = error.message;
1563
- var count = (counts[message] || 0) + 1;
1564
- counts[message] = count;
1565
- if (count >= mainErrorCount) {
1566
- mainError = error;
1567
- mainErrorCount = count;
1568
- }
1569
- }
1570
- return mainError;
1571
- };
1572
- });
1573
-
1574
- // ../../node_modules/retry/lib/retry.js
1575
- var require_retry = __commonJS((exports) => {
1576
- var RetryOperation = require_retry_operation();
1577
- exports.operation = function(options) {
1578
- var timeouts = exports.timeouts(options);
1579
- return new RetryOperation(timeouts, {
1580
- forever: options && (options.forever || options.retries === Infinity),
1581
- unref: options && options.unref,
1582
- maxRetryTime: options && options.maxRetryTime
1583
- });
1584
- };
1585
- exports.timeouts = function(options) {
1586
- if (options instanceof Array) {
1587
- return [].concat(options);
1588
- }
1589
- var opts = {
1590
- retries: 10,
1591
- factor: 2,
1592
- minTimeout: 1 * 1000,
1593
- maxTimeout: Infinity,
1594
- randomize: false
1595
- };
1596
- for (var key in options) {
1597
- opts[key] = options[key];
1598
- }
1599
- if (opts.minTimeout > opts.maxTimeout) {
1600
- throw new Error("minTimeout is greater than maxTimeout");
1601
- }
1602
- var timeouts = [];
1603
- for (var i = 0;i < opts.retries; i++) {
1604
- timeouts.push(this.createTimeout(i, opts));
1605
- }
1606
- if (options && options.forever && !timeouts.length) {
1607
- timeouts.push(this.createTimeout(i, opts));
1608
- }
1609
- timeouts.sort(function(a, b) {
1610
- return a - b;
1611
- });
1612
- return timeouts;
1613
- };
1614
- exports.createTimeout = function(attempt, opts) {
1615
- var random = opts.randomize ? Math.random() + 1 : 1;
1616
- var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
1617
- timeout = Math.min(timeout, opts.maxTimeout);
1618
- return timeout;
1619
- };
1620
- exports.wrap = function(obj, options, methods) {
1621
- if (options instanceof Array) {
1622
- methods = options;
1623
- options = null;
1624
- }
1625
- if (!methods) {
1626
- methods = [];
1627
- for (var key in obj) {
1628
- if (typeof obj[key] === "function") {
1629
- methods.push(key);
1630
- }
1631
- }
1632
- }
1633
- for (var i = 0;i < methods.length; i++) {
1634
- var method = methods[i];
1635
- var original = obj[method];
1636
- obj[method] = function retryWrapper(original2) {
1637
- var op = exports.operation(options);
1638
- var args = Array.prototype.slice.call(arguments, 1);
1639
- var callback = args.pop();
1640
- args.push(function(err) {
1641
- if (op.retry(err)) {
1642
- return;
1643
- }
1644
- if (err) {
1645
- arguments[0] = op.mainError();
1646
- }
1647
- callback.apply(this, arguments);
1648
- });
1649
- op.attempt(function() {
1650
- original2.apply(obj, args);
1651
- });
1652
- }.bind(obj, original);
1653
- obj[method].options = options;
1654
- }
1655
- };
1656
- });
1657
-
1658
- // ../../node_modules/p-retry/index.js
1659
- var require_p_retry = __commonJS((exports, module) => {
1660
- var retry = require_retry();
1661
- var networkErrorMsgs = [
1662
- "Failed to fetch",
1663
- "NetworkError when attempting to fetch resource.",
1664
- "The Internet connection appears to be offline.",
1665
- "Network request failed"
1666
- ];
1667
-
1668
- class AbortError extends Error {
1669
- constructor(message) {
1670
- super();
1671
- if (message instanceof Error) {
1672
- this.originalError = message;
1673
- ({ message } = message);
1674
- } else {
1675
- this.originalError = new Error(message);
1676
- this.originalError.stack = this.stack;
1677
- }
1678
- this.name = "AbortError";
1679
- this.message = message;
1680
- }
1681
- }
1682
- var decorateErrorWithCounts = (error, attemptNumber, options) => {
1683
- const retriesLeft = options.retries - (attemptNumber - 1);
1684
- error.attemptNumber = attemptNumber;
1685
- error.retriesLeft = retriesLeft;
1686
- return error;
1687
- };
1688
- var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage);
1689
- var pRetry = (input, options) => new Promise((resolve, reject) => {
1690
- options = {
1691
- onFailedAttempt: () => {},
1692
- retries: 10,
1693
- ...options
1694
- };
1695
- const operation = retry.operation(options);
1696
- operation.attempt(async (attemptNumber) => {
1697
- try {
1698
- resolve(await input(attemptNumber));
1699
- } catch (error) {
1700
- if (!(error instanceof Error)) {
1701
- reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`));
1702
- return;
1703
- }
1704
- if (error instanceof AbortError) {
1705
- operation.stop();
1706
- reject(error.originalError);
1707
- } else if (error instanceof TypeError && !isNetworkError(error.message)) {
1708
- operation.stop();
1709
- reject(error);
1710
- } else {
1711
- decorateErrorWithCounts(error, attemptNumber, options);
1712
- try {
1713
- await options.onFailedAttempt(error);
1714
- } catch (error2) {
1715
- reject(error2);
1716
- return;
1717
- }
1718
- if (!operation.retry(error)) {
1719
- reject(operation.mainError());
1720
- }
1721
- }
1722
- }
1723
- });
1724
- });
1725
- module.exports = pRetry;
1726
- module.exports.default = pRetry;
1727
- module.exports.AbortError = AbortError;
1728
- });
1729
-
1730
1441
  // ../../node_modules/eventemitter3/index.js
1731
1442
  var require_eventemitter3 = __commonJS((exports, module) => {
1732
1443
  var has = Object.prototype.hasOwnProperty;
@@ -9894,6 +9605,530 @@ var require_picocolors = __commonJS((exports, module) => {
9894
9605
  module.exports.createColors = createColors;
9895
9606
  });
9896
9607
 
9608
+ // ../../node_modules/fast-redact/lib/validator.js
9609
+ var require_validator = __commonJS((exports, module) => {
9610
+ module.exports = validator2;
9611
+ function validator2(opts = {}) {
9612
+ const {
9613
+ ERR_PATHS_MUST_BE_STRINGS = () => "fast-redact - Paths must be (non-empty) strings",
9614
+ ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})`
9615
+ } = opts;
9616
+ return function validate({ paths }) {
9617
+ paths.forEach((s) => {
9618
+ if (typeof s !== "string") {
9619
+ throw Error(ERR_PATHS_MUST_BE_STRINGS());
9620
+ }
9621
+ try {
9622
+ if (/〇/.test(s))
9623
+ throw Error();
9624
+ const expr = (s[0] === "[" ? "" : ".") + s.replace(/^\*/, "〇").replace(/\.\*/g, ".〇").replace(/\[\*\]/g, "[〇]");
9625
+ if (/\n|\r|;/.test(expr))
9626
+ throw Error();
9627
+ if (/\/\*/.test(expr))
9628
+ throw Error();
9629
+ Function(`
9630
+ 'use strict'
9631
+ const o = new Proxy({}, { get: () => o, set: () => { throw Error() } });
9632
+ const 〇 = null;
9633
+ o${expr}
9634
+ if ([o${expr}].length !== 1) throw Error()`)();
9635
+ } catch (e) {
9636
+ throw Error(ERR_INVALID_PATH(s));
9637
+ }
9638
+ });
9639
+ };
9640
+ }
9641
+ });
9642
+
9643
+ // ../../node_modules/fast-redact/lib/rx.js
9644
+ var require_rx = __commonJS((exports, module) => {
9645
+ module.exports = /[^.[\]]+|\[((?:.)*?)\]/g;
9646
+ });
9647
+
9648
+ // ../../node_modules/fast-redact/lib/parse.js
9649
+ var require_parse4 = __commonJS((exports, module) => {
9650
+ var rx = require_rx();
9651
+ module.exports = parse4;
9652
+ function parse4({ paths }) {
9653
+ const wildcards = [];
9654
+ var wcLen = 0;
9655
+ const secret = paths.reduce(function(o, strPath, ix) {
9656
+ var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, ""));
9657
+ const leadingBracket = strPath[0] === "[";
9658
+ path = path.map((p) => {
9659
+ if (p[0] === "[")
9660
+ return p.substr(1, p.length - 2);
9661
+ else
9662
+ return p;
9663
+ });
9664
+ const star = path.indexOf("*");
9665
+ if (star > -1) {
9666
+ const before = path.slice(0, star);
9667
+ const beforeStr = before.join(".");
9668
+ const after = path.slice(star + 1, path.length);
9669
+ const nested = after.length > 0;
9670
+ wcLen++;
9671
+ wildcards.push({
9672
+ before,
9673
+ beforeStr,
9674
+ after,
9675
+ nested
9676
+ });
9677
+ } else {
9678
+ o[strPath] = {
9679
+ path,
9680
+ val: undefined,
9681
+ precensored: false,
9682
+ circle: "",
9683
+ escPath: JSON.stringify(strPath),
9684
+ leadingBracket
9685
+ };
9686
+ }
9687
+ return o;
9688
+ }, {});
9689
+ return { wildcards, wcLen, secret };
9690
+ }
9691
+ });
9692
+
9693
+ // ../../node_modules/fast-redact/lib/redactor.js
9694
+ var require_redactor = __commonJS((exports, module) => {
9695
+ var rx = require_rx();
9696
+ module.exports = redactor;
9697
+ function redactor({ secret, serialize: serialize3, wcLen, strict, isCensorFct, censorFctTakesPath }, state) {
9698
+ const redact = Function("o", `
9699
+ if (typeof o !== 'object' || o == null) {
9700
+ ${strictImpl(strict, serialize3)}
9701
+ }
9702
+ const { censor, secret } = this
9703
+ const originalSecret = {}
9704
+ const secretKeys = Object.keys(secret)
9705
+ for (var i = 0; i < secretKeys.length; i++) {
9706
+ originalSecret[secretKeys[i]] = secret[secretKeys[i]]
9707
+ }
9708
+
9709
+ ${redactTmpl(secret, isCensorFct, censorFctTakesPath)}
9710
+ this.compileRestore()
9711
+ ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)}
9712
+ this.secret = originalSecret
9713
+ ${resultTmpl(serialize3)}
9714
+ `).bind(state);
9715
+ redact.state = state;
9716
+ if (serialize3 === false) {
9717
+ redact.restore = (o) => state.restore(o);
9718
+ }
9719
+ return redact;
9720
+ }
9721
+ function redactTmpl(secret, isCensorFct, censorFctTakesPath) {
9722
+ return Object.keys(secret).map((path) => {
9723
+ const { escPath, leadingBracket, path: arrPath } = secret[path];
9724
+ const skip = leadingBracket ? 1 : 0;
9725
+ const delim = leadingBracket ? "" : ".";
9726
+ const hops = [];
9727
+ var match;
9728
+ while ((match = rx.exec(path)) !== null) {
9729
+ const [, ix] = match;
9730
+ const { index, input } = match;
9731
+ if (index > skip)
9732
+ hops.push(input.substring(0, index - (ix ? 0 : 1)));
9733
+ }
9734
+ var existence = hops.map((p) => `o${delim}${p}`).join(" && ");
9735
+ if (existence.length === 0)
9736
+ existence += `o${delim}${path} != null`;
9737
+ else
9738
+ existence += ` && o${delim}${path} != null`;
9739
+ const circularDetection = `
9740
+ switch (true) {
9741
+ ${hops.reverse().map((p) => `
9742
+ case o${delim}${p} === censor:
9743
+ secret[${escPath}].circle = ${JSON.stringify(p)}
9744
+ break
9745
+ `).join(`
9746
+ `)}
9747
+ }
9748
+ `;
9749
+ const censorArgs = censorFctTakesPath ? `val, ${JSON.stringify(arrPath)}` : `val`;
9750
+ return `
9751
+ if (${existence}) {
9752
+ const val = o${delim}${path}
9753
+ if (val === censor) {
9754
+ secret[${escPath}].precensored = true
9755
+ } else {
9756
+ secret[${escPath}].val = val
9757
+ o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : "censor"}
9758
+ ${circularDetection}
9759
+ }
9760
+ }
9761
+ `;
9762
+ }).join(`
9763
+ `);
9764
+ }
9765
+ function dynamicRedactTmpl(hasWildcards, isCensorFct, censorFctTakesPath) {
9766
+ return hasWildcards === true ? `
9767
+ {
9768
+ const { wildcards, wcLen, groupRedact, nestedRedact } = this
9769
+ for (var i = 0; i < wcLen; i++) {
9770
+ const { before, beforeStr, after, nested } = wildcards[i]
9771
+ if (nested === true) {
9772
+ secret[beforeStr] = secret[beforeStr] || []
9773
+ nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath})
9774
+ } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath})
9775
+ }
9776
+ }
9777
+ ` : "";
9778
+ }
9779
+ function resultTmpl(serialize3) {
9780
+ return serialize3 === false ? `return o` : `
9781
+ var s = this.serialize(o)
9782
+ this.restore(o)
9783
+ return s
9784
+ `;
9785
+ }
9786
+ function strictImpl(strict, serialize3) {
9787
+ return strict === true ? `throw Error('fast-redact: primitives cannot be redacted')` : serialize3 === false ? `return o` : `return this.serialize(o)`;
9788
+ }
9789
+ });
9790
+
9791
+ // ../../node_modules/fast-redact/lib/modifiers.js
9792
+ var require_modifiers = __commonJS((exports, module) => {
9793
+ module.exports = {
9794
+ groupRedact,
9795
+ groupRestore,
9796
+ nestedRedact,
9797
+ nestedRestore
9798
+ };
9799
+ function groupRestore({ keys: keys2, values, target }) {
9800
+ if (target == null || typeof target === "string")
9801
+ return;
9802
+ const length = keys2.length;
9803
+ for (var i = 0;i < length; i++) {
9804
+ const k = keys2[i];
9805
+ target[k] = values[i];
9806
+ }
9807
+ }
9808
+ function groupRedact(o, path, censor, isCensorFct, censorFctTakesPath) {
9809
+ const target = get(o, path);
9810
+ if (target == null || typeof target === "string")
9811
+ return { keys: null, values: null, target, flat: true };
9812
+ const keys2 = Object.keys(target);
9813
+ const keysLength = keys2.length;
9814
+ const pathLength = path.length;
9815
+ const pathWithKey = censorFctTakesPath ? [...path] : undefined;
9816
+ const values = new Array(keysLength);
9817
+ for (var i = 0;i < keysLength; i++) {
9818
+ const key = keys2[i];
9819
+ values[i] = target[key];
9820
+ if (censorFctTakesPath) {
9821
+ pathWithKey[pathLength] = key;
9822
+ target[key] = censor(target[key], pathWithKey);
9823
+ } else if (isCensorFct) {
9824
+ target[key] = censor(target[key]);
9825
+ } else {
9826
+ target[key] = censor;
9827
+ }
9828
+ }
9829
+ return { keys: keys2, values, target, flat: true };
9830
+ }
9831
+ function nestedRestore(instructions) {
9832
+ for (let i = 0;i < instructions.length; i++) {
9833
+ const { target, path, value } = instructions[i];
9834
+ let current = target;
9835
+ for (let i2 = path.length - 1;i2 > 0; i2--) {
9836
+ current = current[path[i2]];
9837
+ }
9838
+ current[path[0]] = value;
9839
+ }
9840
+ }
9841
+ function nestedRedact(store, o, path, ns, censor, isCensorFct, censorFctTakesPath) {
9842
+ const target = get(o, path);
9843
+ if (target == null)
9844
+ return;
9845
+ const keys2 = Object.keys(target);
9846
+ const keysLength = keys2.length;
9847
+ for (var i = 0;i < keysLength; i++) {
9848
+ const key = keys2[i];
9849
+ specialSet(store, target, key, path, ns, censor, isCensorFct, censorFctTakesPath);
9850
+ }
9851
+ return store;
9852
+ }
9853
+ function has(obj, prop) {
9854
+ return obj !== undefined && obj !== null ? "hasOwn" in Object ? Object.hasOwn(obj, prop) : Object.prototype.hasOwnProperty.call(obj, prop) : false;
9855
+ }
9856
+ function specialSet(store, o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) {
9857
+ const afterPathLen = afterPath.length;
9858
+ const lastPathIndex = afterPathLen - 1;
9859
+ const originalKey = k;
9860
+ var i = -1;
9861
+ var n;
9862
+ var nv;
9863
+ var ov;
9864
+ var oov = null;
9865
+ var wc = null;
9866
+ var kIsWc;
9867
+ var wcov;
9868
+ var consecutive = false;
9869
+ var level = 0;
9870
+ var depth = 0;
9871
+ var redactPathCurrent = tree();
9872
+ ov = n = o[k];
9873
+ if (typeof n !== "object")
9874
+ return;
9875
+ while (n != null && ++i < afterPathLen) {
9876
+ depth += 1;
9877
+ k = afterPath[i];
9878
+ oov = ov;
9879
+ if (k !== "*" && !wc && !(typeof n === "object" && (k in n))) {
9880
+ break;
9881
+ }
9882
+ if (k === "*") {
9883
+ if (wc === "*") {
9884
+ consecutive = true;
9885
+ }
9886
+ wc = k;
9887
+ if (i !== lastPathIndex) {
9888
+ continue;
9889
+ }
9890
+ }
9891
+ if (wc) {
9892
+ const wcKeys = Object.keys(n);
9893
+ for (var j = 0;j < wcKeys.length; j++) {
9894
+ const wck = wcKeys[j];
9895
+ wcov = n[wck];
9896
+ kIsWc = k === "*";
9897
+ if (consecutive) {
9898
+ redactPathCurrent = node(redactPathCurrent, wck, depth);
9899
+ level = i;
9900
+ ov = iterateNthLevel(wcov, level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, o[originalKey], depth + 1);
9901
+ } else {
9902
+ if (kIsWc || typeof wcov === "object" && wcov !== null && k in wcov) {
9903
+ if (kIsWc) {
9904
+ ov = wcov;
9905
+ } else {
9906
+ ov = wcov[k];
9907
+ }
9908
+ nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor;
9909
+ if (kIsWc) {
9910
+ const rv = restoreInstr(node(redactPathCurrent, wck, depth), ov, o[originalKey]);
9911
+ store.push(rv);
9912
+ n[wck] = nv;
9913
+ } else {
9914
+ if (wcov[k] === nv) {} else if (nv === undefined && censor !== undefined || has(wcov, k) && nv === ov) {
9915
+ redactPathCurrent = node(redactPathCurrent, wck, depth);
9916
+ } else {
9917
+ redactPathCurrent = node(redactPathCurrent, wck, depth);
9918
+ const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, o[originalKey]);
9919
+ store.push(rv);
9920
+ wcov[k] = nv;
9921
+ }
9922
+ }
9923
+ }
9924
+ }
9925
+ }
9926
+ wc = null;
9927
+ } else {
9928
+ ov = n[k];
9929
+ redactPathCurrent = node(redactPathCurrent, k, depth);
9930
+ nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor;
9931
+ if (has(n, k) && nv === ov || nv === undefined && censor !== undefined) {} else {
9932
+ const rv = restoreInstr(redactPathCurrent, ov, o[originalKey]);
9933
+ store.push(rv);
9934
+ n[k] = nv;
9935
+ }
9936
+ n = n[k];
9937
+ }
9938
+ if (typeof n !== "object")
9939
+ break;
9940
+ if (ov === oov || typeof ov === "undefined") {}
9941
+ }
9942
+ }
9943
+ function get(o, p) {
9944
+ var i = -1;
9945
+ var l = p.length;
9946
+ var n = o;
9947
+ while (n != null && ++i < l) {
9948
+ n = n[p[i]];
9949
+ }
9950
+ return n;
9951
+ }
9952
+ function iterateNthLevel(wcov, level, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth) {
9953
+ if (level === 0) {
9954
+ if (kIsWc || typeof wcov === "object" && wcov !== null && k in wcov) {
9955
+ if (kIsWc) {
9956
+ ov = wcov;
9957
+ } else {
9958
+ ov = wcov[k];
9959
+ }
9960
+ nv = i !== lastPathIndex ? ov : isCensorFct ? censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov) : censor;
9961
+ if (kIsWc) {
9962
+ const rv = restoreInstr(redactPathCurrent, ov, parent);
9963
+ store.push(rv);
9964
+ n[wck] = nv;
9965
+ } else {
9966
+ if (wcov[k] === nv) {} else if (nv === undefined && censor !== undefined || has(wcov, k) && nv === ov) {} else {
9967
+ const rv = restoreInstr(node(redactPathCurrent, k, depth + 1), ov, parent);
9968
+ store.push(rv);
9969
+ wcov[k] = nv;
9970
+ }
9971
+ }
9972
+ }
9973
+ }
9974
+ for (const key in wcov) {
9975
+ if (typeof wcov[key] === "object") {
9976
+ redactPathCurrent = node(redactPathCurrent, key, depth);
9977
+ iterateNthLevel(wcov[key], level - 1, k, path, afterPath, censor, isCensorFct, censorFctTakesPath, originalKey, n, nv, ov, kIsWc, wck, i, lastPathIndex, redactPathCurrent, store, parent, depth + 1);
9978
+ }
9979
+ }
9980
+ }
9981
+ function tree() {
9982
+ return { parent: null, key: null, children: [], depth: 0 };
9983
+ }
9984
+ function node(parent, key, depth) {
9985
+ if (parent.depth === depth) {
9986
+ return node(parent.parent, key, depth);
9987
+ }
9988
+ var child = {
9989
+ parent,
9990
+ key,
9991
+ depth,
9992
+ children: []
9993
+ };
9994
+ parent.children.push(child);
9995
+ return child;
9996
+ }
9997
+ function restoreInstr(node2, value, target) {
9998
+ let current = node2;
9999
+ const path = [];
10000
+ do {
10001
+ path.push(current.key);
10002
+ current = current.parent;
10003
+ } while (current.parent != null);
10004
+ return { path, value, target };
10005
+ }
10006
+ });
10007
+
10008
+ // ../../node_modules/fast-redact/lib/restorer.js
10009
+ var require_restorer = __commonJS((exports, module) => {
10010
+ var { groupRestore, nestedRestore } = require_modifiers();
10011
+ module.exports = restorer;
10012
+ function restorer() {
10013
+ return function compileRestore() {
10014
+ if (this.restore) {
10015
+ this.restore.state.secret = this.secret;
10016
+ return;
10017
+ }
10018
+ const { secret, wcLen } = this;
10019
+ const paths = Object.keys(secret);
10020
+ const resetters = resetTmpl(secret, paths);
10021
+ const hasWildcards = wcLen > 0;
10022
+ const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret };
10023
+ this.restore = Function("o", restoreTmpl(resetters, paths, hasWildcards)).bind(state);
10024
+ this.restore.state = state;
10025
+ };
10026
+ }
10027
+ function resetTmpl(secret, paths) {
10028
+ return paths.map((path) => {
10029
+ const { circle, escPath, leadingBracket } = secret[path];
10030
+ const delim = leadingBracket ? "" : ".";
10031
+ const reset = circle ? `o.${circle} = secret[${escPath}].val` : `o${delim}${path} = secret[${escPath}].val`;
10032
+ const clear = `secret[${escPath}].val = undefined`;
10033
+ return `
10034
+ if (secret[${escPath}].val !== undefined) {
10035
+ try { ${reset} } catch (e) {}
10036
+ ${clear}
10037
+ }
10038
+ `;
10039
+ }).join("");
10040
+ }
10041
+ function restoreTmpl(resetters, paths, hasWildcards) {
10042
+ const dynamicReset = hasWildcards === true ? `
10043
+ const keys = Object.keys(secret)
10044
+ const len = keys.length
10045
+ for (var i = len - 1; i >= ${paths.length}; i--) {
10046
+ const k = keys[i]
10047
+ const o = secret[k]
10048
+ if (o) {
10049
+ if (o.flat === true) this.groupRestore(o)
10050
+ else this.nestedRestore(o)
10051
+ secret[k] = null
10052
+ }
10053
+ }
10054
+ ` : "";
10055
+ return `
10056
+ const secret = this.secret
10057
+ ${dynamicReset}
10058
+ ${resetters}
10059
+ return o
10060
+ `;
10061
+ }
10062
+ });
10063
+
10064
+ // ../../node_modules/fast-redact/lib/state.js
10065
+ var require_state = __commonJS((exports, module) => {
10066
+ module.exports = state;
10067
+ function state(o) {
10068
+ const {
10069
+ secret,
10070
+ censor,
10071
+ compileRestore,
10072
+ serialize: serialize3,
10073
+ groupRedact,
10074
+ nestedRedact,
10075
+ wildcards,
10076
+ wcLen
10077
+ } = o;
10078
+ const builder = [{ secret, censor, compileRestore }];
10079
+ if (serialize3 !== false)
10080
+ builder.push({ serialize: serialize3 });
10081
+ if (wcLen > 0)
10082
+ builder.push({ groupRedact, nestedRedact, wildcards, wcLen });
10083
+ return Object.assign(...builder);
10084
+ }
10085
+ });
10086
+
10087
+ // ../../node_modules/fast-redact/index.js
10088
+ var require_fast_redact = __commonJS((exports, module) => {
10089
+ var validator2 = require_validator();
10090
+ var parse4 = require_parse4();
10091
+ var redactor = require_redactor();
10092
+ var restorer = require_restorer();
10093
+ var { groupRedact, nestedRedact } = require_modifiers();
10094
+ var state = require_state();
10095
+ var rx = require_rx();
10096
+ var validate5 = validator2();
10097
+ var noop = (o) => o;
10098
+ noop.restore = noop;
10099
+ var DEFAULT_CENSOR = "[REDACTED]";
10100
+ fastRedact.rx = rx;
10101
+ fastRedact.validator = validator2;
10102
+ module.exports = fastRedact;
10103
+ function fastRedact(opts = {}) {
10104
+ const paths = Array.from(new Set(opts.paths || []));
10105
+ const serialize3 = "serialize" in opts ? opts.serialize === false ? opts.serialize : typeof opts.serialize === "function" ? opts.serialize : JSON.stringify : JSON.stringify;
10106
+ const remove = opts.remove;
10107
+ if (remove === true && serialize3 !== JSON.stringify) {
10108
+ throw Error("fast-redact – remove option may only be set when serializer is JSON.stringify");
10109
+ }
10110
+ const censor = remove === true ? undefined : ("censor" in opts) ? opts.censor : DEFAULT_CENSOR;
10111
+ const isCensorFct = typeof censor === "function";
10112
+ const censorFctTakesPath = isCensorFct && censor.length > 1;
10113
+ if (paths.length === 0)
10114
+ return serialize3 || noop;
10115
+ validate5({ paths, serialize: serialize3, censor });
10116
+ const { wildcards, wcLen, secret } = parse4({ paths, censor });
10117
+ const compileRestore = restorer();
10118
+ const strict = "strict" in opts ? opts.strict : true;
10119
+ return redactor({ secret, wcLen, serialize: serialize3, strict, isCensorFct, censorFctTakesPath }, state({
10120
+ secret,
10121
+ censor,
10122
+ compileRestore,
10123
+ serialize: serialize3,
10124
+ groupRedact,
10125
+ nestedRedact,
10126
+ wildcards,
10127
+ wcLen
10128
+ }));
10129
+ }
10130
+ });
10131
+
9897
10132
  // ../../node_modules/randombytes/index.js
9898
10133
  var require_randombytes = __commonJS((exports, module) => {
9899
10134
  module.exports = __require("crypto").randomBytes;
@@ -11605,31 +11840,31 @@ var require_pbkdf2 = __commonJS((exports) => {
11605
11840
 
11606
11841
  // ../../node_modules/browserify-cipher/index.js
11607
11842
  var require_browserify_cipher = __commonJS((exports) => {
11608
- var crypto = __require("crypto");
11609
- exports.createCipher = exports.Cipher = crypto.createCipher;
11610
- exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv;
11611
- exports.createDecipher = exports.Decipher = crypto.createDecipher;
11612
- exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv;
11613
- exports.listCiphers = exports.getCiphers = crypto.getCiphers;
11843
+ var crypto2 = __require("crypto");
11844
+ exports.createCipher = exports.Cipher = crypto2.createCipher;
11845
+ exports.createCipheriv = exports.Cipheriv = crypto2.createCipheriv;
11846
+ exports.createDecipher = exports.Decipher = crypto2.createDecipher;
11847
+ exports.createDecipheriv = exports.Decipheriv = crypto2.createDecipheriv;
11848
+ exports.listCiphers = exports.getCiphers = crypto2.getCiphers;
11614
11849
  });
11615
11850
 
11616
11851
  // ../../node_modules/diffie-hellman/index.js
11617
11852
  var require_diffie_hellman = __commonJS((exports) => {
11618
- var crypto = __require("crypto");
11619
- exports.DiffieHellmanGroup = crypto.DiffieHellmanGroup;
11620
- exports.createDiffieHellmanGroup = crypto.createDiffieHellmanGroup;
11621
- exports.getDiffieHellman = crypto.getDiffieHellman;
11622
- exports.createDiffieHellman = crypto.createDiffieHellman;
11623
- exports.DiffieHellman = crypto.DiffieHellman;
11853
+ var crypto2 = __require("crypto");
11854
+ exports.DiffieHellmanGroup = crypto2.DiffieHellmanGroup;
11855
+ exports.createDiffieHellmanGroup = crypto2.createDiffieHellmanGroup;
11856
+ exports.getDiffieHellman = crypto2.getDiffieHellman;
11857
+ exports.createDiffieHellman = crypto2.createDiffieHellman;
11858
+ exports.DiffieHellman = crypto2.DiffieHellman;
11624
11859
  });
11625
11860
 
11626
11861
  // ../../node_modules/browserify-sign/index.js
11627
11862
  var require_browserify_sign = __commonJS((exports) => {
11628
- var crypto = __require("crypto");
11629
- exports.createSign = crypto.createSign;
11630
- exports.Sign = crypto.Sign;
11631
- exports.createVerify = crypto.createVerify;
11632
- exports.Verify = crypto.Verify;
11863
+ var crypto2 = __require("crypto");
11864
+ exports.createSign = crypto2.createSign;
11865
+ exports.Sign = crypto2.Sign;
11866
+ exports.createVerify = crypto2.createVerify;
11867
+ exports.Verify = crypto2.Verify;
11633
11868
  });
11634
11869
 
11635
11870
  // ../../node_modules/elliptic/package.json
@@ -14736,15 +14971,15 @@ var require_brorand = __commonJS((exports, module) => {
14736
14971
  }
14737
14972
  } else {
14738
14973
  try {
14739
- crypto = __require("crypto");
14740
- if (typeof crypto.randomBytes !== "function")
14974
+ crypto2 = __require("crypto");
14975
+ if (typeof crypto2.randomBytes !== "function")
14741
14976
  throw new Error("Not supported");
14742
14977
  Rand.prototype._rand = function _rand(n) {
14743
- return crypto.randomBytes(n);
14978
+ return crypto2.randomBytes(n);
14744
14979
  };
14745
14980
  } catch (e) {}
14746
14981
  }
14747
- var crypto;
14982
+ var crypto2;
14748
14983
  });
14749
14984
 
14750
14985
  // ../../node_modules/elliptic/lib/elliptic/curve/base.js
@@ -21360,12 +21595,12 @@ var require_evp_bytestokey = __commonJS((exports, module) => {
21360
21595
 
21361
21596
  // ../../node_modules/browserify-aes/index.js
21362
21597
  var require_browserify_aes = __commonJS((exports) => {
21363
- var crypto = __require("crypto");
21364
- exports.createCipher = exports.Cipher = crypto.createCipher;
21365
- exports.createCipheriv = exports.Cipheriv = crypto.createCipheriv;
21366
- exports.createDecipher = exports.Decipher = crypto.createDecipher;
21367
- exports.createDecipheriv = exports.Decipheriv = crypto.createDecipheriv;
21368
- exports.listCiphers = exports.getCiphers = crypto.getCiphers;
21598
+ var crypto2 = __require("crypto");
21599
+ exports.createCipher = exports.Cipher = crypto2.createCipher;
21600
+ exports.createCipheriv = exports.Cipheriv = crypto2.createCipheriv;
21601
+ exports.createDecipher = exports.Decipher = crypto2.createDecipher;
21602
+ exports.createDecipheriv = exports.Decipheriv = crypto2.createDecipheriv;
21603
+ exports.listCiphers = exports.getCiphers = crypto2.getCiphers;
21369
21604
  });
21370
21605
 
21371
21606
  // ../../node_modules/parse-asn1/fixProc.js
@@ -24708,21 +24943,21 @@ var require_browser2 = __commonJS((exports) => {
24708
24943
 
24709
24944
  // ../../node_modules/public-encrypt/index.js
24710
24945
  var require_public_encrypt = __commonJS((exports) => {
24711
- var crypto = __require("crypto");
24712
- if (typeof crypto.publicEncrypt !== "function") {
24713
- crypto = require_browser2();
24946
+ var crypto2 = __require("crypto");
24947
+ if (typeof crypto2.publicEncrypt !== "function") {
24948
+ crypto2 = require_browser2();
24714
24949
  }
24715
- exports.publicEncrypt = crypto.publicEncrypt;
24716
- exports.privateDecrypt = crypto.privateDecrypt;
24717
- if (typeof crypto.privateEncrypt !== "function") {
24950
+ exports.publicEncrypt = crypto2.publicEncrypt;
24951
+ exports.privateDecrypt = crypto2.privateDecrypt;
24952
+ if (typeof crypto2.privateEncrypt !== "function") {
24718
24953
  exports.privateEncrypt = require_browser2().privateEncrypt;
24719
24954
  } else {
24720
- exports.privateEncrypt = crypto.privateEncrypt;
24955
+ exports.privateEncrypt = crypto2.privateEncrypt;
24721
24956
  }
24722
- if (typeof crypto.publicDecrypt !== "function") {
24957
+ if (typeof crypto2.publicDecrypt !== "function") {
24723
24958
  exports.publicDecrypt = require_browser2().publicDecrypt;
24724
24959
  } else {
24725
- exports.publicDecrypt = crypto.publicDecrypt;
24960
+ exports.publicDecrypt = crypto2.publicDecrypt;
24726
24961
  }
24727
24962
  });
24728
24963
 
@@ -24732,7 +24967,7 @@ var require_browser3 = __commonJS((exports) => {
24732
24967
  var randombytes = require_randombytes();
24733
24968
  var Buffer2 = safeBuffer.Buffer;
24734
24969
  var kBufferMaxLength = safeBuffer.kMaxLength;
24735
- var crypto = global.crypto || global.msCrypto;
24970
+ var crypto2 = global.crypto || global.msCrypto;
24736
24971
  var kMaxUint32 = Math.pow(2, 32) - 1;
24737
24972
  function assertOffset(offset, length) {
24738
24973
  if (typeof offset !== "number" || offset !== offset) {
@@ -24756,7 +24991,7 @@ var require_browser3 = __commonJS((exports) => {
24756
24991
  throw new RangeError("buffer too small");
24757
24992
  }
24758
24993
  }
24759
- if (crypto && crypto.getRandomValues || true) {
24994
+ if (crypto2 && crypto2.getRandomValues || true) {
24760
24995
  exports.randomFill = randomFill;
24761
24996
  exports.randomFillSync = randomFillSync2;
24762
24997
  } else {}
@@ -24814,10 +25049,10 @@ var require_browser3 = __commonJS((exports) => {
24814
25049
 
24815
25050
  // ../../node_modules/randomfill/index.js
24816
25051
  var require_randomfill = __commonJS((exports, module) => {
24817
- var crypto = __require("crypto");
24818
- if (typeof crypto.randomFill === "function" && typeof crypto.randomFillSync === "function") {
24819
- exports.randomFill = crypto.randomFill;
24820
- exports.randomFillSync = crypto.randomFillSync;
25052
+ var crypto2 = __require("crypto");
25053
+ if (typeof crypto2.randomFill === "function" && typeof crypto2.randomFillSync === "function") {
25054
+ exports.randomFill = crypto2.randomFill;
25055
+ exports.randomFillSync = crypto2.randomFillSync;
24821
25056
  } else {
24822
25057
  module.exports = require_browser3();
24823
25058
  }
@@ -25032,24 +25267,76 @@ var ModelType = {
25032
25267
  var MODEL_SETTINGS = {
25033
25268
  DEFAULT_MAX_TOKENS: "DEFAULT_MAX_TOKENS",
25034
25269
  DEFAULT_TEMPERATURE: "DEFAULT_TEMPERATURE",
25270
+ DEFAULT_TOP_P: "DEFAULT_TOP_P",
25271
+ DEFAULT_TOP_K: "DEFAULT_TOP_K",
25272
+ DEFAULT_MIN_P: "DEFAULT_MIN_P",
25273
+ DEFAULT_SEED: "DEFAULT_SEED",
25274
+ DEFAULT_REPETITION_PENALTY: "DEFAULT_REPETITION_PENALTY",
25035
25275
  DEFAULT_FREQUENCY_PENALTY: "DEFAULT_FREQUENCY_PENALTY",
25036
25276
  DEFAULT_PRESENCE_PENALTY: "DEFAULT_PRESENCE_PENALTY",
25037
25277
  TEXT_SMALL_MAX_TOKENS: "TEXT_SMALL_MAX_TOKENS",
25038
25278
  TEXT_SMALL_TEMPERATURE: "TEXT_SMALL_TEMPERATURE",
25279
+ TEXT_SMALL_TOP_P: "TEXT_SMALL_TOP_P",
25280
+ TEXT_SMALL_TOP_K: "TEXT_SMALL_TOP_K",
25281
+ TEXT_SMALL_MIN_P: "TEXT_SMALL_MIN_P",
25282
+ TEXT_SMALL_SEED: "TEXT_SMALL_SEED",
25283
+ TEXT_SMALL_REPETITION_PENALTY: "TEXT_SMALL_REPETITION_PENALTY",
25039
25284
  TEXT_SMALL_FREQUENCY_PENALTY: "TEXT_SMALL_FREQUENCY_PENALTY",
25040
25285
  TEXT_SMALL_PRESENCE_PENALTY: "TEXT_SMALL_PRESENCE_PENALTY",
25041
25286
  TEXT_LARGE_MAX_TOKENS: "TEXT_LARGE_MAX_TOKENS",
25042
25287
  TEXT_LARGE_TEMPERATURE: "TEXT_LARGE_TEMPERATURE",
25288
+ TEXT_LARGE_TOP_P: "TEXT_LARGE_TOP_P",
25289
+ TEXT_LARGE_TOP_K: "TEXT_LARGE_TOP_K",
25290
+ TEXT_LARGE_MIN_P: "TEXT_LARGE_MIN_P",
25291
+ TEXT_LARGE_SEED: "TEXT_LARGE_SEED",
25292
+ TEXT_LARGE_REPETITION_PENALTY: "TEXT_LARGE_REPETITION_PENALTY",
25043
25293
  TEXT_LARGE_FREQUENCY_PENALTY: "TEXT_LARGE_FREQUENCY_PENALTY",
25044
25294
  TEXT_LARGE_PRESENCE_PENALTY: "TEXT_LARGE_PRESENCE_PENALTY",
25045
25295
  OBJECT_SMALL_MAX_TOKENS: "OBJECT_SMALL_MAX_TOKENS",
25046
25296
  OBJECT_SMALL_TEMPERATURE: "OBJECT_SMALL_TEMPERATURE",
25297
+ OBJECT_SMALL_TOP_P: "OBJECT_SMALL_TOP_P",
25298
+ OBJECT_SMALL_TOP_K: "OBJECT_SMALL_TOP_K",
25299
+ OBJECT_SMALL_MIN_P: "OBJECT_SMALL_MIN_P",
25300
+ OBJECT_SMALL_SEED: "OBJECT_SMALL_SEED",
25301
+ OBJECT_SMALL_REPETITION_PENALTY: "OBJECT_SMALL_REPETITION_PENALTY",
25047
25302
  OBJECT_SMALL_FREQUENCY_PENALTY: "OBJECT_SMALL_FREQUENCY_PENALTY",
25048
25303
  OBJECT_SMALL_PRESENCE_PENALTY: "OBJECT_SMALL_PRESENCE_PENALTY",
25049
25304
  OBJECT_LARGE_MAX_TOKENS: "OBJECT_LARGE_MAX_TOKENS",
25050
25305
  OBJECT_LARGE_TEMPERATURE: "OBJECT_LARGE_TEMPERATURE",
25306
+ OBJECT_LARGE_TOP_P: "OBJECT_LARGE_TOP_P",
25307
+ OBJECT_LARGE_TOP_K: "OBJECT_LARGE_TOP_K",
25308
+ OBJECT_LARGE_MIN_P: "OBJECT_LARGE_MIN_P",
25309
+ OBJECT_LARGE_SEED: "OBJECT_LARGE_SEED",
25310
+ OBJECT_LARGE_REPETITION_PENALTY: "OBJECT_LARGE_REPETITION_PENALTY",
25051
25311
  OBJECT_LARGE_FREQUENCY_PENALTY: "OBJECT_LARGE_FREQUENCY_PENALTY",
25052
25312
  OBJECT_LARGE_PRESENCE_PENALTY: "OBJECT_LARGE_PRESENCE_PENALTY",
25313
+ TEXT_REASONING_SMALL_MAX_TOKENS: "TEXT_REASONING_SMALL_MAX_TOKENS",
25314
+ TEXT_REASONING_SMALL_TEMPERATURE: "TEXT_REASONING_SMALL_TEMPERATURE",
25315
+ TEXT_REASONING_SMALL_TOP_P: "TEXT_REASONING_SMALL_TOP_P",
25316
+ TEXT_REASONING_SMALL_TOP_K: "TEXT_REASONING_SMALL_TOP_K",
25317
+ TEXT_REASONING_SMALL_MIN_P: "TEXT_REASONING_SMALL_MIN_P",
25318
+ TEXT_REASONING_SMALL_SEED: "TEXT_REASONING_SMALL_SEED",
25319
+ TEXT_REASONING_SMALL_REPETITION_PENALTY: "TEXT_REASONING_SMALL_REPETITION_PENALTY",
25320
+ TEXT_REASONING_SMALL_FREQUENCY_PENALTY: "TEXT_REASONING_SMALL_FREQUENCY_PENALTY",
25321
+ TEXT_REASONING_SMALL_PRESENCE_PENALTY: "TEXT_REASONING_SMALL_PRESENCE_PENALTY",
25322
+ TEXT_REASONING_LARGE_MAX_TOKENS: "TEXT_REASONING_LARGE_MAX_TOKENS",
25323
+ TEXT_REASONING_LARGE_TEMPERATURE: "TEXT_REASONING_LARGE_TEMPERATURE",
25324
+ TEXT_REASONING_LARGE_TOP_P: "TEXT_REASONING_LARGE_TOP_P",
25325
+ TEXT_REASONING_LARGE_TOP_K: "TEXT_REASONING_LARGE_TOP_K",
25326
+ TEXT_REASONING_LARGE_MIN_P: "TEXT_REASONING_LARGE_MIN_P",
25327
+ TEXT_REASONING_LARGE_SEED: "TEXT_REASONING_LARGE_SEED",
25328
+ TEXT_REASONING_LARGE_REPETITION_PENALTY: "TEXT_REASONING_LARGE_REPETITION_PENALTY",
25329
+ TEXT_REASONING_LARGE_FREQUENCY_PENALTY: "TEXT_REASONING_LARGE_FREQUENCY_PENALTY",
25330
+ TEXT_REASONING_LARGE_PRESENCE_PENALTY: "TEXT_REASONING_LARGE_PRESENCE_PENALTY",
25331
+ TEXT_COMPLETION_MAX_TOKENS: "TEXT_COMPLETION_MAX_TOKENS",
25332
+ TEXT_COMPLETION_TEMPERATURE: "TEXT_COMPLETION_TEMPERATURE",
25333
+ TEXT_COMPLETION_TOP_P: "TEXT_COMPLETION_TOP_P",
25334
+ TEXT_COMPLETION_TOP_K: "TEXT_COMPLETION_TOP_K",
25335
+ TEXT_COMPLETION_MIN_P: "TEXT_COMPLETION_MIN_P",
25336
+ TEXT_COMPLETION_SEED: "TEXT_COMPLETION_SEED",
25337
+ TEXT_COMPLETION_REPETITION_PENALTY: "TEXT_COMPLETION_REPETITION_PENALTY",
25338
+ TEXT_COMPLETION_FREQUENCY_PENALTY: "TEXT_COMPLETION_FREQUENCY_PENALTY",
25339
+ TEXT_COMPLETION_PRESENCE_PENALTY: "TEXT_COMPLETION_PRESENCE_PENALTY",
25053
25340
  MODEL_MAX_TOKEN: "MODEL_MAX_TOKEN",
25054
25341
  MODEL_TEMPERATURE: "MODEL_TEMPERATURE",
25055
25342
  MODEL_FREQ_PENALTY: "MODEL_FREQ_PENALTY",
@@ -26036,6 +26323,8 @@ function mergeContent(firstContent, secondContent) {
26036
26323
  return secondContent;
26037
26324
  if (typeof secondContent === "string")
26038
26325
  return firstContent + secondContent;
26326
+ else if (Array.isArray(secondContent) && secondContent.length === 0)
26327
+ return firstContent;
26039
26328
  else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c)))
26040
26329
  return [{
26041
26330
  type: "text",
@@ -26212,9 +26501,10 @@ function _mergeDicts(left = {}, right = {}) {
26212
26501
  "name",
26213
26502
  "output_version",
26214
26503
  "model_provider"
26215
- ].includes(key))
26216
- merged[key] = value;
26217
- else
26504
+ ].includes(key)) {
26505
+ if (value)
26506
+ merged[key] = value;
26507
+ } else
26218
26508
  merged[key] += value;
26219
26509
  else if (typeof merged[key] === "object" && !Array.isArray(merged[key]))
26220
26510
  merged[key] = _mergeDicts(merged[key], value);
@@ -26275,9 +26565,17 @@ Right ${typeof right}`);
26275
26565
  Left ${left}
26276
26566
  Right ${right}`);
26277
26567
  }
26278
- var BaseMessageChunk = class extends BaseMessage {
26568
+ var BaseMessageChunk = class BaseMessageChunk2 extends BaseMessage {
26279
26569
  static isInstance(obj) {
26280
- return super.isInstance(obj) && "concat" in obj && typeof obj.concat === "function";
26570
+ if (!super.isInstance(obj))
26571
+ return false;
26572
+ let proto = Object.getPrototypeOf(obj);
26573
+ while (proto !== null) {
26574
+ if (proto === BaseMessageChunk2.prototype)
26575
+ return true;
26576
+ proto = Object.getPrototypeOf(proto);
26577
+ }
26578
+ return false;
26281
26579
  }
26282
26580
  };
26283
26581
 
@@ -26398,47 +26696,227 @@ function isToolMessageChunk(x) {
26398
26696
  }
26399
26697
 
26400
26698
  // ../../node_modules/@langchain/core/dist/utils/json.js
26401
- function parsePartialJson(s) {
26402
- if (typeof s === "undefined")
26403
- return null;
26699
+ function strictParsePartialJson(s) {
26404
26700
  try {
26405
26701
  return JSON.parse(s);
26406
26702
  } catch {}
26407
- let new_s = "";
26408
- const stack = [];
26409
- let isInsideString = false;
26410
- let escaped = false;
26411
- for (let char of s) {
26412
- if (isInsideString)
26413
- if (char === '"' && !escaped)
26414
- isInsideString = false;
26415
- else if (char === `
26416
- ` && !escaped)
26417
- char = "\\n";
26418
- else if (char === "\\")
26419
- escaped = !escaped;
26420
- else
26703
+ const buffer = s.trim();
26704
+ if (buffer.length === 0)
26705
+ throw new Error("Unexpected end of JSON input");
26706
+ let pos = 0;
26707
+ function skipWhitespace() {
26708
+ while (pos < buffer.length && /\s/.test(buffer[pos]))
26709
+ pos += 1;
26710
+ }
26711
+ function parseString() {
26712
+ if (buffer[pos] !== '"')
26713
+ throw new Error(`Expected '"' at position ${pos}, got '${buffer[pos]}'`);
26714
+ pos += 1;
26715
+ let result = "";
26716
+ let escaped = false;
26717
+ while (pos < buffer.length) {
26718
+ const char = buffer[pos];
26719
+ if (escaped) {
26720
+ if (char === "n")
26721
+ result += `
26722
+ `;
26723
+ else if (char === "t")
26724
+ result += "\t";
26725
+ else if (char === "r")
26726
+ result += "\r";
26727
+ else if (char === "\\")
26728
+ result += "\\";
26729
+ else if (char === '"')
26730
+ result += '"';
26731
+ else if (char === "b")
26732
+ result += "\b";
26733
+ else if (char === "f")
26734
+ result += "\f";
26735
+ else if (char === "/")
26736
+ result += "/";
26737
+ else if (char === "u") {
26738
+ const hex = buffer.substring(pos + 1, pos + 5);
26739
+ if (/^[0-9A-Fa-f]{0,4}$/.test(hex)) {
26740
+ if (hex.length === 4)
26741
+ result += String.fromCharCode(Number.parseInt(hex, 16));
26742
+ else
26743
+ result += `u${hex}`;
26744
+ pos += hex.length;
26745
+ } else
26746
+ throw new Error(`Invalid unicode escape sequence '\\u${hex}' at position ${pos}`);
26747
+ } else
26748
+ throw new Error(`Invalid escape sequence '\\${char}' at position ${pos}`);
26421
26749
  escaped = false;
26422
- else if (char === '"') {
26423
- isInsideString = true;
26424
- escaped = false;
26425
- } else if (char === "{")
26426
- stack.push("}");
26427
- else if (char === "[")
26428
- stack.push("]");
26429
- else if (char === "}" || char === "]")
26430
- if (stack && stack[stack.length - 1] === char)
26431
- stack.pop();
26432
- else
26433
- return null;
26434
- new_s += char;
26750
+ } else if (char === "\\")
26751
+ escaped = true;
26752
+ else if (char === '"') {
26753
+ pos += 1;
26754
+ return result;
26755
+ } else
26756
+ result += char;
26757
+ pos += 1;
26758
+ }
26759
+ if (escaped)
26760
+ result += "\\";
26761
+ return result;
26762
+ }
26763
+ function parseNumber() {
26764
+ const start = pos;
26765
+ let numStr = "";
26766
+ if (buffer[pos] === "-") {
26767
+ numStr += "-";
26768
+ pos += 1;
26769
+ }
26770
+ if (pos < buffer.length && buffer[pos] === "0") {
26771
+ numStr += "0";
26772
+ pos += 1;
26773
+ if (buffer[pos] >= "0" && buffer[pos] <= "9")
26774
+ throw new Error(`Invalid number at position ${start}`);
26775
+ }
26776
+ if (pos < buffer.length && buffer[pos] >= "1" && buffer[pos] <= "9")
26777
+ while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") {
26778
+ numStr += buffer[pos];
26779
+ pos += 1;
26780
+ }
26781
+ if (pos < buffer.length && buffer[pos] === ".") {
26782
+ numStr += ".";
26783
+ pos += 1;
26784
+ while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") {
26785
+ numStr += buffer[pos];
26786
+ pos += 1;
26787
+ }
26788
+ }
26789
+ if (pos < buffer.length && (buffer[pos] === "e" || buffer[pos] === "E")) {
26790
+ numStr += buffer[pos];
26791
+ pos += 1;
26792
+ if (pos < buffer.length && (buffer[pos] === "+" || buffer[pos] === "-")) {
26793
+ numStr += buffer[pos];
26794
+ pos += 1;
26795
+ }
26796
+ while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") {
26797
+ numStr += buffer[pos];
26798
+ pos += 1;
26799
+ }
26800
+ }
26801
+ if (numStr === "-")
26802
+ return -0;
26803
+ const num = Number.parseFloat(numStr);
26804
+ if (Number.isNaN(num)) {
26805
+ pos = start;
26806
+ throw new Error(`Invalid number '${numStr}' at position ${start}`);
26807
+ }
26808
+ return num;
26809
+ }
26810
+ function parseValue() {
26811
+ skipWhitespace();
26812
+ if (pos >= buffer.length)
26813
+ throw new Error(`Unexpected end of input at position ${pos}`);
26814
+ const char = buffer[pos];
26815
+ if (char === "{")
26816
+ return parseObject();
26817
+ if (char === "[")
26818
+ return parseArray();
26819
+ if (char === '"')
26820
+ return parseString();
26821
+ if ("null".startsWith(buffer.substring(pos, pos + 4))) {
26822
+ pos += Math.min(4, buffer.length - pos);
26823
+ return null;
26824
+ }
26825
+ if ("true".startsWith(buffer.substring(pos, pos + 4))) {
26826
+ pos += Math.min(4, buffer.length - pos);
26827
+ return true;
26828
+ }
26829
+ if ("false".startsWith(buffer.substring(pos, pos + 5))) {
26830
+ pos += Math.min(5, buffer.length - pos);
26831
+ return false;
26832
+ }
26833
+ if (char === "-" || char >= "0" && char <= "9")
26834
+ return parseNumber();
26835
+ throw new Error(`Unexpected character '${char}' at position ${pos}`);
26836
+ }
26837
+ function parseArray() {
26838
+ if (buffer[pos] !== "[")
26839
+ throw new Error(`Expected '[' at position ${pos}, got '${buffer[pos]}'`);
26840
+ const arr = [];
26841
+ pos += 1;
26842
+ skipWhitespace();
26843
+ if (pos >= buffer.length)
26844
+ return arr;
26845
+ if (buffer[pos] === "]") {
26846
+ pos += 1;
26847
+ return arr;
26848
+ }
26849
+ while (pos < buffer.length) {
26850
+ skipWhitespace();
26851
+ if (pos >= buffer.length)
26852
+ return arr;
26853
+ arr.push(parseValue());
26854
+ skipWhitespace();
26855
+ if (pos >= buffer.length)
26856
+ return arr;
26857
+ if (buffer[pos] === "]") {
26858
+ pos += 1;
26859
+ return arr;
26860
+ } else if (buffer[pos] === ",") {
26861
+ pos += 1;
26862
+ continue;
26863
+ }
26864
+ throw new Error(`Expected ',' or ']' at position ${pos}, got '${buffer[pos]}'`);
26865
+ }
26866
+ return arr;
26867
+ }
26868
+ function parseObject() {
26869
+ if (buffer[pos] !== "{")
26870
+ throw new Error(`Expected '{' at position ${pos}, got '${buffer[pos]}'`);
26871
+ const obj = {};
26872
+ pos += 1;
26873
+ skipWhitespace();
26874
+ if (pos >= buffer.length)
26875
+ return obj;
26876
+ if (buffer[pos] === "}") {
26877
+ pos += 1;
26878
+ return obj;
26879
+ }
26880
+ while (pos < buffer.length) {
26881
+ skipWhitespace();
26882
+ if (pos >= buffer.length)
26883
+ return obj;
26884
+ const key = parseString();
26885
+ skipWhitespace();
26886
+ if (pos >= buffer.length)
26887
+ return obj;
26888
+ if (buffer[pos] !== ":")
26889
+ throw new Error(`Expected ':' at position ${pos}, got '${buffer[pos]}'`);
26890
+ pos += 1;
26891
+ skipWhitespace();
26892
+ if (pos >= buffer.length)
26893
+ return obj;
26894
+ obj[key] = parseValue();
26895
+ skipWhitespace();
26896
+ if (pos >= buffer.length)
26897
+ return obj;
26898
+ if (buffer[pos] === "}") {
26899
+ pos += 1;
26900
+ return obj;
26901
+ } else if (buffer[pos] === ",") {
26902
+ pos += 1;
26903
+ continue;
26904
+ }
26905
+ throw new Error(`Expected ',' or '}' at position ${pos}, got '${buffer[pos]}'`);
26906
+ }
26907
+ return obj;
26435
26908
  }
26436
- if (isInsideString)
26437
- new_s += '"';
26438
- for (let i = stack.length - 1;i >= 0; i -= 1)
26439
- new_s += stack[i];
26909
+ const value = parseValue();
26910
+ skipWhitespace();
26911
+ if (pos < buffer.length)
26912
+ throw new Error(`Unexpected character '${buffer[pos]}' at position ${pos}`);
26913
+ return value;
26914
+ }
26915
+ function parsePartialJson(s) {
26440
26916
  try {
26441
- return JSON.parse(new_s);
26917
+ if (typeof s === "undefined")
26918
+ return null;
26919
+ return strictParsePartialJson(s);
26442
26920
  } catch {
26443
26921
  return null;
26444
26922
  }
@@ -26911,59 +27389,12 @@ var AIMessageChunk = class extends BaseMessageChunk {
26911
27389
  tool_call_chunks: [],
26912
27390
  usage_metadata: fields.usage_metadata !== undefined ? fields.usage_metadata : undefined
26913
27391
  };
26914
- else {
26915
- const toolCallChunks = fields.tool_call_chunks ?? [];
26916
- const groupedToolCallChunks = toolCallChunks.reduce((acc, chunk) => {
26917
- const matchedChunkIndex = acc.findIndex(([match]) => {
26918
- if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== undefined)
26919
- return chunk.id === match.id && chunk.index === match.index;
26920
- if ("id" in chunk && chunk.id)
26921
- return chunk.id === match.id;
26922
- if ("index" in chunk && chunk.index !== undefined)
26923
- return chunk.index === match.index;
26924
- return false;
26925
- });
26926
- if (matchedChunkIndex !== -1)
26927
- acc[matchedChunkIndex].push(chunk);
26928
- else
26929
- acc.push([chunk]);
26930
- return acc;
26931
- }, []);
26932
- const toolCalls = [];
26933
- const invalidToolCalls = [];
26934
- for (const chunks of groupedToolCallChunks) {
26935
- let parsedArgs = null;
26936
- const name = chunks[0]?.name ?? "";
26937
- const joinedArgs = chunks.map((c) => c.args || "").join("");
26938
- const argsStr = joinedArgs.length ? joinedArgs : "{}";
26939
- const id = chunks[0]?.id;
26940
- try {
26941
- parsedArgs = parsePartialJson(argsStr);
26942
- if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs))
26943
- throw new Error("Malformed tool call chunk args.");
26944
- toolCalls.push({
26945
- name,
26946
- args: parsedArgs,
26947
- id,
26948
- type: "tool_call"
26949
- });
26950
- } catch {
26951
- invalidToolCalls.push({
26952
- name,
26953
- args: argsStr,
26954
- id,
26955
- error: "Malformed args.",
26956
- type: "invalid_tool_call"
26957
- });
26958
- }
26959
- }
27392
+ else
26960
27393
  initParams = {
26961
27394
  ...fields,
26962
- tool_calls: toolCalls,
26963
- invalid_tool_calls: invalidToolCalls,
27395
+ ...collapseToolCallChunks(fields.tool_call_chunks ?? []),
26964
27396
  usage_metadata: fields.usage_metadata !== undefined ? fields.usage_metadata : undefined
26965
27397
  };
26966
- }
26967
27398
  super(initParams);
26968
27399
  this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks;
26969
27400
  this.tool_calls = initParams.tool_calls ?? this.tool_calls;
@@ -27062,6 +27493,57 @@ function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") {
27062
27493
  return string_messages.join(`
27063
27494
  `);
27064
27495
  }
27496
+ function collapseToolCallChunks(chunks) {
27497
+ const groupedToolCallChunks = chunks.reduce((acc, chunk) => {
27498
+ const matchedChunkIndex = acc.findIndex(([match]) => {
27499
+ if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== undefined)
27500
+ return chunk.id === match.id && chunk.index === match.index;
27501
+ if ("id" in chunk && chunk.id)
27502
+ return chunk.id === match.id;
27503
+ if ("index" in chunk && chunk.index !== undefined)
27504
+ return chunk.index === match.index;
27505
+ return false;
27506
+ });
27507
+ if (matchedChunkIndex !== -1)
27508
+ acc[matchedChunkIndex].push(chunk);
27509
+ else
27510
+ acc.push([chunk]);
27511
+ return acc;
27512
+ }, []);
27513
+ const toolCalls = [];
27514
+ const invalidToolCalls = [];
27515
+ for (const chunks$1 of groupedToolCallChunks) {
27516
+ let parsedArgs = null;
27517
+ const name = chunks$1[0]?.name ?? "";
27518
+ const joinedArgs = chunks$1.map((c) => c.args || "").join("").trim();
27519
+ const argsStr = joinedArgs.length ? joinedArgs : "{}";
27520
+ const id = chunks$1[0]?.id;
27521
+ try {
27522
+ parsedArgs = parsePartialJson(argsStr);
27523
+ if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs))
27524
+ throw new Error("Malformed tool call chunk args.");
27525
+ toolCalls.push({
27526
+ name,
27527
+ args: parsedArgs,
27528
+ id,
27529
+ type: "tool_call"
27530
+ });
27531
+ } catch {
27532
+ invalidToolCalls.push({
27533
+ name,
27534
+ args: argsStr,
27535
+ id,
27536
+ error: "Malformed args.",
27537
+ type: "invalid_tool_call"
27538
+ });
27539
+ }
27540
+ }
27541
+ return {
27542
+ tool_call_chunks: chunks,
27543
+ tool_calls: toolCalls,
27544
+ invalid_tool_calls: invalidToolCalls
27545
+ };
27546
+ }
27065
27547
 
27066
27548
  // ../../node_modules/@langchain/core/dist/utils/env.js
27067
27549
  var env_exports = {};
@@ -27311,7 +27793,6 @@ function warnOnce(message) {
27311
27793
 
27312
27794
  // ../../node_modules/langsmith/dist/utils/_uuid.js
27313
27795
  var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
27314
- var UUID7_WARNING_EMITTED = false;
27315
27796
  function assertUuid(str, which) {
27316
27797
  if (!UUID_REGEX.test(str)) {
27317
27798
  const msg = which !== undefined ? `Invalid UUID for ${which}: ${str}` : `Invalid UUID: ${str}`;
@@ -27323,22 +27804,8 @@ function uuid7FromTime(timestamp) {
27323
27804
  const msecs = typeof timestamp === "string" ? Date.parse(timestamp) : timestamp;
27324
27805
  return v72({ msecs, seq: 0 });
27325
27806
  }
27326
- function getUuidVersion(uuidStr) {
27327
- if (!UUID_REGEX.test(uuidStr)) {
27328
- return null;
27329
- }
27330
- const versionChar = uuidStr[14];
27331
- return parseInt(versionChar, 16);
27332
- }
27333
- function warnIfNotUuidV7(uuidStr, _idType) {
27334
- const version3 = getUuidVersion(uuidStr);
27335
- if (version3 !== null && version3 !== 7 && !UUID7_WARNING_EMITTED) {
27336
- UUID7_WARNING_EMITTED = true;
27337
- warnOnce(`LangSmith now uses UUID v7 for run and trace identifiers. ` + `This warning appears when passing custom IDs. ` + `Please use: import { uuidv7 } from 'langsmith'; const id = uuidv7(); ` + `Future versions will require UUID v7.`);
27338
- }
27339
- }
27340
27807
  // ../../node_modules/langsmith/dist/index.js
27341
- var __version__ = "0.3.80";
27808
+ var __version__ = "0.3.82";
27342
27809
 
27343
27810
  // ../../node_modules/langsmith/dist/utils/env.js
27344
27811
  var globalEnv;
@@ -27925,10 +28392,213 @@ class LangSmithToOTELTranslator {
27925
28392
  }
27926
28393
  }
27927
28394
 
28395
+ // ../../node_modules/langsmith/dist/utils/is-network-error/index.js
28396
+ var objectToString = Object.prototype.toString;
28397
+ var isError = (value) => objectToString.call(value) === "[object Error]";
28398
+ var errorMessages = new Set([
28399
+ "network error",
28400
+ "Failed to fetch",
28401
+ "NetworkError when attempting to fetch resource.",
28402
+ "The Internet connection appears to be offline.",
28403
+ "Network request failed",
28404
+ "fetch failed",
28405
+ "terminated",
28406
+ " A network error occurred.",
28407
+ "Network connection lost"
28408
+ ]);
28409
+ function isNetworkError(error) {
28410
+ const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
28411
+ if (!isValid) {
28412
+ return false;
28413
+ }
28414
+ const { message, stack } = error;
28415
+ if (message === "Load failed") {
28416
+ return stack === undefined || "__sentry_captured__" in error;
28417
+ }
28418
+ if (message.startsWith("error sending request for url")) {
28419
+ return true;
28420
+ }
28421
+ return errorMessages.has(message);
28422
+ }
28423
+
28424
+ // ../../node_modules/langsmith/dist/utils/p-retry/index.js
28425
+ function validateRetries(retries) {
28426
+ if (typeof retries === "number") {
28427
+ if (retries < 0) {
28428
+ throw new TypeError("Expected `retries` to be a non-negative number.");
28429
+ }
28430
+ if (Number.isNaN(retries)) {
28431
+ throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
28432
+ }
28433
+ } else if (retries !== undefined) {
28434
+ throw new TypeError("Expected `retries` to be a number or Infinity.");
28435
+ }
28436
+ }
28437
+ function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) {
28438
+ if (value === undefined) {
28439
+ return;
28440
+ }
28441
+ if (typeof value !== "number" || Number.isNaN(value)) {
28442
+ throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
28443
+ }
28444
+ if (!allowInfinity && !Number.isFinite(value)) {
28445
+ throw new TypeError(`Expected \`${name}\` to be a finite number.`);
28446
+ }
28447
+ if (value < min) {
28448
+ throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`);
28449
+ }
28450
+ }
28451
+
28452
+ class AbortError extends Error {
28453
+ constructor(message) {
28454
+ super();
28455
+ if (message instanceof Error) {
28456
+ this.originalError = message;
28457
+ ({ message } = message);
28458
+ } else {
28459
+ this.originalError = new Error(message);
28460
+ this.originalError.stack = this.stack;
28461
+ }
28462
+ this.name = "AbortError";
28463
+ this.message = message;
28464
+ }
28465
+ }
28466
+ function calculateDelay(retriesConsumed, options) {
28467
+ const attempt = Math.max(1, retriesConsumed + 1);
28468
+ const random = options.randomize ? Math.random() + 1 : 1;
28469
+ let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
28470
+ timeout = Math.min(timeout, options.maxTimeout);
28471
+ return timeout;
28472
+ }
28473
+ function calculateRemainingTime(start, max) {
28474
+ if (!Number.isFinite(max)) {
28475
+ return max;
28476
+ }
28477
+ return max - (performance.now() - start);
28478
+ }
28479
+ async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) {
28480
+ const normalizedError = error instanceof Error ? error : new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
28481
+ if (normalizedError instanceof AbortError) {
28482
+ throw normalizedError.originalError;
28483
+ }
28484
+ const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
28485
+ const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
28486
+ const context = Object.freeze({
28487
+ error: normalizedError,
28488
+ attemptNumber,
28489
+ retriesLeft,
28490
+ retriesConsumed
28491
+ });
28492
+ await options.onFailedAttempt(context);
28493
+ if (calculateRemainingTime(startTime, maxRetryTime) <= 0) {
28494
+ throw normalizedError;
28495
+ }
28496
+ const consumeRetry = await options.shouldConsumeRetry(context);
28497
+ const remainingTime = calculateRemainingTime(startTime, maxRetryTime);
28498
+ if (remainingTime <= 0 || retriesLeft <= 0) {
28499
+ throw normalizedError;
28500
+ }
28501
+ if (normalizedError instanceof TypeError && !isNetworkError(normalizedError)) {
28502
+ if (consumeRetry) {
28503
+ throw normalizedError;
28504
+ }
28505
+ options.signal?.throwIfAborted();
28506
+ return false;
28507
+ }
28508
+ if (!await options.shouldRetry(context)) {
28509
+ throw normalizedError;
28510
+ }
28511
+ if (!consumeRetry) {
28512
+ options.signal?.throwIfAborted();
28513
+ return false;
28514
+ }
28515
+ const delayTime = calculateDelay(retriesConsumed, options);
28516
+ const finalDelay = Math.min(delayTime, remainingTime);
28517
+ if (finalDelay > 0) {
28518
+ await new Promise((resolve, reject) => {
28519
+ const onAbort = () => {
28520
+ clearTimeout(timeoutToken);
28521
+ options.signal?.removeEventListener("abort", onAbort);
28522
+ reject(options.signal.reason);
28523
+ };
28524
+ const timeoutToken = setTimeout(() => {
28525
+ options.signal?.removeEventListener("abort", onAbort);
28526
+ resolve();
28527
+ }, finalDelay);
28528
+ if (options.unref) {
28529
+ timeoutToken.unref?.();
28530
+ }
28531
+ options.signal?.addEventListener("abort", onAbort, { once: true });
28532
+ });
28533
+ }
28534
+ options.signal?.throwIfAborted();
28535
+ return true;
28536
+ }
28537
+ async function pRetry(input, options = {}) {
28538
+ options = { ...options };
28539
+ validateRetries(options.retries);
28540
+ if (Object.hasOwn(options, "forever")) {
28541
+ throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
28542
+ }
28543
+ options.retries ??= 10;
28544
+ options.factor ??= 2;
28545
+ options.minTimeout ??= 1000;
28546
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
28547
+ options.maxRetryTime ??= Number.POSITIVE_INFINITY;
28548
+ options.randomize ??= false;
28549
+ options.onFailedAttempt ??= () => {};
28550
+ options.shouldRetry ??= () => true;
28551
+ options.shouldConsumeRetry ??= () => true;
28552
+ validateNumberOption("factor", options.factor, {
28553
+ min: 0,
28554
+ allowInfinity: false
28555
+ });
28556
+ validateNumberOption("minTimeout", options.minTimeout, {
28557
+ min: 0,
28558
+ allowInfinity: false
28559
+ });
28560
+ validateNumberOption("maxTimeout", options.maxTimeout, {
28561
+ min: 0,
28562
+ allowInfinity: true
28563
+ });
28564
+ validateNumberOption("maxRetryTime", options.maxRetryTime, {
28565
+ min: 0,
28566
+ allowInfinity: true
28567
+ });
28568
+ if (!(options.factor > 0)) {
28569
+ options.factor = 1;
28570
+ }
28571
+ options.signal?.throwIfAborted();
28572
+ let attemptNumber = 0;
28573
+ let retriesConsumed = 0;
28574
+ const startTime = performance.now();
28575
+ while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
28576
+ attemptNumber++;
28577
+ try {
28578
+ options.signal?.throwIfAborted();
28579
+ const result = await input(attemptNumber);
28580
+ options.signal?.throwIfAborted();
28581
+ return result;
28582
+ } catch (error) {
28583
+ if (await onAttemptFailure({
28584
+ error,
28585
+ attemptNumber,
28586
+ retriesConsumed,
28587
+ startTime,
28588
+ options
28589
+ })) {
28590
+ retriesConsumed++;
28591
+ }
28592
+ }
28593
+ }
28594
+ throw new Error("Retry attempts exhausted without throwing an error.");
28595
+ }
28596
+
27928
28597
  // ../../node_modules/langsmith/dist/utils/async_caller.js
27929
- var import_p_retry = __toESM(require_p_retry(), 1);
27930
28598
  var import_p_queue = __toESM(require_dist3(), 1);
27931
28599
  var STATUS_RETRYABLE = [
28600
+ 408,
28601
+ 425,
27932
28602
  429,
27933
28603
  500,
27934
28604
  502,
@@ -27998,14 +28668,14 @@ class AsyncCaller {
27998
28668
  this.queueSizeBytes += sizeBytes;
27999
28669
  }
28000
28670
  const onFailedResponseHook = this.onFailedResponseHook;
28001
- let promise = this.queue.add(() => import_p_retry.default(() => callable(...args).catch((error) => {
28671
+ let promise = this.queue.add(() => pRetry(() => callable(...args).catch((error) => {
28002
28672
  if (error instanceof Error) {
28003
28673
  throw error;
28004
28674
  } else {
28005
28675
  throw new Error(error);
28006
28676
  }
28007
28677
  }), {
28008
- async onFailedAttempt(error) {
28678
+ async onFailedAttempt({ error }) {
28009
28679
  if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.name === "TimeoutError" || error.message.startsWith("AbortError")) {
28010
28680
  throw error;
28011
28681
  }
@@ -31633,8 +32303,30 @@ var isTracingEnabled = (tracingEnabled) => {
31633
32303
 
31634
32304
  // ../../node_modules/langsmith/dist/singletons/constants.js
31635
32305
  var _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables");
32306
+ var _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots");
32307
+
32308
+ // ../../node_modules/langsmith/dist/utils/context_vars.js
32309
+ function getContextVar(runTree, key) {
32310
+ if (_LC_CONTEXT_VARIABLES_KEY in runTree) {
32311
+ const contextVars = runTree[_LC_CONTEXT_VARIABLES_KEY];
32312
+ return contextVars[key];
32313
+ }
32314
+ return;
32315
+ }
32316
+ function setContextVar(runTree, key, value) {
32317
+ const contextVars = _LC_CONTEXT_VARIABLES_KEY in runTree ? runTree[_LC_CONTEXT_VARIABLES_KEY] : {};
32318
+ contextVars[key] = value;
32319
+ runTree[_LC_CONTEXT_VARIABLES_KEY] = contextVars;
32320
+ }
31636
32321
 
31637
32322
  // ../../node_modules/langsmith/dist/run_trees.js
32323
+ var TIMESTAMP_LENGTH = 36;
32324
+ var UUID_NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
32325
+ function getReplicaKey(replica) {
32326
+ const sortedKeys = Object.keys(replica).sort();
32327
+ const keyData = sortedKeys.map((key) => `${key}:${replica[key] ?? ""}`).join("|");
32328
+ return v52(keyData, UUID_NAMESPACE_DNS);
32329
+ }
31638
32330
  function stripNonAlphanumeric(input) {
31639
32331
  return input.replace(/[-:.]/g, "");
31640
32332
  }
@@ -31869,6 +32561,12 @@ class RunTree {
31869
32561
  writable: true,
31870
32562
  value: undefined
31871
32563
  });
32564
+ Object.defineProperty(this, "distributedParentId", {
32565
+ enumerable: true,
32566
+ configurable: true,
32567
+ writable: true,
32568
+ value: undefined
32569
+ });
31872
32570
  Object.defineProperty(this, "_serialized_start_time", {
31873
32571
  enumerable: true,
31874
32572
  configurable: true,
@@ -31899,20 +32597,12 @@ class RunTree {
31899
32597
  if (!this.id) {
31900
32598
  this.id = uuid7FromTime(this._serialized_start_time ?? this.start_time);
31901
32599
  }
31902
- if (config.id) {
31903
- warnIfNotUuidV7(config.id, "run_id");
31904
- }
31905
32600
  if (!this.trace_id) {
31906
32601
  if (this.parent_run) {
31907
32602
  this.trace_id = this.parent_run.trace_id ?? this.id;
31908
32603
  } else {
31909
32604
  this.trace_id = this.id;
31910
32605
  }
31911
- } else if (config.trace_id) {
31912
- warnIfNotUuidV7(config.trace_id, "trace_id");
31913
- }
31914
- if (config.parent_run_id) {
31915
- warnIfNotUuidV7(config.parent_run_id, "parent_run_id");
31916
32606
  }
31917
32607
  this.replicas = _ensureWriteReplicas(this.replicas);
31918
32608
  if (!this.dotted_order) {
@@ -31959,11 +32649,16 @@ class RunTree {
31959
32649
  }
31960
32650
  createChild(config) {
31961
32651
  const child_execution_order = this.child_execution_order + 1;
32652
+ const inheritedReplicas = this.replicas?.map((replica) => {
32653
+ const { reroot, ...rest } = replica;
32654
+ return rest;
32655
+ });
32656
+ const childReplicas = config.replicas ?? inheritedReplicas;
31962
32657
  const child = new RunTree({
31963
32658
  ...config,
31964
32659
  parent_run: this,
31965
32660
  project_name: this.project_name,
31966
- replicas: this.replicas,
32661
+ replicas: childReplicas,
31967
32662
  client: this.client,
31968
32663
  tracingEnabled: this.tracingEnabled,
31969
32664
  execution_order: child_execution_order,
@@ -32047,10 +32742,126 @@ class RunTree {
32047
32742
  events: run.events
32048
32743
  };
32049
32744
  }
32050
- _remapForProject(projectName, runtimeEnv, excludeChildRuns = true) {
32745
+ _sliceParentId(parentId, run) {
32746
+ if (run.dotted_order) {
32747
+ const segs = run.dotted_order.split(".");
32748
+ let startIdx = null;
32749
+ for (let idx = 0;idx < segs.length; idx++) {
32750
+ const segId = segs[idx].slice(-TIMESTAMP_LENGTH);
32751
+ if (segId === parentId) {
32752
+ startIdx = idx;
32753
+ break;
32754
+ }
32755
+ }
32756
+ if (startIdx !== null) {
32757
+ const trimmedSegs = segs.slice(startIdx + 1);
32758
+ run.dotted_order = trimmedSegs.join(".");
32759
+ if (trimmedSegs.length > 0) {
32760
+ run.trace_id = trimmedSegs[0].slice(-TIMESTAMP_LENGTH);
32761
+ } else {
32762
+ run.trace_id = run.id;
32763
+ }
32764
+ }
32765
+ }
32766
+ if (run.parent_run_id === parentId) {
32767
+ run.parent_run_id = undefined;
32768
+ }
32769
+ }
32770
+ _setReplicaTraceRoot(replicaKey, traceRootId) {
32771
+ const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {};
32772
+ replicaTraceRoots[replicaKey] = traceRootId;
32773
+ setContextVar(this, _REPLICA_TRACE_ROOTS_KEY, replicaTraceRoots);
32774
+ for (const child of this.child_runs) {
32775
+ child._setReplicaTraceRoot(replicaKey, traceRootId);
32776
+ }
32777
+ }
32778
+ _remapForProject(params) {
32779
+ const { projectName, runtimeEnv, excludeChildRuns = true, reroot = false, distributedParentId, apiUrl, apiKey, workspaceId } = params;
32051
32780
  const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns);
32781
+ if (projectName === this.project_name) {
32782
+ return {
32783
+ ...baseRun,
32784
+ session_name: projectName
32785
+ };
32786
+ }
32787
+ if (reroot) {
32788
+ if (distributedParentId) {
32789
+ this._sliceParentId(distributedParentId, baseRun);
32790
+ } else {
32791
+ baseRun.parent_run_id = undefined;
32792
+ if (baseRun.dotted_order) {
32793
+ const segs = baseRun.dotted_order.split(".");
32794
+ if (segs.length > 0) {
32795
+ baseRun.dotted_order = segs[segs.length - 1];
32796
+ baseRun.trace_id = baseRun.id;
32797
+ }
32798
+ }
32799
+ }
32800
+ const replicaKey = getReplicaKey({
32801
+ projectName,
32802
+ apiUrl,
32803
+ apiKey,
32804
+ workspaceId
32805
+ });
32806
+ this._setReplicaTraceRoot(replicaKey, baseRun.id);
32807
+ }
32808
+ let ancestorRerootedTraceId;
32809
+ if (!reroot) {
32810
+ const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {};
32811
+ const replicaKey = getReplicaKey({
32812
+ projectName,
32813
+ apiUrl,
32814
+ apiKey,
32815
+ workspaceId
32816
+ });
32817
+ ancestorRerootedTraceId = replicaTraceRoots[replicaKey];
32818
+ if (ancestorRerootedTraceId) {
32819
+ baseRun.trace_id = ancestorRerootedTraceId;
32820
+ if (baseRun.dotted_order) {
32821
+ const segs = baseRun.dotted_order.split(".");
32822
+ let rootIdx = null;
32823
+ for (let idx = 0;idx < segs.length; idx++) {
32824
+ const segId = segs[idx].slice(-TIMESTAMP_LENGTH);
32825
+ if (segId === ancestorRerootedTraceId) {
32826
+ rootIdx = idx;
32827
+ break;
32828
+ }
32829
+ }
32830
+ if (rootIdx !== null) {
32831
+ const trimmedSegs = segs.slice(rootIdx);
32832
+ baseRun.dotted_order = trimmedSegs.join(".");
32833
+ }
32834
+ }
32835
+ }
32836
+ }
32837
+ const oldId = baseRun.id;
32838
+ const newId = v52(`${oldId}:${projectName}`, UUID_NAMESPACE_DNS);
32839
+ let newTraceId;
32840
+ if (baseRun.trace_id) {
32841
+ newTraceId = v52(`${baseRun.trace_id}:${projectName}`, UUID_NAMESPACE_DNS);
32842
+ } else {
32843
+ newTraceId = newId;
32844
+ }
32845
+ let newParentId;
32846
+ if (baseRun.parent_run_id) {
32847
+ newParentId = v52(`${baseRun.parent_run_id}:${projectName}`, UUID_NAMESPACE_DNS);
32848
+ }
32849
+ let newDottedOrder;
32850
+ if (baseRun.dotted_order) {
32851
+ const segs = baseRun.dotted_order.split(".");
32852
+ const remappedSegs = segs.map((seg) => {
32853
+ const segId = seg.slice(-TIMESTAMP_LENGTH);
32854
+ const remappedId = v52(`${segId}:${projectName}`, UUID_NAMESPACE_DNS);
32855
+ return seg.slice(0, -TIMESTAMP_LENGTH) + remappedId;
32856
+ });
32857
+ newDottedOrder = remappedSegs.join(".");
32858
+ }
32052
32859
  return {
32053
32860
  ...baseRun,
32861
+ id: newId,
32862
+ trace_id: newTraceId,
32863
+ parent_run_id: newParentId,
32864
+ dotted_order: newDottedOrder,
32054
32865
  session_name: projectName
32055
32866
  };
32056
32867
  }
@@ -32058,8 +32869,17 @@ class RunTree {
32058
32869
  try {
32059
32870
  const runtimeEnv = getRuntimeEnvironment2();
32060
32871
  if (this.replicas && this.replicas.length > 0) {
32061
- for (const { projectName, apiKey, apiUrl, workspaceId } of this.replicas) {
32062
- const runCreate = this._remapForProject(projectName ?? this.project_name, runtimeEnv, true);
32872
+ for (const { projectName, apiKey, apiUrl, workspaceId, reroot } of this.replicas) {
32873
+ const runCreate = this._remapForProject({
32874
+ projectName: projectName ?? this.project_name,
32875
+ runtimeEnv,
32876
+ excludeChildRuns: true,
32877
+ reroot,
32878
+ distributedParentId: this.distributedParentId,
32879
+ apiUrl,
32880
+ apiKey,
32881
+ workspaceId
32882
+ });
32063
32883
  await this.client.createRun(runCreate, {
32064
32884
  apiKey,
32065
32885
  apiUrl,
@@ -32082,8 +32902,17 @@ class RunTree {
32082
32902
  }
32083
32903
  async patchRun(options) {
32084
32904
  if (this.replicas && this.replicas.length > 0) {
32085
- for (const { projectName, apiKey, apiUrl, workspaceId, updates } of this.replicas) {
32086
- const runData = this._remapForProject(projectName ?? this.project_name);
32905
+ for (const { projectName, apiKey, apiUrl, workspaceId, updates, reroot } of this.replicas) {
32906
+ const runData = this._remapForProject({
32907
+ projectName: projectName ?? this.project_name,
32908
+ runtimeEnv: undefined,
32909
+ excludeChildRuns: true,
32910
+ reroot,
32911
+ distributedParentId: this.distributedParentId,
32912
+ apiUrl,
32913
+ apiKey,
32914
+ workspaceId
32915
+ });
32087
32916
  const updatePayload = {
32088
32917
  id: runData.id,
32089
32918
  name: runData.name,
@@ -32235,7 +33064,9 @@ class RunTree {
32235
33064
  config.project_name = baggage.project_name;
32236
33065
  config.replicas = baggage.replicas;
32237
33066
  }
32238
- return new RunTree(config);
33067
+ const runTree = new RunTree(config);
33068
+ runTree.distributedParentId = runTree.id;
33069
+ return runTree;
32239
33070
  }
32240
33071
  toHeaders(headers) {
32241
33072
  const result = {
@@ -35179,8 +36010,187 @@ var EventStreamCallbackHandler = class extends BaseTracer {
35179
36010
  }
35180
36011
  };
35181
36012
 
36013
+ // ../../node_modules/@langchain/core/dist/utils/is-network-error/index.js
36014
+ var objectToString2 = Object.prototype.toString;
36015
+ var isError2 = (value) => objectToString2.call(value) === "[object Error]";
36016
+ var errorMessages2 = new Set([
36017
+ "network error",
36018
+ "Failed to fetch",
36019
+ "NetworkError when attempting to fetch resource.",
36020
+ "The Internet connection appears to be offline.",
36021
+ "Network request failed",
36022
+ "fetch failed",
36023
+ "terminated",
36024
+ " A network error occurred.",
36025
+ "Network connection lost"
36026
+ ]);
36027
+ function isNetworkError2(error) {
36028
+ const isValid = error && isError2(error) && error.name === "TypeError" && typeof error.message === "string";
36029
+ if (!isValid)
36030
+ return false;
36031
+ const { message, stack } = error;
36032
+ if (message === "Load failed")
36033
+ return stack === undefined || "__sentry_captured__" in error;
36034
+ if (message.startsWith("error sending request for url"))
36035
+ return true;
36036
+ return errorMessages2.has(message);
36037
+ }
36038
+
36039
+ // ../../node_modules/@langchain/core/dist/utils/p-retry/index.js
36040
+ function validateRetries2(retries) {
36041
+ if (typeof retries === "number") {
36042
+ if (retries < 0)
36043
+ throw new TypeError("Expected `retries` to be a non-negative number.");
36044
+ if (Number.isNaN(retries))
36045
+ throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.");
36046
+ } else if (retries !== undefined)
36047
+ throw new TypeError("Expected `retries` to be a number or Infinity.");
36048
+ }
36049
+ function validateNumberOption2(name, value, { min = 0, allowInfinity = false } = {}) {
36050
+ if (value === undefined)
36051
+ return;
36052
+ if (typeof value !== "number" || Number.isNaN(value))
36053
+ throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`);
36054
+ if (!allowInfinity && !Number.isFinite(value))
36055
+ throw new TypeError(`Expected \`${name}\` to be a finite number.`);
36056
+ if (value < min)
36057
+ throw new TypeError(`Expected \`${name}\` to be ≥ ${min}.`);
36058
+ }
36059
+ var AbortError2 = class extends Error {
36060
+ constructor(message) {
36061
+ super();
36062
+ if (message instanceof Error) {
36063
+ this.originalError = message;
36064
+ ({ message } = message);
36065
+ } else {
36066
+ this.originalError = new Error(message);
36067
+ this.originalError.stack = this.stack;
36068
+ }
36069
+ this.name = "AbortError";
36070
+ this.message = message;
36071
+ }
36072
+ };
36073
+ function calculateDelay2(retriesConsumed, options) {
36074
+ const attempt = Math.max(1, retriesConsumed + 1);
36075
+ const random = options.randomize ? Math.random() + 1 : 1;
36076
+ let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1));
36077
+ timeout = Math.min(timeout, options.maxTimeout);
36078
+ return timeout;
36079
+ }
36080
+ function calculateRemainingTime2(start, max) {
36081
+ if (!Number.isFinite(max))
36082
+ return max;
36083
+ return max - (performance.now() - start);
36084
+ }
36085
+ async function onAttemptFailure2({ error, attemptNumber, retriesConsumed, startTime, options }) {
36086
+ const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
36087
+ if (normalizedError instanceof AbortError2)
36088
+ throw normalizedError.originalError;
36089
+ const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries;
36090
+ const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY;
36091
+ const context = Object.freeze({
36092
+ error: normalizedError,
36093
+ attemptNumber,
36094
+ retriesLeft,
36095
+ retriesConsumed
36096
+ });
36097
+ await options.onFailedAttempt(context);
36098
+ if (calculateRemainingTime2(startTime, maxRetryTime) <= 0)
36099
+ throw normalizedError;
36100
+ const consumeRetry = await options.shouldConsumeRetry(context);
36101
+ const remainingTime = calculateRemainingTime2(startTime, maxRetryTime);
36102
+ if (remainingTime <= 0 || retriesLeft <= 0)
36103
+ throw normalizedError;
36104
+ if (normalizedError instanceof TypeError && !isNetworkError2(normalizedError)) {
36105
+ if (consumeRetry)
36106
+ throw normalizedError;
36107
+ options.signal?.throwIfAborted();
36108
+ return false;
36109
+ }
36110
+ if (!await options.shouldRetry(context))
36111
+ throw normalizedError;
36112
+ if (!consumeRetry) {
36113
+ options.signal?.throwIfAborted();
36114
+ return false;
36115
+ }
36116
+ const delayTime = calculateDelay2(retriesConsumed, options);
36117
+ const finalDelay = Math.min(delayTime, remainingTime);
36118
+ if (finalDelay > 0)
36119
+ await new Promise((resolve, reject) => {
36120
+ const onAbort = () => {
36121
+ clearTimeout(timeoutToken);
36122
+ options.signal?.removeEventListener("abort", onAbort);
36123
+ reject(options.signal.reason);
36124
+ };
36125
+ const timeoutToken = setTimeout(() => {
36126
+ options.signal?.removeEventListener("abort", onAbort);
36127
+ resolve();
36128
+ }, finalDelay);
36129
+ if (options.unref)
36130
+ timeoutToken.unref?.();
36131
+ options.signal?.addEventListener("abort", onAbort, { once: true });
36132
+ });
36133
+ options.signal?.throwIfAborted();
36134
+ return true;
36135
+ }
36136
+ async function pRetry2(input, options = {}) {
36137
+ options = { ...options };
36138
+ validateRetries2(options.retries);
36139
+ if (Object.hasOwn(options, "forever"))
36140
+ throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");
36141
+ options.retries ??= 10;
36142
+ options.factor ??= 2;
36143
+ options.minTimeout ??= 1000;
36144
+ options.maxTimeout ??= Number.POSITIVE_INFINITY;
36145
+ options.maxRetryTime ??= Number.POSITIVE_INFINITY;
36146
+ options.randomize ??= false;
36147
+ options.onFailedAttempt ??= () => {};
36148
+ options.shouldRetry ??= () => true;
36149
+ options.shouldConsumeRetry ??= () => true;
36150
+ validateNumberOption2("factor", options.factor, {
36151
+ min: 0,
36152
+ allowInfinity: false
36153
+ });
36154
+ validateNumberOption2("minTimeout", options.minTimeout, {
36155
+ min: 0,
36156
+ allowInfinity: false
36157
+ });
36158
+ validateNumberOption2("maxTimeout", options.maxTimeout, {
36159
+ min: 0,
36160
+ allowInfinity: true
36161
+ });
36162
+ validateNumberOption2("maxRetryTime", options.maxRetryTime, {
36163
+ min: 0,
36164
+ allowInfinity: true
36165
+ });
36166
+ if (!(options.factor > 0))
36167
+ options.factor = 1;
36168
+ options.signal?.throwIfAborted();
36169
+ let attemptNumber = 0;
36170
+ let retriesConsumed = 0;
36171
+ const startTime = performance.now();
36172
+ while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) {
36173
+ attemptNumber++;
36174
+ try {
36175
+ options.signal?.throwIfAborted();
36176
+ const result = await input(attemptNumber);
36177
+ options.signal?.throwIfAborted();
36178
+ return result;
36179
+ } catch (error) {
36180
+ if (await onAttemptFailure2({
36181
+ error,
36182
+ attemptNumber,
36183
+ retriesConsumed,
36184
+ startTime,
36185
+ options
36186
+ }))
36187
+ retriesConsumed++;
36188
+ }
36189
+ }
36190
+ throw new Error("Retry attempts exhausted without throwing an error.");
36191
+ }
36192
+
35182
36193
  // ../../node_modules/@langchain/core/dist/utils/async_caller.js
35183
- var import_p_retry2 = __toESM(require_p_retry(), 1);
35184
36194
  var import_p_queue3 = __toESM(require_dist3(), 1);
35185
36195
  var async_caller_exports = {};
35186
36196
  __export(async_caller_exports, { AsyncCaller: () => AsyncCaller2 });
@@ -35221,14 +36231,14 @@ var AsyncCaller2 = class {
35221
36231
  const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default;
35222
36232
  this.queue = new PQueue({ concurrency: this.maxConcurrency });
35223
36233
  }
35224
- call(callable, ...args) {
35225
- return this.queue.add(() => import_p_retry2.default(() => callable(...args).catch((error) => {
36234
+ async call(callable, ...args) {
36235
+ return this.queue.add(() => pRetry2(() => callable(...args).catch((error) => {
35226
36236
  if (error instanceof Error)
35227
36237
  throw error;
35228
36238
  else
35229
36239
  throw new Error(error);
35230
36240
  }), {
35231
- onFailedAttempt: this.onFailedAttempt,
36241
+ onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error),
35232
36242
  retries: this.maxRetries,
35233
36243
  randomize: true
35234
36244
  }), { throwOnTimeout: true });
@@ -35326,6 +36336,10 @@ var _RootEventFilter = class {
35326
36336
  return include;
35327
36337
  }
35328
36338
  };
36339
+ var toBase64Url = (str) => {
36340
+ const encoded = btoa(str);
36341
+ return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
36342
+ };
35329
36343
 
35330
36344
  // ../../node_modules/@langchain/core/dist/utils/types/zod.js
35331
36345
  import { $ZodNever, $ZodOptional, $ZodUnknown, _never, _unknown, clone, globalRegistry, parse as parse3, parseAsync, util } from "zod/v4/core";
@@ -35401,6 +36415,20 @@ function isZodArrayV4(obj) {
35401
36415
  return true;
35402
36416
  return false;
35403
36417
  }
36418
+ function isZodOptionalV4(obj) {
36419
+ if (!isZodSchemaV4(obj))
36420
+ return false;
36421
+ if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional")
36422
+ return true;
36423
+ return false;
36424
+ }
36425
+ function isZodNullableV4(obj) {
36426
+ if (!isZodSchemaV4(obj))
36427
+ return false;
36428
+ if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable")
36429
+ return true;
36430
+ return false;
36431
+ }
35404
36432
  function interopZodObjectStrict(schema, recursive = false) {
35405
36433
  if (isZodSchemaV3(schema))
35406
36434
  return schema.strict();
@@ -35471,6 +36499,18 @@ function interopZodTransformInputSchemaImpl(schema, recursive, cache) {
35471
36499
  ...outputSchema._zod.def,
35472
36500
  element: elementSchema
35473
36501
  });
36502
+ } else if (isZodOptionalV4(outputSchema)) {
36503
+ const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache);
36504
+ outputSchema = clone(outputSchema, {
36505
+ ...outputSchema._zod.def,
36506
+ innerType: innerSchema
36507
+ });
36508
+ } else if (isZodNullableV4(outputSchema)) {
36509
+ const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache);
36510
+ outputSchema = clone(outputSchema, {
36511
+ ...outputSchema._zod.def,
36512
+ innerType: innerSchema
36513
+ });
35474
36514
  }
35475
36515
  }
35476
36516
  const meta = globalRegistry.get(schema);
@@ -35579,7 +36619,7 @@ graph TD;
35579
36619
  async function drawMermaidImage(mermaidSyntax, config) {
35580
36620
  let backgroundColor = config?.backgroundColor ?? "white";
35581
36621
  const imageType = config?.imageType ?? "png";
35582
- const mermaidSyntaxEncoded = btoa(mermaidSyntax);
36622
+ const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax);
35583
36623
  if (backgroundColor !== undefined) {
35584
36624
  const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/;
35585
36625
  if (!hexColorPattern.test(backgroundColor))
@@ -38186,7 +39226,6 @@ async function* consumeAsyncIterableInContext(context, iter) {
38186
39226
  }
38187
39227
 
38188
39228
  // ../../node_modules/@langchain/core/dist/runnables/base.js
38189
- var import_p_retry3 = __toESM(require_p_retry(), 1);
38190
39229
  import { z } from "zod/v3";
38191
39230
  function _coerceToDict2(value, defaultKey) {
38192
39231
  return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value };
@@ -38783,8 +39822,8 @@ var RunnableRetry = class extends RunnableBinding {
38783
39822
  return patchConfig(config, { callbacks: runManager?.getChild(tag) });
38784
39823
  }
38785
39824
  async _invoke(input, config, runManager) {
38786
- return import_p_retry3.default((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
38787
- onFailedAttempt: (error) => this.onFailedAttempt(error, input),
39825
+ return pRetry2((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), {
39826
+ onFailedAttempt: ({ error }) => this.onFailedAttempt(error, input),
38788
39827
  retries: Math.max(this.maxAttemptNumber - 1, 0),
38789
39828
  randomize: true
38790
39829
  });
@@ -38795,7 +39834,7 @@ var RunnableRetry = class extends RunnableBinding {
38795
39834
  async _batch(inputs, configs, runManagers, batchOptions) {
38796
39835
  const resultsMap = {};
38797
39836
  try {
38798
- await import_p_retry3.default(async (attemptNumber) => {
39837
+ await pRetry2(async (attemptNumber) => {
38799
39838
  const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === undefined || resultsMap[i.toString()] instanceof Error);
38800
39839
  const remainingInputs = remainingIndexes.map((i) => inputs[i]);
38801
39840
  const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i]));
@@ -38819,7 +39858,7 @@ var RunnableRetry = class extends RunnableBinding {
38819
39858
  throw firstException;
38820
39859
  return results;
38821
39860
  }, {
38822
- onFailedAttempt: (error) => this.onFailedAttempt(error, error.input),
39861
+ onFailedAttempt: ({ error }) => this.onFailedAttempt(error, error.input),
38823
39862
  retries: Math.max(this.maxAttemptNumber - 1, 0),
38824
39863
  randomize: true
38825
39864
  });
@@ -42448,6 +43487,7 @@ var console_styles = Object.freeze(styles_raw);
42448
43487
  var dist_default = Log;
42449
43488
 
42450
43489
  // src/logger.ts
43490
+ var import_fast_redact = __toESM(require_fast_redact(), 1);
42451
43491
  var __loggerTestHooks = {
42452
43492
  __noop: () => {}
42453
43493
  };
@@ -42501,6 +43541,37 @@ function parseBooleanFromText(value) {
42501
43541
  const normalized = value.toLowerCase().trim();
42502
43542
  return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on";
42503
43543
  }
43544
+ function formatExtraValue(value) {
43545
+ if (value === null)
43546
+ return "null";
43547
+ if (value === undefined)
43548
+ return "undefined";
43549
+ if (typeof value === "string")
43550
+ return value;
43551
+ if (typeof value === "number" || typeof value === "boolean")
43552
+ return String(value);
43553
+ if (value instanceof Error)
43554
+ return value.message;
43555
+ return safeStringify(value);
43556
+ }
43557
+ function formatPrettyLog(context, message, isJsonMode) {
43558
+ if (isJsonMode) {
43559
+ return message;
43560
+ }
43561
+ const src = context.src;
43562
+ const srcPart = src ? `[${src.toUpperCase()}] ` : "";
43563
+ const excludeKeys = ["src", "agentId", "agentName"];
43564
+ const extraPairs = [];
43565
+ for (const [key, value] of Object.entries(context)) {
43566
+ if (excludeKeys.includes(key))
43567
+ continue;
43568
+ if (value === undefined)
43569
+ continue;
43570
+ extraPairs.push(`${key}=${formatExtraValue(value)}`);
43571
+ }
43572
+ const extrasPart = extraPairs.length > 0 ? ` (${extraPairs.join(", ")})` : "";
43573
+ return `${srcPart}${message}${extrasPart}`;
43574
+ }
42504
43575
  var DEFAULT_LOG_LEVEL = "info";
42505
43576
  var effectiveLogLevel = getEnv3("LOG_LEVEL") || DEFAULT_LOG_LEVEL;
42506
43577
  var customLevels = {
@@ -42516,6 +43587,46 @@ var customLevels = {
42516
43587
  };
42517
43588
  var raw = parseBooleanFromText(getEnv3("LOG_JSON_FORMAT"));
42518
43589
  var showTimestamps = parseBooleanFromText(getEnv3("LOG_TIMESTAMPS") ?? "true");
43590
+ var serverId = getEnv3("SERVER_ID") || (typeof crypto !== "undefined" && crypto.randomUUID ? crypto.randomUUID().slice(0, 8) : Math.random().toString(36).slice(2, 10));
43591
+ var redact = import_fast_redact.default({
43592
+ paths: [
43593
+ "password",
43594
+ "passwd",
43595
+ "secret",
43596
+ "token",
43597
+ "apiKey",
43598
+ "api_key",
43599
+ "apiSecret",
43600
+ "api_secret",
43601
+ "authorization",
43602
+ "auth",
43603
+ "credential",
43604
+ "credentials",
43605
+ "privateKey",
43606
+ "private_key",
43607
+ "accessToken",
43608
+ "access_token",
43609
+ "refreshToken",
43610
+ "refresh_token",
43611
+ "cookie",
43612
+ "session",
43613
+ "jwt",
43614
+ "bearer",
43615
+ "*.password",
43616
+ "*.secret",
43617
+ "*.token",
43618
+ "*.apiKey",
43619
+ "*.api_key",
43620
+ "*.authorization",
43621
+ "*.credential",
43622
+ "*.credentials",
43623
+ "*.privateKey",
43624
+ "*.accessToken",
43625
+ "*.refreshToken"
43626
+ ],
43627
+ serialize: false,
43628
+ censor: "[REDACTED]"
43629
+ });
42519
43630
  function createInMemoryDestination(maxLogs = 100) {
42520
43631
  const logs = [];
42521
43632
  return {
@@ -42664,24 +43775,31 @@ function sealAdze(base) {
42664
43775
  const metaBase = { ...base };
42665
43776
  delete metaBase.namespace;
42666
43777
  delete metaBase.namespaces;
42667
- if (raw) {
42668
- if (!metaBase.name) {
42669
- metaBase.name = "elizaos";
42670
- }
42671
- if (!metaBase.hostname) {
42672
- let hostname = "unknown";
42673
- if (typeof process !== "undefined" && process.platform) {
42674
- try {
42675
- const os = __require("os");
42676
- hostname = os.hostname();
42677
- } catch {
42678
- hostname = "localhost";
42679
- }
42680
- } else if (typeof window !== "undefined" && window.location) {
42681
- hostname = window.location.hostname || "browser";
43778
+ if (!metaBase.name) {
43779
+ metaBase.name = "elizaos";
43780
+ }
43781
+ if (!metaBase.pid && typeof process !== "undefined" && process.pid) {
43782
+ metaBase.pid = process.pid;
43783
+ }
43784
+ if (!metaBase.environment && typeof process !== "undefined" && process.env) {
43785
+ metaBase.environment = "development";
43786
+ }
43787
+ if (!metaBase.serverId) {
43788
+ metaBase.serverId = serverId;
43789
+ }
43790
+ if (raw && !metaBase.hostname) {
43791
+ let hostname = "unknown";
43792
+ if (typeof process !== "undefined" && process.platform) {
43793
+ try {
43794
+ const os = __require("os");
43795
+ hostname = os.hostname();
43796
+ } catch {
43797
+ hostname = "localhost";
42682
43798
  }
42683
- metaBase.hostname = hostname;
43799
+ } else if (typeof window !== "undefined" && window.location) {
43800
+ hostname = window.location.hostname || "browser";
42684
43801
  }
43802
+ metaBase.hostname = hostname;
42685
43803
  }
42686
43804
  const globalConfig = {
42687
43805
  activeLevel: getAdzeActiveLevel(),
@@ -42736,6 +43854,15 @@ function createLogger(bindings = false) {
42736
43854
  console[consoleMethod](message);
42737
43855
  }
42738
43856
  };
43857
+ const safeRedact2 = (obj) => {
43858
+ try {
43859
+ const copy = { ...obj };
43860
+ redact(copy);
43861
+ return copy;
43862
+ } catch {
43863
+ return obj;
43864
+ }
43865
+ };
42739
43866
  const adaptArgs2 = (obj, msg, ...args) => {
42740
43867
  if (typeof obj === "string") {
42741
43868
  return msg !== undefined ? [obj, msg, ...args] : [obj, ...args];
@@ -42743,10 +43870,13 @@ function createLogger(bindings = false) {
42743
43870
  if (obj instanceof Error) {
42744
43871
  return msg !== undefined ? [obj.message, msg, ...args] : [obj.message, ...args];
42745
43872
  }
43873
+ const redactedObj = safeRedact2(obj);
42746
43874
  if (msg !== undefined) {
42747
- return [msg, obj, ...args];
43875
+ const formatted2 = formatPrettyLog(redactedObj, msg, false);
43876
+ return [formatted2, ...args];
42748
43877
  }
42749
- return [obj, ...args];
43878
+ const formatted = formatPrettyLog(redactedObj, "", false);
43879
+ return formatted ? [formatted, ...args] : [...args];
42750
43880
  };
42751
43881
  return {
42752
43882
  level: currentLevel2,
@@ -42815,6 +43945,15 @@ function createLogger(bindings = false) {
42815
43945
  console.log(`[${method.toUpperCase()}]`, ...args);
42816
43946
  }
42817
43947
  };
43948
+ const safeRedact = (obj) => {
43949
+ try {
43950
+ const copy = { ...obj };
43951
+ redact(copy);
43952
+ return copy;
43953
+ } catch {
43954
+ return obj;
43955
+ }
43956
+ };
42818
43957
  const adaptArgs = (obj, msg, ...args) => {
42819
43958
  if (typeof obj === "string") {
42820
43959
  return msg !== undefined ? [obj, msg, ...args] : [obj, ...args];
@@ -42822,10 +43961,19 @@ function createLogger(bindings = false) {
42822
43961
  if (obj instanceof Error) {
42823
43962
  return msg !== undefined ? [obj.message, { error: obj }, msg, ...args] : [obj.message, { error: obj }, ...args];
42824
43963
  }
43964
+ const redactedObj = safeRedact(obj);
42825
43965
  if (msg !== undefined) {
42826
- return [msg, obj, ...args];
43966
+ if (!raw) {
43967
+ const formatted = formatPrettyLog(redactedObj, msg, raw);
43968
+ return [formatted, ...args];
43969
+ }
43970
+ return [msg, redactedObj, ...args];
42827
43971
  }
42828
- return [obj, ...args];
43972
+ if (!raw) {
43973
+ const formatted = formatPrettyLog(redactedObj, "", raw);
43974
+ return formatted ? [formatted, ...args] : [...args];
43975
+ }
43976
+ return [redactedObj, ...args];
42829
43977
  };
42830
43978
  const trace = (obj, msg, ...args) => invoke("verbose", ...adaptArgs(obj, msg, ...args));
42831
43979
  const debug = (obj, msg, ...args) => invoke("debug", ...adaptArgs(obj, msg, ...args));
@@ -42934,7 +44082,7 @@ var formatPosts = ({
42934
44082
  const messageStrings = roomMessages.filter((message) => message.entityId).map((message) => {
42935
44083
  const entity = entities.find((entity2) => entity2.id === message.entityId);
42936
44084
  if (!entity) {
42937
- logger_default.warn({ entityId: message.entityId }, "core::prompts:formatPosts - no entity for");
44085
+ logger_default.warn({ src: "core:utils", entityId: message.entityId }, "No entity found for message");
42938
44086
  }
42939
44087
  const userName = entity?.names[0] || "Unknown User";
42940
44088
  const displayName = entity?.names[0] || "unknown";
@@ -43019,7 +44167,6 @@ function parseKeyValueXml(text) {
43019
44167
  let xmlContent;
43020
44168
  if (xmlBlockMatch) {
43021
44169
  xmlContent = xmlBlockMatch[1];
43022
- logger_default.debug("Found response XML block");
43023
44170
  } else {
43024
44171
  const findFirstXmlBlock = (input) => {
43025
44172
  let i = 0;
@@ -43092,12 +44239,10 @@ function parseKeyValueXml(text) {
43092
44239
  };
43093
44240
  const fb = findFirstXmlBlock(text);
43094
44241
  if (!fb) {
43095
- logger_default.warn("Could not find XML block in text");
43096
- logger_default.debug({ textPreview: text.substring(0, 200) + "..." }, "Text content");
44242
+ logger_default.warn({ src: "core:utils" }, "Could not find XML block in text");
43097
44243
  return null;
43098
44244
  }
43099
44245
  xmlContent = fb.content;
43100
- logger_default.debug(`Found XML block with tag: ${fb.tag}`);
43101
44246
  }
43102
44247
  const result = {};
43103
44248
  const extractDirectChildren = (input) => {
@@ -43182,8 +44327,7 @@ function parseKeyValueXml(text) {
43182
44327
  }
43183
44328
  }
43184
44329
  if (Object.keys(result).length === 0) {
43185
- logger_default.warn("No key-value pairs extracted from XML content");
43186
- logger_default.debug({ xmlPreview: xmlContent.substring(0, 200) + "..." }, "XML content was");
44330
+ logger_default.warn({ src: "core:utils" }, "No key-value pairs extracted from XML content");
43187
44331
  return null;
43188
44332
  }
43189
44333
  return result;
@@ -43234,17 +44378,12 @@ function truncateToCompleteSentence(text, maxLength) {
43234
44378
  return `${hardTruncated}...`;
43235
44379
  }
43236
44380
  async function splitChunks(content, chunkSize = 512, bleed = 20) {
43237
- logger_default.debug("[splitChunks] Starting text split");
43238
44381
  const characterstoTokens = 3.5;
43239
44382
  const textSplitter = new RecursiveCharacterTextSplitter({
43240
44383
  chunkSize: Number(Math.floor(chunkSize * characterstoTokens)),
43241
44384
  chunkOverlap: Number(Math.floor(bleed * characterstoTokens))
43242
44385
  });
43243
44386
  const chunks = await textSplitter.splitText(content);
43244
- logger_default.debug({
43245
- numberOfChunks: chunks.length,
43246
- averageChunkSize: chunks.reduce((acc, chunk) => acc + chunk.length, 0) / chunks.length
43247
- }, "[splitChunks] Split complete");
43248
44387
  return chunks;
43249
44388
  }
43250
44389
  async function trimTokens(prompt, maxTokens, runtime) {
@@ -44321,8 +45460,8 @@ Here are the actions taken by the assistant to fulfill the request:
44321
45460
  `;
44322
45461
 
44323
45462
  // src/roles.ts
44324
- async function getUserServerRole(runtime, entityId, serverId) {
44325
- const worldId = createUniqueUuid(runtime, serverId);
45463
+ async function getUserServerRole(runtime, entityId, serverId2) {
45464
+ const worldId = createUniqueUuid(runtime, serverId2);
44326
45465
  const world = await runtime.getWorld(worldId);
44327
45466
  if (!world || !world.metadata?.roles) {
44328
45467
  return "NONE" /* NONE */;
@@ -44337,12 +45476,12 @@ async function getUserServerRole(runtime, entityId, serverId) {
44337
45476
  }
44338
45477
  async function findWorldsForOwner(runtime, entityId) {
44339
45478
  if (!entityId) {
44340
- logger.error("User ID is required to find server");
45479
+ logger.error({ src: "core:roles", agentId: runtime.agentId }, "User ID is required to find server");
44341
45480
  return null;
44342
45481
  }
44343
45482
  const worlds = await runtime.getAllWorlds();
44344
45483
  if (!worlds || worlds.length === 0) {
44345
- logger.info("No worlds found for this agent");
45484
+ logger.debug({ src: "core:roles", agentId: runtime.agentId }, "No worlds found for agent");
44346
45485
  return null;
44347
45486
  }
44348
45487
  const ownerWorlds = [];
@@ -44407,6 +45546,44 @@ function v43(options, buf, offset) {
44407
45546
  return _v4(options, buf, offset);
44408
45547
  }
44409
45548
  var v4_default = v43;
45549
+ // src/utils/type-guards.ts
45550
+ function isPlainObject(value) {
45551
+ if (typeof value !== "object" || value === null) {
45552
+ return false;
45553
+ }
45554
+ if (Array.isArray(value)) {
45555
+ return false;
45556
+ }
45557
+ if (isBuffer(value)) {
45558
+ return false;
45559
+ }
45560
+ if (value instanceof Date) {
45561
+ return false;
45562
+ }
45563
+ if (value instanceof RegExp) {
45564
+ return false;
45565
+ }
45566
+ if (value instanceof Map) {
45567
+ return false;
45568
+ }
45569
+ if (value instanceof Set) {
45570
+ return false;
45571
+ }
45572
+ if (value instanceof WeakMap) {
45573
+ return false;
45574
+ }
45575
+ if (value instanceof WeakSet) {
45576
+ return false;
45577
+ }
45578
+ if (value instanceof Error) {
45579
+ return false;
45580
+ }
45581
+ if (value instanceof Promise) {
45582
+ return false;
45583
+ }
45584
+ return true;
45585
+ }
45586
+
44410
45587
  // src/services/default-message-service.ts
44411
45588
  var latestResponseIds = new Map;
44412
45589
 
@@ -44421,7 +45598,12 @@ class DefaultMessageService {
44421
45598
  let timeoutId = undefined;
44422
45599
  const responseId = v4_default();
44423
45600
  try {
44424
- runtime.logger.info(`[MessageService] Message received from ${message.entityId} in room ${message.roomId}`);
45601
+ runtime.logger.info({
45602
+ src: "service:message",
45603
+ agentId: runtime.agentId,
45604
+ entityId: message.entityId,
45605
+ roomId: message.roomId
45606
+ }, "Message received");
44425
45607
  if (!latestResponseIds.has(runtime.agentId)) {
44426
45608
  latestResponseIds.set(runtime.agentId, new Map);
44427
45609
  }
@@ -44430,10 +45612,10 @@ class DefaultMessageService {
44430
45612
  throw new Error("Agent responses map not found");
44431
45613
  const previousResponseId = agentResponses.get(message.roomId);
44432
45614
  if (previousResponseId) {
44433
- logger.warn(`[MessageService] Updating response ID for room ${message.roomId} from ${previousResponseId} to ${responseId}`);
45615
+ logger.debug({ src: "service:message", roomId: message.roomId, previousResponseId, responseId }, "Updating response ID");
44434
45616
  }
44435
45617
  agentResponses.set(message.roomId, responseId);
44436
- const runId = runtime.startRun();
45618
+ const runId = runtime.startRun(message.roomId);
44437
45619
  const startTime = Date.now();
44438
45620
  await runtime.emitEvent("RUN_STARTED" /* RUN_STARTED */, {
44439
45621
  runtime,
@@ -44470,7 +45652,7 @@ class DefaultMessageService {
44470
45652
  return result;
44471
45653
  } catch (error) {
44472
45654
  clearTimeout(timeoutId);
44473
- runtime.logger.error({ error }, "[MessageService] Error in handleMessage:");
45655
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error in handleMessage");
44474
45656
  throw error;
44475
45657
  }
44476
45658
  }
@@ -44480,7 +45662,7 @@ class DefaultMessageService {
44480
45662
  if (!agentResponses)
44481
45663
  throw new Error("Agent responses map not found");
44482
45664
  if (message.entityId === runtime.agentId) {
44483
- runtime.logger.debug(`[MessageService] Skipping message from self (${runtime.agentId})`);
45665
+ runtime.logger.debug({ src: "service:message", agentId: runtime.agentId }, "Skipping message from self");
44484
45666
  await this.emitRunEnded(runtime, runId, message, startTime, "self");
44485
45667
  return {
44486
45668
  didRespond: false,
@@ -44490,13 +45672,16 @@ class DefaultMessageService {
44490
45672
  mode: "none"
44491
45673
  };
44492
45674
  }
44493
- runtime.logger.debug(`[MessageService] Processing message: ${truncateToCompleteSentence(message.content.text || "", 50)}...`);
44494
- runtime.logger.debug("[MessageService] Saving message to memory and queueing embeddings");
45675
+ runtime.logger.debug({
45676
+ src: "service:message",
45677
+ messagePreview: truncateToCompleteSentence(message.content.text || "", 50)
45678
+ }, "Processing message");
45679
+ runtime.logger.debug({ src: "service:message" }, "Saving message to memory");
44495
45680
  let memoryToQueue;
44496
45681
  if (message.id) {
44497
45682
  const existingMemory = await runtime.getMemoryById(message.id);
44498
45683
  if (existingMemory) {
44499
- runtime.logger.debug("[MessageService] Memory already exists, skipping creation");
45684
+ runtime.logger.debug({ src: "service:message" }, "Memory already exists, skipping creation");
44500
45685
  memoryToQueue = existingMemory;
44501
45686
  } else {
44502
45687
  const createdMemoryId = await runtime.createMemory(message, "messages");
@@ -44512,7 +45697,7 @@ class DefaultMessageService {
44512
45697
  const agentUserState = await runtime.getParticipantUserState(message.roomId, runtime.agentId);
44513
45698
  const defLllmOff = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_DEFLLMOFF"));
44514
45699
  if (defLllmOff && agentUserState === null) {
44515
- runtime.logger.debug("[MessageService] LLM is off by default");
45700
+ runtime.logger.debug({ src: "service:message" }, "LLM is off by default");
44516
45701
  await this.emitRunEnded(runtime, runId, message, startTime, "off");
44517
45702
  return {
44518
45703
  didRespond: false,
@@ -44523,7 +45708,7 @@ class DefaultMessageService {
44523
45708
  };
44524
45709
  }
44525
45710
  if (agentUserState === "MUTED" && !message.content.text?.toLowerCase().includes(runtime.character.name.toLowerCase())) {
44526
- runtime.logger.debug(`[MessageService] Ignoring muted room ${message.roomId}`);
45711
+ runtime.logger.debug({ src: "service:message", roomId: message.roomId }, "Ignoring muted room");
44527
45712
  await this.emitRunEnded(runtime, runId, message, startTime, "muted");
44528
45713
  return {
44529
45714
  didRespond: false,
@@ -44543,24 +45728,31 @@ class DefaultMessageService {
44543
45728
  }
44544
45729
  }
44545
45730
  const responseDecision = this.shouldRespond(runtime, message, room ?? undefined, mentionContext);
44546
- runtime.logger.debug(`[MessageService] Response decision: ${JSON.stringify(responseDecision)}`);
45731
+ runtime.logger.debug({ src: "service:message", responseDecision }, "Response decision");
44547
45732
  let shouldRespondToMessage = true;
44548
45733
  if (responseDecision.skipEvaluation) {
44549
- runtime.logger.debug(`[MessageService] Skipping evaluation for ${runtime.character.name} (${responseDecision.reason})`);
45734
+ runtime.logger.debug({
45735
+ src: "service:message",
45736
+ agentName: runtime.character.name,
45737
+ reason: responseDecision.reason
45738
+ }, "Skipping LLM evaluation");
44550
45739
  shouldRespondToMessage = responseDecision.shouldRespond;
44551
45740
  } else {
44552
45741
  const shouldRespondPrompt = composePromptFromState({
44553
45742
  state,
44554
45743
  template: runtime.character.templates?.shouldRespondTemplate || shouldRespondTemplate
44555
45744
  });
44556
- runtime.logger.debug(`[MessageService] Using LLM evaluation for ${runtime.character.name} (${responseDecision.reason})`);
45745
+ runtime.logger.debug({
45746
+ src: "service:message",
45747
+ agentName: runtime.character.name,
45748
+ reason: responseDecision.reason
45749
+ }, "Using LLM evaluation");
44557
45750
  const response = await runtime.useModel(ModelType.TEXT_SMALL, {
44558
45751
  prompt: shouldRespondPrompt
44559
45752
  });
44560
- runtime.logger.debug(`[MessageService] LLM evaluation result:
44561
- ${response}`);
45753
+ runtime.logger.debug({ src: "service:message", response }, "LLM evaluation result");
44562
45754
  const responseObject = parseKeyValueXml(response);
44563
- runtime.logger.debug({ responseObject }, "[MessageService] Parsed evaluation result:");
45755
+ runtime.logger.debug({ src: "service:message", responseObject }, "Parsed evaluation result");
44564
45756
  const nonResponseActions = ["IGNORE", "NONE"];
44565
45757
  shouldRespondToMessage = responseObject?.action && !nonResponseActions.includes(responseObject.action.toUpperCase());
44566
45758
  }
@@ -44575,7 +45767,7 @@ ${response}`);
44575
45767
  mode = result.mode;
44576
45768
  const currentResponseId = agentResponses.get(message.roomId);
44577
45769
  if (currentResponseId !== responseId) {
44578
- runtime.logger.info(`Response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`);
45770
+ runtime.logger.info({ src: "service:message", agentId: runtime.agentId, roomId: message.roomId }, "Response discarded - newer message being processed");
44579
45771
  return {
44580
45772
  didRespond: false,
44581
45773
  responseContent: null,
@@ -44593,14 +45785,14 @@ ${response}`);
44593
45785
  if (responseContent) {
44594
45786
  if (mode === "simple") {
44595
45787
  if (responseContent.providers && responseContent.providers.length > 0) {
44596
- runtime.logger.debug({ providers: responseContent.providers }, "[MessageService] Simple response used providers");
45788
+ runtime.logger.debug({ src: "service:message", providers: responseContent.providers }, "Simple response used providers");
44597
45789
  }
44598
45790
  if (callback) {
44599
45791
  await callback(responseContent);
44600
45792
  }
44601
45793
  } else if (mode === "actions") {
44602
45794
  await runtime.processActions(message, responseMessages, state, async (content) => {
44603
- runtime.logger.debug({ content }, "action callback");
45795
+ runtime.logger.debug({ src: "service:message", content }, "Action callback");
44604
45796
  responseContent.actionCallbacks = content;
44605
45797
  if (callback) {
44606
45798
  return callback(content);
@@ -44610,11 +45802,11 @@ ${response}`);
44610
45802
  }
44611
45803
  }
44612
45804
  } else {
44613
- runtime.logger.debug("[MessageService] Agent decided not to respond (shouldRespond is false).");
45805
+ runtime.logger.debug({ src: "service:message" }, "Agent decided not to respond");
44614
45806
  const currentResponseId = agentResponses.get(message.roomId);
44615
45807
  const keepResp = parseBooleanFromText2(runtime.getSetting("BOOTSTRAP_KEEP_RESP"));
44616
45808
  if (currentResponseId !== responseId && !keepResp) {
44617
- runtime.logger.info(`Ignore response discarded - newer message being processed for agent: ${runtime.agentId}, room: ${message.roomId}`);
45809
+ runtime.logger.info({ src: "service:message", agentId: runtime.agentId, roomId: message.roomId }, "Ignore response discarded - newer message being processed");
44618
45810
  await this.emitRunEnded(runtime, runId, message, startTime, "replaced");
44619
45811
  return {
44620
45812
  didRespond: false,
@@ -44625,7 +45817,7 @@ ${response}`);
44625
45817
  };
44626
45818
  }
44627
45819
  if (!message.id) {
44628
- runtime.logger.error("[MessageService] Message ID is missing, cannot create ignore response.");
45820
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId }, "Message ID is missing, cannot create ignore response");
44629
45821
  await this.emitRunEnded(runtime, runId, message, startTime, "noMessageId");
44630
45822
  return {
44631
45823
  didRespond: false,
@@ -44653,14 +45845,14 @@ ${response}`);
44653
45845
  createdAt: Date.now()
44654
45846
  };
44655
45847
  await runtime.createMemory(ignoreMemory, "messages");
44656
- runtime.logger.debug("[MessageService] Saved ignore response to memory", `memoryId: ${ignoreMemory.id}`);
45848
+ runtime.logger.debug({ src: "service:message", memoryId: ignoreMemory.id }, "Saved ignore response to memory");
44657
45849
  }
44658
45850
  agentResponses.delete(message.roomId);
44659
45851
  if (agentResponses.size === 0) {
44660
45852
  latestResponseIds.delete(runtime.agentId);
44661
45853
  }
44662
45854
  await runtime.evaluate(message, state, shouldRespondToMessage, async (content) => {
44663
- runtime.logger.debug({ content }, "evaluate callback");
45855
+ runtime.logger.debug({ src: "service:message", content }, "Evaluate callback");
44664
45856
  if (responseContent) {
44665
45857
  responseContent.evalCallbacks = content;
44666
45858
  }
@@ -44733,7 +45925,7 @@ ${response}`);
44733
45925
  mode
44734
45926
  };
44735
45927
  } catch (error) {
44736
- console.error("error is", error);
45928
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error processing message");
44737
45929
  await runtime.emitEvent("RUN_ENDED" /* RUN_ENDED */, {
44738
45930
  runtime,
44739
45931
  runId,
@@ -44794,7 +45986,7 @@ ${response}`);
44794
45986
  if (!attachments || attachments.length === 0) {
44795
45987
  return [];
44796
45988
  }
44797
- runtime.logger.debug(`[MessageService] Processing ${attachments.length} attachment(s)`);
45989
+ runtime.logger.debug({ src: "service:message", count: attachments.length }, "Processing attachments");
44798
45990
  const processedAttachments = [];
44799
45991
  for (const attachment of attachments) {
44800
45992
  try {
@@ -44802,7 +45994,7 @@ ${response}`);
44802
45994
  const isRemote = /^(http|https):\/\//.test(attachment.url);
44803
45995
  const url = isRemote ? attachment.url : getLocalServerUrl(attachment.url);
44804
45996
  if (attachment.contentType === "image" /* IMAGE */ && !attachment.description) {
44805
- runtime.logger.debug(`[MessageService] Generating description for image: ${attachment.url}`);
45997
+ runtime.logger.debug({ src: "service:message", imageUrl: attachment.url }, "Generating image description");
44806
45998
  let imageUrl = url;
44807
45999
  if (!isRemote) {
44808
46000
  const res = await fetch(url);
@@ -44824,7 +46016,10 @@ ${response}`);
44824
46016
  processedAttachment.description = parsedXml.description || "";
44825
46017
  processedAttachment.title = parsedXml.title || "Image";
44826
46018
  processedAttachment.text = parsedXml.text || parsedXml.description || "";
44827
- runtime.logger.debug(`[MessageService] Generated description: ${processedAttachment.description?.substring(0, 100)}...`);
46019
+ runtime.logger.debug({
46020
+ src: "service:message",
46021
+ descriptionPreview: processedAttachment.description?.substring(0, 100)
46022
+ }, "Generated image description");
44828
46023
  } else {
44829
46024
  const responseStr = response;
44830
46025
  const titleMatch = responseStr.match(/<title>([^<]+)<\/title>/);
@@ -44834,21 +46029,27 @@ ${response}`);
44834
46029
  processedAttachment.title = titleMatch?.[1] || "Image";
44835
46030
  processedAttachment.description = descMatch?.[1] || "";
44836
46031
  processedAttachment.text = textMatch?.[1] || descMatch?.[1] || "";
44837
- runtime.logger.debug(`[MessageService] Used fallback XML parsing - description: ${processedAttachment.description?.substring(0, 100)}...`);
46032
+ runtime.logger.debug({
46033
+ src: "service:message",
46034
+ descriptionPreview: processedAttachment.description?.substring(0, 100)
46035
+ }, "Used fallback XML parsing for description");
44838
46036
  } else {
44839
- runtime.logger.warn(`[MessageService] Failed to parse XML response for image description`);
46037
+ runtime.logger.warn({ src: "service:message" }, "Failed to parse XML response for image description");
44840
46038
  }
44841
46039
  }
44842
46040
  } else if (response && typeof response === "object" && "description" in response) {
44843
46041
  processedAttachment.description = response.description;
44844
46042
  processedAttachment.title = response.title || "Image";
44845
46043
  processedAttachment.text = response.description;
44846
- runtime.logger.debug(`[MessageService] Generated description: ${processedAttachment.description?.substring(0, 100)}...`);
46044
+ runtime.logger.debug({
46045
+ src: "service:message",
46046
+ descriptionPreview: processedAttachment.description?.substring(0, 100)
46047
+ }, "Generated image description");
44847
46048
  } else {
44848
- runtime.logger.warn(`[MessageService] Unexpected response format for image description`);
46049
+ runtime.logger.warn({ src: "service:message" }, "Unexpected response format for image description");
44849
46050
  }
44850
46051
  } catch (error) {
44851
- runtime.logger.error({ error }, `[MessageService] Error generating image description:`);
46052
+ runtime.logger.error({ src: "service:message", error }, "Error generating image description");
44852
46053
  }
44853
46054
  } else if (attachment.contentType === "document" /* DOCUMENT */ && !attachment.text) {
44854
46055
  const res = await fetch(url);
@@ -44857,18 +46058,18 @@ ${response}`);
44857
46058
  const contentType = res.headers.get("content-type") || "";
44858
46059
  const isPlainText = contentType.startsWith("text/plain");
44859
46060
  if (isPlainText) {
44860
- runtime.logger.debug(`[MessageService] Processing plain text document: ${attachment.url}`);
46061
+ runtime.logger.debug({ src: "service:message", documentUrl: attachment.url }, "Processing plain text document");
44861
46062
  const textContent = await res.text();
44862
46063
  processedAttachment.text = textContent;
44863
46064
  processedAttachment.title = processedAttachment.title || "Text File";
44864
- runtime.logger.debug(`[MessageService] Extracted text content (first 100 chars): ${processedAttachment.text?.substring(0, 100)}...`);
46065
+ runtime.logger.debug({ src: "service:message", textPreview: processedAttachment.text?.substring(0, 100) }, "Extracted text content");
44865
46066
  } else {
44866
- runtime.logger.warn(`[MessageService] Skipping non-plain-text document: ${contentType}`);
46067
+ runtime.logger.warn({ src: "service:message", contentType }, "Skipping non-plain-text document");
44867
46068
  }
44868
46069
  }
44869
46070
  processedAttachments.push(processedAttachment);
44870
46071
  } catch (error) {
44871
- runtime.logger.error({ error, attachmentUrl: attachment.url }, `[MessageService] Failed to process attachment ${attachment.url}:`);
46072
+ runtime.logger.error({ src: "service:message", error, attachmentUrl: attachment.url }, "Failed to process attachment");
44872
46073
  processedAttachments.push(attachment);
44873
46074
  }
44874
46075
  }
@@ -44877,7 +46078,7 @@ ${response}`);
44877
46078
  async runSingleShotCore(runtime, message, state, opts) {
44878
46079
  state = await runtime.composeState(message, ["ACTIONS"]);
44879
46080
  if (!state.values?.actionNames) {
44880
- runtime.logger.warn("actionNames data missing from state, even though it was requested");
46081
+ runtime.logger.warn({ src: "service:message" }, "actionNames data missing from state");
44881
46082
  }
44882
46083
  const prompt = composePromptFromState({
44883
46084
  state,
@@ -44887,9 +46088,9 @@ ${response}`);
44887
46088
  let retries = 0;
44888
46089
  while (retries < opts.maxRetries && (!responseContent?.thought || !responseContent?.actions)) {
44889
46090
  const response = await runtime.useModel(ModelType.TEXT_LARGE, { prompt });
44890
- runtime.logger.debug({ response }, "[MessageService] *** Raw LLM Response ***");
46091
+ runtime.logger.debug({ src: "service:message", response }, "Raw LLM response");
44891
46092
  const parsedXml = parseKeyValueXml(response);
44892
- runtime.logger.debug({ parsedXml }, "[MessageService] *** Parsed XML Content ***");
46093
+ runtime.logger.debug({ src: "service:message", parsedXml }, "Parsed XML content");
44893
46094
  if (parsedXml) {
44894
46095
  responseContent = {
44895
46096
  ...parsedXml,
@@ -44904,7 +46105,7 @@ ${response}`);
44904
46105
  }
44905
46106
  retries++;
44906
46107
  if (!responseContent?.thought || !responseContent?.actions) {
44907
- runtime.logger.warn({ response, parsedXml, responseContent }, "[MessageService] *** Missing required fields (thought or actions), retrying... ***");
46108
+ runtime.logger.warn({ src: "service:message", retries, maxRetries: opts.maxRetries }, "Missing required fields (thought or actions), retrying");
44908
46109
  }
44909
46110
  }
44910
46111
  if (!responseContent) {
@@ -44947,7 +46148,11 @@ ${response}`);
44947
46148
  let iterationCount = 0;
44948
46149
  while (iterationCount < opts.maxMultiStepIterations) {
44949
46150
  iterationCount++;
44950
- runtime.logger.debug(`[MultiStep] Starting iteration ${iterationCount}/${opts.maxMultiStepIterations}`);
46151
+ runtime.logger.debug({
46152
+ src: "service:message",
46153
+ iteration: iterationCount,
46154
+ maxIterations: opts.maxMultiStepIterations
46155
+ }, "Starting multi-step iteration");
44951
46156
  accumulatedState = await runtime.composeState(message, [
44952
46157
  "RECENT_MESSAGES",
44953
46158
  "ACTION_STATE"
@@ -44960,7 +46165,7 @@ ${response}`);
44960
46165
  const stepResultRaw = await runtime.useModel(ModelType.TEXT_LARGE, { prompt });
44961
46166
  const parsedStep = parseKeyValueXml(stepResultRaw);
44962
46167
  if (!parsedStep) {
44963
- runtime.logger.warn(`[MultiStep] Failed to parse step result at iteration ${iterationCount}`);
46168
+ runtime.logger.warn({ src: "service:message", iteration: iterationCount }, "Failed to parse multi-step result");
44964
46169
  traceActionResult.push({
44965
46170
  data: { actionName: "parse_error" },
44966
46171
  success: false,
@@ -44970,7 +46175,7 @@ ${response}`);
44970
46175
  }
44971
46176
  const { thought, providers = [], action, isFinish } = parsedStep;
44972
46177
  if (isFinish === "true" || isFinish === true) {
44973
- runtime.logger.info(`[MultiStep] Task marked as complete at iteration ${iterationCount}`);
46178
+ runtime.logger.info({ src: "service:message", agentId: runtime.agentId, iteration: iterationCount }, "Multi-step task completed");
44974
46179
  if (callback) {
44975
46180
  await callback({
44976
46181
  text: "",
@@ -44980,14 +46185,14 @@ ${response}`);
44980
46185
  break;
44981
46186
  }
44982
46187
  if ((!providers || providers.length === 0) && !action) {
44983
- runtime.logger.warn(`[MultiStep] No providers or action specified at iteration ${iterationCount}, forcing completion`);
46188
+ runtime.logger.warn({ src: "service:message", iteration: iterationCount }, "No providers or action specified, forcing completion");
44984
46189
  break;
44985
46190
  }
44986
46191
  try {
44987
46192
  for (const providerName of providers) {
44988
46193
  const provider = runtime.providers.find((p) => p.name === providerName);
44989
46194
  if (!provider) {
44990
- runtime.logger.warn(`[MultiStep] Provider not found: ${providerName}`);
46195
+ runtime.logger.warn({ src: "service:message", providerName }, "Provider not found");
44991
46196
  traceActionResult.push({
44992
46197
  data: { actionName: providerName },
44993
46198
  success: false,
@@ -44997,7 +46202,7 @@ ${response}`);
44997
46202
  }
44998
46203
  const providerResult = await provider.get(runtime, message, state);
44999
46204
  if (!providerResult) {
45000
- runtime.logger.warn(`[MultiStep] Provider returned no result: ${providerName}`);
46205
+ runtime.logger.warn({ src: "service:message", providerName }, "Provider returned no result");
45001
46206
  traceActionResult.push({
45002
46207
  data: { actionName: providerName },
45003
46208
  success: false,
@@ -45050,7 +46255,7 @@ ${response}`);
45050
46255
  });
45051
46256
  }
45052
46257
  } catch (err) {
45053
- runtime.logger.error({ err }, "[MultiStep] Error executing step");
46258
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error: err }, "Error executing multi-step action");
45054
46259
  traceActionResult.push({
45055
46260
  data: { actionName: action || "unknown" },
45056
46261
  success: false,
@@ -45059,7 +46264,7 @@ ${response}`);
45059
46264
  }
45060
46265
  }
45061
46266
  if (iterationCount >= opts.maxMultiStepIterations) {
45062
- runtime.logger.warn(`[MultiStep] Reached maximum iterations (${opts.maxMultiStepIterations}), forcing completion`);
46267
+ runtime.logger.warn({ src: "service:message", maxIterations: opts.maxMultiStepIterations }, "Reached maximum iterations, forcing completion");
45063
46268
  }
45064
46269
  accumulatedState = await runtime.composeState(message, [
45065
46270
  "RECENT_MESSAGES",
@@ -45114,25 +46319,30 @@ ${response}`);
45114
46319
  async deleteMessage(runtime, message) {
45115
46320
  try {
45116
46321
  if (!message.id) {
45117
- runtime.logger.error("[MessageService] Cannot delete memory: message ID is missing");
46322
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId }, "Cannot delete memory: message ID is missing");
45118
46323
  return;
45119
46324
  }
45120
- runtime.logger.info("[MessageService] Deleting memory for message", message.id, "from room", message.roomId);
46325
+ runtime.logger.info({
46326
+ src: "service:message",
46327
+ agentId: runtime.agentId,
46328
+ messageId: message.id,
46329
+ roomId: message.roomId
46330
+ }, "Deleting memory");
45121
46331
  await runtime.deleteMemory(message.id);
45122
- runtime.logger.debug({ messageId: message.id }, "[MessageService] Successfully deleted memory for message");
46332
+ runtime.logger.debug({ src: "service:message", messageId: message.id }, "Successfully deleted memory");
45123
46333
  } catch (error) {
45124
- runtime.logger.error({ error }, "[MessageService] Error in deleteMessage:");
46334
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error in deleteMessage");
45125
46335
  throw error;
45126
46336
  }
45127
46337
  }
45128
46338
  async clearChannel(runtime, roomId, channelId) {
45129
46339
  try {
45130
- runtime.logger.info(`[MessageService] Clearing message memories from channel ${channelId} -> room ${roomId}`);
46340
+ runtime.logger.info({ src: "service:message", agentId: runtime.agentId, channelId, roomId }, "Clearing message memories from channel");
45131
46341
  const memories = await runtime.getMemoriesByRoomIds({
45132
46342
  tableName: "messages",
45133
46343
  roomIds: [roomId]
45134
46344
  });
45135
- runtime.logger.info(`[MessageService] Found ${memories.length} message memories to delete from channel ${channelId}`);
46345
+ runtime.logger.debug({ src: "service:message", channelId, count: memories.length }, "Found message memories to delete");
45136
46346
  let deletedCount = 0;
45137
46347
  for (const memory of memories) {
45138
46348
  if (memory.id) {
@@ -45140,13 +46350,19 @@ ${response}`);
45140
46350
  await runtime.deleteMemory(memory.id);
45141
46351
  deletedCount++;
45142
46352
  } catch (error) {
45143
- runtime.logger.warn({ error, memoryId: memory.id }, `[MessageService] Failed to delete message memory ${memory.id}:`);
46353
+ runtime.logger.warn({ src: "service:message", error, memoryId: memory.id }, "Failed to delete message memory");
45144
46354
  }
45145
46355
  }
45146
46356
  }
45147
- runtime.logger.info(`[MessageService] Successfully cleared ${deletedCount}/${memories.length} message memories from channel ${channelId}`);
46357
+ runtime.logger.info({
46358
+ src: "service:message",
46359
+ agentId: runtime.agentId,
46360
+ channelId,
46361
+ deletedCount,
46362
+ totalCount: memories.length
46363
+ }, "Cleared message memories from channel");
45148
46364
  } catch (error) {
45149
- runtime.logger.error({ error }, "[MessageService] Error in clearChannel:");
46365
+ runtime.logger.error({ src: "service:message", agentId: runtime.agentId, error }, "Error in clearChannel");
45150
46366
  throw error;
45151
46367
  }
45152
46368
  }
@@ -46025,8 +47241,8 @@ class AgentRuntime {
46025
47241
  initPromise;
46026
47242
  initResolver;
46027
47243
  initRejecter;
46028
- migratedPlugins = new Set;
46029
47244
  currentRunId;
47245
+ currentRoomId;
46030
47246
  currentActionContext;
46031
47247
  maxWorkingMemoryEntries = 50;
46032
47248
  messageService = null;
@@ -46055,7 +47271,7 @@ class AgentRuntime {
46055
47271
  }
46056
47272
  }
46057
47273
  }
46058
- this.logger.debug(`Success: Agent ID: ${this.agentId}`);
47274
+ this.logger.debug({ src: "agent", agentId: this.agentId, agentName: this.character?.name }, "Initialized");
46059
47275
  this.currentRunId = undefined;
46060
47276
  if (opts.settings?.MAX_WORKING_MEMORY_ENTRIES) {
46061
47277
  this.maxWorkingMemoryEntries = parseInt(opts.settings.MAX_WORKING_MEMORY_ENTRIES, 10) || 50;
@@ -46066,12 +47282,14 @@ class AgentRuntime {
46066
47282
  createRunId() {
46067
47283
  return v4_default();
46068
47284
  }
46069
- startRun() {
47285
+ startRun(roomId) {
46070
47286
  this.currentRunId = this.createRunId();
47287
+ this.currentRoomId = roomId;
46071
47288
  return this.currentRunId;
46072
47289
  }
46073
47290
  endRun() {
46074
47291
  this.currentRunId = undefined;
47292
+ this.currentRoomId = undefined;
46075
47293
  }
46076
47294
  getCurrentRunId() {
46077
47295
  if (!this.currentRunId) {
@@ -46082,20 +47300,20 @@ class AgentRuntime {
46082
47300
  async registerPlugin(plugin) {
46083
47301
  if (!plugin?.name) {
46084
47302
  const errorMsg = "Plugin or plugin name is undefined";
46085
- this.logger.error(`*** registerPlugin: ${errorMsg}`);
46086
- throw new Error(`*** registerPlugin: ${errorMsg}`);
47303
+ this.logger.error({ src: "agent", agentId: this.agentId, error: errorMsg }, "Plugin registration failed");
47304
+ throw new Error(`registerPlugin: ${errorMsg}`);
46087
47305
  }
46088
47306
  const existingPlugin = this.plugins.find((p) => p.name === plugin.name);
46089
47307
  if (existingPlugin) {
46090
- this.logger.warn(`${this.character.name}(${this.agentId}) - Plugin ${plugin.name} is already registered. Skipping re-registration.`);
47308
+ this.logger.warn({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin already registered, skipping");
46091
47309
  return;
46092
47310
  }
46093
47311
  this.plugins.push(plugin);
46094
- this.logger.debug(`Success: Plugin ${plugin.name} added to active plugins for ${this.character.name}(${this.agentId}).`);
47312
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin added");
46095
47313
  if (plugin.init) {
46096
47314
  try {
46097
47315
  await plugin.init(plugin.config || {}, this);
46098
- this.logger.debug(`Success: Plugin ${plugin.name} initialized successfully`);
47316
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Plugin initialized");
46099
47317
  } catch (error) {
46100
47318
  const errorMessage = error instanceof Error ? error.message : String(error);
46101
47319
  if (errorMessage.includes("API key") || errorMessage.includes("environment variables") || errorMessage.includes("Invalid plugin configuration")) {
@@ -46108,7 +47326,7 @@ class AgentRuntime {
46108
47326
  }
46109
47327
  }
46110
47328
  if (plugin.adapter) {
46111
- this.logger.debug(`Registering database adapter for plugin ${plugin.name}`);
47329
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name }, "Registering database adapter");
46112
47330
  this.registerDatabaseAdapter(plugin.adapter);
46113
47331
  }
46114
47332
  if (plugin.actions) {
@@ -46146,20 +47364,28 @@ class AgentRuntime {
46146
47364
  }
46147
47365
  if (plugin.services) {
46148
47366
  for (const service of plugin.services) {
46149
- if (!this.servicePromises.has(service.serviceType)) {
46150
- this._createServiceResolver(service.serviceType);
47367
+ const serviceType = service.serviceType;
47368
+ this.logger.debug({ src: "agent", agentId: this.agentId, plugin: plugin.name, serviceType }, "Registering service");
47369
+ if (!this.servicePromises.has(serviceType)) {
47370
+ this._createServiceResolver(serviceType);
46151
47371
  }
46152
- this.serviceRegistrationStatus.set(service.serviceType, "pending");
47372
+ this.serviceRegistrationStatus.set(serviceType, "pending");
46153
47373
  this.registerService(service).catch((error) => {
46154
- this.logger.error(`Service registration failed for ${service.serviceType}: ${error instanceof Error ? error.message : String(error)}`);
46155
- const handler = this.servicePromiseHandlers.get(service.serviceType);
47374
+ this.logger.error({
47375
+ src: "agent",
47376
+ agentId: this.agentId,
47377
+ plugin: plugin.name,
47378
+ serviceType,
47379
+ error: error instanceof Error ? error.message : String(error)
47380
+ }, "Service registration failed");
47381
+ const handler = this.servicePromiseHandlers.get(serviceType);
46156
47382
  if (handler) {
46157
- const serviceError = new Error(`Service ${service.serviceType} failed to register: ${error instanceof Error ? error.message : String(error)}`);
47383
+ const serviceError = new Error(`Service ${serviceType} from plugin ${plugin.name} failed to register: ${error instanceof Error ? error.message : String(error)}`);
46158
47384
  handler.reject(serviceError);
46159
- this.servicePromiseHandlers.delete(service.serviceType);
46160
- this.servicePromises.delete(service.serviceType);
47385
+ this.servicePromiseHandlers.delete(serviceType);
47386
+ this.servicePromises.delete(serviceType);
46161
47387
  }
46162
- this.serviceRegistrationStatus.set(service.serviceType, "failed");
47388
+ this.serviceRegistrationStatus.set(serviceType, "failed");
46163
47389
  });
46164
47390
  }
46165
47391
  }
@@ -46168,9 +47394,9 @@ class AgentRuntime {
46168
47394
  return this.services;
46169
47395
  }
46170
47396
  async stop() {
46171
- this.logger.debug(`runtime::stop - character ${this.character.name}`);
46172
- for (const [serviceName, services] of this.services) {
46173
- this.logger.debug(`runtime::stop - requesting service stop for ${serviceName}`);
47397
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Stopping runtime");
47398
+ for (const [serviceType, services] of this.services) {
47399
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Stopping service");
46174
47400
  for (const service of services) {
46175
47401
  await service.stop();
46176
47402
  }
@@ -46188,8 +47414,7 @@ class AgentRuntime {
46188
47414
  }
46189
47415
  await Promise.all(pluginRegistrationPromises);
46190
47416
  if (!this.adapter) {
46191
- const errorMsg = "Database adapter not initialized. Make sure @elizaos/plugin-sql is included in your plugins.";
46192
- this.logger.error(errorMsg);
47417
+ this.logger.error({ src: "agent", agentId: this.agentId }, "Database adapter not initialized");
46193
47418
  throw new Error("Database adapter not initialized. The SQL plugin (@elizaos/plugin-sql) is required for agent initialization. Please ensure it is included in your character configuration.");
46194
47419
  }
46195
47420
  if (!await this.adapter.isReady()) {
@@ -46198,11 +47423,11 @@ class AgentRuntime {
46198
47423
  this.messageService = new DefaultMessageService;
46199
47424
  const skipMigrations = options?.skipMigrations ?? false;
46200
47425
  if (skipMigrations) {
46201
- this.logger.info("Skipping plugin migrations (skipMigrations=true)");
47426
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Skipping plugin migrations");
46202
47427
  } else {
46203
- this.logger.info("Running plugin migrations...");
47428
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Running plugin migrations");
46204
47429
  await this.runPluginMigrations();
46205
- this.logger.info("Plugin migrations completed.");
47430
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
46206
47431
  }
46207
47432
  const existingAgent = await this.ensureAgentExists({
46208
47433
  ...this.character,
@@ -46245,7 +47470,7 @@ class AgentRuntime {
46245
47470
  agentEntity = await this.getEntityById(this.agentId);
46246
47471
  if (!agentEntity)
46247
47472
  throw new Error(`Agent entity not found for ${this.agentId}`);
46248
- this.logger.debug(`Success: Agent entity created successfully for ${this.character.name}`);
47473
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent entity created");
46249
47474
  }
46250
47475
  const room = await this.getRoom(this.agentId);
46251
47476
  if (!room) {
@@ -46255,7 +47480,7 @@ class AgentRuntime {
46255
47480
  source: "elizaos",
46256
47481
  type: "SELF" /* SELF */,
46257
47482
  channelId: this.agentId,
46258
- serverId: this.agentId,
47483
+ messageServerId: this.agentId,
46259
47484
  worldId: this.agentId
46260
47485
  });
46261
47486
  }
@@ -46263,14 +47488,13 @@ class AgentRuntime {
46263
47488
  if (!participants.includes(this.agentId)) {
46264
47489
  const added = await this.addParticipant(this.agentId, this.agentId);
46265
47490
  if (!added) {
46266
- const errorMsg = `Failed to add agent ${this.agentId} as participant to its own room`;
46267
- throw new Error(errorMsg);
47491
+ throw new Error(`Failed to add agent ${this.agentId} as participant to its own room`);
46268
47492
  }
46269
- this.logger.debug(`Agent ${this.character.name} linked to its own room successfully`);
47493
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Agent linked to room");
46270
47494
  }
46271
47495
  const embeddingModel = this.getModel(ModelType.TEXT_EMBEDDING);
46272
47496
  if (!embeddingModel) {
46273
- this.logger.warn(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered. Skipping embedding dimension setup.`);
47497
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "No TEXT_EMBEDDING model registered, skipping embedding setup");
46274
47498
  } else {
46275
47499
  await this.ensureEmbeddingDimension();
46276
47500
  }
@@ -46280,7 +47504,7 @@ class AgentRuntime {
46280
47504
  }
46281
47505
  } catch (error) {
46282
47506
  const errorMsg = error instanceof Error ? error.message : String(error);
46283
- this.logger.error(`Runtime initialization failed: ${errorMsg}`);
47507
+ this.logger.error({ src: "agent", agentId: this.agentId, error: errorMsg }, "Runtime initialization failed");
46284
47508
  if (this.initRejecter) {
46285
47509
  this.initRejecter(error);
46286
47510
  this.initRejecter = undefined;
@@ -46300,31 +47524,34 @@ class AgentRuntime {
46300
47524
  }
46301
47525
  async runPluginMigrations() {
46302
47526
  if (!this.adapter) {
46303
- this.logger.warn("Database adapter not found, skipping plugin migrations.");
47527
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter not found, skipping plugin migrations");
46304
47528
  return;
46305
47529
  }
46306
47530
  if (typeof this.adapter.runPluginMigrations !== "function") {
46307
- this.logger.warn("Database adapter does not support plugin migrations.");
47531
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter does not support plugin migrations");
46308
47532
  return;
46309
47533
  }
46310
47534
  const pluginsWithSchemas = this.plugins.filter((p) => p.schema).map((p) => ({ name: p.name, schema: p.schema }));
46311
47535
  if (pluginsWithSchemas.length === 0) {
46312
- this.logger.info("No plugins with schemas found, skipping migrations.");
47536
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "No plugins with schemas, skipping migrations");
46313
47537
  return;
46314
47538
  }
46315
- this.logger.info(`Found ${pluginsWithSchemas.length} plugins with schemas to migrate.`);
47539
+ this.logger.debug({ src: "agent", agentId: this.agentId, count: pluginsWithSchemas.length }, "Found plugins with schemas");
46316
47540
  try {
46317
47541
  const isProduction = false;
46318
47542
  const forceDestructive = process.env.ELIZA_ALLOW_DESTRUCTIVE_MIGRATIONS === "true";
46319
- const options = {
47543
+ await this.adapter.runPluginMigrations(pluginsWithSchemas, {
46320
47544
  verbose: !isProduction,
46321
47545
  force: forceDestructive,
46322
47546
  dryRun: false
46323
- };
46324
- await this.adapter.runPluginMigrations(pluginsWithSchemas, options);
46325
- this.logger.info("Plugin migrations completed successfully.");
47547
+ });
47548
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Plugin migrations completed");
46326
47549
  } catch (error) {
46327
- this.logger.error(error instanceof Error ? error : new Error(String(error)), "Failed to run plugin migrations");
47550
+ this.logger.error({
47551
+ src: "agent",
47552
+ agentId: this.agentId,
47553
+ error: error instanceof Error ? error.message : String(error)
47554
+ }, "Plugin migrations failed");
46328
47555
  throw error;
46329
47556
  }
46330
47557
  }
@@ -46361,26 +47588,22 @@ class AgentRuntime {
46361
47588
  }
46362
47589
  registerDatabaseAdapter(adapter) {
46363
47590
  if (this.adapter) {
46364
- this.logger.warn("Database adapter already registered. Additional adapters will be ignored. This may lead to unexpected behavior.");
47591
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter already registered, ignoring");
46365
47592
  } else {
46366
47593
  this.adapter = adapter;
46367
- this.logger.debug("Success: Database adapter registered successfully.");
47594
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "Database adapter registered");
46368
47595
  }
46369
47596
  }
46370
47597
  registerProvider(provider) {
46371
47598
  this.providers.push(provider);
46372
- this.logger.debug(`Success: Provider ${provider.name} registered successfully.`);
47599
+ this.logger.debug({ src: "agent", agentId: this.agentId, provider: provider.name }, "Provider registered");
46373
47600
  }
46374
47601
  registerAction(action) {
46375
47602
  if (this.actions.find((a) => a.name === action.name)) {
46376
- this.logger.warn(`${this.character.name}(${this.agentId}) - Action ${action.name} already exists. Skipping registration.`);
47603
+ this.logger.warn({ src: "agent", agentId: this.agentId, action: action.name }, "Action already registered, skipping");
46377
47604
  } else {
46378
- try {
46379
- this.actions.push(action);
46380
- this.logger.success(`${this.character.name}(${this.agentId}) - Action ${action.name} registered successfully.`);
46381
- } catch (e) {
46382
- console.error("Error registering action", e);
46383
- }
47605
+ this.actions.push(action);
47606
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Action registered");
46384
47607
  }
46385
47608
  }
46386
47609
  registerEvaluator(evaluator) {
@@ -46391,7 +47614,7 @@ class AgentRuntime {
46391
47614
  }
46392
47615
  updateActionStep(plan, index, stepUpdates) {
46393
47616
  if (!plan.steps || index < 0 || index >= plan.steps.length) {
46394
- this.logger.warn(`Invalid step index: ${index} for plan with ${plan.steps?.length || 0} steps`);
47617
+ this.logger.warn({ src: "agent", agentId: this.agentId, index, stepsCount: plan.steps?.length || 0 }, "Invalid step index");
46395
47618
  return plan;
46396
47619
  }
46397
47620
  return {
@@ -46430,13 +47653,17 @@ class AgentRuntime {
46430
47653
  return actionString.toLowerCase().replace(/_/g, "");
46431
47654
  };
46432
47655
  if (!response.content?.actions || response.content.actions.length === 0) {
46433
- this.logger.warn("No action found in the response content.");
47656
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "No action found in response");
46434
47657
  continue;
46435
47658
  }
46436
47659
  const actions = response.content.actions;
46437
47660
  const actionResults = [];
46438
47661
  let accumulatedState = state;
46439
- this.logger.debug(`Found actions: ${this.actions.map((a) => normalizeAction(a.name))}`);
47662
+ this.logger.trace({
47663
+ src: "agent",
47664
+ agentId: this.agentId,
47665
+ actions: this.actions.map((a) => normalizeAction(a.name))
47666
+ }, "Available actions");
46440
47667
  for (const responseAction of actions) {
46441
47668
  if (actionPlan) {
46442
47669
  actionPlan = this.updateActionPlan(actionPlan, { currentStep: actionIndex + 1 });
@@ -46449,34 +47676,31 @@ class AgentRuntime {
46449
47676
  accumulatedState.data.actionPlan = actionPlan;
46450
47677
  accumulatedState.data.actionResults = actionResults;
46451
47678
  }
46452
- this.logger.debug(`Success: Calling action: ${responseAction}`);
47679
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: responseAction }, "Processing action");
46453
47680
  const normalizedResponseAction = normalizeAction(responseAction);
46454
47681
  let action = this.actions.find((a) => normalizeAction(a.name) === normalizedResponseAction);
46455
47682
  if (!action) {
46456
47683
  action = this.actions.find((a) => normalizeAction(a.name).includes(normalizedResponseAction) || normalizedResponseAction.includes(normalizeAction(a.name)));
46457
47684
  }
46458
- if (action) {
46459
- this.logger.debug(`Success: Found action: ${action?.name}`);
46460
- } else {
46461
- this.logger.debug("Attempting to find action in similes.");
47685
+ if (!action) {
46462
47686
  for (const _action of this.actions) {
46463
47687
  const exactSimileMatch = _action.similes?.find((simile) => normalizeAction(simile) === normalizedResponseAction);
46464
47688
  if (exactSimileMatch) {
46465
47689
  action = _action;
46466
- this.logger.debug(`Success: Action found in similes (exact match): ${action.name}`);
47690
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name, match: "simile" }, "Action resolved via simile");
46467
47691
  break;
46468
47692
  }
46469
47693
  const fuzzySimileMatch = _action.similes?.find((simile) => normalizeAction(simile).includes(normalizedResponseAction) || normalizedResponseAction.includes(normalizeAction(simile)));
46470
47694
  if (fuzzySimileMatch) {
46471
47695
  action = _action;
46472
- this.logger.debug(`Success: Action found in similes (fuzzy match): ${action.name}`);
47696
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name, match: "fuzzy" }, "Action resolved via fuzzy match");
46473
47697
  break;
46474
47698
  }
46475
47699
  }
46476
47700
  }
46477
47701
  if (!action) {
46478
- const errorMsg = `No action found for: ${responseAction}`;
46479
- this.logger.error(errorMsg);
47702
+ const errorMsg = `Action not found: ${responseAction}`;
47703
+ this.logger.error({ src: "agent", agentId: this.agentId, action: responseAction }, "Action not found");
46480
47704
  if (actionPlan && actionPlan.steps[actionIndex]) {
46481
47705
  actionPlan = this.updateActionStep(actionPlan, actionIndex, {
46482
47706
  status: "failed",
@@ -46502,7 +47726,7 @@ class AgentRuntime {
46502
47726
  continue;
46503
47727
  }
46504
47728
  if (!action.handler) {
46505
- this.logger.error(`Action ${action.name} has no handler.`);
47729
+ this.logger.error({ src: "agent", agentId: this.agentId, action: action.name }, "Action has no handler");
46506
47730
  if (actionPlan && actionPlan.steps[actionIndex]) {
46507
47731
  actionPlan = this.updateActionStep(actionPlan, actionIndex, {
46508
47732
  status: "failed",
@@ -46513,7 +47737,7 @@ class AgentRuntime {
46513
47737
  continue;
46514
47738
  }
46515
47739
  try {
46516
- this.logger.debug(`Executing handler for action: ${action.name}`);
47740
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Executing action");
46517
47741
  const actionId = v4_default();
46518
47742
  this.currentActionContext = {
46519
47743
  actionName: action.name,
@@ -46538,7 +47762,6 @@ class AgentRuntime {
46538
47762
  };
46539
47763
  }
46540
47764
  try {
46541
- this.logger.debug(`Creating action start message for: ${action.name}`);
46542
47765
  await this.emitEvent("ACTION_STARTED" /* ACTION_STARTED */, {
46543
47766
  messageId: actionId,
46544
47767
  roomId: message.roomId,
@@ -46555,7 +47778,7 @@ class AgentRuntime {
46555
47778
  }
46556
47779
  });
46557
47780
  } catch (error) {
46558
- this.logger.error("Failed to create action start message:", String(error));
47781
+ this.logger.error({ src: "agent", agentId: this.agentId, action: action.name, error: String(error) }, "Failed to emit action start event");
46559
47782
  }
46560
47783
  let storedCallbackData = [];
46561
47784
  const storageCallback = async (response2) => {
@@ -46640,8 +47863,12 @@ class AgentRuntime {
46640
47863
  }
46641
47864
  });
46642
47865
  } catch (error) {
46643
- const errorMessage = error instanceof Error ? error.message : String(error);
46644
- this.logger.error(`Failed to emit ACTION_COMPLETED event for action ${action.name} (${actionId}): ${errorMessage}`);
47866
+ this.logger.error({
47867
+ src: "agent",
47868
+ agentId: this.agentId,
47869
+ action: action.name,
47870
+ error: error instanceof Error ? error.message : String(error)
47871
+ }, "Failed to emit ACTION_COMPLETED event");
46645
47872
  }
46646
47873
  if (callback) {
46647
47874
  for (const content of storedCallbackData) {
@@ -46679,13 +47906,7 @@ class AgentRuntime {
46679
47906
  }
46680
47907
  };
46681
47908
  await this.createMemory(actionMemory, "messages");
46682
- this.logger.debug(`Action ${action.name} completed`, JSON.stringify({
46683
- isLegacyReturn,
46684
- result: isLegacyReturn ? result : undefined,
46685
- hasValues: actionResult ? !!actionResult.values : false,
46686
- hasData: actionResult ? !!actionResult.data : false,
46687
- hasText: actionResult ? !!actionResult.text : false
46688
- }));
47909
+ this.logger.debug({ src: "agent", agentId: this.agentId, action: action.name }, "Action completed");
46689
47910
  await this.adapter.log({
46690
47911
  entityId: message.entityId,
46691
47912
  roomId: message.roomId,
@@ -46712,7 +47933,7 @@ class AgentRuntime {
46712
47933
  this.currentActionContext = undefined;
46713
47934
  } catch (error) {
46714
47935
  const errorMessage = error instanceof Error ? error.message : String(error);
46715
- this.logger.error(error);
47936
+ this.logger.error({ src: "agent", agentId: this.agentId, action: action.name, error: errorMessage }, "Action execution failed");
46716
47937
  if (actionPlan && actionPlan.steps[actionIndex]) {
46717
47938
  actionPlan = this.updateActionStep(actionPlan, actionIndex, {
46718
47939
  status: "failed",
@@ -46795,7 +48016,12 @@ class AgentRuntime {
46795
48016
  }
46796
48017
  return null;
46797
48018
  } catch (error) {
46798
- this.logger.error({ error, evaluatorName: evaluator.name }, `Error validating evaluator ${evaluator.name}`);
48019
+ this.logger.error({
48020
+ src: "agent",
48021
+ agentId: this.agentId,
48022
+ evaluator: evaluator.name,
48023
+ error: error instanceof Error ? error.message : String(error)
48024
+ }, "Evaluator validation failed");
46799
48025
  return null;
46800
48026
  }
46801
48027
  });
@@ -46822,24 +48048,35 @@ class AgentRuntime {
46822
48048
  });
46823
48049
  }
46824
48050
  } catch (error) {
46825
- this.logger.error({ error, evaluatorName: evaluator.name }, `Error executing evaluator ${evaluator.name}`);
48051
+ this.logger.error({
48052
+ src: "agent",
48053
+ agentId: this.agentId,
48054
+ evaluator: evaluator.name,
48055
+ error: error instanceof Error ? error.message : String(error)
48056
+ }, "Evaluator execution failed");
46826
48057
  }
46827
48058
  }));
46828
48059
  return evaluators;
46829
48060
  } catch (error) {
46830
- this.logger.error({ error, messageId: message.id, roomId: message.roomId }, "Error in evaluate method");
48061
+ this.logger.error({
48062
+ src: "agent",
48063
+ agentId: this.agentId,
48064
+ messageId: message.id,
48065
+ channelId: message.roomId,
48066
+ error: error instanceof Error ? error.message : String(error)
48067
+ }, "Evaluate method failed");
46831
48068
  return [];
46832
48069
  }
46833
48070
  }
46834
48071
  async ensureConnections(entities, rooms, source, world) {
46835
48072
  if (!entities) {
46836
48073
  console.trace();
46837
- this.logger.error("ensureConnections - no entities");
48074
+ this.logger.error({ src: "agent", agentId: this.agentId }, "ensureConnections called without entities");
46838
48075
  return;
46839
48076
  }
46840
48077
  if (!rooms || rooms.length === 0) {
46841
48078
  console.trace();
46842
- this.logger.error("ensureConnections - no rooms");
48079
+ this.logger.error({ src: "agent", agentId: this.agentId }, "ensureConnections called without rooms");
46843
48080
  return;
46844
48081
  }
46845
48082
  await this.ensureWorldExists({ ...world, agentId: this.agentId });
@@ -46856,12 +48093,12 @@ class AgentRuntime {
46856
48093
  const roomsToCreate = roomIds.filter((id) => !roomsIdExists?.includes(id));
46857
48094
  const rf = {
46858
48095
  worldId: world.id,
46859
- serverId: world.serverId,
48096
+ messageServerId: world.messageServerId,
46860
48097
  source,
46861
48098
  agentId: this.agentId
46862
48099
  };
46863
48100
  if (roomsToCreate.length) {
46864
- this.logger.debug("runtime/ensureConnections - create", roomsToCreate.length.toLocaleString(), "rooms");
48101
+ this.logger.debug({ src: "agent", agentId: this.agentId, count: roomsToCreate.length }, "Creating rooms");
46865
48102
  const roomObjsToCreate = rooms.filter((r2) => roomsToCreate.includes(r2.id)).map((r2) => ({ ...r2, ...rf }));
46866
48103
  await this.createRooms(roomObjsToCreate);
46867
48104
  }
@@ -46876,10 +48113,10 @@ class AgentRuntime {
46876
48113
  };
46877
48114
  const wf = {
46878
48115
  worldId: world.id,
46879
- serverId: world.serverId
48116
+ messageServerId: world.messageServerId
46880
48117
  };
46881
48118
  if (entitiesToCreate.length) {
46882
- this.logger.debug("runtime/ensureConnections - creating", entitiesToCreate.length.toLocaleString(), "entities...");
48119
+ this.logger.debug({ src: "agent", agentId: this.agentId, count: entitiesToCreate.length }, "Creating entities");
46883
48120
  const ef = {
46884
48121
  ...r,
46885
48122
  ...wf,
@@ -46897,13 +48134,18 @@ class AgentRuntime {
46897
48134
  const entityIdsInFirstRoomFiltered = entityIdsInFirstRoom.filter(Boolean);
46898
48135
  const missingIdsInRoom = entityIds.filter((id) => !entityIdsInFirstRoomFiltered.includes(id));
46899
48136
  if (missingIdsInRoom.length) {
46900
- this.logger.debug("runtime/ensureConnections - Missing", missingIdsInRoom.length.toLocaleString(), "connections in", firstRoom.id);
48137
+ this.logger.debug({
48138
+ src: "agent",
48139
+ agentId: this.agentId,
48140
+ count: missingIdsInRoom.length,
48141
+ channelId: firstRoom.id
48142
+ }, "Adding missing participants");
46901
48143
  const batches = chunkArray(missingIdsInRoom, 5000);
46902
48144
  for (const batch of batches) {
46903
48145
  await this.addParticipantsRoom(batch, firstRoom.id);
46904
48146
  }
46905
48147
  }
46906
- this.logger.success(`Success: Successfully connected world`);
48148
+ this.logger.success({ src: "agent", agentId: this.agentId, worldId: world.id }, "World connected");
46907
48149
  }
46908
48150
  async ensureConnection({
46909
48151
  entityId,
@@ -46915,12 +48157,12 @@ class AgentRuntime {
46915
48157
  source,
46916
48158
  type,
46917
48159
  channelId,
46918
- serverId,
48160
+ messageServerId,
46919
48161
  userId,
46920
48162
  metadata
46921
48163
  }) {
46922
- if (!worldId && serverId) {
46923
- worldId = createUniqueUuid(this, serverId);
48164
+ if (!worldId && messageServerId) {
48165
+ worldId = createUniqueUuid(this, messageServerId);
46924
48166
  }
46925
48167
  const names3 = [name, userName].filter(Boolean);
46926
48168
  const entityMetadata = {
@@ -46941,13 +48183,13 @@ class AgentRuntime {
46941
48183
  agentId: this.agentId
46942
48184
  });
46943
48185
  if (success) {
46944
- this.logger.debug(`Created new entity ${entityId} for user ${name || userName || "unknown"}`);
48186
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, userName: name || userName }, "Entity created");
46945
48187
  } else {
46946
48188
  throw new Error(`Failed to create entity ${entityId}`);
46947
48189
  }
46948
48190
  } catch (error) {
46949
48191
  if (error.message?.includes("duplicate key") || error.code === "23505") {
46950
- this.logger.debug(`Entity ${entityId} exists in database but not for this agent. This is normal in multi-agent setups.`);
48192
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId }, "Entity exists in database (multi-agent setup)");
46951
48193
  } else {
46952
48194
  throw error;
46953
48195
  }
@@ -46970,9 +48212,9 @@ class AgentRuntime {
46970
48212
  }
46971
48213
  await this.ensureWorldExists({
46972
48214
  id: worldId,
46973
- name: worldName || serverId ? `World for server ${serverId}` : `World for room ${roomId}`,
48215
+ name: worldName || messageServerId ? `World for server ${messageServerId}` : `World for room ${roomId}`,
46974
48216
  agentId: this.agentId,
46975
- serverId: serverId || "default",
48217
+ messageServerId,
46976
48218
  metadata
46977
48219
  });
46978
48220
  await this.ensureRoomExists({
@@ -46981,7 +48223,7 @@ class AgentRuntime {
46981
48223
  source: source || "default",
46982
48224
  type: type || "DM" /* DM */,
46983
48225
  channelId,
46984
- serverId,
48226
+ messageServerId,
46985
48227
  worldId
46986
48228
  });
46987
48229
  try {
@@ -46992,22 +48234,28 @@ class AgentRuntime {
46992
48234
  if (!added) {
46993
48235
  throw new Error(`Failed to add participant ${entityId} to room ${roomId}`);
46994
48236
  }
46995
- this.logger.debug(`Added participant ${entityId} to room ${roomId} directly`);
48237
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Participant added");
46996
48238
  } else {
46997
48239
  throw error;
46998
48240
  }
46999
48241
  }
47000
48242
  await this.ensureParticipantInRoom(this.agentId, roomId);
47001
- this.logger.debug(`Success: Successfully connected entity ${entityId} in room ${roomId}`);
48243
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "Entity connected");
47002
48244
  } catch (error) {
47003
- this.logger.error(`Failed to ensure connection: ${error instanceof Error ? error.message : String(error)}`);
48245
+ this.logger.error({
48246
+ src: "agent",
48247
+ agentId: this.agentId,
48248
+ entityId,
48249
+ channelId: roomId,
48250
+ error: error instanceof Error ? error.message : String(error)
48251
+ }, "Connection setup failed");
47004
48252
  throw error;
47005
48253
  }
47006
48254
  }
47007
48255
  async ensureParticipantInRoom(entityId, roomId) {
47008
48256
  const entity = await this.getEntityById(entityId);
47009
48257
  if (!entity && entityId !== this.agentId) {
47010
- this.logger.warn(`Entity ${entityId} not directly accessible to agent ${this.agentId}. Will attempt to add as participant anyway.`);
48258
+ this.logger.warn({ src: "agent", agentId: this.agentId, entityId }, "Entity not accessible, attempting to add as participant");
47011
48259
  } else if (!entity && entityId === this.agentId) {
47012
48260
  throw new Error(`Agent entity ${entityId} not found, cannot add as participant.`);
47013
48261
  } else if (!entity) {
@@ -47020,9 +48268,9 @@ class AgentRuntime {
47020
48268
  throw new Error(`Failed to add participant ${entityId} to room ${roomId}`);
47021
48269
  }
47022
48270
  if (entityId === this.agentId) {
47023
- this.logger.debug(`Agent ${this.character.name} linked to room ${roomId} successfully.`);
48271
+ this.logger.debug({ src: "agent", agentId: this.agentId, channelId: roomId }, "Agent linked to room");
47024
48272
  } else {
47025
- this.logger.debug(`User ${entityId} linked to room ${roomId} successfully.`);
48273
+ this.logger.debug({ src: "agent", agentId: this.agentId, entityId, channelId: roomId }, "User linked to room");
47026
48274
  }
47027
48275
  }
47028
48276
  }
@@ -47035,32 +48283,39 @@ class AgentRuntime {
47035
48283
  async getParticipantsForRoom(roomId) {
47036
48284
  return await this.adapter.getParticipantsForRoom(roomId);
47037
48285
  }
48286
+ async isRoomParticipant(roomId, entityId) {
48287
+ return await this.adapter.isRoomParticipant(roomId, entityId);
48288
+ }
47038
48289
  async addParticipant(entityId, roomId) {
47039
48290
  return await this.adapter.addParticipantsRoom([entityId], roomId);
47040
48291
  }
47041
48292
  async addParticipantsRoom(entityIds, roomId) {
47042
48293
  return await this.adapter.addParticipantsRoom(entityIds, roomId);
47043
48294
  }
47044
- async ensureWorldExists({ id, name, serverId, metadata }) {
48295
+ async ensureWorldExists({ id, name, messageServerId, metadata }) {
47045
48296
  const world = await this.getWorld(id);
47046
48297
  if (!world) {
47047
- this.logger.debug("Creating world:", JSON.stringify({
47048
- id,
47049
- name,
47050
- serverId,
47051
- agentId: this.agentId
47052
- }));
48298
+ this.logger.debug({ src: "agent", agentId: this.agentId, worldId: id, name, messageServerId }, "Creating world");
47053
48299
  await this.adapter.createWorld({
47054
48300
  id,
47055
48301
  name,
47056
48302
  agentId: this.agentId,
47057
- serverId: serverId || "default",
48303
+ messageServerId,
47058
48304
  metadata
47059
48305
  });
47060
- this.logger.debug(`World ${id} created successfully.`);
48306
+ this.logger.debug({ src: "agent", agentId: this.agentId, worldId: id, messageServerId }, "World created");
47061
48307
  }
47062
48308
  }
47063
- async ensureRoomExists({ id, name, source, type, channelId, serverId, worldId, metadata }) {
48309
+ async ensureRoomExists({
48310
+ id,
48311
+ name,
48312
+ source,
48313
+ type,
48314
+ channelId,
48315
+ messageServerId,
48316
+ worldId,
48317
+ metadata
48318
+ }) {
47064
48319
  if (!worldId)
47065
48320
  throw new Error("worldId is required");
47066
48321
  const room = await this.getRoom(id);
@@ -47072,11 +48327,11 @@ class AgentRuntime {
47072
48327
  source,
47073
48328
  type,
47074
48329
  channelId,
47075
- serverId,
48330
+ messageServerId,
47076
48331
  worldId,
47077
48332
  metadata
47078
48333
  });
47079
- this.logger.debug(`Room ${id} created successfully.`);
48334
+ this.logger.debug({ src: "agent", agentId: this.agentId, channelId: id }, "Room created");
47080
48335
  }
47081
48336
  }
47082
48337
  async composeState(message, includeList = null, onlyInclude = false, skipCache = false) {
@@ -47103,7 +48358,7 @@ class AgentRuntime {
47103
48358
  const result = await provider.get(this, message, cachedState);
47104
48359
  const duration = Date.now() - start;
47105
48360
  if (duration > 100) {
47106
- this.logger.debug(`${provider.name} Provider took ${duration}ms to respond`);
48361
+ this.logger.debug({ src: "agent", agentId: this.agentId, provider: provider.name, duration }, "Slow provider");
47107
48362
  }
47108
48363
  return {
47109
48364
  ...result,
@@ -47161,7 +48416,7 @@ class AgentRuntime {
47161
48416
  getService(serviceName) {
47162
48417
  const serviceInstances = this.services.get(serviceName);
47163
48418
  if (!serviceInstances || serviceInstances.length === 0) {
47164
- this.logger.debug(`Service ${serviceName} not found`);
48419
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceName }, "Service not found");
47165
48420
  return null;
47166
48421
  }
47167
48422
  return serviceInstances[0];
@@ -47172,7 +48427,7 @@ class AgentRuntime {
47172
48427
  getServicesByType(serviceName) {
47173
48428
  const serviceInstances = this.services.get(serviceName);
47174
48429
  if (!serviceInstances || serviceInstances.length === 0) {
47175
- this.logger.debug(`No services found for type ${serviceName}`);
48430
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceName }, "No services found for type");
47176
48431
  return [];
47177
48432
  }
47178
48433
  return serviceInstances;
@@ -47209,22 +48464,28 @@ class AgentRuntime {
47209
48464
  }
47210
48465
  async registerService(serviceDef) {
47211
48466
  const serviceType = serviceDef.serviceType;
48467
+ const serviceName = serviceDef.name || "Unknown";
47212
48468
  if (!serviceType) {
47213
- this.logger.warn(`Service ${serviceDef.name} is missing serviceType. Please define a static serviceType property.`);
48469
+ this.logger.warn({ src: "agent", agentId: this.agentId, serviceName }, "Service missing serviceType property");
47214
48470
  return;
47215
48471
  }
47216
- this.logger.debug(`${this.character.name}(${this.agentId}) - Registering service:`, serviceType);
48472
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Registering service");
47217
48473
  this.serviceRegistrationStatus.set(serviceType, "registering");
47218
48474
  try {
47219
- this.logger.debug(`Service ${serviceType} waiting for initialization...`);
48475
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service waiting for init");
47220
48476
  const initTimeout = new Promise((_, reject) => {
47221
48477
  setTimeout(() => {
47222
48478
  reject(new Error(`Service ${serviceType} registration timed out waiting for runtime initialization (30s timeout)`));
47223
48479
  }, 30000);
47224
48480
  });
47225
48481
  await Promise.race([this.initPromise, initTimeout]);
47226
- this.logger.debug(`Service ${serviceType} proceeding - initialization complete`);
48482
+ if (typeof serviceDef.start !== "function") {
48483
+ throw new Error(`Service ${serviceType} does not have a static start method. All services must implement static async start(runtime: IAgentRuntime): Promise<Service>.`);
48484
+ }
47227
48485
  const serviceInstance = await serviceDef.start(this);
48486
+ if (!serviceInstance) {
48487
+ throw new Error(`Service ${serviceType} start() method returned null or undefined. It must return a Service instance.`);
48488
+ }
47228
48489
  if (!this.services.has(serviceType)) {
47229
48490
  this.services.set(serviceType, []);
47230
48491
  }
@@ -47238,20 +48499,35 @@ class AgentRuntime {
47238
48499
  handler.resolve(serviceInstance);
47239
48500
  this.servicePromiseHandlers.delete(serviceType);
47240
48501
  } else {
47241
- this.logger.debug(`${this.character.name} - Service ${serviceType} has no servicePromiseHandler`);
48502
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service has no promise handler");
47242
48503
  }
47243
48504
  if (typeof serviceDef.registerSendHandlers === "function") {
47244
48505
  serviceDef.registerSendHandlers(this, serviceInstance);
47245
48506
  }
47246
48507
  this.serviceRegistrationStatus.set(serviceType, "registered");
47247
- this.logger.debug(`${this.character.name}(${this.agentId}) - Service ${serviceType} registered successfully`);
48508
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType }, "Service registered");
47248
48509
  } catch (error) {
47249
48510
  const errorMessage = error instanceof Error ? error.message : String(error);
47250
- this.logger.error(`${this.character.name}(${this.agentId}) - Failed to register service ${serviceType}: ${errorMessage}`);
48511
+ const errorStack = error instanceof Error ? error.stack : undefined;
48512
+ this.logger.error({ src: "agent", agentId: this.agentId, serviceType, error: errorMessage }, "Service registration failed");
48513
+ if (errorStack) {
48514
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType, stack: errorStack }, "Service error stack");
48515
+ }
47251
48516
  if (error?.message?.includes("timed out waiting for runtime initialization")) {
47252
48517
  this.logger.error(`Service ${serviceType} failed due to runtime initialization timeout. Check if runtime.initialize() is being called and completing successfully.`);
48518
+ } else if (error?.message?.includes("Not implemented")) {
48519
+ this.logger.error(`Service ${serviceType} failed because it does not implement the static start() method. ` + `All services must override the base Service.start() method. ` + `Add: static async start(runtime: IAgentRuntime): Promise<${serviceName}> { return new ${serviceName}(runtime); }`);
48520
+ if (errorStack) {
48521
+ this.logger.debug(`Stack trace: ${errorStack}`);
48522
+ }
47253
48523
  } else if (error?.message?.includes("Service") && error?.message?.includes("failed to start")) {
47254
- this.logger.error(`Service ${serviceType} failed to start. Check service implementation and dependencies.`);
48524
+ this.logger.error(`Service ${serviceType} (${serviceName}) failed to start. Check service implementation and dependencies.`);
48525
+ } else if (error?.message?.includes("does not have a static start method")) {
48526
+ this.logger.error({ src: "agent", agentId: this.agentId, serviceType, serviceName, error: error?.message }, "Service missing required static start() method implementation");
48527
+ } else {
48528
+ if (errorStack) {
48529
+ this.logger.debug({ src: "agent", agentId: this.agentId, serviceType, serviceName, stack: errorStack }, "Service error stack");
48530
+ }
47255
48531
  }
47256
48532
  this.serviceRegistrationStatus.set(serviceType, "failed");
47257
48533
  const handler = this.servicePromiseHandlers.get(serviceType);
@@ -47314,13 +48590,13 @@ class AgentRuntime {
47314
48590
  if (provider) {
47315
48591
  const modelWithProvider = models.find((m) => m.provider === provider);
47316
48592
  if (modelWithProvider) {
47317
- this.logger.debug(`[AgentRuntime][${this.character.name}] Using model ${modelKey} from provider ${provider}`);
48593
+ this.logger.debug({ src: "agent", agentId: this.agentId, model: modelKey, provider }, "Using model");
47318
48594
  return modelWithProvider.handler;
47319
48595
  } else {
47320
- this.logger.warn(`[AgentRuntime][${this.character.name}] No model found for provider ${provider}`);
48596
+ this.logger.warn({ src: "agent", agentId: this.agentId, model: modelKey, provider }, "Model provider not found");
47321
48597
  }
47322
48598
  }
47323
- this.logger.debug(`[AgentRuntime][${this.character.name}] Using model ${modelKey} from provider ${models[0].provider}`);
48599
+ this.logger.debug({ src: "agent", agentId: this.agentId, model: modelKey, provider: models[0].provider }, "Using model");
47324
48600
  return models[0].handler;
47325
48601
  }
47326
48602
  getModelSettings(modelType) {
@@ -47344,23 +48620,40 @@ class AgentRuntime {
47344
48620
  return numValue;
47345
48621
  }
47346
48622
  }
47347
- const legacyValue = this.getSetting(legacyKey);
47348
- if (legacyValue !== null && legacyValue !== undefined) {
47349
- const numValue = Number(legacyValue);
47350
- if (!isNaN(numValue)) {
47351
- return numValue;
48623
+ if (legacyKey) {
48624
+ const legacyValue = this.getSetting(legacyKey);
48625
+ if (legacyValue !== null && legacyValue !== undefined) {
48626
+ const numValue = Number(legacyValue);
48627
+ if (!isNaN(numValue)) {
48628
+ return numValue;
48629
+ }
47352
48630
  }
47353
48631
  }
47354
48632
  return null;
47355
48633
  };
47356
48634
  const maxTokens = getSettingWithFallback("MAX_TOKENS", MODEL_SETTINGS.MODEL_MAX_TOKEN);
47357
48635
  const temperature = getSettingWithFallback("TEMPERATURE", MODEL_SETTINGS.MODEL_TEMPERATURE);
48636
+ const topP = getSettingWithFallback("TOP_P");
48637
+ const topK = getSettingWithFallback("TOP_K");
48638
+ const minP = getSettingWithFallback("MIN_P");
48639
+ const seed = getSettingWithFallback("SEED");
48640
+ const repetitionPenalty = getSettingWithFallback("REPETITION_PENALTY");
47358
48641
  const frequencyPenalty = getSettingWithFallback("FREQUENCY_PENALTY", MODEL_SETTINGS.MODEL_FREQ_PENALTY);
47359
48642
  const presencePenalty = getSettingWithFallback("PRESENCE_PENALTY", MODEL_SETTINGS.MODEL_PRESENCE_PENALTY);
47360
48643
  if (maxTokens !== null)
47361
48644
  modelSettings.maxTokens = maxTokens;
47362
48645
  if (temperature !== null)
47363
48646
  modelSettings.temperature = temperature;
48647
+ if (topP !== null)
48648
+ modelSettings.topP = topP;
48649
+ if (topK !== null)
48650
+ modelSettings.topK = topK;
48651
+ if (minP !== null)
48652
+ modelSettings.minP = minP;
48653
+ if (seed !== null)
48654
+ modelSettings.seed = seed;
48655
+ if (repetitionPenalty !== null)
48656
+ modelSettings.repetitionPenalty = repetitionPenalty;
47364
48657
  if (frequencyPenalty !== null)
47365
48658
  modelSettings.frequencyPenalty = frequencyPenalty;
47366
48659
  if (presencePenalty !== null)
@@ -47375,8 +48668,29 @@ class AgentRuntime {
47375
48668
  const errorMsg = `No handler found for delegate type: ${modelKey}`;
47376
48669
  throw new Error(errorMsg);
47377
48670
  }
47378
- this.logger.debug(`[useModel] ${modelKey} input: ` + JSON.stringify(params, safeReplacer(), 2).replace(/\\n/g, `
47379
- `));
48671
+ const binaryModels = [
48672
+ ModelType.TRANSCRIPTION,
48673
+ ModelType.IMAGE,
48674
+ ModelType.AUDIO,
48675
+ ModelType.VIDEO
48676
+ ];
48677
+ if (!binaryModels.includes(modelKey)) {
48678
+ this.logger.trace({ src: "agent", agentId: this.agentId, model: modelKey, params }, "Model input");
48679
+ } else {
48680
+ let sizeInfo = "unknown size";
48681
+ if (Buffer.isBuffer(params)) {
48682
+ sizeInfo = `${params.length} bytes`;
48683
+ } else if (typeof Blob !== "undefined" && params instanceof Blob) {
48684
+ sizeInfo = `${params.size} bytes`;
48685
+ } else if (typeof params === "object" && params !== null) {
48686
+ if ("audio" in params && Buffer.isBuffer(params.audio)) {
48687
+ sizeInfo = `${params.audio.length} bytes`;
48688
+ } else if ("audio" in params && typeof Blob !== "undefined" && params.audio instanceof Blob) {
48689
+ sizeInfo = `${params.audio.size} bytes`;
48690
+ }
48691
+ }
48692
+ this.logger.trace({ src: "agent", agentId: this.agentId, model: modelKey, size: sizeInfo }, "Model input (binary)");
48693
+ }
47380
48694
  let modelParams;
47381
48695
  if (params === null || params === undefined || typeof params !== "object" || Array.isArray(params) || BufferUtils.isBuffer(params)) {
47382
48696
  modelParams = params;
@@ -47390,13 +48704,22 @@ class AgentRuntime {
47390
48704
  } else {
47391
48705
  modelParams = params;
47392
48706
  }
48707
+ if (isPlainObject(modelParams)) {
48708
+ if (modelParams.user === undefined && this.character?.name) {
48709
+ modelParams.user = this.character.name;
48710
+ }
48711
+ }
47393
48712
  }
47394
48713
  const startTime = typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
47395
48714
  try {
47396
48715
  const response = await model(this, modelParams);
47397
48716
  const elapsedTime = (typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now()) - startTime;
47398
- this.logger.debug(`[useModel] ${modelKey} output (took ${Number(elapsedTime.toFixed(2)).toLocaleString()}ms):`, Array.isArray(response) ? `${JSON.stringify(response.slice(0, 5))}...${JSON.stringify(response.slice(-5))} (${response.length} items)` : JSON.stringify(response, safeReplacer(), 2).replace(/\\n/g, `
47399
- `));
48717
+ this.logger.trace({
48718
+ src: "agent",
48719
+ agentId: this.agentId,
48720
+ model: modelKey,
48721
+ duration: Number(elapsedTime.toFixed(2))
48722
+ }, "Model output");
47400
48723
  if (modelKey !== ModelType.TEXT_EMBEDDING && promptContent) {
47401
48724
  if (this.currentActionContext) {
47402
48725
  this.currentActionContext.prompts.push({
@@ -47408,7 +48731,7 @@ class AgentRuntime {
47408
48731
  }
47409
48732
  this.adapter.log({
47410
48733
  entityId: this.agentId,
47411
- roomId: this.agentId,
48734
+ roomId: this.currentRoomId ?? this.agentId,
47412
48735
  body: {
47413
48736
  modelType,
47414
48737
  modelKey,
@@ -47417,6 +48740,7 @@ class AgentRuntime {
47417
48740
  prompt: promptContent
47418
48741
  },
47419
48742
  prompt: promptContent,
48743
+ systemPrompt: this.character?.system || null,
47420
48744
  runId: this.getCurrentRunId(),
47421
48745
  timestamp: Date.now(),
47422
48746
  executionTime: elapsedTime,
@@ -47469,10 +48793,18 @@ ${input}`;
47469
48793
  const params = {
47470
48794
  prompt,
47471
48795
  maxTokens: options?.maxTokens,
48796
+ minTokens: options?.minTokens,
47472
48797
  temperature: options?.temperature,
48798
+ topP: options?.topP,
48799
+ topK: options?.topK,
48800
+ minP: options?.minP,
48801
+ seed: options?.seed,
48802
+ repetitionPenalty: options?.repetitionPenalty,
47473
48803
  frequencyPenalty: options?.frequencyPenalty,
47474
48804
  presencePenalty: options?.presencePenalty,
47475
- stopSequences: options?.stopSequences
48805
+ stopSequences: options?.stopSequences,
48806
+ user: options?.user !== undefined ? options.user : this.character?.name,
48807
+ responseFormat: options?.responseFormat
47476
48808
  };
47477
48809
  const response = await this.useModel(modelType, params);
47478
48810
  return {
@@ -47502,36 +48834,42 @@ ${input}`;
47502
48834
  }
47503
48835
  await Promise.all(eventHandlers.map((handler) => handler(paramsWithRuntime)));
47504
48836
  } catch (error) {
47505
- this.logger.error(`Error during emitEvent for ${eventName} (handler execution): ${error}`);
48837
+ this.logger.error({
48838
+ src: "agent",
48839
+ agentId: this.agentId,
48840
+ eventName,
48841
+ error: error instanceof Error ? error.message : String(error)
48842
+ }, "Event handler failed");
47506
48843
  }
47507
48844
  }
47508
48845
  }
47509
48846
  async ensureEmbeddingDimension() {
47510
- this.logger.debug(`[AgentRuntime][${this.character.name}] Starting ensureEmbeddingDimension`);
47511
48847
  if (!this.adapter) {
47512
- throw new Error(`[AgentRuntime][${this.character.name}] Database adapter not initialized before ensureEmbeddingDimension`);
48848
+ throw new Error("Database adapter not initialized before ensureEmbeddingDimension");
47513
48849
  }
47514
48850
  try {
47515
48851
  const model = this.getModel(ModelType.TEXT_EMBEDDING);
47516
48852
  if (!model) {
47517
- throw new Error(`[AgentRuntime][${this.character.name}] No TEXT_EMBEDDING model registered`);
48853
+ throw new Error("No TEXT_EMBEDDING model registered");
47518
48854
  }
47519
- this.logger.debug(`[AgentRuntime][${this.character.name}] Getting embedding dimensions`);
47520
48855
  const embedding = await this.useModel(ModelType.TEXT_EMBEDDING, null);
47521
48856
  if (!embedding || !embedding.length) {
47522
- throw new Error(`[AgentRuntime][${this.character.name}] Invalid embedding received`);
48857
+ throw new Error("Invalid embedding received");
47523
48858
  }
47524
- this.logger.debug(`[AgentRuntime][${this.character.name}] Setting embedding dimension: ${embedding.length}`);
47525
48859
  await this.adapter.ensureEmbeddingDimension(embedding.length);
47526
- this.logger.debug(`[AgentRuntime][${this.character.name}] Successfully set embedding dimension`);
48860
+ this.logger.debug({ src: "agent", agentId: this.agentId, dimension: embedding.length }, "Embedding dimension set");
47527
48861
  } catch (error) {
47528
- this.logger.debug(`[AgentRuntime][${this.character.name}] Error in ensureEmbeddingDimension: ${error}`);
48862
+ this.logger.error({
48863
+ src: "agent",
48864
+ agentId: this.agentId,
48865
+ error: error instanceof Error ? error.message : String(error)
48866
+ }, "Embedding dimension setup failed");
47529
48867
  throw error;
47530
48868
  }
47531
48869
  }
47532
48870
  registerTaskWorker(taskHandler) {
47533
48871
  if (this.taskWorkers.has(taskHandler.name)) {
47534
- this.logger.warn(`Task definition ${taskHandler.name} already registered. Will be overwritten.`);
48872
+ this.logger.warn({ src: "agent", agentId: this.agentId, task: taskHandler.name }, "Task worker already registered, overwriting");
47535
48873
  }
47536
48874
  this.taskWorkers.set(taskHandler.name, taskHandler);
47537
48875
  }
@@ -47593,7 +48931,7 @@ ${input}`;
47593
48931
  if (!refreshedAgent) {
47594
48932
  throw new Error(`Failed to retrieve agent after update: ${agent.id}`);
47595
48933
  }
47596
- this.logger.debug(`Updated existing agent ${agent.id} on restart (merged ${Object.keys(existingAgent.settings || {}).length} DB settings with ${Object.keys(agent.settings || {}).length} character settings)`);
48934
+ this.logger.debug({ src: "agent", agentId: agent.id }, "Agent updated on restart");
47597
48935
  return refreshedAgent;
47598
48936
  }
47599
48937
  const newAgent = {
@@ -47604,7 +48942,7 @@ ${input}`;
47604
48942
  if (!created) {
47605
48943
  throw new Error(`Failed to create agent: ${agent.id}`);
47606
48944
  }
47607
- this.logger.debug(`Created new agent ${agent.id}`);
48945
+ this.logger.debug({ src: "agent", agentId: agent.id }, "Agent created");
47608
48946
  return newAgent;
47609
48947
  }
47610
48948
  async getEntityById(entityId) {
@@ -47662,7 +49000,11 @@ ${input}`;
47662
49000
  text: memoryText
47663
49001
  });
47664
49002
  } catch (error) {
47665
- this.logger.error("Failed to generate embedding:", error);
49003
+ this.logger.error({
49004
+ src: "agent",
49005
+ agentId: this.agentId,
49006
+ error: error instanceof Error ? error.message : String(error)
49007
+ }, "Embedding generation failed");
47666
49008
  memory.embedding = await this.useModel(ModelType.TEXT_EMBEDDING, null);
47667
49009
  }
47668
49010
  return memory;
@@ -47676,7 +49018,6 @@ ${input}`;
47676
49018
  return;
47677
49019
  }
47678
49020
  if (!memory.content?.text) {
47679
- this.logger.debug("Skipping embedding generation for memory without text content");
47680
49021
  return;
47681
49022
  }
47682
49023
  await this.emitEvent("EMBEDDING_GENERATION_REQUESTED" /* EMBEDDING_GENERATION_REQUESTED */, {
@@ -47704,7 +49045,12 @@ ${input}`;
47704
49045
  });
47705
49046
  allMemories.push(...memories);
47706
49047
  } catch (error) {
47707
- this.logger.debug(`Failed to get memories from table ${tableName}: ${error}`);
49048
+ this.logger.debug({
49049
+ src: "agent",
49050
+ agentId: this.agentId,
49051
+ tableName,
49052
+ error: error instanceof Error ? error.message : String(error)
49053
+ }, "Failed to get memories");
47708
49054
  }
47709
49055
  }
47710
49056
  return allMemories;
@@ -47756,16 +49102,15 @@ ${input}`;
47756
49102
  await this.adapter.deleteManyMemories(memoryIds);
47757
49103
  }
47758
49104
  async clearAllAgentMemories() {
47759
- this.logger.info(`Clearing all memories for agent ${this.character.name} (${this.agentId})`);
49105
+ this.logger.info({ src: "agent", agentId: this.agentId }, "Clearing all memories");
47760
49106
  const allMemories = await this.getAllMemories();
47761
49107
  const memoryIds = allMemories.map((memory) => memory.id).filter((id) => id !== undefined);
47762
49108
  if (memoryIds.length === 0) {
47763
- this.logger.info("No memories found to delete");
49109
+ this.logger.debug({ src: "agent", agentId: this.agentId }, "No memories to delete");
47764
49110
  return;
47765
49111
  }
47766
- this.logger.info(`Found ${memoryIds.length} memories to delete`);
47767
49112
  await this.adapter.deleteManyMemories(memoryIds);
47768
- this.logger.info(`Successfully cleared all ${memoryIds.length} memories for agent`);
49113
+ this.logger.info({ src: "agent", agentId: this.agentId, count: memoryIds.length }, "Memories cleared");
47769
49114
  }
47770
49115
  async deleteAllMemories(roomId, tableName) {
47771
49116
  await this.adapter.deleteAllMemories(roomId, tableName);
@@ -47803,7 +49148,15 @@ ${input}`;
47803
49148
  async getRoomsByIds(roomIds) {
47804
49149
  return await this.adapter.getRoomsByIds(roomIds);
47805
49150
  }
47806
- async createRoom({ id, name, source, type, channelId, serverId, worldId }) {
49151
+ async createRoom({
49152
+ id,
49153
+ name,
49154
+ source,
49155
+ type,
49156
+ channelId,
49157
+ messageServerId,
49158
+ worldId
49159
+ }) {
47807
49160
  if (!worldId)
47808
49161
  throw new Error("worldId is required");
47809
49162
  const res = await this.adapter.createRooms([
@@ -47813,7 +49166,7 @@ ${input}`;
47813
49166
  source,
47814
49167
  type,
47815
49168
  channelId,
47816
- serverId,
49169
+ messageServerId,
47817
49170
  worldId
47818
49171
  }
47819
49172
  ]);
@@ -47930,29 +49283,38 @@ ${input}`;
47930
49283
  message: controlMessage,
47931
49284
  source: "agent"
47932
49285
  });
47933
- this.logger.debug(`Sent control message: ${action} to room ${roomId}`);
49286
+ this.logger.debug({ src: "agent", agentId: this.agentId, action, channelId: roomId }, "Control message sent");
47934
49287
  } catch (error) {
47935
- this.logger.error(`Error sending control message: ${error}`);
49288
+ this.logger.error({
49289
+ src: "agent",
49290
+ agentId: this.agentId,
49291
+ error: error instanceof Error ? error.message : String(error)
49292
+ }, "Control message failed");
47936
49293
  }
47937
49294
  }
47938
49295
  registerSendHandler(source, handler) {
47939
49296
  if (this.sendHandlers.has(source)) {
47940
- this.logger.warn(`Send handler for source '${source}' already registered. Overwriting.`);
49297
+ this.logger.warn({ src: "agent", agentId: this.agentId, handlerSource: source }, "Send handler already registered, overwriting");
47941
49298
  }
47942
49299
  this.sendHandlers.set(source, handler);
47943
- this.logger.info(`Registered send handler for source: ${source}`);
49300
+ this.logger.debug({ src: "agent", agentId: this.agentId, handlerSource: source }, "Send handler registered");
47944
49301
  }
47945
49302
  async sendMessageToTarget(target, content) {
47946
49303
  const handler = this.sendHandlers.get(target.source);
47947
49304
  if (!handler) {
47948
49305
  const errorMsg = `No send handler registered for source: ${target.source}`;
47949
- this.logger.error(errorMsg);
49306
+ this.logger.error({ src: "agent", agentId: this.agentId, handlerSource: target.source }, "Send handler not found");
47950
49307
  throw new Error(errorMsg);
47951
49308
  }
47952
49309
  try {
47953
49310
  await handler(this, target, content);
47954
49311
  } catch (error) {
47955
- this.logger.error(`Error executing send handler for source ${target.source}:`, error);
49312
+ this.logger.error({
49313
+ src: "agent",
49314
+ agentId: this.agentId,
49315
+ handlerSource: target.source,
49316
+ error: error instanceof Error ? error.message : String(error)
49317
+ }, "Send handler failed");
47956
49318
  throw error;
47957
49319
  }
47958
49320
  }
@@ -47963,7 +49325,7 @@ ${input}`;
47963
49325
  if (this.adapter && "runMigrations" in this.adapter) {
47964
49326
  await this.adapter.runMigrations(migrationsPaths);
47965
49327
  } else {
47966
- this.logger.warn("Database adapter does not support migrations.");
49328
+ this.logger.warn({ src: "agent", agentId: this.agentId }, "Database adapter does not support migrations");
47967
49329
  }
47968
49330
  }
47969
49331
  async isReady() {
@@ -48024,8 +49386,8 @@ function getCryptoModule() {
48024
49386
  return require_crypto_browserify();
48025
49387
  }
48026
49388
  function createHash(algorithm) {
48027
- const crypto = getCryptoModule();
48028
- const hash = crypto.createHash(algorithm);
49389
+ const crypto2 = getCryptoModule();
49390
+ const hash = crypto2.createHash(algorithm);
48029
49391
  return {
48030
49392
  update(data2) {
48031
49393
  hash.update(data2);
@@ -48040,15 +49402,15 @@ function createCipheriv(algorithm, key, iv) {
48040
49402
  if (algorithm !== "aes-256-cbc") {
48041
49403
  throw new Error(`Unsupported algorithm: ${algorithm}. Only 'aes-256-cbc' is currently supported.`);
48042
49404
  }
48043
- const crypto = getCryptoModule();
48044
- return crypto.createCipheriv(algorithm, key, iv);
49405
+ const crypto2 = getCryptoModule();
49406
+ return crypto2.createCipheriv(algorithm, key, iv);
48045
49407
  }
48046
49408
  function createDecipheriv(algorithm, key, iv) {
48047
49409
  if (algorithm !== "aes-256-cbc") {
48048
49410
  throw new Error(`Unsupported algorithm: ${algorithm}. Only 'aes-256-cbc' is currently supported.`);
48049
49411
  }
48050
- const crypto = getCryptoModule();
48051
- return crypto.createDecipheriv(algorithm, key, iv);
49412
+ const crypto2 = getCryptoModule();
49413
+ return crypto2.createDecipheriv(algorithm, key, iv);
48052
49414
  }
48053
49415
 
48054
49416
  // src/settings.ts
@@ -48080,7 +49442,7 @@ function getSalt() {
48080
49442
  }
48081
49443
  }
48082
49444
  if (currentEnvSalt === "secretsalt" && !saltErrorLogged) {
48083
- logger.warn("SECRET_SALT is not set or using default value");
49445
+ logger.warn({ src: "core:settings" }, "SECRET_SALT is not set or using default value");
48084
49446
  saltErrorLogged = true;
48085
49447
  }
48086
49448
  saltCache = {
@@ -48095,15 +49457,12 @@ function clearSaltCache() {
48095
49457
  }
48096
49458
  function encryptStringValue(value, salt) {
48097
49459
  if (value === undefined || value === null) {
48098
- logger.debug("Attempted to encrypt undefined or null value");
48099
49460
  return value;
48100
49461
  }
48101
49462
  if (typeof value === "boolean" || typeof value === "number") {
48102
- logger.debug("Value is a boolean or number, returning as is");
48103
49463
  return value;
48104
49464
  }
48105
49465
  if (typeof value !== "string") {
48106
- logger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
48107
49466
  return value;
48108
49467
  }
48109
49468
  const parts = value.split(":");
@@ -48111,7 +49470,6 @@ function encryptStringValue(value, salt) {
48111
49470
  try {
48112
49471
  const possibleIv = BufferUtils.fromHex(parts[0]);
48113
49472
  if (possibleIv.length === 16) {
48114
- logger.debug("Value appears to be already encrypted, skipping re-encryption");
48115
49473
  return value;
48116
49474
  }
48117
49475
  } catch (e) {}
@@ -48132,7 +49490,6 @@ function decryptStringValue(value, salt) {
48132
49490
  return value;
48133
49491
  }
48134
49492
  if (typeof value !== "string") {
48135
- logger.debug(`Value is not a string (type: ${typeof value}), returning as is`);
48136
49493
  return value;
48137
49494
  }
48138
49495
  const parts = value.split(":");
@@ -48142,9 +49499,6 @@ function decryptStringValue(value, salt) {
48142
49499
  const iv = BufferUtils.fromHex(parts[0]);
48143
49500
  const encrypted = parts[1];
48144
49501
  if (iv.length !== 16) {
48145
- if (iv.length) {
48146
- logger.debug(`Invalid IV length (${iv.length}) - expected 16 bytes`);
48147
- }
48148
49502
  return value;
48149
49503
  }
48150
49504
  const key = createHash("sha256").update(salt).digest().slice(0, 32);
@@ -48153,7 +49507,7 @@ function decryptStringValue(value, salt) {
48153
49507
  decrypted += decipher.final("utf8");
48154
49508
  return decrypted;
48155
49509
  } catch (error) {
48156
- logger.error(`Error decrypting value: ${error}`);
49510
+ logger.error({ src: "core:settings", error }, "Decryption failed");
48157
49511
  return value;
48158
49512
  }
48159
49513
  }
@@ -48185,11 +49539,11 @@ function unsaltWorldSettings(worldSettings, salt) {
48185
49539
  }
48186
49540
  return unsaltedSettings;
48187
49541
  }
48188
- async function updateWorldSettings(runtime, serverId, worldSettings) {
48189
- const worldId = createUniqueUuid(runtime, serverId);
49542
+ async function updateWorldSettings(runtime, serverId2, worldSettings) {
49543
+ const worldId = createUniqueUuid(runtime, serverId2);
48190
49544
  const world = await runtime.getWorld(worldId);
48191
49545
  if (!world) {
48192
- logger.error(`No world found for server ${serverId}`);
49546
+ logger.error({ src: "core:settings", serverId: serverId2 }, "World not found");
48193
49547
  return false;
48194
49548
  }
48195
49549
  if (!world.metadata) {
@@ -48201,8 +49555,8 @@ async function updateWorldSettings(runtime, serverId, worldSettings) {
48201
49555
  await runtime.updateWorld(world);
48202
49556
  return true;
48203
49557
  }
48204
- async function getWorldSettings(runtime, serverId) {
48205
- const worldId = createUniqueUuid(runtime, serverId);
49558
+ async function getWorldSettings(runtime, serverId2) {
49559
+ const worldId = createUniqueUuid(runtime, serverId2);
48206
49560
  const world = await runtime.getWorld(worldId);
48207
49561
  if (!world || !world.metadata?.settings) {
48208
49562
  return null;
@@ -48213,7 +49567,7 @@ async function getWorldSettings(runtime, serverId) {
48213
49567
  }
48214
49568
  async function initializeOnboarding(runtime, world, config) {
48215
49569
  if (world.metadata?.settings) {
48216
- logger.info(`Onboarding state already exists for server ${world.serverId}`);
49570
+ logger.debug({ src: "core:settings", serverId: world.messageServerId }, "Onboarding state already exists");
48217
49571
  const saltedSettings = world.metadata.settings;
48218
49572
  const salt = getSalt();
48219
49573
  return unsaltWorldSettings(saltedSettings, salt);
@@ -48229,7 +49583,7 @@ async function initializeOnboarding(runtime, world, config) {
48229
49583
  }
48230
49584
  world.metadata.settings = worldSettings;
48231
49585
  await runtime.updateWorld(world);
48232
- logger.info(`Initialized settings config for server ${world.serverId}`);
49586
+ logger.info({ src: "core:settings", serverId: world.messageServerId }, "Settings config initialized");
48233
49587
  return worldSettings;
48234
49588
  }
48235
49589
  function encryptedCharacter(character) {
@@ -48346,30 +49700,30 @@ function isAutoInstallAllowed() {
48346
49700
  async function tryInstallPlugin(pluginName) {
48347
49701
  try {
48348
49702
  if (!isAutoInstallAllowed()) {
48349
- logger.debug(`Auto-install disabled or not allowed in this environment. Skipping install for ${pluginName}.`);
49703
+ logger.debug({ src: "core:plugin", pluginName }, "Auto-install disabled, skipping");
48350
49704
  return false;
48351
49705
  }
48352
49706
  if (attemptedInstalls.has(pluginName)) {
48353
- logger.debug(`Auto-install already attempted for ${pluginName}. Skipping.`);
49707
+ logger.debug({ src: "core:plugin", pluginName }, "Auto-install already attempted, skipping");
48354
49708
  return false;
48355
49709
  }
48356
49710
  attemptedInstalls.add(pluginName);
48357
49711
  if (typeof Bun === "undefined" || typeof Bun.spawn !== "function") {
48358
- logger.warn(`Bun runtime not available. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
49712
+ logger.warn({ src: "core:plugin", pluginName }, "Bun runtime not available, cannot auto-install");
48359
49713
  return false;
48360
49714
  }
48361
49715
  try {
48362
49716
  const check = Bun.spawn(["bun", "--version"], { stdout: "pipe", stderr: "pipe" });
48363
49717
  const code = await check.exited;
48364
49718
  if (code !== 0) {
48365
- logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
49719
+ logger.warn({ src: "core:plugin", pluginName }, "Bun not available on PATH, cannot auto-install");
48366
49720
  return false;
48367
49721
  }
48368
49722
  } catch {
48369
- logger.warn(`Bun not available on PATH. Cannot auto-install ${pluginName}. Please run: bun add ${pluginName}`);
49723
+ logger.warn({ src: "core:plugin", pluginName }, "Bun not available on PATH, cannot auto-install");
48370
49724
  return false;
48371
49725
  }
48372
- logger.info(`Attempting to auto-install missing plugin: ${pluginName}`);
49726
+ logger.info({ src: "core:plugin", pluginName }, "Auto-installing missing plugin");
48373
49727
  const install = Bun.spawn(["bun", "add", pluginName], {
48374
49728
  cwd: process.cwd(),
48375
49729
  env: process.env,
@@ -48378,14 +49732,14 @@ async function tryInstallPlugin(pluginName) {
48378
49732
  });
48379
49733
  const exit = await install.exited;
48380
49734
  if (exit === 0) {
48381
- logger.info(`Successfully installed ${pluginName}. Retrying import...`);
49735
+ logger.info({ src: "core:plugin", pluginName }, "Plugin installed, retrying import");
48382
49736
  return true;
48383
49737
  }
48384
- logger.error(`bun add ${pluginName} failed with exit code ${exit}. Please install manually.`);
49738
+ logger.error({ src: "core:plugin", pluginName, exitCode: exit }, "Plugin installation failed");
48385
49739
  return false;
48386
49740
  } catch (e) {
48387
49741
  const message = e instanceof Error ? e.message : String(e);
48388
- logger.error(`Unexpected error during auto-install of ${pluginName}: ${message}`);
49742
+ logger.error({ src: "core:plugin", pluginName, error: message }, "Unexpected error during auto-install");
48389
49743
  return false;
48390
49744
  }
48391
49745
  }
@@ -48446,7 +49800,7 @@ async function loadAndPreparePlugin(pluginName) {
48446
49800
  try {
48447
49801
  pluginModule = await import(pluginName);
48448
49802
  } catch (error) {
48449
- logger.warn(`Failed to load plugin ${pluginName}: ${error}`);
49803
+ logger.warn({ src: "core:plugin", pluginName, error }, "Failed to load plugin");
48450
49804
  const attempted = await tryInstallPlugin(pluginName);
48451
49805
  if (!attempted) {
48452
49806
  return null;
@@ -48454,12 +49808,12 @@ async function loadAndPreparePlugin(pluginName) {
48454
49808
  try {
48455
49809
  pluginModule = await import(pluginName);
48456
49810
  } catch (secondError) {
48457
- logger.error(`Auto-install attempted for ${pluginName} but import still failed: ${secondError}`);
49811
+ logger.error({ src: "core:plugin", pluginName, error: secondError }, "Import failed after auto-install");
48458
49812
  return null;
48459
49813
  }
48460
49814
  }
48461
49815
  if (!pluginModule) {
48462
- logger.error(`Failed to load module for plugin ${pluginName}.`);
49816
+ logger.error({ src: "core:plugin", pluginName }, "Failed to load plugin module");
48463
49817
  return null;
48464
49818
  }
48465
49819
  const expectedFunctionName = `${pluginName.replace(/^@elizaos\/plugin-/, "").replace(/^@elizaos\//, "").replace(/-./g, (match) => match[1].toUpperCase())}Plugin`;
@@ -48480,54 +49834,86 @@ async function loadAndPreparePlugin(pluginName) {
48480
49834
  return produced;
48481
49835
  }
48482
49836
  } catch (err) {
48483
- logger.debug(`Factory export threw for ${pluginName}: ${err}`);
49837
+ logger.debug({ src: "core:plugin", pluginName, error: err }, "Factory export threw");
48484
49838
  }
48485
49839
  }
48486
49840
  }
48487
- logger.warn(`Could not find a valid plugin export in ${pluginName}.`);
49841
+ logger.warn({ src: "core:plugin", pluginName }, "No valid plugin export found");
48488
49842
  return null;
48489
49843
  } catch (error) {
48490
- logger.error(`Error loading plugin ${pluginName}: ${error}`);
49844
+ logger.error({ src: "core:plugin", pluginName, error }, "Error loading plugin");
48491
49845
  return null;
48492
49846
  }
48493
49847
  }
49848
+ function normalizePluginName(pluginName) {
49849
+ const scopedMatch = pluginName.match(/^@[^/]+\/plugin-(.+)$/);
49850
+ if (scopedMatch) {
49851
+ return scopedMatch[1];
49852
+ }
49853
+ return pluginName;
49854
+ }
48494
49855
  function resolvePluginDependencies(availablePlugins, isTestMode = false) {
48495
49856
  const resolutionOrder = [];
48496
49857
  const visited = new Set;
48497
49858
  const visiting = new Set;
49859
+ const lookupMap = new Map;
49860
+ for (const [key, plugin] of availablePlugins.entries()) {
49861
+ lookupMap.set(key, plugin);
49862
+ if (plugin.name !== key) {
49863
+ lookupMap.set(plugin.name, plugin);
49864
+ }
49865
+ if (!plugin.name.startsWith("@")) {
49866
+ lookupMap.set(`@elizaos/plugin-${plugin.name}`, plugin);
49867
+ }
49868
+ const normalizedKey = normalizePluginName(key);
49869
+ if (normalizedKey !== key) {
49870
+ lookupMap.set(normalizedKey, plugin);
49871
+ }
49872
+ }
48498
49873
  function visit(pluginName) {
48499
- if (!availablePlugins.has(pluginName)) {
48500
- logger.warn(`Plugin dependency "${pluginName}" not found and will be skipped.`);
48501
- return;
49874
+ const plugin = lookupMap.get(pluginName);
49875
+ if (!plugin) {
49876
+ const normalizedName = normalizePluginName(pluginName);
49877
+ const pluginByNormalized = lookupMap.get(normalizedName);
49878
+ if (!pluginByNormalized) {
49879
+ logger.warn({ src: "core:plugin", pluginName }, "Plugin dependency not found, skipping");
49880
+ return;
49881
+ }
49882
+ return visit(pluginByNormalized.name);
48502
49883
  }
48503
- if (visited.has(pluginName))
49884
+ const canonicalName = plugin.name;
49885
+ if (visited.has(canonicalName))
48504
49886
  return;
48505
- if (visiting.has(pluginName)) {
48506
- logger.error(`Circular dependency detected involving plugin: ${pluginName}`);
49887
+ if (visiting.has(canonicalName)) {
49888
+ logger.error({ src: "core:plugin", pluginName: canonicalName }, "Circular dependency detected");
48507
49889
  return;
48508
49890
  }
48509
- visiting.add(pluginName);
48510
- const plugin = availablePlugins.get(pluginName);
48511
- if (plugin) {
48512
- const deps = [...plugin.dependencies || []];
48513
- if (isTestMode) {
48514
- deps.push(...plugin.testDependencies || []);
48515
- }
48516
- for (const dep of deps) {
48517
- visit(dep);
48518
- }
49891
+ visiting.add(canonicalName);
49892
+ const deps = [...plugin.dependencies || []];
49893
+ if (isTestMode) {
49894
+ deps.push(...plugin.testDependencies || []);
49895
+ }
49896
+ for (const dep of deps) {
49897
+ visit(dep);
48519
49898
  }
48520
- visiting.delete(pluginName);
48521
- visited.add(pluginName);
48522
- resolutionOrder.push(pluginName);
49899
+ visiting.delete(canonicalName);
49900
+ visited.add(canonicalName);
49901
+ resolutionOrder.push(canonicalName);
48523
49902
  }
48524
- for (const name of availablePlugins.keys()) {
48525
- if (!visited.has(name)) {
48526
- visit(name);
49903
+ for (const plugin of availablePlugins.values()) {
49904
+ if (!visited.has(plugin.name)) {
49905
+ visit(plugin.name);
48527
49906
  }
48528
49907
  }
48529
- const finalPlugins = resolutionOrder.map((name) => availablePlugins.get(name)).filter((p) => Boolean(p));
48530
- logger.info({ plugins: finalPlugins.map((p) => p.name) }, `Final plugins being loaded:`);
49908
+ const finalPlugins = resolutionOrder.map((name) => {
49909
+ for (const plugin of availablePlugins.values()) {
49910
+ if (plugin.name === name) {
49911
+ return plugin;
49912
+ }
49913
+ }
49914
+ return null;
49915
+ }).filter((p) => Boolean(p));
49916
+ logger.debug({ src: "core:plugin", plugins: finalPlugins.map((p) => p.name) }, "Plugins resolved");
48531
49917
  return finalPlugins;
48532
49918
  }
48533
49919
  async function loadPlugin(nameOrPlugin) {
@@ -48536,31 +49922,38 @@ async function loadPlugin(nameOrPlugin) {
48536
49922
  }
48537
49923
  const validation = validatePlugin(nameOrPlugin);
48538
49924
  if (!validation.isValid) {
48539
- logger.error(`Invalid plugin provided: ${validation.errors.join(", ")}`);
49925
+ logger.error({ src: "core:plugin", errors: validation.errors }, "Invalid plugin provided");
48540
49926
  return null;
48541
49927
  }
48542
49928
  return nameOrPlugin;
48543
49929
  }
49930
+ function queueDependency(depName, seenDependencies, pluginMap, queue2) {
49931
+ const normalizedDepName = normalizePluginName(depName);
49932
+ const alreadyQueued = seenDependencies.has(depName) || seenDependencies.has(normalizedDepName) || Array.from(pluginMap.keys()).some((key) => normalizePluginName(key) === normalizedDepName) || Array.from(pluginMap.values()).some((p) => normalizePluginName(p.name) === normalizedDepName || p.name === depName || p.name === normalizedDepName);
49933
+ if (!alreadyQueued) {
49934
+ seenDependencies.add(depName);
49935
+ seenDependencies.add(normalizedDepName);
49936
+ queue2.push(depName);
49937
+ }
49938
+ }
48544
49939
  async function resolvePluginsImpl(plugins, isTestMode = false) {
48545
49940
  const pluginMap = new Map;
48546
49941
  const queue2 = [...plugins];
49942
+ const seenDependencies = new Set;
48547
49943
  while (queue2.length > 0) {
48548
49944
  const next = queue2.shift();
48549
49945
  const loaded = await loadPlugin(next);
48550
49946
  if (!loaded)
48551
49947
  continue;
48552
- if (!pluginMap.has(loaded.name)) {
48553
- pluginMap.set(loaded.name, loaded);
49948
+ const canonicalName = loaded.name;
49949
+ if (!pluginMap.has(canonicalName)) {
49950
+ pluginMap.set(canonicalName, loaded);
48554
49951
  for (const depName of loaded.dependencies ?? []) {
48555
- if (!pluginMap.has(depName)) {
48556
- queue2.push(depName);
48557
- }
49952
+ queueDependency(depName, seenDependencies, pluginMap, queue2);
48558
49953
  }
48559
49954
  if (isTestMode) {
48560
49955
  for (const depName of loaded.testDependencies ?? []) {
48561
- if (!pluginMap.has(depName)) {
48562
- queue2.push(depName);
48563
- }
49956
+ queueDependency(depName, seenDependencies, pluginMap, queue2);
48564
49957
  }
48565
49958
  }
48566
49959
  }
@@ -48574,7 +49967,8 @@ async function resolvePlugins(plugins, isTestMode = false) {
48574
49967
  }
48575
49968
  const pluginObjects = plugins.filter((p) => typeof p !== "string");
48576
49969
  if (plugins.some((p) => typeof p === "string")) {
48577
- logger.warn("Browser environment: String plugin references are not supported. Only Plugin objects will be used. Skipped plugins: " + plugins.filter((p) => typeof p === "string").join(", "));
49970
+ const skippedPlugins = plugins.filter((p) => typeof p === "string");
49971
+ logger.warn({ src: "core:plugin", skippedPlugins }, "Browser environment: String plugin references not supported");
48578
49972
  }
48579
49973
  const pluginMap = new Map;
48580
49974
  for (const plugin of pluginObjects) {
@@ -48589,17 +49983,26 @@ class ElizaOS extends EventTarget {
48589
49983
  initFunctions = new Map;
48590
49984
  editableMode = false;
48591
49985
  async addAgents(agents, options) {
49986
+ const createdRuntimes = [];
48592
49987
  const promises = agents.map(async (agent) => {
48593
49988
  const character = agent.character;
48594
49989
  await setDefaultSecretsFromEnv(character, { skipEnvMerge: options?.isTestMode });
48595
- const resolvedPlugins = agent.plugins ? await resolvePlugins(agent.plugins, options?.isTestMode || false) : [];
49990
+ let resolvedPlugins = agent.plugins ? await resolvePlugins(agent.plugins, options?.isTestMode || false) : [];
49991
+ if (agent.databaseAdapter) {
49992
+ resolvedPlugins = resolvedPlugins.filter((p) => p.name !== "@elizaos/plugin-sql");
49993
+ }
48596
49994
  const runtime = new AgentRuntime({
48597
49995
  character,
48598
49996
  plugins: resolvedPlugins,
48599
49997
  settings: agent.settings || {}
48600
49998
  });
49999
+ if (agent.databaseAdapter) {
50000
+ runtime.registerDatabaseAdapter(agent.databaseAdapter);
50001
+ }
48601
50002
  runtime.elizaOS = this;
48602
- this.runtimes.set(runtime.agentId, runtime);
50003
+ if (!options?.ephemeral) {
50004
+ this.runtimes.set(runtime.agentId, runtime);
50005
+ }
48603
50006
  if (typeof agent.init === "function") {
48604
50007
  this.initFunctions.set(runtime.agentId, agent.init);
48605
50008
  }
@@ -48611,15 +50014,33 @@ class ElizaOS extends EventTarget {
48611
50014
  character: {
48612
50015
  ...characterWithoutSecrets,
48613
50016
  settings: settingsWithoutSecrets
48614
- }
50017
+ },
50018
+ ephemeral: options?.ephemeral
48615
50019
  }
48616
50020
  }));
50021
+ createdRuntimes.push(runtime);
48617
50022
  return runtime.agentId;
48618
50023
  });
48619
50024
  const ids = await Promise.all(promises);
50025
+ if (options?.autoStart) {
50026
+ await Promise.all(createdRuntimes.map(async (runtime) => {
50027
+ await runtime.initialize({ skipMigrations: options?.skipMigrations });
50028
+ const initFn = this.initFunctions.get(runtime.agentId);
50029
+ if (initFn) {
50030
+ await initFn(runtime);
50031
+ this.initFunctions.delete(runtime.agentId);
50032
+ }
50033
+ this.dispatchEvent(new CustomEvent("agent:started", {
50034
+ detail: { agentId: runtime.agentId }
50035
+ }));
50036
+ }));
50037
+ }
48620
50038
  this.dispatchEvent(new CustomEvent("agents:added", {
48621
- detail: { agentIds: ids, count: ids.length }
50039
+ detail: { agentIds: ids, count: ids.length, ephemeral: options?.ephemeral }
48622
50040
  }));
50041
+ if (options?.returnRuntimes) {
50042
+ return createdRuntimes;
50043
+ }
48623
50044
  return ids;
48624
50045
  }
48625
50046
  registerAgent(runtime) {
@@ -48719,10 +50140,18 @@ class ElizaOS extends EventTarget {
48719
50140
  getAgentByCharacterId(characterId) {
48720
50141
  return this.getAgents().find((runtime) => runtime.character.id === characterId);
48721
50142
  }
48722
- async sendMessage(agentId, message, options) {
48723
- const runtime = this.runtimes.get(agentId);
48724
- if (!runtime) {
48725
- throw new Error(`Agent ${agentId} not found`);
50143
+ async sendMessage(target, message, options) {
50144
+ let runtime;
50145
+ let agentId;
50146
+ if (typeof target === "string") {
50147
+ agentId = target;
50148
+ runtime = this.runtimes.get(agentId);
50149
+ if (!runtime) {
50150
+ throw new Error(`Agent ${agentId} not found in registry`);
50151
+ }
50152
+ } else {
50153
+ runtime = target;
50154
+ agentId = runtime.agentId;
48726
50155
  }
48727
50156
  if (!runtime.messageService) {
48728
50157
  throw new Error("messageService is not initialized on runtime");
@@ -48750,6 +50179,13 @@ class ElizaOS extends EventTarget {
48750
50179
  useMultiStep: options?.useMultiStep,
48751
50180
  maxMultiStepIterations: options?.maxMultiStepIterations
48752
50181
  };
50182
+ const handleMessageWithEntityContext = async (handler) => {
50183
+ if (runtime.withEntityContext) {
50184
+ return await runtime.withEntityContext(userMessage.entityId, handler);
50185
+ } else {
50186
+ return await handler();
50187
+ }
50188
+ };
48753
50189
  const isAsyncMode = !!options?.onResponse;
48754
50190
  if (isAsyncMode) {
48755
50191
  const callback = async (content) => {
@@ -48764,7 +50200,7 @@ class ElizaOS extends EventTarget {
48764
50200
  }
48765
50201
  return [];
48766
50202
  };
48767
- runtime.messageService.handleMessage(runtime, userMessage, callback, processingOptions).then(() => {
50203
+ handleMessageWithEntityContext(() => runtime.messageService.handleMessage(runtime, userMessage, callback, processingOptions)).then(() => {
48768
50204
  if (options.onComplete)
48769
50205
  options.onComplete();
48770
50206
  }).catch((error) => {
@@ -48776,13 +50212,13 @@ class ElizaOS extends EventTarget {
48776
50212
  }));
48777
50213
  return { messageId, userMessage };
48778
50214
  } else {
48779
- const result = await runtime.messageService.handleMessage(runtime, userMessage, undefined, processingOptions);
50215
+ const processing = await handleMessageWithEntityContext(() => runtime.messageService.handleMessage(runtime, userMessage, undefined, processingOptions));
48780
50216
  if (options?.onComplete)
48781
50217
  await options.onComplete();
48782
50218
  this.dispatchEvent(new CustomEvent("message:sent", {
48783
- detail: { agentId, messageId, mode: "sync", result }
50219
+ detail: { agentId, messageId, mode: "sync", processing }
48784
50220
  }));
48785
- return { messageId, userMessage, result };
50221
+ return { messageId, userMessage, processing };
48786
50222
  }
48787
50223
  }
48788
50224
  async sendMessages(messages) {
@@ -48925,7 +50361,7 @@ async function getRecentInteractions(runtime, sourceEntityId, candidateEntities,
48925
50361
  async function findEntityByName(runtime, message, state) {
48926
50362
  const room = state.data.room ?? await runtime.getRoom(message.roomId);
48927
50363
  if (!room) {
48928
- logger.warn("Room not found for entity search");
50364
+ logger.warn({ src: "core:entities", roomId: message.roomId }, "Room not found for entity search");
48929
50365
  return null;
48930
50366
  }
48931
50367
  const world = room.worldId ? await runtime.getWorld(room.worldId) : null;
@@ -48976,7 +50412,7 @@ async function findEntityByName(runtime, message, state) {
48976
50412
  });
48977
50413
  const resolution = parseKeyValueXml(result);
48978
50414
  if (!resolution) {
48979
- logger.warn("Failed to parse entity resolution result");
50415
+ logger.warn({ src: "core:entities" }, "Failed to parse entity resolution result");
48980
50416
  return null;
48981
50417
  }
48982
50418
  if (resolution.type === "EXACT_MATCH" && resolution.entityId) {
@@ -49125,6 +50561,7 @@ export {
49125
50561
  parseCharacter,
49126
50562
  parseBooleanFromText2 as parseBooleanFromText,
49127
50563
  parseAndValidateCharacter,
50564
+ normalizePluginName,
49128
50565
  normalizeJsonString,
49129
50566
  multiStepSummaryTemplate,
49130
50567
  multiStepDecisionTemplate,
@@ -49246,5 +50683,5 @@ export {
49246
50683
  AgentRuntime
49247
50684
  };
49248
50685
 
49249
- //# debugId=E31A2F74693DFF0064756E2164756E21
50686
+ //# debugId=C468BC8B5AE0993F64756E2164756E21
49250
50687
  //# sourceMappingURL=index.node.js.map