@everworker/oneringai 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -8
- package/dist/{ImageModel-C7EyUfU0.d.ts → ImageModel-BkAX5Rr5.d.ts} +76 -1
- package/dist/{ImageModel-B-uH3JEz.d.cts → ImageModel-DtN780fU.d.cts} +76 -1
- package/dist/capabilities/images/index.cjs +96 -0
- package/dist/capabilities/images/index.cjs.map +1 -1
- package/dist/capabilities/images/index.d.cts +1 -1
- package/dist/capabilities/images/index.d.ts +1 -1
- package/dist/capabilities/images/index.js +96 -0
- package/dist/capabilities/images/index.js.map +1 -1
- package/dist/index.cjs +968 -1007
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2433 -2655
- package/dist/index.d.ts +2433 -2655
- package/dist/index.js +962 -1001
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1597,6 +1597,64 @@ var init_Metrics = __esm({
|
|
|
1597
1597
|
}
|
|
1598
1598
|
});
|
|
1599
1599
|
|
|
1600
|
+
// src/core/ScopedConnectorRegistry.ts
|
|
1601
|
+
var ScopedConnectorRegistry;
|
|
1602
|
+
var init_ScopedConnectorRegistry = __esm({
|
|
1603
|
+
"src/core/ScopedConnectorRegistry.ts"() {
|
|
1604
|
+
init_Connector();
|
|
1605
|
+
ScopedConnectorRegistry = class {
|
|
1606
|
+
constructor(policy, context) {
|
|
1607
|
+
this.policy = policy;
|
|
1608
|
+
this.context = context;
|
|
1609
|
+
}
|
|
1610
|
+
get(name) {
|
|
1611
|
+
if (!Connector.has(name)) {
|
|
1612
|
+
const available = this.list().join(", ") || "none";
|
|
1613
|
+
throw new Error(`Connector '${name}' not found. Available: ${available}`);
|
|
1614
|
+
}
|
|
1615
|
+
const connector = Connector.get(name);
|
|
1616
|
+
if (!this.policy.canAccess(connector, this.context)) {
|
|
1617
|
+
const available = this.list().join(", ") || "none";
|
|
1618
|
+
throw new Error(`Connector '${name}' not found. Available: ${available}`);
|
|
1619
|
+
}
|
|
1620
|
+
return connector;
|
|
1621
|
+
}
|
|
1622
|
+
has(name) {
|
|
1623
|
+
if (!Connector.has(name)) return false;
|
|
1624
|
+
const connector = Connector.get(name);
|
|
1625
|
+
return this.policy.canAccess(connector, this.context);
|
|
1626
|
+
}
|
|
1627
|
+
list() {
|
|
1628
|
+
return this.listAll().map((c) => c.name);
|
|
1629
|
+
}
|
|
1630
|
+
listAll() {
|
|
1631
|
+
return Connector.listAll().filter((c) => this.policy.canAccess(c, this.context));
|
|
1632
|
+
}
|
|
1633
|
+
size() {
|
|
1634
|
+
return this.listAll().length;
|
|
1635
|
+
}
|
|
1636
|
+
getDescriptionsForTools() {
|
|
1637
|
+
const connectors = this.listAll();
|
|
1638
|
+
if (connectors.length === 0) {
|
|
1639
|
+
return "No connectors registered yet.";
|
|
1640
|
+
}
|
|
1641
|
+
return connectors.map((c) => ` - "${c.name}": ${c.displayName} - ${c.config.description || "No description"}`).join("\n");
|
|
1642
|
+
}
|
|
1643
|
+
getInfo() {
|
|
1644
|
+
const info = {};
|
|
1645
|
+
for (const connector of this.listAll()) {
|
|
1646
|
+
info[connector.name] = {
|
|
1647
|
+
displayName: connector.displayName,
|
|
1648
|
+
description: connector.config.description || "",
|
|
1649
|
+
baseURL: connector.baseURL
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
return info;
|
|
1653
|
+
}
|
|
1654
|
+
};
|
|
1655
|
+
}
|
|
1656
|
+
});
|
|
1657
|
+
|
|
1600
1658
|
// src/core/Connector.ts
|
|
1601
1659
|
var Connector_exports = {};
|
|
1602
1660
|
__export(Connector_exports, {
|
|
@@ -1616,6 +1674,7 @@ var init_Connector = __esm({
|
|
|
1616
1674
|
init_BackoffStrategy();
|
|
1617
1675
|
init_Logger();
|
|
1618
1676
|
init_Metrics();
|
|
1677
|
+
init_ScopedConnectorRegistry();
|
|
1619
1678
|
DEFAULT_CONNECTOR_TIMEOUT = 3e4;
|
|
1620
1679
|
DEFAULT_MAX_RETRIES = 3;
|
|
1621
1680
|
DEFAULT_RETRYABLE_STATUSES = [429, 500, 502, 503, 504];
|
|
@@ -1700,6 +1759,50 @@ var init_Connector = __esm({
|
|
|
1700
1759
|
static size() {
|
|
1701
1760
|
return _Connector.registry.size;
|
|
1702
1761
|
}
|
|
1762
|
+
// ============ Access Control ============
|
|
1763
|
+
static _accessPolicy = null;
|
|
1764
|
+
/**
|
|
1765
|
+
* Set a global access policy for connector scoping.
|
|
1766
|
+
* Pass null to clear the policy.
|
|
1767
|
+
*/
|
|
1768
|
+
static setAccessPolicy(policy) {
|
|
1769
|
+
_Connector._accessPolicy = policy;
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Get the current global access policy (or null if none set).
|
|
1773
|
+
*/
|
|
1774
|
+
static getAccessPolicy() {
|
|
1775
|
+
return _Connector._accessPolicy;
|
|
1776
|
+
}
|
|
1777
|
+
/**
|
|
1778
|
+
* Create a scoped (filtered) view of the connector registry.
|
|
1779
|
+
* Requires a global access policy to be set via setAccessPolicy().
|
|
1780
|
+
*
|
|
1781
|
+
* @param context - Opaque context passed to the policy (e.g., { userId, tenantId })
|
|
1782
|
+
* @returns IConnectorRegistry that only exposes accessible connectors
|
|
1783
|
+
* @throws Error if no access policy is set
|
|
1784
|
+
*/
|
|
1785
|
+
static scoped(context) {
|
|
1786
|
+
if (!_Connector._accessPolicy) {
|
|
1787
|
+
throw new Error("No access policy set. Call Connector.setAccessPolicy() first.");
|
|
1788
|
+
}
|
|
1789
|
+
return new ScopedConnectorRegistry(_Connector._accessPolicy, context);
|
|
1790
|
+
}
|
|
1791
|
+
/**
|
|
1792
|
+
* Return the static Connector methods as an IConnectorRegistry object (unfiltered).
|
|
1793
|
+
* Useful when code accepts the interface but you want the full admin view.
|
|
1794
|
+
*/
|
|
1795
|
+
static asRegistry() {
|
|
1796
|
+
return {
|
|
1797
|
+
get: (name) => _Connector.get(name),
|
|
1798
|
+
has: (name) => _Connector.has(name),
|
|
1799
|
+
list: () => _Connector.list(),
|
|
1800
|
+
listAll: () => _Connector.listAll(),
|
|
1801
|
+
size: () => _Connector.size(),
|
|
1802
|
+
getDescriptionsForTools: () => _Connector.getDescriptionsForTools(),
|
|
1803
|
+
getInfo: () => _Connector.getInfo()
|
|
1804
|
+
};
|
|
1805
|
+
}
|
|
1703
1806
|
/**
|
|
1704
1807
|
* Get connector descriptions formatted for tool parameters
|
|
1705
1808
|
* Useful for generating dynamic tool descriptions
|
|
@@ -5291,8 +5394,8 @@ var require_utils = __commonJS({
|
|
|
5291
5394
|
}
|
|
5292
5395
|
return ind;
|
|
5293
5396
|
}
|
|
5294
|
-
function removeDotSegments(
|
|
5295
|
-
let input =
|
|
5397
|
+
function removeDotSegments(path6) {
|
|
5398
|
+
let input = path6;
|
|
5296
5399
|
const output = [];
|
|
5297
5400
|
let nextSlash = -1;
|
|
5298
5401
|
let len = 0;
|
|
@@ -5490,8 +5593,8 @@ var require_schemes = __commonJS({
|
|
|
5490
5593
|
wsComponent.secure = void 0;
|
|
5491
5594
|
}
|
|
5492
5595
|
if (wsComponent.resourceName) {
|
|
5493
|
-
const [
|
|
5494
|
-
wsComponent.path =
|
|
5596
|
+
const [path6, query] = wsComponent.resourceName.split("?");
|
|
5597
|
+
wsComponent.path = path6 && path6 !== "/" ? path6 : void 0;
|
|
5495
5598
|
wsComponent.query = query;
|
|
5496
5599
|
wsComponent.resourceName = void 0;
|
|
5497
5600
|
}
|
|
@@ -6429,13 +6532,13 @@ var require_core = __commonJS({
|
|
|
6429
6532
|
}, warn() {
|
|
6430
6533
|
}, error() {
|
|
6431
6534
|
} };
|
|
6432
|
-
function getLogger(
|
|
6433
|
-
if (
|
|
6535
|
+
function getLogger(logger2) {
|
|
6536
|
+
if (logger2 === false)
|
|
6434
6537
|
return noLogs;
|
|
6435
|
-
if (
|
|
6538
|
+
if (logger2 === void 0)
|
|
6436
6539
|
return console;
|
|
6437
|
-
if (
|
|
6438
|
-
return
|
|
6540
|
+
if (logger2.log && logger2.warn && logger2.error)
|
|
6541
|
+
return logger2;
|
|
6439
6542
|
throw new Error("logger must implement log, warn and error methods");
|
|
6440
6543
|
}
|
|
6441
6544
|
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
|
@@ -12254,13 +12357,13 @@ var require_core3 = __commonJS({
|
|
|
12254
12357
|
}, warn() {
|
|
12255
12358
|
}, error() {
|
|
12256
12359
|
} };
|
|
12257
|
-
function getLogger(
|
|
12258
|
-
if (
|
|
12360
|
+
function getLogger(logger2) {
|
|
12361
|
+
if (logger2 === false)
|
|
12259
12362
|
return noLogs;
|
|
12260
|
-
if (
|
|
12363
|
+
if (logger2 === void 0)
|
|
12261
12364
|
return console;
|
|
12262
|
-
if (
|
|
12263
|
-
return
|
|
12365
|
+
if (logger2.log && logger2.warn && logger2.error)
|
|
12366
|
+
return logger2;
|
|
12264
12367
|
throw new Error("logger must implement log, warn and error methods");
|
|
12265
12368
|
}
|
|
12266
12369
|
var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
|
|
@@ -14421,12 +14524,12 @@ var require_dist = __commonJS({
|
|
|
14421
14524
|
throw new Error(`Unknown format "${name}"`);
|
|
14422
14525
|
return f;
|
|
14423
14526
|
};
|
|
14424
|
-
function addFormats(ajv, list,
|
|
14527
|
+
function addFormats(ajv, list, fs18, exportName) {
|
|
14425
14528
|
var _a;
|
|
14426
14529
|
var _b;
|
|
14427
14530
|
(_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 ? _a : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
|
|
14428
14531
|
for (const f of list)
|
|
14429
|
-
ajv.addFormat(f,
|
|
14532
|
+
ajv.addFormat(f, fs18[f]);
|
|
14430
14533
|
}
|
|
14431
14534
|
module.exports = exports$1 = formatsPlugin;
|
|
14432
14535
|
Object.defineProperty(exports$1, "__esModule", { value: true });
|
|
@@ -14439,8 +14542,8 @@ var require_windows = __commonJS({
|
|
|
14439
14542
|
"node_modules/isexe/windows.js"(exports$1, module) {
|
|
14440
14543
|
module.exports = isexe;
|
|
14441
14544
|
isexe.sync = sync;
|
|
14442
|
-
var
|
|
14443
|
-
function checkPathExt(
|
|
14545
|
+
var fs18 = __require("fs");
|
|
14546
|
+
function checkPathExt(path6, options) {
|
|
14444
14547
|
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
14445
14548
|
if (!pathext) {
|
|
14446
14549
|
return true;
|
|
@@ -14451,25 +14554,25 @@ var require_windows = __commonJS({
|
|
|
14451
14554
|
}
|
|
14452
14555
|
for (var i = 0; i < pathext.length; i++) {
|
|
14453
14556
|
var p = pathext[i].toLowerCase();
|
|
14454
|
-
if (p &&
|
|
14557
|
+
if (p && path6.substr(-p.length).toLowerCase() === p) {
|
|
14455
14558
|
return true;
|
|
14456
14559
|
}
|
|
14457
14560
|
}
|
|
14458
14561
|
return false;
|
|
14459
14562
|
}
|
|
14460
|
-
function checkStat(stat5,
|
|
14563
|
+
function checkStat(stat5, path6, options) {
|
|
14461
14564
|
if (!stat5.isSymbolicLink() && !stat5.isFile()) {
|
|
14462
14565
|
return false;
|
|
14463
14566
|
}
|
|
14464
|
-
return checkPathExt(
|
|
14567
|
+
return checkPathExt(path6, options);
|
|
14465
14568
|
}
|
|
14466
|
-
function isexe(
|
|
14467
|
-
|
|
14468
|
-
cb(er, er ? false : checkStat(stat5,
|
|
14569
|
+
function isexe(path6, options, cb) {
|
|
14570
|
+
fs18.stat(path6, function(er, stat5) {
|
|
14571
|
+
cb(er, er ? false : checkStat(stat5, path6, options));
|
|
14469
14572
|
});
|
|
14470
14573
|
}
|
|
14471
|
-
function sync(
|
|
14472
|
-
return checkStat(
|
|
14574
|
+
function sync(path6, options) {
|
|
14575
|
+
return checkStat(fs18.statSync(path6), path6, options);
|
|
14473
14576
|
}
|
|
14474
14577
|
}
|
|
14475
14578
|
});
|
|
@@ -14479,14 +14582,14 @@ var require_mode = __commonJS({
|
|
|
14479
14582
|
"node_modules/isexe/mode.js"(exports$1, module) {
|
|
14480
14583
|
module.exports = isexe;
|
|
14481
14584
|
isexe.sync = sync;
|
|
14482
|
-
var
|
|
14483
|
-
function isexe(
|
|
14484
|
-
|
|
14585
|
+
var fs18 = __require("fs");
|
|
14586
|
+
function isexe(path6, options, cb) {
|
|
14587
|
+
fs18.stat(path6, function(er, stat5) {
|
|
14485
14588
|
cb(er, er ? false : checkStat(stat5, options));
|
|
14486
14589
|
});
|
|
14487
14590
|
}
|
|
14488
|
-
function sync(
|
|
14489
|
-
return checkStat(
|
|
14591
|
+
function sync(path6, options) {
|
|
14592
|
+
return checkStat(fs18.statSync(path6), options);
|
|
14490
14593
|
}
|
|
14491
14594
|
function checkStat(stat5, options) {
|
|
14492
14595
|
return stat5.isFile() && checkMode(stat5, options);
|
|
@@ -14519,7 +14622,7 @@ var require_isexe = __commonJS({
|
|
|
14519
14622
|
}
|
|
14520
14623
|
module.exports = isexe;
|
|
14521
14624
|
isexe.sync = sync;
|
|
14522
|
-
function isexe(
|
|
14625
|
+
function isexe(path6, options, cb) {
|
|
14523
14626
|
if (typeof options === "function") {
|
|
14524
14627
|
cb = options;
|
|
14525
14628
|
options = {};
|
|
@@ -14529,7 +14632,7 @@ var require_isexe = __commonJS({
|
|
|
14529
14632
|
throw new TypeError("callback not provided");
|
|
14530
14633
|
}
|
|
14531
14634
|
return new Promise(function(resolve4, reject) {
|
|
14532
|
-
isexe(
|
|
14635
|
+
isexe(path6, options || {}, function(er, is) {
|
|
14533
14636
|
if (er) {
|
|
14534
14637
|
reject(er);
|
|
14535
14638
|
} else {
|
|
@@ -14538,7 +14641,7 @@ var require_isexe = __commonJS({
|
|
|
14538
14641
|
});
|
|
14539
14642
|
});
|
|
14540
14643
|
}
|
|
14541
|
-
core(
|
|
14644
|
+
core(path6, options || {}, function(er, is) {
|
|
14542
14645
|
if (er) {
|
|
14543
14646
|
if (er.code === "EACCES" || options && options.ignoreErrors) {
|
|
14544
14647
|
er = null;
|
|
@@ -14548,9 +14651,9 @@ var require_isexe = __commonJS({
|
|
|
14548
14651
|
cb(er, is);
|
|
14549
14652
|
});
|
|
14550
14653
|
}
|
|
14551
|
-
function sync(
|
|
14654
|
+
function sync(path6, options) {
|
|
14552
14655
|
try {
|
|
14553
|
-
return core.sync(
|
|
14656
|
+
return core.sync(path6, options || {});
|
|
14554
14657
|
} catch (er) {
|
|
14555
14658
|
if (options && options.ignoreErrors || er.code === "EACCES") {
|
|
14556
14659
|
return false;
|
|
@@ -14566,7 +14669,7 @@ var require_isexe = __commonJS({
|
|
|
14566
14669
|
var require_which = __commonJS({
|
|
14567
14670
|
"node_modules/which/which.js"(exports$1, module) {
|
|
14568
14671
|
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
14569
|
-
var
|
|
14672
|
+
var path6 = __require("path");
|
|
14570
14673
|
var COLON = isWindows ? ";" : ":";
|
|
14571
14674
|
var isexe = require_isexe();
|
|
14572
14675
|
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
@@ -14604,7 +14707,7 @@ var require_which = __commonJS({
|
|
|
14604
14707
|
return opt.all && found.length ? resolve4(found) : reject(getNotFoundError(cmd));
|
|
14605
14708
|
const ppRaw = pathEnv[i];
|
|
14606
14709
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
14607
|
-
const pCmd =
|
|
14710
|
+
const pCmd = path6.join(pathPart, cmd);
|
|
14608
14711
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
14609
14712
|
resolve4(subStep(p, i, 0));
|
|
14610
14713
|
});
|
|
@@ -14631,7 +14734,7 @@ var require_which = __commonJS({
|
|
|
14631
14734
|
for (let i = 0; i < pathEnv.length; i++) {
|
|
14632
14735
|
const ppRaw = pathEnv[i];
|
|
14633
14736
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
14634
|
-
const pCmd =
|
|
14737
|
+
const pCmd = path6.join(pathPart, cmd);
|
|
14635
14738
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
14636
14739
|
for (let j = 0; j < pathExt.length; j++) {
|
|
14637
14740
|
const cur = p + pathExt[j];
|
|
@@ -14677,7 +14780,7 @@ var require_path_key = __commonJS({
|
|
|
14677
14780
|
// node_modules/cross-spawn/lib/util/resolveCommand.js
|
|
14678
14781
|
var require_resolveCommand = __commonJS({
|
|
14679
14782
|
"node_modules/cross-spawn/lib/util/resolveCommand.js"(exports$1, module) {
|
|
14680
|
-
var
|
|
14783
|
+
var path6 = __require("path");
|
|
14681
14784
|
var which = require_which();
|
|
14682
14785
|
var getPathKey = require_path_key();
|
|
14683
14786
|
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
@@ -14695,7 +14798,7 @@ var require_resolveCommand = __commonJS({
|
|
|
14695
14798
|
try {
|
|
14696
14799
|
resolved = which.sync(parsed.command, {
|
|
14697
14800
|
path: env[getPathKey({ env })],
|
|
14698
|
-
pathExt: withoutPathExt ?
|
|
14801
|
+
pathExt: withoutPathExt ? path6.delimiter : void 0
|
|
14699
14802
|
});
|
|
14700
14803
|
} catch (e) {
|
|
14701
14804
|
} finally {
|
|
@@ -14704,7 +14807,7 @@ var require_resolveCommand = __commonJS({
|
|
|
14704
14807
|
}
|
|
14705
14808
|
}
|
|
14706
14809
|
if (resolved) {
|
|
14707
|
-
resolved =
|
|
14810
|
+
resolved = path6.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
14708
14811
|
}
|
|
14709
14812
|
return resolved;
|
|
14710
14813
|
}
|
|
@@ -14755,8 +14858,8 @@ var require_shebang_command = __commonJS({
|
|
|
14755
14858
|
if (!match) {
|
|
14756
14859
|
return null;
|
|
14757
14860
|
}
|
|
14758
|
-
const [
|
|
14759
|
-
const binary =
|
|
14861
|
+
const [path6, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
14862
|
+
const binary = path6.split("/").pop();
|
|
14760
14863
|
if (binary === "env") {
|
|
14761
14864
|
return argument;
|
|
14762
14865
|
}
|
|
@@ -14768,16 +14871,16 @@ var require_shebang_command = __commonJS({
|
|
|
14768
14871
|
// node_modules/cross-spawn/lib/util/readShebang.js
|
|
14769
14872
|
var require_readShebang = __commonJS({
|
|
14770
14873
|
"node_modules/cross-spawn/lib/util/readShebang.js"(exports$1, module) {
|
|
14771
|
-
var
|
|
14874
|
+
var fs18 = __require("fs");
|
|
14772
14875
|
var shebangCommand = require_shebang_command();
|
|
14773
14876
|
function readShebang(command) {
|
|
14774
14877
|
const size = 150;
|
|
14775
14878
|
const buffer = Buffer.alloc(size);
|
|
14776
14879
|
let fd;
|
|
14777
14880
|
try {
|
|
14778
|
-
fd =
|
|
14779
|
-
|
|
14780
|
-
|
|
14881
|
+
fd = fs18.openSync(command, "r");
|
|
14882
|
+
fs18.readSync(fd, buffer, 0, size, 0);
|
|
14883
|
+
fs18.closeSync(fd);
|
|
14781
14884
|
} catch (e) {
|
|
14782
14885
|
}
|
|
14783
14886
|
return shebangCommand(buffer.toString());
|
|
@@ -14789,7 +14892,7 @@ var require_readShebang = __commonJS({
|
|
|
14789
14892
|
// node_modules/cross-spawn/lib/parse.js
|
|
14790
14893
|
var require_parse = __commonJS({
|
|
14791
14894
|
"node_modules/cross-spawn/lib/parse.js"(exports$1, module) {
|
|
14792
|
-
var
|
|
14895
|
+
var path6 = __require("path");
|
|
14793
14896
|
var resolveCommand = require_resolveCommand();
|
|
14794
14897
|
var escape2 = require_escape();
|
|
14795
14898
|
var readShebang = require_readShebang();
|
|
@@ -14814,7 +14917,7 @@ var require_parse = __commonJS({
|
|
|
14814
14917
|
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
14815
14918
|
if (parsed.options.forceShell || needsShell) {
|
|
14816
14919
|
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
14817
|
-
parsed.command =
|
|
14920
|
+
parsed.command = path6.normalize(parsed.command);
|
|
14818
14921
|
parsed.command = escape2.command(parsed.command);
|
|
14819
14922
|
parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
|
|
14820
14923
|
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
|
|
@@ -14924,6 +15027,7 @@ var require_cross_spawn = __commonJS({
|
|
|
14924
15027
|
|
|
14925
15028
|
// src/core/index.ts
|
|
14926
15029
|
init_Connector();
|
|
15030
|
+
init_ScopedConnectorRegistry();
|
|
14927
15031
|
|
|
14928
15032
|
// src/core/BaseAgent.ts
|
|
14929
15033
|
init_Connector();
|
|
@@ -17998,12 +18102,28 @@ var ContentType = /* @__PURE__ */ ((ContentType2) => {
|
|
|
17998
18102
|
ContentType2["TOOL_RESULT"] = "tool_result";
|
|
17999
18103
|
return ContentType2;
|
|
18000
18104
|
})(ContentType || {});
|
|
18105
|
+
var AGENT_DEFAULTS = {
|
|
18106
|
+
/** Default maximum iterations for agentic loop */
|
|
18107
|
+
MAX_ITERATIONS: 50,
|
|
18108
|
+
/** Default temperature for LLM calls */
|
|
18109
|
+
DEFAULT_TEMPERATURE: 0.7,
|
|
18110
|
+
/** Message injected when max iterations is reached */
|
|
18111
|
+
MAX_ITERATIONS_MESSAGE: `You have reached the maximum iteration limit for this execution. Please:
|
|
18112
|
+
1. Summarize what you have accomplished so far
|
|
18113
|
+
2. Explain what remains to be done (if anything)
|
|
18114
|
+
3. Ask the user if they would like you to continue
|
|
18115
|
+
|
|
18116
|
+
Do NOT use any tools in this response - just provide a clear summary and ask for confirmation to proceed.`
|
|
18117
|
+
};
|
|
18118
|
+
var TOKEN_ESTIMATION = {
|
|
18119
|
+
/** Characters per token for mixed content */
|
|
18120
|
+
MIXED_CHARS_PER_TOKEN: 3.5};
|
|
18001
18121
|
|
|
18002
18122
|
// src/core/context-nextgen/BasePluginNextGen.ts
|
|
18003
18123
|
var simpleTokenEstimator = {
|
|
18004
18124
|
estimateTokens(text) {
|
|
18005
18125
|
if (!text || text.length === 0) return 0;
|
|
18006
|
-
return Math.ceil(text.length /
|
|
18126
|
+
return Math.ceil(text.length / TOKEN_ESTIMATION.MIXED_CHARS_PER_TOKEN);
|
|
18007
18127
|
},
|
|
18008
18128
|
estimateDataTokens(data) {
|
|
18009
18129
|
const text = typeof data === "string" ? data : JSON.stringify(data);
|
|
@@ -18773,6 +18893,13 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18773
18893
|
_destroyed = false;
|
|
18774
18894
|
_tokenCache = null;
|
|
18775
18895
|
_instructionsTokenCache = null;
|
|
18896
|
+
/**
|
|
18897
|
+
* Synchronous snapshot of entries for getState() serialization.
|
|
18898
|
+
* Updated on every mutation (store, delete, evict, cleanupRaw, restoreState).
|
|
18899
|
+
* Solves the async/sync mismatch: IMemoryStorage.getAll() is async but
|
|
18900
|
+
* IContextPluginNextGen.getState() must be sync.
|
|
18901
|
+
*/
|
|
18902
|
+
_syncEntries = /* @__PURE__ */ new Map();
|
|
18776
18903
|
constructor(pluginConfig = {}) {
|
|
18777
18904
|
this.storage = pluginConfig.storage ?? new InMemoryStorage();
|
|
18778
18905
|
this.config = pluginConfig.config ?? DEFAULT_MEMORY_CONFIG;
|
|
@@ -18833,28 +18960,13 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18833
18960
|
getState() {
|
|
18834
18961
|
return {
|
|
18835
18962
|
version: 1,
|
|
18836
|
-
entries:
|
|
18837
|
-
// Will be populated by async getStateAsync()
|
|
18838
|
-
};
|
|
18839
|
-
}
|
|
18840
|
-
async getStateAsync() {
|
|
18841
|
-
const entries = await this.storage.getAll();
|
|
18842
|
-
return {
|
|
18843
|
-
version: 1,
|
|
18844
|
-
entries: entries.map((e) => ({
|
|
18845
|
-
key: e.key,
|
|
18846
|
-
description: e.description,
|
|
18847
|
-
value: e.value,
|
|
18848
|
-
scope: e.scope,
|
|
18849
|
-
sizeBytes: e.sizeBytes,
|
|
18850
|
-
basePriority: e.basePriority,
|
|
18851
|
-
pinned: e.pinned
|
|
18852
|
-
}))
|
|
18963
|
+
entries: Array.from(this._syncEntries.values())
|
|
18853
18964
|
};
|
|
18854
18965
|
}
|
|
18855
18966
|
restoreState(state) {
|
|
18856
18967
|
const s = state;
|
|
18857
18968
|
if (!s || !s.entries) return;
|
|
18969
|
+
this._syncEntries.clear();
|
|
18858
18970
|
for (const entry of s.entries) {
|
|
18859
18971
|
const memEntry = createMemoryEntry({
|
|
18860
18972
|
key: entry.key,
|
|
@@ -18865,6 +18977,15 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18865
18977
|
pinned: entry.pinned
|
|
18866
18978
|
}, this.config);
|
|
18867
18979
|
this.storage.set(entry.key, memEntry);
|
|
18980
|
+
this._syncEntries.set(entry.key, {
|
|
18981
|
+
key: entry.key,
|
|
18982
|
+
description: entry.description,
|
|
18983
|
+
value: entry.value,
|
|
18984
|
+
scope: entry.scope,
|
|
18985
|
+
sizeBytes: entry.sizeBytes,
|
|
18986
|
+
basePriority: entry.basePriority,
|
|
18987
|
+
pinned: entry.pinned
|
|
18988
|
+
});
|
|
18868
18989
|
}
|
|
18869
18990
|
this._tokenCache = null;
|
|
18870
18991
|
}
|
|
@@ -18893,6 +19014,15 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18893
19014
|
}, this.config);
|
|
18894
19015
|
await this.ensureCapacity(entry.sizeBytes);
|
|
18895
19016
|
await this.storage.set(finalKey, entry);
|
|
19017
|
+
this._syncEntries.set(finalKey, {
|
|
19018
|
+
key: finalKey,
|
|
19019
|
+
description,
|
|
19020
|
+
value,
|
|
19021
|
+
scope,
|
|
19022
|
+
sizeBytes: entry.sizeBytes,
|
|
19023
|
+
basePriority: finalPriority,
|
|
19024
|
+
pinned: options?.pinned
|
|
19025
|
+
});
|
|
18896
19026
|
this._tokenCache = null;
|
|
18897
19027
|
return { key: finalKey, sizeBytes: entry.sizeBytes };
|
|
18898
19028
|
}
|
|
@@ -18918,6 +19048,7 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18918
19048
|
const exists = await this.storage.has(key);
|
|
18919
19049
|
if (exists) {
|
|
18920
19050
|
await this.storage.delete(key);
|
|
19051
|
+
this._syncEntries.delete(key);
|
|
18921
19052
|
this._tokenCache = null;
|
|
18922
19053
|
return true;
|
|
18923
19054
|
}
|
|
@@ -18981,6 +19112,7 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18981
19112
|
const evictedKeys = [];
|
|
18982
19113
|
for (const entry of toEvict) {
|
|
18983
19114
|
await this.storage.delete(entry.key);
|
|
19115
|
+
this._syncEntries.delete(entry.key);
|
|
18984
19116
|
evictedKeys.push(entry.key);
|
|
18985
19117
|
}
|
|
18986
19118
|
if (evictedKeys.length > 0) {
|
|
@@ -18997,6 +19129,7 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
18997
19129
|
const keys = [];
|
|
18998
19130
|
for (const entry of rawEntries) {
|
|
18999
19131
|
await this.storage.delete(entry.key);
|
|
19132
|
+
this._syncEntries.delete(entry.key);
|
|
19000
19133
|
keys.push(entry.key);
|
|
19001
19134
|
}
|
|
19002
19135
|
if (keys.length > 0) {
|
|
@@ -19063,6 +19196,7 @@ var WorkingMemoryPluginNextGen = class {
|
|
|
19063
19196
|
for (const entry of evictable) {
|
|
19064
19197
|
if (freedBytes >= bytesToFree && freedCount >= entriesToFree) break;
|
|
19065
19198
|
await this.storage.delete(entry.key);
|
|
19199
|
+
this._syncEntries.delete(entry.key);
|
|
19066
19200
|
freedBytes += entry.sizeBytes;
|
|
19067
19201
|
freedCount++;
|
|
19068
19202
|
}
|
|
@@ -19325,6 +19459,7 @@ var InContextMemoryPluginNextGen = class {
|
|
|
19325
19459
|
};
|
|
19326
19460
|
this.entries.set(key, entry);
|
|
19327
19461
|
this.enforceMaxEntries();
|
|
19462
|
+
this.enforceTokenLimit();
|
|
19328
19463
|
this._tokenCache = null;
|
|
19329
19464
|
}
|
|
19330
19465
|
/**
|
|
@@ -19395,16 +19530,43 @@ ${valueStr}
|
|
|
19395
19530
|
}
|
|
19396
19531
|
enforceMaxEntries() {
|
|
19397
19532
|
if (this.entries.size <= this.config.maxEntries) return;
|
|
19398
|
-
const evictable =
|
|
19399
|
-
const priorityDiff = PRIORITY_VALUES[a.priority] - PRIORITY_VALUES[b.priority];
|
|
19400
|
-
if (priorityDiff !== 0) return priorityDiff;
|
|
19401
|
-
return a.updatedAt - b.updatedAt;
|
|
19402
|
-
});
|
|
19533
|
+
const evictable = this.getEvictableEntries();
|
|
19403
19534
|
while (this.entries.size > this.config.maxEntries && evictable.length > 0) {
|
|
19404
19535
|
const toEvict = evictable.shift();
|
|
19405
19536
|
this.entries.delete(toEvict.key);
|
|
19406
19537
|
}
|
|
19407
19538
|
}
|
|
19539
|
+
enforceTokenLimit() {
|
|
19540
|
+
const maxTokens = this.config.maxTotalTokens;
|
|
19541
|
+
if (maxTokens <= 0) return;
|
|
19542
|
+
let totalTokens = this.estimateTotalTokens();
|
|
19543
|
+
if (totalTokens <= maxTokens) return;
|
|
19544
|
+
const evictable = this.getEvictableEntries();
|
|
19545
|
+
while (totalTokens > maxTokens && evictable.length > 0) {
|
|
19546
|
+
const toEvict = evictable.shift();
|
|
19547
|
+
const entryTokens = this.estimator.estimateTokens(this.formatEntry(toEvict));
|
|
19548
|
+
this.entries.delete(toEvict.key);
|
|
19549
|
+
totalTokens -= entryTokens;
|
|
19550
|
+
}
|
|
19551
|
+
}
|
|
19552
|
+
estimateTotalTokens() {
|
|
19553
|
+
let total = 0;
|
|
19554
|
+
for (const entry of this.entries.values()) {
|
|
19555
|
+
total += this.estimator.estimateTokens(this.formatEntry(entry));
|
|
19556
|
+
}
|
|
19557
|
+
return total;
|
|
19558
|
+
}
|
|
19559
|
+
/**
|
|
19560
|
+
* Get entries sorted by eviction priority (lowest priority, oldest first).
|
|
19561
|
+
* Critical entries are excluded.
|
|
19562
|
+
*/
|
|
19563
|
+
getEvictableEntries() {
|
|
19564
|
+
return Array.from(this.entries.values()).filter((e) => e.priority !== "critical").sort((a, b) => {
|
|
19565
|
+
const priorityDiff = PRIORITY_VALUES[a.priority] - PRIORITY_VALUES[b.priority];
|
|
19566
|
+
if (priorityDiff !== 0) return priorityDiff;
|
|
19567
|
+
return a.updatedAt - b.updatedAt;
|
|
19568
|
+
});
|
|
19569
|
+
}
|
|
19408
19570
|
assertNotDestroyed() {
|
|
19409
19571
|
if (this._destroyed) {
|
|
19410
19572
|
throw new Error("InContextMemoryPluginNextGen is destroyed");
|
|
@@ -19892,8 +20054,8 @@ ${trimmedSection}` : trimmedSection;
|
|
|
19892
20054
|
var DEFAULT_THRESHOLD = 0.7;
|
|
19893
20055
|
var DefaultCompactionStrategy = class {
|
|
19894
20056
|
name = "default";
|
|
19895
|
-
displayName = "
|
|
19896
|
-
description = "
|
|
20057
|
+
displayName = "Dumb";
|
|
20058
|
+
description = "Do not use";
|
|
19897
20059
|
threshold;
|
|
19898
20060
|
constructor(config) {
|
|
19899
20061
|
this.threshold = config?.threshold ?? DEFAULT_THRESHOLD;
|
|
@@ -20536,7 +20698,7 @@ var DEFAULT_FEATURES = {
|
|
|
20536
20698
|
};
|
|
20537
20699
|
var DEFAULT_CONFIG2 = {
|
|
20538
20700
|
responseReserve: 4096,
|
|
20539
|
-
strategy: "
|
|
20701
|
+
strategy: "algorithmic"
|
|
20540
20702
|
};
|
|
20541
20703
|
|
|
20542
20704
|
// src/core/context-nextgen/AgentContextNextGen.ts
|
|
@@ -24494,6 +24656,8 @@ var BaseAgent = class extends EventEmitter {
|
|
|
24494
24656
|
_sessionConfig = null;
|
|
24495
24657
|
_autoSaveInterval = null;
|
|
24496
24658
|
_pendingSessionLoad = null;
|
|
24659
|
+
/** Whether caller provided explicit instructions/systemPrompt (takes precedence over saved session) */
|
|
24660
|
+
_hasExplicitInstructions = false;
|
|
24497
24661
|
// Provider for LLM calls - single instance shared by all methods
|
|
24498
24662
|
_provider;
|
|
24499
24663
|
// ===== Constructor =====
|
|
@@ -24525,7 +24689,7 @@ var BaseAgent = class extends EventEmitter {
|
|
|
24525
24689
|
*/
|
|
24526
24690
|
resolveConnector(ref) {
|
|
24527
24691
|
if (typeof ref === "string") {
|
|
24528
|
-
return Connector.get(ref);
|
|
24692
|
+
return this._config.registry ? this._config.registry.get(ref) : Connector.get(ref);
|
|
24529
24693
|
}
|
|
24530
24694
|
return ref;
|
|
24531
24695
|
}
|
|
@@ -24670,9 +24834,14 @@ var BaseAgent = class extends EventEmitter {
|
|
|
24670
24834
|
/**
|
|
24671
24835
|
* Restore context from saved state.
|
|
24672
24836
|
* Override in subclasses to restore agent-specific state from agentState field.
|
|
24837
|
+
* Preserves explicit instructions if caller provided them at construction time.
|
|
24673
24838
|
*/
|
|
24674
24839
|
async restoreContextState(state) {
|
|
24840
|
+
const explicitPrompt = this._hasExplicitInstructions ? this._agentContext.systemPrompt : void 0;
|
|
24675
24841
|
this._agentContext.restoreState(state);
|
|
24842
|
+
if (this._hasExplicitInstructions && explicitPrompt !== void 0) {
|
|
24843
|
+
this._agentContext.systemPrompt = explicitPrompt;
|
|
24844
|
+
}
|
|
24676
24845
|
}
|
|
24677
24846
|
// ===== Public Permission API =====
|
|
24678
24847
|
/**
|
|
@@ -25769,126 +25938,6 @@ function assertNotDestroyed(obj, operation) {
|
|
|
25769
25938
|
|
|
25770
25939
|
// src/core/Agent.ts
|
|
25771
25940
|
init_Metrics();
|
|
25772
|
-
|
|
25773
|
-
// src/core/constants.ts
|
|
25774
|
-
var PROACTIVE_STRATEGY_DEFAULTS = {
|
|
25775
|
-
/** Target utilization after compaction */
|
|
25776
|
-
TARGET_UTILIZATION: 0.65,
|
|
25777
|
-
/** Base reduction factor for round 1 */
|
|
25778
|
-
BASE_REDUCTION_FACTOR: 0.5,
|
|
25779
|
-
/** Reduction step per round (more aggressive each round) */
|
|
25780
|
-
REDUCTION_STEP: 0.15,
|
|
25781
|
-
/** Maximum compaction rounds */
|
|
25782
|
-
MAX_ROUNDS: 3
|
|
25783
|
-
};
|
|
25784
|
-
var AGGRESSIVE_STRATEGY_DEFAULTS = {
|
|
25785
|
-
/** Threshold to trigger compaction */
|
|
25786
|
-
THRESHOLD: 0.6,
|
|
25787
|
-
/** Target utilization after compaction */
|
|
25788
|
-
TARGET_UTILIZATION: 0.5,
|
|
25789
|
-
/** Reduction factor (keep 30% of original) */
|
|
25790
|
-
REDUCTION_FACTOR: 0.3
|
|
25791
|
-
};
|
|
25792
|
-
var LAZY_STRATEGY_DEFAULTS = {
|
|
25793
|
-
/** Target utilization after compaction */
|
|
25794
|
-
TARGET_UTILIZATION: 0.85,
|
|
25795
|
-
/** Reduction factor (keep 70% of original) */
|
|
25796
|
-
REDUCTION_FACTOR: 0.7
|
|
25797
|
-
};
|
|
25798
|
-
var ADAPTIVE_STRATEGY_DEFAULTS = {
|
|
25799
|
-
/** Number of compactions to learn from */
|
|
25800
|
-
LEARNING_WINDOW: 10,
|
|
25801
|
-
/** Compactions per minute threshold to switch to aggressive */
|
|
25802
|
-
SWITCH_THRESHOLD: 5,
|
|
25803
|
-
/** Low utilization threshold to switch to lazy */
|
|
25804
|
-
LOW_UTILIZATION_THRESHOLD: 70,
|
|
25805
|
-
/** Low frequency threshold to switch to lazy */
|
|
25806
|
-
LOW_FREQUENCY_THRESHOLD: 0.5
|
|
25807
|
-
};
|
|
25808
|
-
var ROLLING_WINDOW_DEFAULTS = {
|
|
25809
|
-
/** Default maximum messages to keep */
|
|
25810
|
-
MAX_MESSAGES: 20
|
|
25811
|
-
};
|
|
25812
|
-
var AGENT_DEFAULTS = {
|
|
25813
|
-
/** Default maximum iterations for agentic loop */
|
|
25814
|
-
MAX_ITERATIONS: 50,
|
|
25815
|
-
/** Default temperature for LLM calls */
|
|
25816
|
-
DEFAULT_TEMPERATURE: 0.7,
|
|
25817
|
-
/** Message injected when max iterations is reached */
|
|
25818
|
-
MAX_ITERATIONS_MESSAGE: `You have reached the maximum iteration limit for this execution. Please:
|
|
25819
|
-
1. Summarize what you have accomplished so far
|
|
25820
|
-
2. Explain what remains to be done (if anything)
|
|
25821
|
-
3. Ask the user if they would like you to continue
|
|
25822
|
-
|
|
25823
|
-
Do NOT use any tools in this response - just provide a clear summary and ask for confirmation to proceed.`
|
|
25824
|
-
};
|
|
25825
|
-
var STRATEGY_THRESHOLDS = {
|
|
25826
|
-
proactive: {
|
|
25827
|
-
// Most balanced - good for general use
|
|
25828
|
-
compactionTrigger: 0.75,
|
|
25829
|
-
// Start compaction at 75%
|
|
25830
|
-
compactionTarget: 0.65,
|
|
25831
|
-
// Reduce to 65%
|
|
25832
|
-
smartCompactionTrigger: 0.7,
|
|
25833
|
-
// Trigger smart compaction at 70%
|
|
25834
|
-
maxToolResultsPercent: 0.3,
|
|
25835
|
-
// Tool results can use up to 30% of context
|
|
25836
|
-
protectedContextPercent: 0.1
|
|
25837
|
-
// Protect at least 10% of context (recent messages)
|
|
25838
|
-
},
|
|
25839
|
-
aggressive: {
|
|
25840
|
-
// Memory-constrained - compact early and often
|
|
25841
|
-
compactionTrigger: 0.6,
|
|
25842
|
-
compactionTarget: 0.5,
|
|
25843
|
-
smartCompactionTrigger: 0.55,
|
|
25844
|
-
maxToolResultsPercent: 0.25,
|
|
25845
|
-
protectedContextPercent: 0.08
|
|
25846
|
-
},
|
|
25847
|
-
lazy: {
|
|
25848
|
-
// Preserve context - only compact when critical
|
|
25849
|
-
compactionTrigger: 0.9,
|
|
25850
|
-
compactionTarget: 0.85,
|
|
25851
|
-
smartCompactionTrigger: 0.85,
|
|
25852
|
-
maxToolResultsPercent: 0.4,
|
|
25853
|
-
// Allow more tool results
|
|
25854
|
-
protectedContextPercent: 0.15
|
|
25855
|
-
// Protect more recent context
|
|
25856
|
-
},
|
|
25857
|
-
adaptive: {
|
|
25858
|
-
// Starts with proactive, adjusts based on performance
|
|
25859
|
-
compactionTrigger: 0.75,
|
|
25860
|
-
compactionTarget: 0.65,
|
|
25861
|
-
smartCompactionTrigger: 0.7,
|
|
25862
|
-
maxToolResultsPercent: 0.3,
|
|
25863
|
-
protectedContextPercent: 0.1
|
|
25864
|
-
},
|
|
25865
|
-
"rolling-window": {
|
|
25866
|
-
// Fixed window, similar to lazy but with message count focus
|
|
25867
|
-
compactionTrigger: 0.85,
|
|
25868
|
-
compactionTarget: 0.75,
|
|
25869
|
-
smartCompactionTrigger: 0.8,
|
|
25870
|
-
maxToolResultsPercent: 0.35,
|
|
25871
|
-
protectedContextPercent: 0.12
|
|
25872
|
-
}
|
|
25873
|
-
};
|
|
25874
|
-
var SAFETY_CAPS = {
|
|
25875
|
-
/** Always keep at least this many messages */
|
|
25876
|
-
MIN_PROTECTED_MESSAGES: 10
|
|
25877
|
-
};
|
|
25878
|
-
var GUARDIAN_DEFAULTS = {
|
|
25879
|
-
/** Enable guardian validation (can be disabled for testing) */
|
|
25880
|
-
ENABLED: true,
|
|
25881
|
-
/** Maximum tool result size in tokens before truncation (4KB ≈ 1000 tokens) */
|
|
25882
|
-
MAX_TOOL_RESULT_TOKENS: 2e3,
|
|
25883
|
-
/** Minimum system prompt tokens to preserve during emergency compaction */
|
|
25884
|
-
MIN_SYSTEM_PROMPT_TOKENS: 3e3,
|
|
25885
|
-
/** Number of most recent messages to always protect (increased from 4) */
|
|
25886
|
-
PROTECTED_RECENT_MESSAGES: 20,
|
|
25887
|
-
/** Truncation suffix for oversized content */
|
|
25888
|
-
TRUNCATION_SUFFIX: "\n\n[Content truncated by ContextGuardian - original data may be available in memory]"
|
|
25889
|
-
};
|
|
25890
|
-
|
|
25891
|
-
// src/core/Agent.ts
|
|
25892
25941
|
var Agent = class _Agent extends BaseAgent {
|
|
25893
25942
|
// ===== Agent-specific State =====
|
|
25894
25943
|
hookManager;
|
|
@@ -25983,6 +26032,7 @@ var Agent = class _Agent extends BaseAgent {
|
|
|
25983
26032
|
});
|
|
25984
26033
|
if (config.instructions) {
|
|
25985
26034
|
this._agentContext.systemPrompt = config.instructions;
|
|
26035
|
+
this._hasExplicitInstructions = true;
|
|
25986
26036
|
}
|
|
25987
26037
|
this._agentContext.tools.on("tool:registered", ({ name }) => {
|
|
25988
26038
|
const permission = this._agentContext.tools.getPermission(name);
|
|
@@ -27094,10 +27144,6 @@ var Agent = class _Agent extends BaseAgent {
|
|
|
27094
27144
|
this._logger.debug("Agent destroyed");
|
|
27095
27145
|
}
|
|
27096
27146
|
};
|
|
27097
|
-
|
|
27098
|
-
// src/core/context/SmartCompactor.ts
|
|
27099
|
-
init_Logger();
|
|
27100
|
-
logger.child({ component: "SmartCompactor" });
|
|
27101
27147
|
(class {
|
|
27102
27148
|
static DEFAULT_PATHS = [
|
|
27103
27149
|
"./oneringai.config.json",
|
|
@@ -27106,8 +27152,8 @@ logger.child({ component: "SmartCompactor" });
|
|
|
27106
27152
|
/**
|
|
27107
27153
|
* Load configuration from file
|
|
27108
27154
|
*/
|
|
27109
|
-
static async load(
|
|
27110
|
-
const configPath =
|
|
27155
|
+
static async load(path6) {
|
|
27156
|
+
const configPath = path6 ? resolve(path6) : await this.findConfig();
|
|
27111
27157
|
if (!configPath) {
|
|
27112
27158
|
throw new Error("Configuration file not found. Searched: " + this.DEFAULT_PATHS.join(", "));
|
|
27113
27159
|
}
|
|
@@ -27127,14 +27173,14 @@ logger.child({ component: "SmartCompactor" });
|
|
|
27127
27173
|
/**
|
|
27128
27174
|
* Load configuration synchronously
|
|
27129
27175
|
*/
|
|
27130
|
-
static loadSync(
|
|
27131
|
-
const configPath =
|
|
27176
|
+
static loadSync(path6) {
|
|
27177
|
+
const configPath = path6 ? resolve(path6) : this.findConfigSync();
|
|
27132
27178
|
if (!configPath) {
|
|
27133
27179
|
throw new Error("Configuration file not found. Searched: " + this.DEFAULT_PATHS.join(", "));
|
|
27134
27180
|
}
|
|
27135
27181
|
try {
|
|
27136
|
-
const
|
|
27137
|
-
const content =
|
|
27182
|
+
const fs18 = __require("fs");
|
|
27183
|
+
const content = fs18.readFileSync(configPath, "utf-8");
|
|
27138
27184
|
let config = JSON.parse(content);
|
|
27139
27185
|
config = this.interpolateEnvVars(config);
|
|
27140
27186
|
this.validate(config);
|
|
@@ -27150,10 +27196,10 @@ logger.child({ component: "SmartCompactor" });
|
|
|
27150
27196
|
* Find configuration file in default paths
|
|
27151
27197
|
*/
|
|
27152
27198
|
static async findConfig() {
|
|
27153
|
-
for (const
|
|
27199
|
+
for (const path6 of this.DEFAULT_PATHS) {
|
|
27154
27200
|
try {
|
|
27155
|
-
await promises.access(resolve(
|
|
27156
|
-
return resolve(
|
|
27201
|
+
await promises.access(resolve(path6));
|
|
27202
|
+
return resolve(path6);
|
|
27157
27203
|
} catch {
|
|
27158
27204
|
}
|
|
27159
27205
|
}
|
|
@@ -27163,11 +27209,11 @@ logger.child({ component: "SmartCompactor" });
|
|
|
27163
27209
|
* Find configuration file synchronously
|
|
27164
27210
|
*/
|
|
27165
27211
|
static findConfigSync() {
|
|
27166
|
-
const
|
|
27167
|
-
for (const
|
|
27212
|
+
const fs18 = __require("fs");
|
|
27213
|
+
for (const path6 of this.DEFAULT_PATHS) {
|
|
27168
27214
|
try {
|
|
27169
|
-
|
|
27170
|
-
return resolve(
|
|
27215
|
+
fs18.accessSync(resolve(path6));
|
|
27216
|
+
return resolve(path6);
|
|
27171
27217
|
} catch {
|
|
27172
27218
|
}
|
|
27173
27219
|
}
|
|
@@ -30746,8 +30792,8 @@ async function random(size) {
|
|
|
30746
30792
|
const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
|
|
30747
30793
|
let result = "";
|
|
30748
30794
|
while (result.length < size) {
|
|
30749
|
-
const
|
|
30750
|
-
for (const randomByte of
|
|
30795
|
+
const randomBytes4 = await getRandomValues(size - result.length);
|
|
30796
|
+
for (const randomByte of randomBytes4) {
|
|
30751
30797
|
if (randomByte < evenDistCutoff) {
|
|
30752
30798
|
result += mask[randomByte % mask.length];
|
|
30753
30799
|
}
|
|
@@ -32220,7 +32266,7 @@ var MCPClient = class extends EventEmitter {
|
|
|
32220
32266
|
this.transport = this.createTransport();
|
|
32221
32267
|
this.client = new Client(
|
|
32222
32268
|
{
|
|
32223
|
-
name: "@oneringai
|
|
32269
|
+
name: "@everworker/oneringai",
|
|
32224
32270
|
version: "0.2.0"
|
|
32225
32271
|
},
|
|
32226
32272
|
{
|
|
@@ -32722,9 +32768,9 @@ var MCPRegistry = class {
|
|
|
32722
32768
|
/**
|
|
32723
32769
|
* Load MCP configuration from file and create clients
|
|
32724
32770
|
*/
|
|
32725
|
-
static async loadFromConfigFile(
|
|
32771
|
+
static async loadFromConfigFile(path6) {
|
|
32726
32772
|
try {
|
|
32727
|
-
const configPath = resolve(
|
|
32773
|
+
const configPath = resolve(path6);
|
|
32728
32774
|
const content = await promises.readFile(configPath, "utf-8");
|
|
32729
32775
|
const config = JSON.parse(content);
|
|
32730
32776
|
if (!config.mcp) {
|
|
@@ -32736,7 +32782,7 @@ var MCPRegistry = class {
|
|
|
32736
32782
|
if (error instanceof MCPError) {
|
|
32737
32783
|
throw error;
|
|
32738
32784
|
}
|
|
32739
|
-
throw new MCPError(`Failed to load MCP configuration from '${
|
|
32785
|
+
throw new MCPError(`Failed to load MCP configuration from '${path6}'`, void 0, error);
|
|
32740
32786
|
}
|
|
32741
32787
|
}
|
|
32742
32788
|
/**
|
|
@@ -34704,8 +34750,8 @@ var GoogleImageProvider = class extends BaseMediaProvider {
|
|
|
34704
34750
|
if (Buffer.isBuffer(image)) {
|
|
34705
34751
|
imageBytes = image.toString("base64");
|
|
34706
34752
|
} else {
|
|
34707
|
-
const
|
|
34708
|
-
const buffer =
|
|
34753
|
+
const fs18 = await import('fs');
|
|
34754
|
+
const buffer = fs18.readFileSync(image);
|
|
34709
34755
|
imageBytes = buffer.toString("base64");
|
|
34710
34756
|
}
|
|
34711
34757
|
return {
|
|
@@ -35266,393 +35312,6 @@ var ErrorHandler = class extends EventEmitter {
|
|
|
35266
35312
|
};
|
|
35267
35313
|
var globalErrorHandler = new ErrorHandler();
|
|
35268
35314
|
|
|
35269
|
-
// src/core/context/ContextGuardian.ts
|
|
35270
|
-
init_Logger();
|
|
35271
|
-
var logger3 = logger.child({ component: "ContextGuardian" });
|
|
35272
|
-
var ContextGuardian = class {
|
|
35273
|
-
_enabled;
|
|
35274
|
-
_maxToolResultTokens;
|
|
35275
|
-
_minSystemPromptTokens;
|
|
35276
|
-
_configuredProtectedMessages;
|
|
35277
|
-
_maxContextTokens;
|
|
35278
|
-
_strategy;
|
|
35279
|
-
_estimator;
|
|
35280
|
-
constructor(estimator, config = {}) {
|
|
35281
|
-
this._estimator = estimator;
|
|
35282
|
-
this._enabled = config.enabled ?? GUARDIAN_DEFAULTS.ENABLED;
|
|
35283
|
-
this._maxToolResultTokens = config.maxToolResultTokens ?? GUARDIAN_DEFAULTS.MAX_TOOL_RESULT_TOKENS;
|
|
35284
|
-
this._minSystemPromptTokens = config.minSystemPromptTokens ?? GUARDIAN_DEFAULTS.MIN_SYSTEM_PROMPT_TOKENS;
|
|
35285
|
-
this._configuredProtectedMessages = config.protectedRecentMessages ?? GUARDIAN_DEFAULTS.PROTECTED_RECENT_MESSAGES;
|
|
35286
|
-
this._maxContextTokens = config.maxContextTokens;
|
|
35287
|
-
this._strategy = config.strategy ?? "proactive";
|
|
35288
|
-
}
|
|
35289
|
-
/**
|
|
35290
|
-
* Get effective protected message count, considering strategy and context size.
|
|
35291
|
-
* Uses percentage-based calculation if maxContextTokens is available.
|
|
35292
|
-
*
|
|
35293
|
-
* NOTE: If an explicit value was configured (not using default), it's honored
|
|
35294
|
-
* without applying minimum caps - this allows tests and special cases to work.
|
|
35295
|
-
*/
|
|
35296
|
-
get _protectedRecentMessages() {
|
|
35297
|
-
if (this._configuredProtectedMessages !== GUARDIAN_DEFAULTS.PROTECTED_RECENT_MESSAGES) {
|
|
35298
|
-
return this._configuredProtectedMessages;
|
|
35299
|
-
}
|
|
35300
|
-
if (this._maxContextTokens) {
|
|
35301
|
-
const thresholds = STRATEGY_THRESHOLDS[this._strategy];
|
|
35302
|
-
const percentBasedTokens = Math.floor(this._maxContextTokens * thresholds.protectedContextPercent);
|
|
35303
|
-
const percentBasedMessages = Math.floor(percentBasedTokens / 100);
|
|
35304
|
-
const calculated = Math.max(percentBasedMessages, this._configuredProtectedMessages);
|
|
35305
|
-
return Math.max(calculated, SAFETY_CAPS.MIN_PROTECTED_MESSAGES);
|
|
35306
|
-
}
|
|
35307
|
-
return Math.max(this._configuredProtectedMessages, SAFETY_CAPS.MIN_PROTECTED_MESSAGES);
|
|
35308
|
-
}
|
|
35309
|
-
/**
|
|
35310
|
-
* Check if guardian is enabled
|
|
35311
|
-
*/
|
|
35312
|
-
get enabled() {
|
|
35313
|
-
return this._enabled;
|
|
35314
|
-
}
|
|
35315
|
-
/**
|
|
35316
|
-
* Validate that input fits within token limits
|
|
35317
|
-
*
|
|
35318
|
-
* @param input - The InputItem[] to validate
|
|
35319
|
-
* @param maxTokens - Maximum allowed tokens (after reserving for response)
|
|
35320
|
-
* @returns Validation result with actual counts and breakdown
|
|
35321
|
-
*/
|
|
35322
|
-
validate(input, maxTokens) {
|
|
35323
|
-
const breakdown = {
|
|
35324
|
-
system: 0,
|
|
35325
|
-
user: 0,
|
|
35326
|
-
assistant: 0,
|
|
35327
|
-
tool_use: 0,
|
|
35328
|
-
tool_result: 0,
|
|
35329
|
-
other: 0
|
|
35330
|
-
};
|
|
35331
|
-
let actualTokens = 0;
|
|
35332
|
-
for (const item of input) {
|
|
35333
|
-
const tokens = this.estimateInputItemTokens(item);
|
|
35334
|
-
actualTokens += tokens;
|
|
35335
|
-
if (item.type === "message") {
|
|
35336
|
-
const msg = item;
|
|
35337
|
-
if (msg.role === "developer" /* DEVELOPER */) {
|
|
35338
|
-
breakdown.system += tokens;
|
|
35339
|
-
} else if (msg.role === "user" /* USER */) {
|
|
35340
|
-
const hasToolResult = msg.content.some((c) => c.type === "tool_result" /* TOOL_RESULT */);
|
|
35341
|
-
if (hasToolResult) {
|
|
35342
|
-
breakdown.tool_result += tokens;
|
|
35343
|
-
} else {
|
|
35344
|
-
breakdown.user += tokens;
|
|
35345
|
-
}
|
|
35346
|
-
} else if (msg.role === "assistant" /* ASSISTANT */) {
|
|
35347
|
-
const hasToolUse = msg.content.some((c) => c.type === "tool_use" /* TOOL_USE */);
|
|
35348
|
-
if (hasToolUse) {
|
|
35349
|
-
breakdown.tool_use += tokens;
|
|
35350
|
-
} else {
|
|
35351
|
-
breakdown.assistant += tokens;
|
|
35352
|
-
}
|
|
35353
|
-
}
|
|
35354
|
-
} else {
|
|
35355
|
-
breakdown.other += tokens;
|
|
35356
|
-
}
|
|
35357
|
-
}
|
|
35358
|
-
const valid = actualTokens <= maxTokens;
|
|
35359
|
-
const overageTokens = valid ? 0 : actualTokens - maxTokens;
|
|
35360
|
-
logger3.debug({
|
|
35361
|
-
actualTokens,
|
|
35362
|
-
maxTokens,
|
|
35363
|
-
valid,
|
|
35364
|
-
overageTokens,
|
|
35365
|
-
breakdown
|
|
35366
|
-
}, `Guardian validation: ${valid ? "PASS" : "FAIL"}`);
|
|
35367
|
-
return {
|
|
35368
|
-
valid,
|
|
35369
|
-
actualTokens,
|
|
35370
|
-
targetTokens: maxTokens,
|
|
35371
|
-
overageTokens,
|
|
35372
|
-
breakdown
|
|
35373
|
-
};
|
|
35374
|
-
}
|
|
35375
|
-
/**
|
|
35376
|
-
* Apply graceful degradation to reduce input size
|
|
35377
|
-
*
|
|
35378
|
-
* @param input - The InputItem[] to potentially modify
|
|
35379
|
-
* @param targetTokens - Target token count to achieve
|
|
35380
|
-
* @returns Degradation result with potentially modified input
|
|
35381
|
-
*/
|
|
35382
|
-
applyGracefulDegradation(input, targetTokens) {
|
|
35383
|
-
const log = [];
|
|
35384
|
-
let tokensFreed = 0;
|
|
35385
|
-
let currentInput = [...input];
|
|
35386
|
-
const initialValidation = this.validate(currentInput, targetTokens);
|
|
35387
|
-
if (initialValidation.valid) {
|
|
35388
|
-
return {
|
|
35389
|
-
input: currentInput,
|
|
35390
|
-
log: ["No degradation needed"],
|
|
35391
|
-
finalTokens: initialValidation.actualTokens,
|
|
35392
|
-
tokensFreed: 0,
|
|
35393
|
-
success: true
|
|
35394
|
-
};
|
|
35395
|
-
}
|
|
35396
|
-
log.push(`Starting graceful degradation: ${initialValidation.actualTokens} tokens, target: ${targetTokens}`);
|
|
35397
|
-
const level1Result = this.truncateToolResults(currentInput, log);
|
|
35398
|
-
currentInput = level1Result.input;
|
|
35399
|
-
tokensFreed += level1Result.tokensFreed;
|
|
35400
|
-
let validation = this.validate(currentInput, targetTokens);
|
|
35401
|
-
if (validation.valid) {
|
|
35402
|
-
log.push(`Level 1 (truncate tool results) successful: ${validation.actualTokens} tokens`);
|
|
35403
|
-
return {
|
|
35404
|
-
input: currentInput,
|
|
35405
|
-
log,
|
|
35406
|
-
finalTokens: validation.actualTokens,
|
|
35407
|
-
tokensFreed,
|
|
35408
|
-
success: true
|
|
35409
|
-
};
|
|
35410
|
-
}
|
|
35411
|
-
const level2Result = this.removeOldestToolPairs(currentInput, validation.overageTokens, log);
|
|
35412
|
-
currentInput = level2Result.input;
|
|
35413
|
-
tokensFreed += level2Result.tokensFreed;
|
|
35414
|
-
validation = this.validate(currentInput, targetTokens);
|
|
35415
|
-
if (validation.valid) {
|
|
35416
|
-
log.push(`Level 2 (remove tool pairs) successful: ${validation.actualTokens} tokens`);
|
|
35417
|
-
return {
|
|
35418
|
-
input: currentInput,
|
|
35419
|
-
log,
|
|
35420
|
-
finalTokens: validation.actualTokens,
|
|
35421
|
-
tokensFreed,
|
|
35422
|
-
success: true
|
|
35423
|
-
};
|
|
35424
|
-
}
|
|
35425
|
-
const level3Result = this.truncateSystemPrompt(currentInput, log);
|
|
35426
|
-
currentInput = level3Result.input;
|
|
35427
|
-
tokensFreed += level3Result.tokensFreed;
|
|
35428
|
-
validation = this.validate(currentInput, targetTokens);
|
|
35429
|
-
if (validation.valid) {
|
|
35430
|
-
log.push(`Level 3 (truncate system prompt) successful: ${validation.actualTokens} tokens`);
|
|
35431
|
-
return {
|
|
35432
|
-
input: currentInput,
|
|
35433
|
-
log,
|
|
35434
|
-
finalTokens: validation.actualTokens,
|
|
35435
|
-
tokensFreed,
|
|
35436
|
-
success: true
|
|
35437
|
-
};
|
|
35438
|
-
}
|
|
35439
|
-
log.push(`All degradation levels exhausted: ${validation.actualTokens} tokens (target: ${targetTokens})`);
|
|
35440
|
-
throw new ContextOverflowError(
|
|
35441
|
-
"All graceful degradation levels exhausted",
|
|
35442
|
-
{
|
|
35443
|
-
actualTokens: validation.actualTokens,
|
|
35444
|
-
maxTokens: targetTokens,
|
|
35445
|
-
overageTokens: validation.overageTokens,
|
|
35446
|
-
breakdown: validation.breakdown,
|
|
35447
|
-
degradationLog: log
|
|
35448
|
-
}
|
|
35449
|
-
);
|
|
35450
|
-
}
|
|
35451
|
-
/**
|
|
35452
|
-
* Emergency compact - more aggressive than graceful degradation
|
|
35453
|
-
* Used when even graceful degradation fails
|
|
35454
|
-
*
|
|
35455
|
-
* @param input - The InputItem[] to compact
|
|
35456
|
-
* @param targetTokens - Target token count
|
|
35457
|
-
* @returns Compacted InputItem[] (may lose significant data)
|
|
35458
|
-
*/
|
|
35459
|
-
emergencyCompact(input, targetTokens) {
|
|
35460
|
-
const log = ["EMERGENCY COMPACTION"];
|
|
35461
|
-
let result = [...input];
|
|
35462
|
-
const systemMessages = [];
|
|
35463
|
-
const otherMessages = [];
|
|
35464
|
-
for (const item of result) {
|
|
35465
|
-
if (item.type === "message" && item.role === "developer" /* DEVELOPER */) {
|
|
35466
|
-
systemMessages.push(item);
|
|
35467
|
-
} else {
|
|
35468
|
-
otherMessages.push(item);
|
|
35469
|
-
}
|
|
35470
|
-
}
|
|
35471
|
-
const truncatedSystem = systemMessages.map(
|
|
35472
|
-
(item) => this.truncateMessage(item, this._minSystemPromptTokens)
|
|
35473
|
-
);
|
|
35474
|
-
const protectedMessages = otherMessages.slice(-this._protectedRecentMessages);
|
|
35475
|
-
result = [...truncatedSystem, ...protectedMessages];
|
|
35476
|
-
const validation = this.validate(result, targetTokens);
|
|
35477
|
-
if (!validation.valid) {
|
|
35478
|
-
log.push(`Emergency compaction failed: still at ${validation.actualTokens} tokens`);
|
|
35479
|
-
logger3.error({ validation, log }, "Emergency compaction failed");
|
|
35480
|
-
}
|
|
35481
|
-
return result;
|
|
35482
|
-
}
|
|
35483
|
-
// ============================================================================
|
|
35484
|
-
// Private Helper Methods
|
|
35485
|
-
// ============================================================================
|
|
35486
|
-
/**
|
|
35487
|
-
* Estimate tokens for an InputItem
|
|
35488
|
-
*/
|
|
35489
|
-
estimateInputItemTokens(item) {
|
|
35490
|
-
if (item.type !== "message") {
|
|
35491
|
-
return 50;
|
|
35492
|
-
}
|
|
35493
|
-
const msg = item;
|
|
35494
|
-
let total = 4;
|
|
35495
|
-
for (const content of msg.content) {
|
|
35496
|
-
if (content.type === "input_text" /* INPUT_TEXT */ || content.type === "output_text" /* OUTPUT_TEXT */) {
|
|
35497
|
-
total += this._estimator.estimateTokens(content.text || "");
|
|
35498
|
-
} else if (content.type === "tool_use" /* TOOL_USE */) {
|
|
35499
|
-
total += this._estimator.estimateTokens(content.name || "");
|
|
35500
|
-
total += this._estimator.estimateDataTokens(content.input || {});
|
|
35501
|
-
} else if (content.type === "tool_result" /* TOOL_RESULT */) {
|
|
35502
|
-
total += this._estimator.estimateTokens(content.content || "");
|
|
35503
|
-
} else if (content.type === "input_image_url" /* INPUT_IMAGE_URL */) {
|
|
35504
|
-
total += 200;
|
|
35505
|
-
}
|
|
35506
|
-
}
|
|
35507
|
-
return total;
|
|
35508
|
-
}
|
|
35509
|
-
/**
|
|
35510
|
-
* Level 1: Truncate large tool results
|
|
35511
|
-
*/
|
|
35512
|
-
truncateToolResults(input, log) {
|
|
35513
|
-
let tokensFreed = 0;
|
|
35514
|
-
const result = [];
|
|
35515
|
-
for (const item of input) {
|
|
35516
|
-
if (item.type !== "message") {
|
|
35517
|
-
result.push(item);
|
|
35518
|
-
continue;
|
|
35519
|
-
}
|
|
35520
|
-
const msg = item;
|
|
35521
|
-
const hasToolResult = msg.content.some((c) => c.type === "tool_result" /* TOOL_RESULT */);
|
|
35522
|
-
if (!hasToolResult) {
|
|
35523
|
-
result.push(item);
|
|
35524
|
-
continue;
|
|
35525
|
-
}
|
|
35526
|
-
const newContent = msg.content.map((c) => {
|
|
35527
|
-
if (c.type !== "tool_result" /* TOOL_RESULT */) return c;
|
|
35528
|
-
const toolResult = c;
|
|
35529
|
-
const content = toolResult.content || "";
|
|
35530
|
-
const currentTokens = this._estimator.estimateTokens(content);
|
|
35531
|
-
if (currentTokens > this._maxToolResultTokens) {
|
|
35532
|
-
const targetChars = this._maxToolResultTokens * 4;
|
|
35533
|
-
const truncated = content.slice(0, targetChars) + GUARDIAN_DEFAULTS.TRUNCATION_SUFFIX;
|
|
35534
|
-
const freed = currentTokens - this._estimator.estimateTokens(truncated);
|
|
35535
|
-
tokensFreed += freed;
|
|
35536
|
-
log.push(`Truncated tool result ${toolResult.tool_use_id}: ${currentTokens} \u2192 ${currentTokens - freed} tokens`);
|
|
35537
|
-
return {
|
|
35538
|
-
...toolResult,
|
|
35539
|
-
content: truncated
|
|
35540
|
-
};
|
|
35541
|
-
}
|
|
35542
|
-
return c;
|
|
35543
|
-
});
|
|
35544
|
-
result.push({
|
|
35545
|
-
...msg,
|
|
35546
|
-
content: newContent
|
|
35547
|
-
});
|
|
35548
|
-
}
|
|
35549
|
-
if (tokensFreed > 0) {
|
|
35550
|
-
log.push(`Level 1: Truncated tool results, freed ${tokensFreed} tokens`);
|
|
35551
|
-
}
|
|
35552
|
-
return { input: result, tokensFreed };
|
|
35553
|
-
}
|
|
35554
|
-
/**
|
|
35555
|
-
* Level 2: Remove oldest unprotected tool pairs
|
|
35556
|
-
*/
|
|
35557
|
-
removeOldestToolPairs(input, overageTokens, log) {
|
|
35558
|
-
const toolPairs = /* @__PURE__ */ new Map();
|
|
35559
|
-
for (let i = 0; i < input.length; i++) {
|
|
35560
|
-
const item = input[i];
|
|
35561
|
-
if (item?.type !== "message") continue;
|
|
35562
|
-
const msg = item;
|
|
35563
|
-
for (const content of msg.content) {
|
|
35564
|
-
if (content.type === "tool_use" /* TOOL_USE */) {
|
|
35565
|
-
const toolUseId = content.id;
|
|
35566
|
-
if (toolUseId) {
|
|
35567
|
-
toolPairs.set(toolUseId, { useIndex: i, resultIndex: null });
|
|
35568
|
-
}
|
|
35569
|
-
} else if (content.type === "tool_result" /* TOOL_RESULT */) {
|
|
35570
|
-
const toolUseId = content.tool_use_id;
|
|
35571
|
-
const pair = toolPairs.get(toolUseId);
|
|
35572
|
-
if (pair) {
|
|
35573
|
-
pair.resultIndex = i;
|
|
35574
|
-
}
|
|
35575
|
-
}
|
|
35576
|
-
}
|
|
35577
|
-
}
|
|
35578
|
-
const sortedPairs = [...toolPairs.entries()].filter(([, pair]) => pair.resultIndex !== null).sort(([, a], [, b]) => a.useIndex - b.useIndex);
|
|
35579
|
-
const protectedStart = input.length - this._protectedRecentMessages;
|
|
35580
|
-
const indicesToRemove = /* @__PURE__ */ new Set();
|
|
35581
|
-
let tokensFreed = 0;
|
|
35582
|
-
for (const [toolUseId, pair] of sortedPairs) {
|
|
35583
|
-
if (tokensFreed >= overageTokens) break;
|
|
35584
|
-
if (pair.useIndex >= protectedStart || pair.resultIndex !== null && pair.resultIndex >= protectedStart) {
|
|
35585
|
-
continue;
|
|
35586
|
-
}
|
|
35587
|
-
indicesToRemove.add(pair.useIndex);
|
|
35588
|
-
if (pair.resultIndex !== null) {
|
|
35589
|
-
indicesToRemove.add(pair.resultIndex);
|
|
35590
|
-
}
|
|
35591
|
-
const useItem = input[pair.useIndex];
|
|
35592
|
-
const resultItem = pair.resultIndex !== null ? input[pair.resultIndex] : null;
|
|
35593
|
-
if (useItem) tokensFreed += this.estimateInputItemTokens(useItem);
|
|
35594
|
-
if (resultItem) tokensFreed += this.estimateInputItemTokens(resultItem);
|
|
35595
|
-
log.push(`Removing tool pair ${toolUseId}`);
|
|
35596
|
-
}
|
|
35597
|
-
const result = input.filter((_, i) => !indicesToRemove.has(i));
|
|
35598
|
-
if (indicesToRemove.size > 0) {
|
|
35599
|
-
log.push(`Level 2: Removed ${indicesToRemove.size} messages (${sortedPairs.length} tool pairs evaluated), freed ${tokensFreed} tokens`);
|
|
35600
|
-
}
|
|
35601
|
-
return { input: result, tokensFreed };
|
|
35602
|
-
}
|
|
35603
|
-
/**
|
|
35604
|
-
* Level 3: Truncate system prompt
|
|
35605
|
-
*/
|
|
35606
|
-
truncateSystemPrompt(input, log) {
|
|
35607
|
-
let tokensFreed = 0;
|
|
35608
|
-
const result = [];
|
|
35609
|
-
for (const item of input) {
|
|
35610
|
-
if (item.type !== "message") {
|
|
35611
|
-
result.push(item);
|
|
35612
|
-
continue;
|
|
35613
|
-
}
|
|
35614
|
-
const msg = item;
|
|
35615
|
-
if (msg.role !== "developer" /* DEVELOPER */) {
|
|
35616
|
-
result.push(item);
|
|
35617
|
-
continue;
|
|
35618
|
-
}
|
|
35619
|
-
const currentTokens = this.estimateInputItemTokens(msg);
|
|
35620
|
-
if (currentTokens > this._minSystemPromptTokens) {
|
|
35621
|
-
const truncated = this.truncateMessage(msg, this._minSystemPromptTokens);
|
|
35622
|
-
const newTokens = this.estimateInputItemTokens(truncated);
|
|
35623
|
-
tokensFreed += currentTokens - newTokens;
|
|
35624
|
-
log.push(`Truncated system prompt: ${currentTokens} \u2192 ${newTokens} tokens`);
|
|
35625
|
-
result.push(truncated);
|
|
35626
|
-
} else {
|
|
35627
|
-
result.push(item);
|
|
35628
|
-
}
|
|
35629
|
-
}
|
|
35630
|
-
if (tokensFreed > 0) {
|
|
35631
|
-
log.push(`Level 3: Truncated system prompt, freed ${tokensFreed} tokens`);
|
|
35632
|
-
}
|
|
35633
|
-
return { input: result, tokensFreed };
|
|
35634
|
-
}
|
|
35635
|
-
/**
|
|
35636
|
-
* Truncate a message to target token count
|
|
35637
|
-
*/
|
|
35638
|
-
truncateMessage(msg, targetTokens) {
|
|
35639
|
-
const newContent = msg.content.map((c) => {
|
|
35640
|
-
if (c.type !== "input_text" /* INPUT_TEXT */ && c.type !== "output_text" /* OUTPUT_TEXT */) {
|
|
35641
|
-
return c;
|
|
35642
|
-
}
|
|
35643
|
-
const text = c.text || "";
|
|
35644
|
-
const currentTokens = this._estimator.estimateTokens(text);
|
|
35645
|
-
if (currentTokens > targetTokens) {
|
|
35646
|
-
const targetChars = targetTokens * 4;
|
|
35647
|
-
const truncated = text.slice(0, targetChars) + GUARDIAN_DEFAULTS.TRUNCATION_SUFFIX;
|
|
35648
|
-
return { ...c, text: truncated };
|
|
35649
|
-
}
|
|
35650
|
-
return c;
|
|
35651
|
-
});
|
|
35652
|
-
return { ...msg, content: newContent };
|
|
35653
|
-
}
|
|
35654
|
-
};
|
|
35655
|
-
|
|
35656
35315
|
// src/capabilities/images/ImageGeneration.ts
|
|
35657
35316
|
init_Connector();
|
|
35658
35317
|
|
|
@@ -36703,8 +36362,8 @@ var OpenAISoraProvider = class extends BaseMediaProvider {
|
|
|
36703
36362
|
return new File([new Uint8Array(image)], "input.png", { type: "image/png" });
|
|
36704
36363
|
}
|
|
36705
36364
|
if (!image.startsWith("http")) {
|
|
36706
|
-
const
|
|
36707
|
-
const data =
|
|
36365
|
+
const fs18 = await import('fs');
|
|
36366
|
+
const data = fs18.readFileSync(image);
|
|
36708
36367
|
return new File([new Uint8Array(data)], "input.png", { type: "image/png" });
|
|
36709
36368
|
}
|
|
36710
36369
|
const response = await fetch(image);
|
|
@@ -36882,22 +36541,22 @@ var GoogleVeoProvider = class extends BaseMediaProvider {
|
|
|
36882
36541
|
if (video.videoBytes) {
|
|
36883
36542
|
buffer = Buffer.from(video.videoBytes, "base64");
|
|
36884
36543
|
} else if (video.uri) {
|
|
36885
|
-
const
|
|
36886
|
-
const
|
|
36887
|
-
const
|
|
36888
|
-
const tempDir =
|
|
36889
|
-
const tempFile =
|
|
36544
|
+
const fs18 = await import('fs/promises');
|
|
36545
|
+
const os3 = await import('os');
|
|
36546
|
+
const path6 = await import('path');
|
|
36547
|
+
const tempDir = os3.tmpdir();
|
|
36548
|
+
const tempFile = path6.join(tempDir, `veo-${Date.now()}.mp4`);
|
|
36890
36549
|
try {
|
|
36891
36550
|
await this.client.files.download({
|
|
36892
36551
|
file: { video },
|
|
36893
36552
|
// Pass as GeneratedVideo
|
|
36894
36553
|
downloadPath: tempFile
|
|
36895
36554
|
});
|
|
36896
|
-
buffer = await
|
|
36897
|
-
await
|
|
36555
|
+
buffer = await fs18.readFile(tempFile);
|
|
36556
|
+
await fs18.unlink(tempFile).catch(() => {
|
|
36898
36557
|
});
|
|
36899
36558
|
} catch (downloadError) {
|
|
36900
|
-
await
|
|
36559
|
+
await fs18.unlink(tempFile).catch(() => {
|
|
36901
36560
|
});
|
|
36902
36561
|
throw new ProviderError(
|
|
36903
36562
|
"google",
|
|
@@ -37019,8 +36678,8 @@ var GoogleVeoProvider = class extends BaseMediaProvider {
|
|
|
37019
36678
|
if (image.startsWith("http://") || image.startsWith("https://")) {
|
|
37020
36679
|
return { imageUri: image };
|
|
37021
36680
|
}
|
|
37022
|
-
const
|
|
37023
|
-
const data = await
|
|
36681
|
+
const fs18 = await import('fs/promises');
|
|
36682
|
+
const data = await fs18.readFile(image);
|
|
37024
36683
|
return {
|
|
37025
36684
|
imageBytes: data.toString("base64")
|
|
37026
36685
|
};
|
|
@@ -37327,8 +36986,8 @@ var GrokImagineProvider = class extends BaseMediaProvider {
|
|
|
37327
36986
|
if (image.startsWith("http") || image.startsWith("data:")) {
|
|
37328
36987
|
return image;
|
|
37329
36988
|
}
|
|
37330
|
-
const
|
|
37331
|
-
const data =
|
|
36989
|
+
const fs18 = await import('fs');
|
|
36990
|
+
const data = fs18.readFileSync(image);
|
|
37332
36991
|
const base64 = data.toString("base64");
|
|
37333
36992
|
const ext = image.split(".").pop()?.toLowerCase() || "png";
|
|
37334
36993
|
const mimeType = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : `image/${ext}`;
|
|
@@ -39715,10 +39374,10 @@ function detectDependencyCycle(tasks) {
|
|
|
39715
39374
|
const visited = /* @__PURE__ */ new Set();
|
|
39716
39375
|
const recStack = /* @__PURE__ */ new Set();
|
|
39717
39376
|
const taskMap = new Map(tasks.map((t) => [t.id, t]));
|
|
39718
|
-
function dfs(taskId,
|
|
39377
|
+
function dfs(taskId, path6) {
|
|
39719
39378
|
if (recStack.has(taskId)) {
|
|
39720
|
-
const cycleStart =
|
|
39721
|
-
return [...
|
|
39379
|
+
const cycleStart = path6.indexOf(taskId);
|
|
39380
|
+
return [...path6.slice(cycleStart), taskId];
|
|
39722
39381
|
}
|
|
39723
39382
|
if (visited.has(taskId)) {
|
|
39724
39383
|
return null;
|
|
@@ -39728,7 +39387,7 @@ function detectDependencyCycle(tasks) {
|
|
|
39728
39387
|
const task = taskMap.get(taskId);
|
|
39729
39388
|
if (task) {
|
|
39730
39389
|
for (const depId of task.dependsOn) {
|
|
39731
|
-
const cycle = dfs(depId, [...
|
|
39390
|
+
const cycle = dfs(depId, [...path6, taskId]);
|
|
39732
39391
|
if (cycle) {
|
|
39733
39392
|
return cycle;
|
|
39734
39393
|
}
|
|
@@ -40110,334 +39769,6 @@ var DEFAULT_CONTEXT_CONFIG = {
|
|
|
40110
39769
|
strategyOptions: {}
|
|
40111
39770
|
};
|
|
40112
39771
|
|
|
40113
|
-
// src/core/context/utils/ContextUtils.ts
|
|
40114
|
-
function estimateComponentTokens(component, estimator) {
|
|
40115
|
-
if (typeof component.content === "string") {
|
|
40116
|
-
return estimator.estimateTokens(component.content);
|
|
40117
|
-
}
|
|
40118
|
-
return estimator.estimateDataTokens(component.content);
|
|
40119
|
-
}
|
|
40120
|
-
function sortCompactableByPriority(components) {
|
|
40121
|
-
return components.filter((c) => c.compactable).sort((a, b) => b.priority - a.priority);
|
|
40122
|
-
}
|
|
40123
|
-
function findCompactorForComponent(component, compactors) {
|
|
40124
|
-
return compactors.find((c) => c.canCompact(component));
|
|
40125
|
-
}
|
|
40126
|
-
async function executeCompactionLoop(options) {
|
|
40127
|
-
const {
|
|
40128
|
-
components,
|
|
40129
|
-
tokensToFree,
|
|
40130
|
-
compactors,
|
|
40131
|
-
estimator,
|
|
40132
|
-
calculateTargetSize,
|
|
40133
|
-
maxRounds = 1,
|
|
40134
|
-
logPrefix = ""
|
|
40135
|
-
} = options;
|
|
40136
|
-
const log = [];
|
|
40137
|
-
let current = [...components];
|
|
40138
|
-
let freedTokens = 0;
|
|
40139
|
-
let round = 0;
|
|
40140
|
-
const sortedComponents = sortCompactableByPriority(current);
|
|
40141
|
-
while (freedTokens < tokensToFree && round < maxRounds) {
|
|
40142
|
-
round++;
|
|
40143
|
-
let roundFreed = 0;
|
|
40144
|
-
for (const component of sortedComponents) {
|
|
40145
|
-
if (freedTokens >= tokensToFree) break;
|
|
40146
|
-
const compactor = findCompactorForComponent(component, compactors);
|
|
40147
|
-
if (!compactor) continue;
|
|
40148
|
-
const beforeSize = estimateComponentTokens(component, estimator);
|
|
40149
|
-
const targetSize = calculateTargetSize(beforeSize, round);
|
|
40150
|
-
if (targetSize >= beforeSize) continue;
|
|
40151
|
-
const compacted = await compactor.compact(component, targetSize);
|
|
40152
|
-
const index = current.findIndex((c) => c.name === component.name);
|
|
40153
|
-
if (index !== -1) {
|
|
40154
|
-
current[index] = compacted;
|
|
40155
|
-
}
|
|
40156
|
-
const afterSize = estimateComponentTokens(compacted, estimator);
|
|
40157
|
-
const saved = beforeSize - afterSize;
|
|
40158
|
-
freedTokens += saved;
|
|
40159
|
-
roundFreed += saved;
|
|
40160
|
-
const prefix = logPrefix ? `${logPrefix}: ` : "";
|
|
40161
|
-
const roundInfo = maxRounds > 1 ? `Round ${round}: ` : "";
|
|
40162
|
-
log.push(
|
|
40163
|
-
`${prefix}${roundInfo}${compactor.name} compacted "${component.name}" by ${saved} tokens`
|
|
40164
|
-
);
|
|
40165
|
-
}
|
|
40166
|
-
if (roundFreed === 0) break;
|
|
40167
|
-
}
|
|
40168
|
-
return { components: current, log, tokensFreed: freedTokens };
|
|
40169
|
-
}
|
|
40170
|
-
|
|
40171
|
-
// src/core/context/strategies/BaseCompactionStrategy.ts
|
|
40172
|
-
var BaseCompactionStrategy = class {
|
|
40173
|
-
metrics = {
|
|
40174
|
-
compactionCount: 0,
|
|
40175
|
-
totalTokensFreed: 0,
|
|
40176
|
-
avgTokensFreedPerCompaction: 0
|
|
40177
|
-
};
|
|
40178
|
-
/**
|
|
40179
|
-
* Get the maximum number of compaction rounds.
|
|
40180
|
-
* Override in subclasses for multi-round strategies.
|
|
40181
|
-
*/
|
|
40182
|
-
getMaxRounds() {
|
|
40183
|
-
return 1;
|
|
40184
|
-
}
|
|
40185
|
-
/**
|
|
40186
|
-
* Get the log prefix for compaction messages.
|
|
40187
|
-
* Override to customize logging.
|
|
40188
|
-
*/
|
|
40189
|
-
getLogPrefix() {
|
|
40190
|
-
return this.name.charAt(0).toUpperCase() + this.name.slice(1);
|
|
40191
|
-
}
|
|
40192
|
-
/**
|
|
40193
|
-
* Compact components to fit within budget.
|
|
40194
|
-
* Uses the shared compaction loop with strategy-specific target calculation.
|
|
40195
|
-
*/
|
|
40196
|
-
async compact(components, budget, compactors, estimator) {
|
|
40197
|
-
const targetUsage = Math.floor(budget.total * this.getTargetUtilization());
|
|
40198
|
-
const tokensToFree = budget.used - targetUsage;
|
|
40199
|
-
const result = await executeCompactionLoop({
|
|
40200
|
-
components,
|
|
40201
|
-
tokensToFree,
|
|
40202
|
-
compactors,
|
|
40203
|
-
estimator,
|
|
40204
|
-
calculateTargetSize: this.calculateTargetSize.bind(this),
|
|
40205
|
-
maxRounds: this.getMaxRounds(),
|
|
40206
|
-
logPrefix: this.getLogPrefix()
|
|
40207
|
-
});
|
|
40208
|
-
this.updateMetrics(result.tokensFreed);
|
|
40209
|
-
return result;
|
|
40210
|
-
}
|
|
40211
|
-
/**
|
|
40212
|
-
* Update internal metrics after compaction
|
|
40213
|
-
*/
|
|
40214
|
-
updateMetrics(tokensFreed) {
|
|
40215
|
-
this.metrics.compactionCount++;
|
|
40216
|
-
this.metrics.totalTokensFreed += tokensFreed;
|
|
40217
|
-
this.metrics.avgTokensFreedPerCompaction = this.metrics.totalTokensFreed / this.metrics.compactionCount;
|
|
40218
|
-
}
|
|
40219
|
-
/**
|
|
40220
|
-
* Get strategy metrics
|
|
40221
|
-
*/
|
|
40222
|
-
getMetrics() {
|
|
40223
|
-
return { ...this.metrics };
|
|
40224
|
-
}
|
|
40225
|
-
/**
|
|
40226
|
-
* Reset metrics (useful for testing)
|
|
40227
|
-
*/
|
|
40228
|
-
resetMetrics() {
|
|
40229
|
-
this.metrics = {
|
|
40230
|
-
compactionCount: 0,
|
|
40231
|
-
totalTokensFreed: 0,
|
|
40232
|
-
avgTokensFreedPerCompaction: 0
|
|
40233
|
-
};
|
|
40234
|
-
}
|
|
40235
|
-
};
|
|
40236
|
-
|
|
40237
|
-
// src/core/context/strategies/ProactiveStrategy.ts
|
|
40238
|
-
var DEFAULT_OPTIONS = {
|
|
40239
|
-
targetUtilization: PROACTIVE_STRATEGY_DEFAULTS.TARGET_UTILIZATION,
|
|
40240
|
-
baseReductionFactor: PROACTIVE_STRATEGY_DEFAULTS.BASE_REDUCTION_FACTOR,
|
|
40241
|
-
reductionStep: PROACTIVE_STRATEGY_DEFAULTS.REDUCTION_STEP,
|
|
40242
|
-
maxRounds: PROACTIVE_STRATEGY_DEFAULTS.MAX_ROUNDS
|
|
40243
|
-
};
|
|
40244
|
-
var ProactiveCompactionStrategy = class extends BaseCompactionStrategy {
|
|
40245
|
-
name = "proactive";
|
|
40246
|
-
options;
|
|
40247
|
-
constructor(options = {}) {
|
|
40248
|
-
super();
|
|
40249
|
-
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
40250
|
-
}
|
|
40251
|
-
shouldCompact(budget, _config) {
|
|
40252
|
-
return budget.status === "warning" || budget.status === "critical";
|
|
40253
|
-
}
|
|
40254
|
-
calculateTargetSize(beforeSize, round) {
|
|
40255
|
-
const reductionFactor = this.options.baseReductionFactor - (round - 1) * this.options.reductionStep;
|
|
40256
|
-
return Math.floor(beforeSize * Math.max(reductionFactor, 0.1));
|
|
40257
|
-
}
|
|
40258
|
-
getTargetUtilization() {
|
|
40259
|
-
return this.options.targetUtilization;
|
|
40260
|
-
}
|
|
40261
|
-
getMaxRounds() {
|
|
40262
|
-
return this.options.maxRounds;
|
|
40263
|
-
}
|
|
40264
|
-
getLogPrefix() {
|
|
40265
|
-
return "Proactive";
|
|
40266
|
-
}
|
|
40267
|
-
};
|
|
40268
|
-
|
|
40269
|
-
// src/core/context/strategies/AggressiveStrategy.ts
|
|
40270
|
-
var DEFAULT_OPTIONS2 = {
|
|
40271
|
-
threshold: AGGRESSIVE_STRATEGY_DEFAULTS.THRESHOLD,
|
|
40272
|
-
targetUtilization: AGGRESSIVE_STRATEGY_DEFAULTS.TARGET_UTILIZATION,
|
|
40273
|
-
reductionFactor: AGGRESSIVE_STRATEGY_DEFAULTS.REDUCTION_FACTOR
|
|
40274
|
-
};
|
|
40275
|
-
var AggressiveCompactionStrategy = class extends BaseCompactionStrategy {
|
|
40276
|
-
name = "aggressive";
|
|
40277
|
-
options;
|
|
40278
|
-
constructor(options = {}) {
|
|
40279
|
-
super();
|
|
40280
|
-
this.options = { ...DEFAULT_OPTIONS2, ...options };
|
|
40281
|
-
}
|
|
40282
|
-
shouldCompact(budget, _config) {
|
|
40283
|
-
const utilizationRatio = (budget.used + budget.reserved) / budget.total;
|
|
40284
|
-
return utilizationRatio >= this.options.threshold;
|
|
40285
|
-
}
|
|
40286
|
-
calculateTargetSize(beforeSize, _round) {
|
|
40287
|
-
return Math.floor(beforeSize * this.options.reductionFactor);
|
|
40288
|
-
}
|
|
40289
|
-
getTargetUtilization() {
|
|
40290
|
-
return this.options.targetUtilization;
|
|
40291
|
-
}
|
|
40292
|
-
getLogPrefix() {
|
|
40293
|
-
return "Aggressive";
|
|
40294
|
-
}
|
|
40295
|
-
};
|
|
40296
|
-
|
|
40297
|
-
// src/core/context/strategies/LazyStrategy.ts
|
|
40298
|
-
var DEFAULT_OPTIONS3 = {
|
|
40299
|
-
targetUtilization: LAZY_STRATEGY_DEFAULTS.TARGET_UTILIZATION,
|
|
40300
|
-
reductionFactor: LAZY_STRATEGY_DEFAULTS.REDUCTION_FACTOR
|
|
40301
|
-
};
|
|
40302
|
-
var LazyCompactionStrategy = class extends BaseCompactionStrategy {
|
|
40303
|
-
name = "lazy";
|
|
40304
|
-
options;
|
|
40305
|
-
constructor(options = {}) {
|
|
40306
|
-
super();
|
|
40307
|
-
this.options = { ...DEFAULT_OPTIONS3, ...options };
|
|
40308
|
-
}
|
|
40309
|
-
shouldCompact(budget, _config) {
|
|
40310
|
-
return budget.status === "critical";
|
|
40311
|
-
}
|
|
40312
|
-
calculateTargetSize(beforeSize, _round) {
|
|
40313
|
-
return Math.floor(beforeSize * this.options.reductionFactor);
|
|
40314
|
-
}
|
|
40315
|
-
getTargetUtilization() {
|
|
40316
|
-
return this.options.targetUtilization;
|
|
40317
|
-
}
|
|
40318
|
-
getLogPrefix() {
|
|
40319
|
-
return "Lazy";
|
|
40320
|
-
}
|
|
40321
|
-
};
|
|
40322
|
-
|
|
40323
|
-
// src/core/context/strategies/RollingWindowStrategy.ts
|
|
40324
|
-
var RollingWindowStrategy = class {
|
|
40325
|
-
constructor(options = {}) {
|
|
40326
|
-
this.options = options;
|
|
40327
|
-
}
|
|
40328
|
-
name = "rolling-window";
|
|
40329
|
-
shouldCompact(_budget, _config) {
|
|
40330
|
-
return false;
|
|
40331
|
-
}
|
|
40332
|
-
async prepareComponents(components) {
|
|
40333
|
-
return components.map((component) => {
|
|
40334
|
-
if (Array.isArray(component.content)) {
|
|
40335
|
-
const maxMessages = this.options.maxMessages ?? ROLLING_WINDOW_DEFAULTS.MAX_MESSAGES;
|
|
40336
|
-
if (component.content.length > maxMessages) {
|
|
40337
|
-
return {
|
|
40338
|
-
...component,
|
|
40339
|
-
content: component.content.slice(-maxMessages),
|
|
40340
|
-
metadata: {
|
|
40341
|
-
...component.metadata,
|
|
40342
|
-
windowed: true,
|
|
40343
|
-
originalLength: component.content.length,
|
|
40344
|
-
keptLength: maxMessages
|
|
40345
|
-
}
|
|
40346
|
-
};
|
|
40347
|
-
}
|
|
40348
|
-
}
|
|
40349
|
-
return component;
|
|
40350
|
-
});
|
|
40351
|
-
}
|
|
40352
|
-
async compact() {
|
|
40353
|
-
return { components: [], log: [], tokensFreed: 0 };
|
|
40354
|
-
}
|
|
40355
|
-
};
|
|
40356
|
-
|
|
40357
|
-
// src/core/context/strategies/AdaptiveStrategy.ts
|
|
40358
|
-
var AdaptiveStrategy = class {
|
|
40359
|
-
constructor(options = {}) {
|
|
40360
|
-
this.options = options;
|
|
40361
|
-
this.currentStrategy = new ProactiveCompactionStrategy();
|
|
40362
|
-
}
|
|
40363
|
-
name = "adaptive";
|
|
40364
|
-
currentStrategy;
|
|
40365
|
-
metrics = {
|
|
40366
|
-
avgUtilization: 0,
|
|
40367
|
-
compactionFrequency: 0,
|
|
40368
|
-
lastCompactions: []
|
|
40369
|
-
};
|
|
40370
|
-
shouldCompact(budget, config) {
|
|
40371
|
-
this.updateMetrics(budget);
|
|
40372
|
-
this.maybeAdapt();
|
|
40373
|
-
return this.currentStrategy.shouldCompact(budget, config);
|
|
40374
|
-
}
|
|
40375
|
-
async compact(components, budget, compactors, estimator) {
|
|
40376
|
-
const result = await this.currentStrategy.compact(components, budget, compactors, estimator);
|
|
40377
|
-
this.metrics.lastCompactions.push(Date.now());
|
|
40378
|
-
const window = this.options.learningWindow ?? ADAPTIVE_STRATEGY_DEFAULTS.LEARNING_WINDOW;
|
|
40379
|
-
if (this.metrics.lastCompactions.length > window) {
|
|
40380
|
-
this.metrics.lastCompactions.shift();
|
|
40381
|
-
}
|
|
40382
|
-
return {
|
|
40383
|
-
...result,
|
|
40384
|
-
log: [`[Adaptive: using ${this.currentStrategy.name}]`, ...result.log]
|
|
40385
|
-
};
|
|
40386
|
-
}
|
|
40387
|
-
updateMetrics(budget) {
|
|
40388
|
-
const alpha = 0.1;
|
|
40389
|
-
this.metrics.avgUtilization = alpha * budget.utilizationPercent + (1 - alpha) * this.metrics.avgUtilization;
|
|
40390
|
-
}
|
|
40391
|
-
maybeAdapt() {
|
|
40392
|
-
const now = Date.now();
|
|
40393
|
-
if (this.metrics.lastCompactions.length >= 2) {
|
|
40394
|
-
const firstCompaction = this.metrics.lastCompactions[0];
|
|
40395
|
-
if (firstCompaction !== void 0) {
|
|
40396
|
-
const timeSpan = now - firstCompaction;
|
|
40397
|
-
this.metrics.compactionFrequency = this.metrics.lastCompactions.length / timeSpan * 6e4;
|
|
40398
|
-
}
|
|
40399
|
-
}
|
|
40400
|
-
const threshold = this.options.switchThreshold ?? ADAPTIVE_STRATEGY_DEFAULTS.SWITCH_THRESHOLD;
|
|
40401
|
-
if (this.metrics.compactionFrequency > threshold) {
|
|
40402
|
-
if (this.currentStrategy.name !== "aggressive") {
|
|
40403
|
-
this.currentStrategy = new AggressiveCompactionStrategy();
|
|
40404
|
-
}
|
|
40405
|
-
} else if (this.metrics.compactionFrequency < ADAPTIVE_STRATEGY_DEFAULTS.LOW_FREQUENCY_THRESHOLD && this.metrics.avgUtilization < ADAPTIVE_STRATEGY_DEFAULTS.LOW_UTILIZATION_THRESHOLD) {
|
|
40406
|
-
if (this.currentStrategy.name !== "lazy") {
|
|
40407
|
-
this.currentStrategy = new LazyCompactionStrategy();
|
|
40408
|
-
}
|
|
40409
|
-
} else {
|
|
40410
|
-
if (this.currentStrategy.name !== "proactive") {
|
|
40411
|
-
this.currentStrategy = new ProactiveCompactionStrategy();
|
|
40412
|
-
}
|
|
40413
|
-
}
|
|
40414
|
-
}
|
|
40415
|
-
getMetrics() {
|
|
40416
|
-
return {
|
|
40417
|
-
...this.metrics,
|
|
40418
|
-
currentStrategy: this.currentStrategy.name
|
|
40419
|
-
};
|
|
40420
|
-
}
|
|
40421
|
-
};
|
|
40422
|
-
|
|
40423
|
-
// src/core/context/strategies/index.ts
|
|
40424
|
-
function createStrategy(name, options = {}) {
|
|
40425
|
-
switch (name) {
|
|
40426
|
-
case "proactive":
|
|
40427
|
-
return new ProactiveCompactionStrategy(options);
|
|
40428
|
-
case "aggressive":
|
|
40429
|
-
return new AggressiveCompactionStrategy(options);
|
|
40430
|
-
case "lazy":
|
|
40431
|
-
return new LazyCompactionStrategy(options);
|
|
40432
|
-
case "rolling-window":
|
|
40433
|
-
return new RollingWindowStrategy(options);
|
|
40434
|
-
case "adaptive":
|
|
40435
|
-
return new AdaptiveStrategy(options);
|
|
40436
|
-
default:
|
|
40437
|
-
throw new Error(`Unknown context strategy: ${name}`);
|
|
40438
|
-
}
|
|
40439
|
-
}
|
|
40440
|
-
|
|
40441
39772
|
// src/infrastructure/context/compactors/TruncateCompactor.ts
|
|
40442
39773
|
var TruncateCompactor = class {
|
|
40443
39774
|
constructor(estimator) {
|
|
@@ -42059,6 +41390,7 @@ init_Connector();
|
|
|
42059
41390
|
|
|
42060
41391
|
// src/tools/connector/ConnectorTools.ts
|
|
42061
41392
|
init_Connector();
|
|
41393
|
+
init_Logger();
|
|
42062
41394
|
var PROTECTED_HEADERS = ["authorization", "x-api-key", "api-key", "bearer"];
|
|
42063
41395
|
function safeStringify2(obj) {
|
|
42064
41396
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
@@ -42125,6 +41457,7 @@ var ConnectorTools = class {
|
|
|
42125
41457
|
*/
|
|
42126
41458
|
static registerService(serviceType, factory) {
|
|
42127
41459
|
this.factories.set(serviceType, factory);
|
|
41460
|
+
logger.debug(`[ConnectorTools.registerService] Registered factory for: ${serviceType} (total factories: ${this.factories.size})`);
|
|
42128
41461
|
}
|
|
42129
41462
|
/**
|
|
42130
41463
|
* Unregister a service tool factory
|
|
@@ -42146,8 +41479,8 @@ var ConnectorTools = class {
|
|
|
42146
41479
|
* // Returns: [slack_api, slack_send_message, slack_list_channels, ...]
|
|
42147
41480
|
* ```
|
|
42148
41481
|
*/
|
|
42149
|
-
static for(connectorOrName, userId) {
|
|
42150
|
-
const connector = this.resolveConnector(connectorOrName);
|
|
41482
|
+
static for(connectorOrName, userId, options) {
|
|
41483
|
+
const connector = this.resolveConnector(connectorOrName, options?.registry);
|
|
42151
41484
|
const tools = [];
|
|
42152
41485
|
if (connector.baseURL) {
|
|
42153
41486
|
tools.push(this.createGenericAPITool(connector, { userId }));
|
|
@@ -42155,7 +41488,11 @@ var ConnectorTools = class {
|
|
|
42155
41488
|
const serviceType = this.detectService(connector);
|
|
42156
41489
|
if (serviceType && this.factories.has(serviceType)) {
|
|
42157
41490
|
const factory = this.factories.get(serviceType);
|
|
42158
|
-
|
|
41491
|
+
const serviceTools = factory(connector, userId);
|
|
41492
|
+
for (const tool of serviceTools) {
|
|
41493
|
+
tool.definition.function.name = `${connector.name}_${tool.definition.function.name}`;
|
|
41494
|
+
}
|
|
41495
|
+
tools.push(...serviceTools);
|
|
42159
41496
|
}
|
|
42160
41497
|
return tools;
|
|
42161
41498
|
}
|
|
@@ -42205,18 +41542,29 @@ var ConnectorTools = class {
|
|
|
42205
41542
|
* }
|
|
42206
41543
|
* ```
|
|
42207
41544
|
*/
|
|
42208
|
-
static discoverAll(userId) {
|
|
41545
|
+
static discoverAll(userId, options) {
|
|
42209
41546
|
const result = /* @__PURE__ */ new Map();
|
|
42210
|
-
|
|
41547
|
+
const allConnectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
41548
|
+
const factoryKeys = Array.from(this.factories.keys());
|
|
41549
|
+
logger.debug(`[ConnectorTools.discoverAll] ${allConnectors.length} connectors in library, ${factoryKeys.length} factories registered: [${factoryKeys.join(", ")}]`);
|
|
41550
|
+
for (const connector of allConnectors) {
|
|
42211
41551
|
const hasServiceType = !!connector.config.serviceType;
|
|
42212
41552
|
const isExternalAPI = connector.baseURL && !connector.vendor;
|
|
42213
|
-
|
|
42214
|
-
|
|
42215
|
-
|
|
42216
|
-
|
|
41553
|
+
const hasVendorFactory = !!connector.vendor && this.factories.has(connector.vendor);
|
|
41554
|
+
logger.debug(`[ConnectorTools.discoverAll] connector=${connector.name}: vendor=${connector.vendor}, serviceType=${connector.config.serviceType}, baseURL=${connector.baseURL ? "yes" : "no"} \u2192 hasServiceType=${hasServiceType}, isExternalAPI=${isExternalAPI}, hasVendorFactory=${hasVendorFactory}`);
|
|
41555
|
+
if (hasServiceType || isExternalAPI || hasVendorFactory) {
|
|
41556
|
+
try {
|
|
41557
|
+
const tools = this.for(connector, userId);
|
|
41558
|
+
logger.debug(`[ConnectorTools.discoverAll] \u2192 ${tools.length} tools: [${tools.map((t) => t.definition.function.name).join(", ")}]`);
|
|
41559
|
+
if (tools.length > 0) {
|
|
41560
|
+
result.set(connector.name, tools);
|
|
41561
|
+
}
|
|
41562
|
+
} catch (err) {
|
|
41563
|
+
logger.error(`[ConnectorTools.discoverAll] \u2192 ERROR generating tools for ${connector.name}: ${err instanceof Error ? err.message : String(err)}`);
|
|
42217
41564
|
}
|
|
42218
41565
|
}
|
|
42219
41566
|
}
|
|
41567
|
+
logger.debug(`[ConnectorTools.discoverAll] Result: ${result.size} connectors with tools`);
|
|
42220
41568
|
return result;
|
|
42221
41569
|
}
|
|
42222
41570
|
/**
|
|
@@ -42226,8 +41574,9 @@ var ConnectorTools = class {
|
|
|
42226
41574
|
* @param serviceType - Service identifier
|
|
42227
41575
|
* @returns Connector or undefined
|
|
42228
41576
|
*/
|
|
42229
|
-
static findConnector(serviceType) {
|
|
42230
|
-
|
|
41577
|
+
static findConnector(serviceType, options) {
|
|
41578
|
+
const connectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
41579
|
+
return connectors.find((c) => this.detectService(c) === serviceType);
|
|
42231
41580
|
}
|
|
42232
41581
|
/**
|
|
42233
41582
|
* Find all connectors for a service type
|
|
@@ -42236,8 +41585,9 @@ var ConnectorTools = class {
|
|
|
42236
41585
|
* @param serviceType - Service identifier
|
|
42237
41586
|
* @returns Array of matching connectors
|
|
42238
41587
|
*/
|
|
42239
|
-
static findConnectors(serviceType) {
|
|
42240
|
-
|
|
41588
|
+
static findConnectors(serviceType, options) {
|
|
41589
|
+
const connectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
41590
|
+
return connectors.filter((c) => this.detectService(c) === serviceType);
|
|
42241
41591
|
}
|
|
42242
41592
|
/**
|
|
42243
41593
|
* List services that have registered tool factories
|
|
@@ -42267,6 +41617,9 @@ var ConnectorTools = class {
|
|
|
42267
41617
|
} else if (connector.baseURL) {
|
|
42268
41618
|
result = detectServiceFromURL(connector.baseURL);
|
|
42269
41619
|
}
|
|
41620
|
+
if (!result && connector.vendor) {
|
|
41621
|
+
result = connector.vendor;
|
|
41622
|
+
}
|
|
42270
41623
|
this.maintainCacheSize(this.serviceTypeCache);
|
|
42271
41624
|
this.serviceTypeCache.set(cacheKey, result);
|
|
42272
41625
|
return result;
|
|
@@ -42284,8 +41637,11 @@ var ConnectorTools = class {
|
|
|
42284
41637
|
}
|
|
42285
41638
|
}
|
|
42286
41639
|
// ============ Private Methods ============
|
|
42287
|
-
static resolveConnector(connectorOrName) {
|
|
42288
|
-
|
|
41640
|
+
static resolveConnector(connectorOrName, registry) {
|
|
41641
|
+
if (typeof connectorOrName === "string") {
|
|
41642
|
+
return registry ? registry.get(connectorOrName) : Connector.get(connectorOrName);
|
|
41643
|
+
}
|
|
41644
|
+
return connectorOrName;
|
|
42289
41645
|
}
|
|
42290
41646
|
static createGenericAPITool(connector, options) {
|
|
42291
41647
|
const toolName = options?.toolName ?? `${connector.name}_api`;
|
|
@@ -43025,7 +42381,7 @@ function initVendorRegistry(templates) {
|
|
|
43025
42381
|
function getVendorTemplate(vendorId) {
|
|
43026
42382
|
if (!vendorRegistry) {
|
|
43027
42383
|
throw new Error(
|
|
43028
|
-
"Vendor registry not initialized. Make sure to import from @oneringai
|
|
42384
|
+
"Vendor registry not initialized. Make sure to import from @everworker/oneringai which auto-registers templates."
|
|
43029
42385
|
);
|
|
43030
42386
|
}
|
|
43031
42387
|
return vendorRegistry.get(vendorId);
|
|
@@ -43033,7 +42389,7 @@ function getVendorTemplate(vendorId) {
|
|
|
43033
42389
|
function getAllVendorTemplates() {
|
|
43034
42390
|
if (!vendorRegistry) {
|
|
43035
42391
|
throw new Error(
|
|
43036
|
-
"Vendor registry not initialized. Make sure to import from @oneringai
|
|
42392
|
+
"Vendor registry not initialized. Make sure to import from @everworker/oneringai which auto-registers templates."
|
|
43037
42393
|
);
|
|
43038
42394
|
}
|
|
43039
42395
|
return Array.from(vendorRegistry.values());
|
|
@@ -43046,7 +42402,7 @@ function getVendorAuthTemplate(vendorId, authId) {
|
|
|
43046
42402
|
function listVendorIds() {
|
|
43047
42403
|
if (!vendorRegistry) {
|
|
43048
42404
|
throw new Error(
|
|
43049
|
-
"Vendor registry not initialized. Make sure to import from @oneringai
|
|
42405
|
+
"Vendor registry not initialized. Make sure to import from @everworker/oneringai which auto-registers templates."
|
|
43050
42406
|
);
|
|
43051
42407
|
}
|
|
43052
42408
|
return Array.from(vendorRegistry.keys());
|
|
@@ -45531,6 +44887,7 @@ __export(tools_exports, {
|
|
|
45531
44887
|
ConnectorTools: () => ConnectorTools,
|
|
45532
44888
|
DEFAULT_FILESYSTEM_CONFIG: () => DEFAULT_FILESYSTEM_CONFIG,
|
|
45533
44889
|
DEFAULT_SHELL_CONFIG: () => DEFAULT_SHELL_CONFIG,
|
|
44890
|
+
FileMediaOutputHandler: () => FileMediaOutputHandler,
|
|
45534
44891
|
ToolRegistry: () => ToolRegistry,
|
|
45535
44892
|
bash: () => bash,
|
|
45536
44893
|
createBashTool: () => createBashTool,
|
|
@@ -45538,8 +44895,12 @@ __export(tools_exports, {
|
|
|
45538
44895
|
createExecuteJavaScriptTool: () => createExecuteJavaScriptTool,
|
|
45539
44896
|
createGlobTool: () => createGlobTool,
|
|
45540
44897
|
createGrepTool: () => createGrepTool,
|
|
44898
|
+
createImageGenerationTool: () => createImageGenerationTool,
|
|
45541
44899
|
createListDirectoryTool: () => createListDirectoryTool,
|
|
45542
44900
|
createReadFileTool: () => createReadFileTool,
|
|
44901
|
+
createSpeechToTextTool: () => createSpeechToTextTool,
|
|
44902
|
+
createTextToSpeechTool: () => createTextToSpeechTool,
|
|
44903
|
+
createVideoTools: () => createVideoTools,
|
|
45543
44904
|
createWriteFileTool: () => createWriteFileTool,
|
|
45544
44905
|
developerTools: () => developerTools,
|
|
45545
44906
|
editFile: () => editFile,
|
|
@@ -45547,6 +44908,7 @@ __export(tools_exports, {
|
|
|
45547
44908
|
expandTilde: () => expandTilde,
|
|
45548
44909
|
getAllBuiltInTools: () => getAllBuiltInTools,
|
|
45549
44910
|
getBackgroundOutput: () => getBackgroundOutput,
|
|
44911
|
+
getMediaOutputHandler: () => getMediaOutputHandler,
|
|
45550
44912
|
getToolByName: () => getToolByName,
|
|
45551
44913
|
getToolCategories: () => getToolCategories,
|
|
45552
44914
|
getToolRegistry: () => getToolRegistry,
|
|
@@ -45560,6 +44922,7 @@ __export(tools_exports, {
|
|
|
45560
44922
|
killBackgroundProcess: () => killBackgroundProcess,
|
|
45561
44923
|
listDirectory: () => listDirectory,
|
|
45562
44924
|
readFile: () => readFile4,
|
|
44925
|
+
setMediaOutputHandler: () => setMediaOutputHandler,
|
|
45563
44926
|
toolRegistry: () => toolRegistry,
|
|
45564
44927
|
validatePath: () => validatePath,
|
|
45565
44928
|
webFetch: () => webFetch,
|
|
@@ -46177,8 +45540,8 @@ WHEN TO USE:
|
|
|
46177
45540
|
return args.pattern;
|
|
46178
45541
|
},
|
|
46179
45542
|
execute: async (args) => {
|
|
46180
|
-
const { pattern, path:
|
|
46181
|
-
const searchDir =
|
|
45543
|
+
const { pattern, path: path6 } = args;
|
|
45544
|
+
const searchDir = path6 || mergedConfig.workingDirectory;
|
|
46182
45545
|
const validation = validatePath(searchDir, {
|
|
46183
45546
|
...mergedConfig,
|
|
46184
45547
|
blockedDirectories: []
|
|
@@ -46398,7 +45761,7 @@ WHEN TO USE:
|
|
|
46398
45761
|
execute: async (args) => {
|
|
46399
45762
|
const {
|
|
46400
45763
|
pattern,
|
|
46401
|
-
path:
|
|
45764
|
+
path: path6,
|
|
46402
45765
|
glob: globPattern,
|
|
46403
45766
|
type: fileType,
|
|
46404
45767
|
output_mode = "files_with_matches",
|
|
@@ -46407,7 +45770,7 @@ WHEN TO USE:
|
|
|
46407
45770
|
context_after = 0,
|
|
46408
45771
|
limit
|
|
46409
45772
|
} = args;
|
|
46410
|
-
const searchPath =
|
|
45773
|
+
const searchPath = path6 || mergedConfig.workingDirectory;
|
|
46411
45774
|
const validation = validatePath(searchPath, {
|
|
46412
45775
|
...mergedConfig,
|
|
46413
45776
|
blockedDirectories: []
|
|
@@ -46625,8 +45988,8 @@ EXAMPLES:
|
|
|
46625
45988
|
return args.path;
|
|
46626
45989
|
},
|
|
46627
45990
|
execute: async (args) => {
|
|
46628
|
-
const { path:
|
|
46629
|
-
const validation = validatePath(
|
|
45991
|
+
const { path: path6, recursive = false, filter, max_depth = 3 } = args;
|
|
45992
|
+
const validation = validatePath(path6, {
|
|
46630
45993
|
...mergedConfig,
|
|
46631
45994
|
blockedDirectories: []
|
|
46632
45995
|
// Allow listing any valid directory
|
|
@@ -46641,7 +46004,7 @@ EXAMPLES:
|
|
|
46641
46004
|
if (!existsSync(resolvedPath)) {
|
|
46642
46005
|
return {
|
|
46643
46006
|
success: false,
|
|
46644
|
-
error: `Directory not found: ${
|
|
46007
|
+
error: `Directory not found: ${path6}`
|
|
46645
46008
|
};
|
|
46646
46009
|
}
|
|
46647
46010
|
try {
|
|
@@ -46649,7 +46012,7 @@ EXAMPLES:
|
|
|
46649
46012
|
if (!stats.isDirectory()) {
|
|
46650
46013
|
return {
|
|
46651
46014
|
success: false,
|
|
46652
|
-
error: `Path is not a directory: ${
|
|
46015
|
+
error: `Path is not a directory: ${path6}. Use read_file to read file contents.`
|
|
46653
46016
|
};
|
|
46654
46017
|
}
|
|
46655
46018
|
const entries = await listDir(
|
|
@@ -46951,19 +46314,19 @@ function killBackgroundProcess(bgId) {
|
|
|
46951
46314
|
var bash = createBashTool();
|
|
46952
46315
|
|
|
46953
46316
|
// src/tools/json/pathUtils.ts
|
|
46954
|
-
function parsePath(
|
|
46955
|
-
if (
|
|
46317
|
+
function parsePath(path6) {
|
|
46318
|
+
if (path6 === "" || path6 === "$") {
|
|
46956
46319
|
return [];
|
|
46957
46320
|
}
|
|
46958
|
-
const keys =
|
|
46321
|
+
const keys = path6.split(".");
|
|
46959
46322
|
const filtered = keys.filter((p) => p.length > 0);
|
|
46960
46323
|
if (filtered.length !== keys.length) {
|
|
46961
|
-
throw new Error(`Invalid path format: ${
|
|
46324
|
+
throw new Error(`Invalid path format: ${path6} (consecutive dots not allowed)`);
|
|
46962
46325
|
}
|
|
46963
46326
|
return filtered;
|
|
46964
46327
|
}
|
|
46965
|
-
function getValueAtPath(obj,
|
|
46966
|
-
const keys = parsePath(
|
|
46328
|
+
function getValueAtPath(obj, path6) {
|
|
46329
|
+
const keys = parsePath(path6);
|
|
46967
46330
|
let current = obj;
|
|
46968
46331
|
for (const key of keys) {
|
|
46969
46332
|
if (current === null || current === void 0) {
|
|
@@ -46973,8 +46336,8 @@ function getValueAtPath(obj, path5) {
|
|
|
46973
46336
|
}
|
|
46974
46337
|
return current;
|
|
46975
46338
|
}
|
|
46976
|
-
function setValueAtPath(obj,
|
|
46977
|
-
const keys = parsePath(
|
|
46339
|
+
function setValueAtPath(obj, path6, value) {
|
|
46340
|
+
const keys = parsePath(path6);
|
|
46978
46341
|
if (keys.length === 0) {
|
|
46979
46342
|
throw new Error("Cannot set root object - path must not be empty");
|
|
46980
46343
|
}
|
|
@@ -47003,8 +46366,8 @@ function setValueAtPath(obj, path5, value) {
|
|
|
47003
46366
|
}
|
|
47004
46367
|
return true;
|
|
47005
46368
|
}
|
|
47006
|
-
function deleteAtPath(obj,
|
|
47007
|
-
const keys = parsePath(
|
|
46369
|
+
function deleteAtPath(obj, path6) {
|
|
46370
|
+
const keys = parsePath(path6);
|
|
47008
46371
|
if (keys.length === 0) {
|
|
47009
46372
|
throw new Error("Cannot delete root object - path must not be empty");
|
|
47010
46373
|
}
|
|
@@ -47034,9 +46397,9 @@ function deleteAtPath(obj, path5) {
|
|
|
47034
46397
|
}
|
|
47035
46398
|
return true;
|
|
47036
46399
|
}
|
|
47037
|
-
function pathExists(obj,
|
|
46400
|
+
function pathExists(obj, path6) {
|
|
47038
46401
|
try {
|
|
47039
|
-
const value = getValueAtPath(obj,
|
|
46402
|
+
const value = getValueAtPath(obj, path6);
|
|
47040
46403
|
return value !== void 0;
|
|
47041
46404
|
} catch {
|
|
47042
46405
|
return false;
|
|
@@ -48481,6 +47844,591 @@ async function executeInVM(code, input, timeout, logs) {
|
|
|
48481
47844
|
const result = await resultPromise;
|
|
48482
47845
|
return result !== void 0 ? result : sandbox.output;
|
|
48483
47846
|
}
|
|
47847
|
+
var MIME_TYPES = {
|
|
47848
|
+
png: "image/png",
|
|
47849
|
+
jpeg: "image/jpeg",
|
|
47850
|
+
jpg: "image/jpeg",
|
|
47851
|
+
webp: "image/webp",
|
|
47852
|
+
gif: "image/gif",
|
|
47853
|
+
mp4: "video/mp4",
|
|
47854
|
+
webm: "video/webm",
|
|
47855
|
+
mp3: "audio/mpeg",
|
|
47856
|
+
wav: "audio/wav",
|
|
47857
|
+
opus: "audio/opus",
|
|
47858
|
+
ogg: "audio/ogg",
|
|
47859
|
+
aac: "audio/aac",
|
|
47860
|
+
flac: "audio/flac",
|
|
47861
|
+
pcm: "audio/pcm"
|
|
47862
|
+
};
|
|
47863
|
+
var FileMediaOutputHandler = class {
|
|
47864
|
+
outputDir;
|
|
47865
|
+
initialized = false;
|
|
47866
|
+
constructor(outputDir) {
|
|
47867
|
+
this.outputDir = outputDir ?? path3.join(os.tmpdir(), "oneringai-media");
|
|
47868
|
+
}
|
|
47869
|
+
async save(data, metadata) {
|
|
47870
|
+
if (!this.initialized) {
|
|
47871
|
+
await fs14.mkdir(this.outputDir, { recursive: true });
|
|
47872
|
+
this.initialized = true;
|
|
47873
|
+
}
|
|
47874
|
+
const filename = metadata.suggestedFilename ?? this.generateFilename(metadata);
|
|
47875
|
+
const filePath = path3.join(this.outputDir, filename);
|
|
47876
|
+
await fs14.writeFile(filePath, data);
|
|
47877
|
+
const format = metadata.format.toLowerCase();
|
|
47878
|
+
const mimeType = MIME_TYPES[format] ?? `application/octet-stream`;
|
|
47879
|
+
return {
|
|
47880
|
+
location: filePath,
|
|
47881
|
+
mimeType,
|
|
47882
|
+
size: data.length
|
|
47883
|
+
};
|
|
47884
|
+
}
|
|
47885
|
+
generateFilename(metadata) {
|
|
47886
|
+
const timestamp = Date.now();
|
|
47887
|
+
const random2 = crypto2.randomBytes(4).toString("hex");
|
|
47888
|
+
const indexSuffix = metadata.index != null ? `_${metadata.index}` : "";
|
|
47889
|
+
return `${metadata.type}_${timestamp}_${random2}${indexSuffix}.${metadata.format}`;
|
|
47890
|
+
}
|
|
47891
|
+
};
|
|
47892
|
+
|
|
47893
|
+
// src/tools/multimedia/config.ts
|
|
47894
|
+
var _outputHandler = null;
|
|
47895
|
+
function getMediaOutputHandler() {
|
|
47896
|
+
if (!_outputHandler) {
|
|
47897
|
+
_outputHandler = new FileMediaOutputHandler();
|
|
47898
|
+
}
|
|
47899
|
+
return _outputHandler;
|
|
47900
|
+
}
|
|
47901
|
+
function setMediaOutputHandler(handler) {
|
|
47902
|
+
_outputHandler = handler;
|
|
47903
|
+
}
|
|
47904
|
+
|
|
47905
|
+
// src/tools/multimedia/imageGeneration.ts
|
|
47906
|
+
function createImageGenerationTool(connector, outputHandler) {
|
|
47907
|
+
const vendor = connector.vendor;
|
|
47908
|
+
const handler = outputHandler ?? getMediaOutputHandler();
|
|
47909
|
+
const vendorModels = vendor ? getImageModelsByVendor(vendor) : [];
|
|
47910
|
+
const modelNames = vendorModels.map((m) => m.name);
|
|
47911
|
+
const properties = {
|
|
47912
|
+
prompt: {
|
|
47913
|
+
type: "string",
|
|
47914
|
+
description: "Text description of the image to generate"
|
|
47915
|
+
}
|
|
47916
|
+
};
|
|
47917
|
+
if (modelNames.length > 0) {
|
|
47918
|
+
const descriptions = vendorModels.map((m) => `${m.name}: ${m.description || m.displayName}`).join("; ");
|
|
47919
|
+
properties.model = {
|
|
47920
|
+
type: "string",
|
|
47921
|
+
enum: modelNames,
|
|
47922
|
+
description: `Image model to use. Options: ${descriptions}`
|
|
47923
|
+
};
|
|
47924
|
+
}
|
|
47925
|
+
const hasSizes = vendorModels.some((m) => m.capabilities.sizes.length > 1);
|
|
47926
|
+
if (hasSizes) {
|
|
47927
|
+
const allSizes = [...new Set(vendorModels.flatMap((m) => m.capabilities.sizes))];
|
|
47928
|
+
properties.size = {
|
|
47929
|
+
type: "string",
|
|
47930
|
+
enum: allSizes,
|
|
47931
|
+
description: "Image dimensions"
|
|
47932
|
+
};
|
|
47933
|
+
}
|
|
47934
|
+
const hasAspectRatios = vendorModels.some((m) => m.capabilities.aspectRatios?.length);
|
|
47935
|
+
if (hasAspectRatios) {
|
|
47936
|
+
const allRatios = [...new Set(vendorModels.flatMap((m) => m.capabilities.aspectRatios ?? []))];
|
|
47937
|
+
properties.aspectRatio = {
|
|
47938
|
+
type: "string",
|
|
47939
|
+
enum: allRatios,
|
|
47940
|
+
description: "Image aspect ratio"
|
|
47941
|
+
};
|
|
47942
|
+
}
|
|
47943
|
+
const hasQuality = vendorModels.some((m) => m.capabilities.features.qualityControl);
|
|
47944
|
+
if (hasQuality) {
|
|
47945
|
+
properties.quality = {
|
|
47946
|
+
type: "string",
|
|
47947
|
+
enum: ["standard", "hd"],
|
|
47948
|
+
description: "Image quality level"
|
|
47949
|
+
};
|
|
47950
|
+
}
|
|
47951
|
+
const hasStyle = vendorModels.some((m) => m.capabilities.features.styleControl);
|
|
47952
|
+
if (hasStyle) {
|
|
47953
|
+
properties.style = {
|
|
47954
|
+
type: "string",
|
|
47955
|
+
enum: ["vivid", "natural"],
|
|
47956
|
+
description: "Image style (vivid for hyper-real, natural for less hyper-real)"
|
|
47957
|
+
};
|
|
47958
|
+
}
|
|
47959
|
+
const maxN = Math.max(...vendorModels.map((m) => m.capabilities.maxImagesPerRequest));
|
|
47960
|
+
if (maxN > 1) {
|
|
47961
|
+
properties.n = {
|
|
47962
|
+
type: "number",
|
|
47963
|
+
description: `Number of images to generate (1-${maxN})`,
|
|
47964
|
+
minimum: 1,
|
|
47965
|
+
maximum: maxN
|
|
47966
|
+
};
|
|
47967
|
+
}
|
|
47968
|
+
return {
|
|
47969
|
+
definition: {
|
|
47970
|
+
type: "function",
|
|
47971
|
+
function: {
|
|
47972
|
+
name: "generate_image",
|
|
47973
|
+
description: `Generate images from text prompts using ${connector.displayName}`,
|
|
47974
|
+
parameters: {
|
|
47975
|
+
type: "object",
|
|
47976
|
+
properties,
|
|
47977
|
+
required: ["prompt"]
|
|
47978
|
+
}
|
|
47979
|
+
}
|
|
47980
|
+
},
|
|
47981
|
+
execute: async (args) => {
|
|
47982
|
+
try {
|
|
47983
|
+
const imageGen = ImageGeneration.create({ connector });
|
|
47984
|
+
const response = await imageGen.generate({
|
|
47985
|
+
prompt: args.prompt,
|
|
47986
|
+
model: args.model,
|
|
47987
|
+
size: args.size,
|
|
47988
|
+
quality: args.quality,
|
|
47989
|
+
style: args.style,
|
|
47990
|
+
n: args.n,
|
|
47991
|
+
response_format: "b64_json"
|
|
47992
|
+
});
|
|
47993
|
+
const images = [];
|
|
47994
|
+
for (let i = 0; i < response.data.length; i++) {
|
|
47995
|
+
const item = response.data[i];
|
|
47996
|
+
let buffer;
|
|
47997
|
+
if (item.b64_json) {
|
|
47998
|
+
buffer = Buffer.from(item.b64_json, "base64");
|
|
47999
|
+
} else if (item.url) {
|
|
48000
|
+
const resp = await fetch(item.url);
|
|
48001
|
+
buffer = Buffer.from(await resp.arrayBuffer());
|
|
48002
|
+
} else {
|
|
48003
|
+
continue;
|
|
48004
|
+
}
|
|
48005
|
+
const modelName = args.model || modelNames[0] || "unknown";
|
|
48006
|
+
const modelInfo = IMAGE_MODEL_REGISTRY[modelName];
|
|
48007
|
+
const format = modelInfo?.capabilities.outputFormats[0] === "url" ? "png" : modelInfo?.capabilities.outputFormats[0] || "png";
|
|
48008
|
+
const result = await handler.save(buffer, {
|
|
48009
|
+
type: "image",
|
|
48010
|
+
format,
|
|
48011
|
+
model: modelName,
|
|
48012
|
+
vendor: vendor || "unknown",
|
|
48013
|
+
index: response.data.length > 1 ? i : void 0
|
|
48014
|
+
});
|
|
48015
|
+
images.push({
|
|
48016
|
+
location: result.location,
|
|
48017
|
+
mimeType: result.mimeType,
|
|
48018
|
+
revisedPrompt: item.revised_prompt
|
|
48019
|
+
});
|
|
48020
|
+
}
|
|
48021
|
+
return { success: true, images };
|
|
48022
|
+
} catch (error) {
|
|
48023
|
+
return {
|
|
48024
|
+
success: false,
|
|
48025
|
+
error: error instanceof Error ? error.message : String(error)
|
|
48026
|
+
};
|
|
48027
|
+
}
|
|
48028
|
+
},
|
|
48029
|
+
describeCall: (args) => args.prompt.length > 50 ? args.prompt.slice(0, 47) + "..." : args.prompt,
|
|
48030
|
+
permission: {
|
|
48031
|
+
scope: "session",
|
|
48032
|
+
riskLevel: "medium",
|
|
48033
|
+
approvalMessage: `Generate image(s) using ${connector.displayName}`
|
|
48034
|
+
}
|
|
48035
|
+
};
|
|
48036
|
+
}
|
|
48037
|
+
|
|
48038
|
+
// src/tools/multimedia/videoGeneration.ts
|
|
48039
|
+
var videoGenInstances = /* @__PURE__ */ new Map();
|
|
48040
|
+
function createVideoTools(connector, outputHandler) {
|
|
48041
|
+
const vendor = connector.vendor;
|
|
48042
|
+
const handler = outputHandler ?? getMediaOutputHandler();
|
|
48043
|
+
const vendorModels = vendor ? getVideoModelsByVendor(vendor) : [];
|
|
48044
|
+
const modelNames = vendorModels.map((m) => m.name);
|
|
48045
|
+
const generateProperties = {
|
|
48046
|
+
prompt: {
|
|
48047
|
+
type: "string",
|
|
48048
|
+
description: "Text description of the video to generate"
|
|
48049
|
+
}
|
|
48050
|
+
};
|
|
48051
|
+
if (modelNames.length > 0) {
|
|
48052
|
+
const descriptions = vendorModels.map((m) => `${m.name}: ${m.displayName}`).join("; ");
|
|
48053
|
+
generateProperties.model = {
|
|
48054
|
+
type: "string",
|
|
48055
|
+
enum: modelNames,
|
|
48056
|
+
description: `Video model to use. Options: ${descriptions}`
|
|
48057
|
+
};
|
|
48058
|
+
}
|
|
48059
|
+
const allDurations = [...new Set(vendorModels.flatMap((m) => m.capabilities.durations))].sort(
|
|
48060
|
+
(a, b) => a - b
|
|
48061
|
+
);
|
|
48062
|
+
if (allDurations.length > 0) {
|
|
48063
|
+
generateProperties.duration = {
|
|
48064
|
+
type: "number",
|
|
48065
|
+
description: `Video duration in seconds. Supported: ${allDurations.join(", ")}`
|
|
48066
|
+
};
|
|
48067
|
+
}
|
|
48068
|
+
const allResolutions = [...new Set(vendorModels.flatMap((m) => m.capabilities.resolutions))];
|
|
48069
|
+
if (allResolutions.length > 0) {
|
|
48070
|
+
generateProperties.resolution = {
|
|
48071
|
+
type: "string",
|
|
48072
|
+
enum: allResolutions,
|
|
48073
|
+
description: "Video resolution"
|
|
48074
|
+
};
|
|
48075
|
+
}
|
|
48076
|
+
const allAspectRatios = [
|
|
48077
|
+
...new Set(vendorModels.flatMap((m) => m.capabilities.aspectRatios ?? []))
|
|
48078
|
+
];
|
|
48079
|
+
if (allAspectRatios.length > 0) {
|
|
48080
|
+
generateProperties.aspectRatio = {
|
|
48081
|
+
type: "string",
|
|
48082
|
+
enum: allAspectRatios,
|
|
48083
|
+
description: "Video aspect ratio"
|
|
48084
|
+
};
|
|
48085
|
+
}
|
|
48086
|
+
const hasSeed = vendorModels.some((m) => m.capabilities.features.seed);
|
|
48087
|
+
if (hasSeed) {
|
|
48088
|
+
generateProperties.seed = {
|
|
48089
|
+
type: "number",
|
|
48090
|
+
description: "Random seed for reproducible generation"
|
|
48091
|
+
};
|
|
48092
|
+
}
|
|
48093
|
+
const generateTool = {
|
|
48094
|
+
definition: {
|
|
48095
|
+
type: "function",
|
|
48096
|
+
function: {
|
|
48097
|
+
name: "generate_video",
|
|
48098
|
+
description: `Start video generation from a text prompt using ${connector.displayName}. Returns a jobId to check status with video_status.`,
|
|
48099
|
+
parameters: {
|
|
48100
|
+
type: "object",
|
|
48101
|
+
properties: generateProperties,
|
|
48102
|
+
required: ["prompt"]
|
|
48103
|
+
}
|
|
48104
|
+
}
|
|
48105
|
+
},
|
|
48106
|
+
execute: async (args) => {
|
|
48107
|
+
try {
|
|
48108
|
+
const videoGen = VideoGeneration.create({ connector });
|
|
48109
|
+
const response = await videoGen.generate({
|
|
48110
|
+
prompt: args.prompt,
|
|
48111
|
+
model: args.model,
|
|
48112
|
+
duration: args.duration,
|
|
48113
|
+
resolution: args.resolution,
|
|
48114
|
+
aspectRatio: args.aspectRatio,
|
|
48115
|
+
seed: args.seed
|
|
48116
|
+
});
|
|
48117
|
+
videoGenInstances.set(response.jobId, videoGen);
|
|
48118
|
+
return {
|
|
48119
|
+
success: true,
|
|
48120
|
+
jobId: response.jobId,
|
|
48121
|
+
status: response.status
|
|
48122
|
+
};
|
|
48123
|
+
} catch (error) {
|
|
48124
|
+
return {
|
|
48125
|
+
success: false,
|
|
48126
|
+
error: error instanceof Error ? error.message : String(error)
|
|
48127
|
+
};
|
|
48128
|
+
}
|
|
48129
|
+
},
|
|
48130
|
+
describeCall: (args) => args.prompt.length > 50 ? args.prompt.slice(0, 47) + "..." : args.prompt,
|
|
48131
|
+
permission: {
|
|
48132
|
+
scope: "session",
|
|
48133
|
+
riskLevel: "medium",
|
|
48134
|
+
approvalMessage: `Generate video using ${connector.displayName}`
|
|
48135
|
+
}
|
|
48136
|
+
};
|
|
48137
|
+
const statusTool = {
|
|
48138
|
+
definition: {
|
|
48139
|
+
type: "function",
|
|
48140
|
+
function: {
|
|
48141
|
+
name: "video_status",
|
|
48142
|
+
description: "Check the status of a video generation job. If completed, downloads and saves the video.",
|
|
48143
|
+
parameters: {
|
|
48144
|
+
type: "object",
|
|
48145
|
+
properties: {
|
|
48146
|
+
jobId: {
|
|
48147
|
+
type: "string",
|
|
48148
|
+
description: "The job ID returned by generate_video"
|
|
48149
|
+
}
|
|
48150
|
+
},
|
|
48151
|
+
required: ["jobId"]
|
|
48152
|
+
}
|
|
48153
|
+
}
|
|
48154
|
+
},
|
|
48155
|
+
execute: async (args) => {
|
|
48156
|
+
try {
|
|
48157
|
+
let videoGen = videoGenInstances.get(args.jobId);
|
|
48158
|
+
if (!videoGen) {
|
|
48159
|
+
videoGen = VideoGeneration.create({ connector });
|
|
48160
|
+
}
|
|
48161
|
+
const status = await videoGen.getStatus(args.jobId);
|
|
48162
|
+
if (status.status === "completed") {
|
|
48163
|
+
let buffer;
|
|
48164
|
+
if (status.video?.b64_json) {
|
|
48165
|
+
buffer = Buffer.from(status.video.b64_json, "base64");
|
|
48166
|
+
} else if (status.video?.url) {
|
|
48167
|
+
const resp = await fetch(status.video.url);
|
|
48168
|
+
buffer = Buffer.from(await resp.arrayBuffer());
|
|
48169
|
+
} else if (videoGen.download) {
|
|
48170
|
+
try {
|
|
48171
|
+
buffer = await videoGen.download(args.jobId);
|
|
48172
|
+
} catch {
|
|
48173
|
+
}
|
|
48174
|
+
}
|
|
48175
|
+
if (buffer) {
|
|
48176
|
+
const format = status.video?.format || "mp4";
|
|
48177
|
+
const modelName = modelNames[0] || "unknown";
|
|
48178
|
+
const result = await handler.save(buffer, {
|
|
48179
|
+
type: "video",
|
|
48180
|
+
format,
|
|
48181
|
+
model: modelName,
|
|
48182
|
+
vendor: vendor || "unknown"
|
|
48183
|
+
});
|
|
48184
|
+
videoGenInstances.delete(args.jobId);
|
|
48185
|
+
return {
|
|
48186
|
+
success: true,
|
|
48187
|
+
status: "completed",
|
|
48188
|
+
location: result.location,
|
|
48189
|
+
mimeType: result.mimeType
|
|
48190
|
+
};
|
|
48191
|
+
}
|
|
48192
|
+
videoGenInstances.delete(args.jobId);
|
|
48193
|
+
return {
|
|
48194
|
+
success: true,
|
|
48195
|
+
status: "completed",
|
|
48196
|
+
location: status.video?.url
|
|
48197
|
+
};
|
|
48198
|
+
}
|
|
48199
|
+
if (status.status === "failed") {
|
|
48200
|
+
videoGenInstances.delete(args.jobId);
|
|
48201
|
+
return {
|
|
48202
|
+
success: false,
|
|
48203
|
+
status: "failed",
|
|
48204
|
+
error: status.error || "Video generation failed"
|
|
48205
|
+
};
|
|
48206
|
+
}
|
|
48207
|
+
return {
|
|
48208
|
+
success: true,
|
|
48209
|
+
status: status.status,
|
|
48210
|
+
progress: status.progress
|
|
48211
|
+
};
|
|
48212
|
+
} catch (error) {
|
|
48213
|
+
return {
|
|
48214
|
+
success: false,
|
|
48215
|
+
error: error instanceof Error ? error.message : String(error)
|
|
48216
|
+
};
|
|
48217
|
+
}
|
|
48218
|
+
},
|
|
48219
|
+
describeCall: (args) => `job ${args.jobId}`,
|
|
48220
|
+
permission: {
|
|
48221
|
+
scope: "session",
|
|
48222
|
+
riskLevel: "low",
|
|
48223
|
+
approvalMessage: "Check video generation status"
|
|
48224
|
+
}
|
|
48225
|
+
};
|
|
48226
|
+
return [generateTool, statusTool];
|
|
48227
|
+
}
|
|
48228
|
+
|
|
48229
|
+
// src/tools/multimedia/textToSpeech.ts
|
|
48230
|
+
function createTextToSpeechTool(connector, outputHandler) {
|
|
48231
|
+
const vendor = connector.vendor;
|
|
48232
|
+
const handler = outputHandler ?? getMediaOutputHandler();
|
|
48233
|
+
const vendorModels = vendor ? getTTSModelsByVendor(vendor) : [];
|
|
48234
|
+
const modelNames = vendorModels.map((m) => m.name);
|
|
48235
|
+
const properties = {
|
|
48236
|
+
text: {
|
|
48237
|
+
type: "string",
|
|
48238
|
+
description: "Text to convert to speech"
|
|
48239
|
+
}
|
|
48240
|
+
};
|
|
48241
|
+
if (modelNames.length > 0) {
|
|
48242
|
+
const descriptions = vendorModels.map((m) => `${m.name}: ${m.description || m.displayName}`).join("; ");
|
|
48243
|
+
properties.model = {
|
|
48244
|
+
type: "string",
|
|
48245
|
+
enum: modelNames,
|
|
48246
|
+
description: `TTS model to use. Options: ${descriptions}`
|
|
48247
|
+
};
|
|
48248
|
+
}
|
|
48249
|
+
const allVoices = [
|
|
48250
|
+
...new Map(
|
|
48251
|
+
vendorModels.flatMap((m) => m.capabilities.voices).map((v) => [v.id, v])
|
|
48252
|
+
).values()
|
|
48253
|
+
];
|
|
48254
|
+
if (allVoices.length > 0) {
|
|
48255
|
+
const voiceDescriptions = allVoices.slice(0, 10).map((v) => `${v.id}${v.name !== v.id ? ` (${v.name})` : ""}`).join(", ");
|
|
48256
|
+
properties.voice = {
|
|
48257
|
+
type: "string",
|
|
48258
|
+
enum: allVoices.map((v) => v.id),
|
|
48259
|
+
description: `Voice to use. Options include: ${voiceDescriptions}${allVoices.length > 10 ? `, and ${allVoices.length - 10} more` : ""}`
|
|
48260
|
+
};
|
|
48261
|
+
}
|
|
48262
|
+
const allFormats = [...new Set(vendorModels.flatMap((m) => [...m.capabilities.formats]))];
|
|
48263
|
+
if (allFormats.length > 0) {
|
|
48264
|
+
properties.format = {
|
|
48265
|
+
type: "string",
|
|
48266
|
+
enum: allFormats,
|
|
48267
|
+
description: `Output audio format: ${allFormats.join(", ")}`
|
|
48268
|
+
};
|
|
48269
|
+
}
|
|
48270
|
+
const hasSpeed = vendorModels.some((m) => m.capabilities.speed.supported);
|
|
48271
|
+
if (hasSpeed) {
|
|
48272
|
+
const speedModel = vendorModels.find((m) => m.capabilities.speed.supported);
|
|
48273
|
+
properties.speed = {
|
|
48274
|
+
type: "number",
|
|
48275
|
+
description: `Speech speed (${speedModel?.capabilities.speed.min ?? 0.25} to ${speedModel?.capabilities.speed.max ?? 4})`,
|
|
48276
|
+
minimum: speedModel?.capabilities.speed.min ?? 0.25,
|
|
48277
|
+
maximum: speedModel?.capabilities.speed.max ?? 4
|
|
48278
|
+
};
|
|
48279
|
+
}
|
|
48280
|
+
return {
|
|
48281
|
+
definition: {
|
|
48282
|
+
type: "function",
|
|
48283
|
+
function: {
|
|
48284
|
+
name: "text_to_speech",
|
|
48285
|
+
description: `Convert text to speech audio using ${connector.displayName}`,
|
|
48286
|
+
parameters: {
|
|
48287
|
+
type: "object",
|
|
48288
|
+
properties,
|
|
48289
|
+
required: ["text"]
|
|
48290
|
+
}
|
|
48291
|
+
}
|
|
48292
|
+
},
|
|
48293
|
+
execute: async (args) => {
|
|
48294
|
+
try {
|
|
48295
|
+
const tts = TextToSpeech.create({
|
|
48296
|
+
connector,
|
|
48297
|
+
model: args.model,
|
|
48298
|
+
voice: args.voice,
|
|
48299
|
+
format: args.format,
|
|
48300
|
+
speed: args.speed
|
|
48301
|
+
});
|
|
48302
|
+
const response = await tts.synthesize(args.text);
|
|
48303
|
+
const format = response.format || args.format || "mp3";
|
|
48304
|
+
const result = await handler.save(response.audio, {
|
|
48305
|
+
type: "audio",
|
|
48306
|
+
format,
|
|
48307
|
+
model: args.model || modelNames[0] || "unknown",
|
|
48308
|
+
vendor: vendor || "unknown"
|
|
48309
|
+
});
|
|
48310
|
+
return {
|
|
48311
|
+
success: true,
|
|
48312
|
+
location: result.location,
|
|
48313
|
+
format,
|
|
48314
|
+
mimeType: result.mimeType
|
|
48315
|
+
};
|
|
48316
|
+
} catch (error) {
|
|
48317
|
+
return {
|
|
48318
|
+
success: false,
|
|
48319
|
+
error: error instanceof Error ? error.message : String(error)
|
|
48320
|
+
};
|
|
48321
|
+
}
|
|
48322
|
+
},
|
|
48323
|
+
describeCall: (args) => args.text.length > 50 ? args.text.slice(0, 47) + "..." : args.text,
|
|
48324
|
+
permission: {
|
|
48325
|
+
scope: "session",
|
|
48326
|
+
riskLevel: "medium",
|
|
48327
|
+
approvalMessage: `Convert text to speech using ${connector.displayName}`
|
|
48328
|
+
}
|
|
48329
|
+
};
|
|
48330
|
+
}
|
|
48331
|
+
function createSpeechToTextTool(connector) {
|
|
48332
|
+
const vendor = connector.vendor;
|
|
48333
|
+
const vendorModels = vendor ? getSTTModelsByVendor(vendor) : [];
|
|
48334
|
+
const modelNames = vendorModels.map((m) => m.name);
|
|
48335
|
+
const properties = {
|
|
48336
|
+
audioFilePath: {
|
|
48337
|
+
type: "string",
|
|
48338
|
+
description: "Path to the audio file to transcribe"
|
|
48339
|
+
}
|
|
48340
|
+
};
|
|
48341
|
+
if (modelNames.length > 0) {
|
|
48342
|
+
const descriptions = vendorModels.map((m) => `${m.name}: ${m.description || m.displayName}`).join("; ");
|
|
48343
|
+
properties.model = {
|
|
48344
|
+
type: "string",
|
|
48345
|
+
enum: modelNames,
|
|
48346
|
+
description: `STT model to use. Options: ${descriptions}`
|
|
48347
|
+
};
|
|
48348
|
+
}
|
|
48349
|
+
properties.language = {
|
|
48350
|
+
type: "string",
|
|
48351
|
+
description: 'Language code (ISO-639-1, e.g., "en", "es", "fr"). Optional for auto-detection.'
|
|
48352
|
+
};
|
|
48353
|
+
properties.prompt = {
|
|
48354
|
+
type: "string",
|
|
48355
|
+
description: "Optional context hint to guide transcription (e.g., domain-specific terms)"
|
|
48356
|
+
};
|
|
48357
|
+
return {
|
|
48358
|
+
definition: {
|
|
48359
|
+
type: "function",
|
|
48360
|
+
function: {
|
|
48361
|
+
name: "speech_to_text",
|
|
48362
|
+
description: `Transcribe audio to text using ${connector.displayName}`,
|
|
48363
|
+
parameters: {
|
|
48364
|
+
type: "object",
|
|
48365
|
+
properties,
|
|
48366
|
+
required: ["audioFilePath"]
|
|
48367
|
+
}
|
|
48368
|
+
}
|
|
48369
|
+
},
|
|
48370
|
+
execute: async (args) => {
|
|
48371
|
+
try {
|
|
48372
|
+
const audioBuffer = await fs14.readFile(args.audioFilePath);
|
|
48373
|
+
const stt = SpeechToText.create({
|
|
48374
|
+
connector,
|
|
48375
|
+
model: args.model,
|
|
48376
|
+
language: args.language
|
|
48377
|
+
});
|
|
48378
|
+
const response = await stt.transcribe(audioBuffer, {
|
|
48379
|
+
prompt: args.prompt
|
|
48380
|
+
});
|
|
48381
|
+
return {
|
|
48382
|
+
success: true,
|
|
48383
|
+
text: response.text,
|
|
48384
|
+
language: response.language,
|
|
48385
|
+
durationSeconds: response.durationSeconds
|
|
48386
|
+
};
|
|
48387
|
+
} catch (error) {
|
|
48388
|
+
return {
|
|
48389
|
+
success: false,
|
|
48390
|
+
error: error instanceof Error ? error.message : String(error)
|
|
48391
|
+
};
|
|
48392
|
+
}
|
|
48393
|
+
},
|
|
48394
|
+
describeCall: (args) => args.audioFilePath,
|
|
48395
|
+
permission: {
|
|
48396
|
+
scope: "session",
|
|
48397
|
+
riskLevel: "low",
|
|
48398
|
+
approvalMessage: `Transcribe audio using ${connector.displayName}`
|
|
48399
|
+
}
|
|
48400
|
+
};
|
|
48401
|
+
}
|
|
48402
|
+
|
|
48403
|
+
// src/tools/multimedia/register.ts
|
|
48404
|
+
var VENDOR_CAPABILITIES = {
|
|
48405
|
+
[Vendor.OpenAI]: ["image", "video", "tts", "stt"],
|
|
48406
|
+
[Vendor.Google]: ["image", "video", "tts"],
|
|
48407
|
+
[Vendor.Grok]: ["image", "video"]
|
|
48408
|
+
};
|
|
48409
|
+
function registerMultimediaTools() {
|
|
48410
|
+
for (const [vendor, capabilities] of Object.entries(VENDOR_CAPABILITIES)) {
|
|
48411
|
+
ConnectorTools.registerService(vendor, (connector, _userId) => {
|
|
48412
|
+
const tools = [];
|
|
48413
|
+
if (capabilities.includes("image")) {
|
|
48414
|
+
tools.push(createImageGenerationTool(connector));
|
|
48415
|
+
}
|
|
48416
|
+
if (capabilities.includes("video")) {
|
|
48417
|
+
tools.push(...createVideoTools(connector));
|
|
48418
|
+
}
|
|
48419
|
+
if (capabilities.includes("tts")) {
|
|
48420
|
+
tools.push(createTextToSpeechTool(connector));
|
|
48421
|
+
}
|
|
48422
|
+
if (capabilities.includes("stt")) {
|
|
48423
|
+
tools.push(createSpeechToTextTool(connector));
|
|
48424
|
+
}
|
|
48425
|
+
return tools;
|
|
48426
|
+
});
|
|
48427
|
+
}
|
|
48428
|
+
}
|
|
48429
|
+
|
|
48430
|
+
// src/tools/multimedia/index.ts
|
|
48431
|
+
registerMultimediaTools();
|
|
48484
48432
|
|
|
48485
48433
|
// src/tools/registry.generated.ts
|
|
48486
48434
|
var toolRegistry = [
|
|
@@ -48724,17 +48672,23 @@ var ToolRegistry = class {
|
|
|
48724
48672
|
*/
|
|
48725
48673
|
static toRegistryEntry(tool, connectorName) {
|
|
48726
48674
|
let serviceType;
|
|
48675
|
+
let displayPrefix;
|
|
48727
48676
|
try {
|
|
48728
48677
|
const connector = Connector.get(connectorName);
|
|
48729
48678
|
serviceType = ConnectorTools.detectService(connector);
|
|
48679
|
+
if (connector.vendor) {
|
|
48680
|
+
const vendorInfo = getVendorInfo(connector.vendor);
|
|
48681
|
+
displayPrefix = vendorInfo?.name || connector.vendor;
|
|
48682
|
+
}
|
|
48730
48683
|
} catch {
|
|
48731
48684
|
}
|
|
48732
48685
|
const serviceInfo = serviceType ? getServiceInfo(serviceType) : void 0;
|
|
48686
|
+
const displayContext = displayPrefix || serviceInfo?.name;
|
|
48733
48687
|
const def = tool.definition.function;
|
|
48734
48688
|
return {
|
|
48735
48689
|
name: def.name,
|
|
48736
48690
|
exportName: def.name,
|
|
48737
|
-
displayName: this.deriveDisplayName(def.name,
|
|
48691
|
+
displayName: this.deriveDisplayName(def.name, displayContext, connectorName),
|
|
48738
48692
|
category: "connector",
|
|
48739
48693
|
description: def.description || `API tool for ${connectorName}`,
|
|
48740
48694
|
tool,
|
|
@@ -48747,14 +48701,21 @@ var ToolRegistry = class {
|
|
|
48747
48701
|
}
|
|
48748
48702
|
/**
|
|
48749
48703
|
* Derive a human-readable display name from a tool name
|
|
48704
|
+
*
|
|
48705
|
+
* @param toolName - Full tool name (e.g., "main-openai_generate_image")
|
|
48706
|
+
* @param contextName - Vendor or service display name (e.g., "OpenAI")
|
|
48707
|
+
* @param connectorName - Connector name used as prefix (e.g., "main-openai")
|
|
48750
48708
|
*/
|
|
48751
|
-
static deriveDisplayName(toolName,
|
|
48752
|
-
|
|
48753
|
-
|
|
48754
|
-
|
|
48709
|
+
static deriveDisplayName(toolName, contextName, connectorName) {
|
|
48710
|
+
let baseName = toolName;
|
|
48711
|
+
if (connectorName && toolName.startsWith(connectorName + "_")) {
|
|
48712
|
+
baseName = toolName.slice(connectorName.length + 1);
|
|
48713
|
+
}
|
|
48714
|
+
if (baseName === "api") {
|
|
48715
|
+
return contextName ? `${contextName} API` : toolName.replace(/_/g, " ");
|
|
48755
48716
|
}
|
|
48756
|
-
const
|
|
48757
|
-
return
|
|
48717
|
+
const readable = baseName.split("_").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
48718
|
+
return contextName ? `${contextName} ${readable}` : readable;
|
|
48758
48719
|
}
|
|
48759
48720
|
};
|
|
48760
48721
|
|
|
@@ -48948,6 +48909,6 @@ REMEMBER: Keep it conversational, ask one question at a time, and only output th
|
|
|
48948
48909
|
}
|
|
48949
48910
|
};
|
|
48950
48911
|
|
|
48951
|
-
export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION,
|
|
48912
|
+
export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, AgentContextNextGen, ApproximateTokenEstimator, BaseMediaProvider, BasePluginNextGen, BaseProvider, BaseTextProvider, BraveProvider, CONNECTOR_CONFIG_VERSION, CONTEXT_SESSION_FORMAT_VERSION, CheckpointManager, CircuitBreaker, CircuitOpenError, Connector, ConnectorConfigStore, ConnectorTools, ConsoleMetrics, ContentType, ContextOverflowError, DEFAULT_ALLOWLIST, DEFAULT_BACKOFF_CONFIG, DEFAULT_BASE_DELAY_MS, DEFAULT_CHECKPOINT_STRATEGY, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONFIG2 as DEFAULT_CONFIG, DEFAULT_CONNECTOR_TIMEOUT, DEFAULT_CONTEXT_CONFIG, DEFAULT_FEATURES, DEFAULT_FILESYSTEM_CONFIG, DEFAULT_HISTORY_MANAGER_CONFIG, DEFAULT_MAX_DELAY_MS, DEFAULT_MAX_RETRIES, DEFAULT_MEMORY_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_RATE_LIMITER_CONFIG, DEFAULT_RETRYABLE_STATUSES, DEFAULT_SHELL_CONFIG, DefaultCompactionStrategy, DependencyCycleError, ErrorHandler, ExecutionContext, ExternalDependencyHandler, FileAgentDefinitionStorage, FileConnectorStorage, FileContextStorage, FileMediaOutputHandler, FilePersistentInstructionsStorage, FileStorage, FrameworkLogger, HookManager, IMAGE_MODELS, IMAGE_MODEL_REGISTRY, ImageGeneration, InContextMemoryPluginNextGen, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, InvalidConfigError, InvalidToolArgumentsError, LLM_MODELS, LoggingPlugin, MCPClient, MCPConnectionError, MCPError, MCPProtocolError, MCPRegistry, MCPResourceError, MCPTimeoutError, MCPToolError, MEMORY_PRIORITY_VALUES, MODEL_REGISTRY, MemoryConnectorStorage, MemoryEvictionCompactor, MemoryStorage, MessageBuilder, MessageRole, ModelNotSupportedError, NoOpMetrics, OAuthManager, ParallelTasksError, PersistentInstructionsPluginNextGen, PlanningAgent, ProviderAuthError, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, RapidAPIProvider, RateLimitError, SERVICE_DEFINITIONS, SERVICE_INFO, SERVICE_URL_PATTERNS, SIMPLE_ICONS_CDN, STT_MODELS, STT_MODEL_REGISTRY, ScopedConnectorRegistry, ScrapeProvider, SearchProvider, SerperProvider, Services, SpeechToText, StrategyRegistry, StreamEventType, StreamHelpers, StreamState, SummarizeCompactor, TERMINAL_TASK_STATUSES, TTS_MODELS, TTS_MODEL_REGISTRY, TaskTimeoutError, TaskValidationError, TavilyProvider, TextToSpeech, TokenBucketRateLimiter, ToolCallState, ToolExecutionError, ToolExecutionPipeline, ToolManager, ToolNotFoundError, ToolPermissionManager, ToolRegistry, ToolTimeoutError, TruncateCompactor, VENDORS, VENDOR_ICON_MAP, VIDEO_MODELS, VIDEO_MODEL_REGISTRY, Vendor, VideoGeneration, WorkingMemory, WorkingMemoryPluginNextGen, addJitter, allVendorTemplates, assertNotDestroyed, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildQueryString, calculateBackoff, calculateCost, calculateEntrySize, calculateImageCost, calculateSTTCost, calculateTTSCost, calculateVideoCost, canTaskExecute, createAgentStorage, createAuthenticatedFetch, createBashTool, createConnectorFromTemplate, createEditFileTool, createEstimator, createExecuteJavaScriptTool, createFileAgentDefinitionStorage, createFileContextStorage, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListDirectoryTool, createMessageWithImages, createMetricsCollector, createPlan, createProvider, createReadFileTool, createSpeechToTextTool, createTask, createTextMessage, createTextToSpeechTool, createVideoProvider, createVideoTools, createWriteFileTool, defaultDescribeCall, detectDependencyCycle, detectServiceFromURL, developerTools, editFile, evaluateCondition, extractJSON, extractJSONField, extractNumber, findConnectorByServiceTypes, forPlan, forTasks, generateEncryptionKey, generateSimplePlan, generateWebAPITool, getActiveImageModels, getActiveModels, getActiveSTTModels, getActiveTTSModels, getActiveVideoModels, getAllBuiltInTools, getAllServiceIds, getAllVendorLogos, getAllVendorTemplates, getBackgroundOutput, getConnectorTools, getCredentialsSetupURL, getDocsURL, getImageModelInfo, getImageModelsByVendor, getImageModelsWithFeature, getMediaOutputHandler, getModelInfo, getModelsByVendor, getNextExecutableTasks, getRegisteredScrapeProviders, getSTTModelInfo, getSTTModelsByVendor, getSTTModelsWithFeature, getServiceDefinition, getServiceInfo, getServicesByCategory, getTTSModelInfo, getTTSModelsByVendor, getTTSModelsWithFeature, getTaskDependencies, getToolByName, getToolCallDescription, getToolCategories, getToolRegistry, getToolsByCategory, getToolsRequiringConnector, getVendorAuthTemplate, getVendorColor, getVendorInfo, getVendorLogo, getVendorLogoCdnUrl, getVendorLogoSvg, getVendorTemplate, getVideoModelInfo, getVideoModelsByVendor, getVideoModelsWithAudio, getVideoModelsWithFeature, glob, globalErrorHandler, grep, hasClipboardImage, hasVendorLogo, isBlockedCommand, isErrorEvent, isExcludedExtension, isKnownService, isOutputTextDelta, isResponseComplete, isSimpleScope, isStreamEvent, isTaskAwareScope, isTaskBlocked, isTerminalMemoryStatus, isTerminalStatus, isToolCallArgumentsDelta, isToolCallArgumentsDone, isToolCallStart, isVendor, killBackgroundProcess, listConnectorsByServiceTypes, listDirectory, listVendorIds, listVendors, listVendorsByAuthType, listVendorsByCategory, listVendorsWithLogos, logger, metrics, readClipboardImage, readFile4 as readFile, registerScrapeProvider, resolveConnector, resolveDependencies, retryWithBackoff, scopeEquals, scopeMatches, setMediaOutputHandler, setMetricsCollector, simpleTokenEstimator, toConnectorOptions, toolRegistry, tools_exports as tools, updateTaskStatus, validatePath, writeFile4 as writeFile };
|
|
48952
48913
|
//# sourceMappingURL=index.js.map
|
|
48953
48914
|
//# sourceMappingURL=index.js.map
|