@everworker/oneringai 0.1.1 → 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 +52 -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 +222 -893
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2234 -2633
- package/dist/index.d.ts +2234 -2633
- package/dist/index.js +223 -887
- 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
|
|
@@ -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;
|
|
@@ -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",
|
|
@@ -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
|
|
|
@@ -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) {
|
|
@@ -42148,8 +41479,8 @@ var ConnectorTools = class {
|
|
|
42148
41479
|
* // Returns: [slack_api, slack_send_message, slack_list_channels, ...]
|
|
42149
41480
|
* ```
|
|
42150
41481
|
*/
|
|
42151
|
-
static for(connectorOrName, userId) {
|
|
42152
|
-
const connector = this.resolveConnector(connectorOrName);
|
|
41482
|
+
static for(connectorOrName, userId, options) {
|
|
41483
|
+
const connector = this.resolveConnector(connectorOrName, options?.registry);
|
|
42153
41484
|
const tools = [];
|
|
42154
41485
|
if (connector.baseURL) {
|
|
42155
41486
|
tools.push(this.createGenericAPITool(connector, { userId }));
|
|
@@ -42211,9 +41542,9 @@ var ConnectorTools = class {
|
|
|
42211
41542
|
* }
|
|
42212
41543
|
* ```
|
|
42213
41544
|
*/
|
|
42214
|
-
static discoverAll(userId) {
|
|
41545
|
+
static discoverAll(userId, options) {
|
|
42215
41546
|
const result = /* @__PURE__ */ new Map();
|
|
42216
|
-
const allConnectors = Connector.listAll();
|
|
41547
|
+
const allConnectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
42217
41548
|
const factoryKeys = Array.from(this.factories.keys());
|
|
42218
41549
|
logger.debug(`[ConnectorTools.discoverAll] ${allConnectors.length} connectors in library, ${factoryKeys.length} factories registered: [${factoryKeys.join(", ")}]`);
|
|
42219
41550
|
for (const connector of allConnectors) {
|
|
@@ -42243,8 +41574,9 @@ var ConnectorTools = class {
|
|
|
42243
41574
|
* @param serviceType - Service identifier
|
|
42244
41575
|
* @returns Connector or undefined
|
|
42245
41576
|
*/
|
|
42246
|
-
static findConnector(serviceType) {
|
|
42247
|
-
|
|
41577
|
+
static findConnector(serviceType, options) {
|
|
41578
|
+
const connectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
41579
|
+
return connectors.find((c) => this.detectService(c) === serviceType);
|
|
42248
41580
|
}
|
|
42249
41581
|
/**
|
|
42250
41582
|
* Find all connectors for a service type
|
|
@@ -42253,8 +41585,9 @@ var ConnectorTools = class {
|
|
|
42253
41585
|
* @param serviceType - Service identifier
|
|
42254
41586
|
* @returns Array of matching connectors
|
|
42255
41587
|
*/
|
|
42256
|
-
static findConnectors(serviceType) {
|
|
42257
|
-
|
|
41588
|
+
static findConnectors(serviceType, options) {
|
|
41589
|
+
const connectors = options?.registry ? options.registry.listAll() : Connector.listAll();
|
|
41590
|
+
return connectors.filter((c) => this.detectService(c) === serviceType);
|
|
42258
41591
|
}
|
|
42259
41592
|
/**
|
|
42260
41593
|
* List services that have registered tool factories
|
|
@@ -42304,8 +41637,11 @@ var ConnectorTools = class {
|
|
|
42304
41637
|
}
|
|
42305
41638
|
}
|
|
42306
41639
|
// ============ Private Methods ============
|
|
42307
|
-
static resolveConnector(connectorOrName) {
|
|
42308
|
-
|
|
41640
|
+
static resolveConnector(connectorOrName, registry) {
|
|
41641
|
+
if (typeof connectorOrName === "string") {
|
|
41642
|
+
return registry ? registry.get(connectorOrName) : Connector.get(connectorOrName);
|
|
41643
|
+
}
|
|
41644
|
+
return connectorOrName;
|
|
42309
41645
|
}
|
|
42310
41646
|
static createGenericAPITool(connector, options) {
|
|
42311
41647
|
const toolName = options?.toolName ?? `${connector.name}_api`;
|
|
@@ -49573,6 +48909,6 @@ REMEMBER: Keep it conversational, ask one question at a time, and only output th
|
|
|
49573
48909
|
}
|
|
49574
48910
|
};
|
|
49575
48911
|
|
|
49576
|
-
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 };
|
|
49577
48913
|
//# sourceMappingURL=index.js.map
|
|
49578
48914
|
//# sourceMappingURL=index.js.map
|