@everworker/oneringai 0.4.3 → 0.4.4
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 +104 -7
- package/dist/capabilities/agents/index.d.cts +1 -1
- package/dist/capabilities/agents/index.d.ts +1 -1
- package/dist/capabilities/images/index.cjs.map +1 -1
- package/dist/capabilities/images/index.js.map +1 -1
- package/dist/{index-CEjKTeSb.d.cts → index-DmYrHH7d.d.cts} +305 -1
- package/dist/{index-CzGnmqOs.d.ts → index-Dyl6pHfq.d.ts} +305 -1
- package/dist/index.cjs +2862 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +568 -18
- package/dist/index.d.ts +568 -18
- package/dist/index.js +2846 -37
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -9992,15 +9992,16 @@ var init_PDFHandler = __esm({
|
|
|
9992
9992
|
const unpdf = await getUnpdf();
|
|
9993
9993
|
const pieces = [];
|
|
9994
9994
|
let pieceIndex = 0;
|
|
9995
|
+
const data = new Uint8Array(buffer);
|
|
9995
9996
|
let metadata = {};
|
|
9996
9997
|
const includeMetadata = options.formatOptions?.pdf?.includeMetadata !== false;
|
|
9997
9998
|
if (includeMetadata) {
|
|
9998
9999
|
try {
|
|
9999
|
-
metadata = await unpdf.getMeta(
|
|
10000
|
+
metadata = await unpdf.getMeta(data);
|
|
10000
10001
|
} catch {
|
|
10001
10002
|
}
|
|
10002
10003
|
}
|
|
10003
|
-
const textResult = await unpdf.extractText(
|
|
10004
|
+
const textResult = await unpdf.extractText(data, { mergePages: false });
|
|
10004
10005
|
const pages = textResult?.pages || textResult?.text ? Array.isArray(textResult.text) ? textResult.text : [textResult.text] : [];
|
|
10005
10006
|
const requestedPages = options.pages;
|
|
10006
10007
|
const pageEntries = pages.map((text, i) => ({ text, pageNum: i + 1 }));
|
|
@@ -10053,7 +10054,7 @@ var init_PDFHandler = __esm({
|
|
|
10053
10054
|
}
|
|
10054
10055
|
if (options.extractImages !== false) {
|
|
10055
10056
|
try {
|
|
10056
|
-
const imagesResult = await unpdf.extractImages(
|
|
10057
|
+
const imagesResult = await unpdf.extractImages(data, {});
|
|
10057
10058
|
const images = imagesResult?.images || [];
|
|
10058
10059
|
for (const img of images) {
|
|
10059
10060
|
if (!img.data) continue;
|
|
@@ -10286,6 +10287,457 @@ init_Connector();
|
|
|
10286
10287
|
init_ScopedConnectorRegistry();
|
|
10287
10288
|
init_StorageRegistry();
|
|
10288
10289
|
|
|
10290
|
+
// src/core/ToolCatalogRegistry.ts
|
|
10291
|
+
init_Logger();
|
|
10292
|
+
var ToolCatalogRegistry = class {
|
|
10293
|
+
/** Category definitions: name → definition */
|
|
10294
|
+
static _categories = /* @__PURE__ */ new Map();
|
|
10295
|
+
/** Tools per category: category name → tool entries */
|
|
10296
|
+
static _tools = /* @__PURE__ */ new Map();
|
|
10297
|
+
/** Whether built-in tools have been registered */
|
|
10298
|
+
static _initialized = false;
|
|
10299
|
+
/** Lazy-loaded ConnectorTools module. null = not attempted, false = failed */
|
|
10300
|
+
static _connectorToolsModule = null;
|
|
10301
|
+
// --- Built-in category descriptions ---
|
|
10302
|
+
static BUILTIN_DESCRIPTIONS = {
|
|
10303
|
+
filesystem: "Read, write, edit, search, and list files and directories",
|
|
10304
|
+
shell: "Execute bash/shell commands",
|
|
10305
|
+
web: "Fetch and process web content",
|
|
10306
|
+
code: "Execute JavaScript code in sandboxed VM",
|
|
10307
|
+
json: "Parse, query, and transform JSON data",
|
|
10308
|
+
desktop: "Screenshot, mouse, keyboard, and window desktop automation",
|
|
10309
|
+
"custom-tools": "Create, save, load, and test custom tool definitions",
|
|
10310
|
+
routines: "Generate and manage agent routines",
|
|
10311
|
+
other: "Miscellaneous tools"
|
|
10312
|
+
};
|
|
10313
|
+
// ========================================================================
|
|
10314
|
+
// Static Helpers (DRY)
|
|
10315
|
+
// ========================================================================
|
|
10316
|
+
/**
|
|
10317
|
+
* Convert a hyphenated or plain name to a display name.
|
|
10318
|
+
* E.g., 'custom-tools' → 'Custom Tools', 'filesystem' → 'Filesystem'
|
|
10319
|
+
*/
|
|
10320
|
+
static toDisplayName(name) {
|
|
10321
|
+
return name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
|
|
10322
|
+
}
|
|
10323
|
+
/**
|
|
10324
|
+
* Parse a connector category name, returning the connector name or null.
|
|
10325
|
+
* E.g., 'connector:github' → 'github', 'filesystem' → null
|
|
10326
|
+
*/
|
|
10327
|
+
static parseConnectorCategory(category) {
|
|
10328
|
+
return category.startsWith("connector:") ? category.slice("connector:".length) : null;
|
|
10329
|
+
}
|
|
10330
|
+
/**
|
|
10331
|
+
* Get the ConnectorTools module (lazy-loaded, cached).
|
|
10332
|
+
* Returns null if ConnectorTools is not available.
|
|
10333
|
+
* Uses false sentinel to prevent retrying after first failure.
|
|
10334
|
+
*/
|
|
10335
|
+
static getConnectorToolsModule() {
|
|
10336
|
+
if (this._connectorToolsModule === null) {
|
|
10337
|
+
try {
|
|
10338
|
+
this._connectorToolsModule = __require("../../tools/connector/ConnectorTools.js");
|
|
10339
|
+
} catch {
|
|
10340
|
+
this._connectorToolsModule = false;
|
|
10341
|
+
}
|
|
10342
|
+
}
|
|
10343
|
+
return this._connectorToolsModule || null;
|
|
10344
|
+
}
|
|
10345
|
+
// ========================================================================
|
|
10346
|
+
// Registration
|
|
10347
|
+
// ========================================================================
|
|
10348
|
+
/**
|
|
10349
|
+
* Register a tool category.
|
|
10350
|
+
* If the category already exists, updates its metadata.
|
|
10351
|
+
* @throws Error if name is empty or whitespace
|
|
10352
|
+
*/
|
|
10353
|
+
static registerCategory(def) {
|
|
10354
|
+
if (!def.name || !def.name.trim()) {
|
|
10355
|
+
throw new Error("[ToolCatalogRegistry] Category name cannot be empty");
|
|
10356
|
+
}
|
|
10357
|
+
this._categories.set(def.name, def);
|
|
10358
|
+
if (!this._tools.has(def.name)) {
|
|
10359
|
+
this._tools.set(def.name, []);
|
|
10360
|
+
}
|
|
10361
|
+
}
|
|
10362
|
+
/**
|
|
10363
|
+
* Register multiple tools in a category.
|
|
10364
|
+
* The category is auto-created if it doesn't exist (with a generic description).
|
|
10365
|
+
* @throws Error if category name is empty or whitespace
|
|
10366
|
+
*/
|
|
10367
|
+
static registerTools(category, tools) {
|
|
10368
|
+
if (!category || !category.trim()) {
|
|
10369
|
+
throw new Error("[ToolCatalogRegistry] Category name cannot be empty");
|
|
10370
|
+
}
|
|
10371
|
+
if (!this._categories.has(category)) {
|
|
10372
|
+
this._categories.set(category, {
|
|
10373
|
+
name: category,
|
|
10374
|
+
displayName: this.toDisplayName(category),
|
|
10375
|
+
description: this.BUILTIN_DESCRIPTIONS[category] ?? `Tools in the ${category} category`
|
|
10376
|
+
});
|
|
10377
|
+
}
|
|
10378
|
+
const existing = this._tools.get(category) ?? [];
|
|
10379
|
+
const existingNames = new Set(existing.map((t) => t.name));
|
|
10380
|
+
const newTools = tools.filter((t) => !existingNames.has(t.name));
|
|
10381
|
+
const updated = existing.map((t) => {
|
|
10382
|
+
const replacement = tools.find((nt) => nt.name === t.name);
|
|
10383
|
+
return replacement ?? t;
|
|
10384
|
+
});
|
|
10385
|
+
this._tools.set(category, [...updated, ...newTools]);
|
|
10386
|
+
}
|
|
10387
|
+
/**
|
|
10388
|
+
* Register a single tool in a category.
|
|
10389
|
+
*/
|
|
10390
|
+
static registerTool(category, tool) {
|
|
10391
|
+
this.registerTools(category, [tool]);
|
|
10392
|
+
}
|
|
10393
|
+
/**
|
|
10394
|
+
* Unregister a category and all its tools.
|
|
10395
|
+
*/
|
|
10396
|
+
static unregisterCategory(category) {
|
|
10397
|
+
const hadCategory = this._categories.delete(category);
|
|
10398
|
+
this._tools.delete(category);
|
|
10399
|
+
return hadCategory;
|
|
10400
|
+
}
|
|
10401
|
+
/**
|
|
10402
|
+
* Unregister a single tool from a category.
|
|
10403
|
+
*/
|
|
10404
|
+
static unregisterTool(category, toolName) {
|
|
10405
|
+
const tools = this._tools.get(category);
|
|
10406
|
+
if (!tools) return false;
|
|
10407
|
+
const idx = tools.findIndex((t) => t.name === toolName);
|
|
10408
|
+
if (idx === -1) return false;
|
|
10409
|
+
tools.splice(idx, 1);
|
|
10410
|
+
return true;
|
|
10411
|
+
}
|
|
10412
|
+
// ========================================================================
|
|
10413
|
+
// Query
|
|
10414
|
+
// ========================================================================
|
|
10415
|
+
/**
|
|
10416
|
+
* Get all registered categories.
|
|
10417
|
+
*/
|
|
10418
|
+
static getCategories() {
|
|
10419
|
+
this.ensureInitialized();
|
|
10420
|
+
return Array.from(this._categories.values());
|
|
10421
|
+
}
|
|
10422
|
+
/**
|
|
10423
|
+
* Get a single category by name.
|
|
10424
|
+
*/
|
|
10425
|
+
static getCategory(name) {
|
|
10426
|
+
this.ensureInitialized();
|
|
10427
|
+
return this._categories.get(name);
|
|
10428
|
+
}
|
|
10429
|
+
/**
|
|
10430
|
+
* Check if a category exists.
|
|
10431
|
+
*/
|
|
10432
|
+
static hasCategory(name) {
|
|
10433
|
+
this.ensureInitialized();
|
|
10434
|
+
return this._categories.has(name);
|
|
10435
|
+
}
|
|
10436
|
+
/**
|
|
10437
|
+
* Get all tools in a category.
|
|
10438
|
+
*/
|
|
10439
|
+
static getToolsInCategory(category) {
|
|
10440
|
+
this.ensureInitialized();
|
|
10441
|
+
return this._tools.get(category) ?? [];
|
|
10442
|
+
}
|
|
10443
|
+
/**
|
|
10444
|
+
* Get all catalog tools across all categories.
|
|
10445
|
+
*/
|
|
10446
|
+
static getAllCatalogTools() {
|
|
10447
|
+
this.ensureInitialized();
|
|
10448
|
+
const all = [];
|
|
10449
|
+
for (const tools of this._tools.values()) {
|
|
10450
|
+
all.push(...tools);
|
|
10451
|
+
}
|
|
10452
|
+
return all;
|
|
10453
|
+
}
|
|
10454
|
+
/**
|
|
10455
|
+
* Find a tool by name across all categories.
|
|
10456
|
+
*/
|
|
10457
|
+
static findTool(name) {
|
|
10458
|
+
this.ensureInitialized();
|
|
10459
|
+
for (const [category, tools] of this._tools) {
|
|
10460
|
+
const entry = tools.find((t) => t.name === name);
|
|
10461
|
+
if (entry) return { category, entry };
|
|
10462
|
+
}
|
|
10463
|
+
return void 0;
|
|
10464
|
+
}
|
|
10465
|
+
// ========================================================================
|
|
10466
|
+
// Filtering
|
|
10467
|
+
// ========================================================================
|
|
10468
|
+
/**
|
|
10469
|
+
* Filter categories by scope.
|
|
10470
|
+
*/
|
|
10471
|
+
static filterCategories(scope) {
|
|
10472
|
+
const all = this.getCategories();
|
|
10473
|
+
if (!scope) return all;
|
|
10474
|
+
return all.filter((cat) => this.isCategoryAllowed(cat.name, scope));
|
|
10475
|
+
}
|
|
10476
|
+
/**
|
|
10477
|
+
* Check if a category is allowed by a scope.
|
|
10478
|
+
*/
|
|
10479
|
+
static isCategoryAllowed(name, scope) {
|
|
10480
|
+
if (!scope) return true;
|
|
10481
|
+
if (Array.isArray(scope)) {
|
|
10482
|
+
return scope.includes(name);
|
|
10483
|
+
}
|
|
10484
|
+
if ("include" in scope) {
|
|
10485
|
+
return scope.include.includes(name);
|
|
10486
|
+
}
|
|
10487
|
+
if ("exclude" in scope) {
|
|
10488
|
+
return !scope.exclude.includes(name);
|
|
10489
|
+
}
|
|
10490
|
+
return true;
|
|
10491
|
+
}
|
|
10492
|
+
// ========================================================================
|
|
10493
|
+
// Connector Discovery
|
|
10494
|
+
// ========================================================================
|
|
10495
|
+
/**
|
|
10496
|
+
* Discover all connector categories with their tools.
|
|
10497
|
+
* Calls ConnectorTools.discoverAll() and filters by scope/identities.
|
|
10498
|
+
*
|
|
10499
|
+
* @param options - Optional filtering
|
|
10500
|
+
* @returns Array of connector category info
|
|
10501
|
+
*/
|
|
10502
|
+
static discoverConnectorCategories(options) {
|
|
10503
|
+
const mod = this.getConnectorToolsModule();
|
|
10504
|
+
if (!mod) return [];
|
|
10505
|
+
try {
|
|
10506
|
+
const discovered = mod.ConnectorTools.discoverAll();
|
|
10507
|
+
const results = [];
|
|
10508
|
+
for (const [connectorName, tools] of discovered) {
|
|
10509
|
+
const catName = `connector:${connectorName}`;
|
|
10510
|
+
if (options?.scope && !this.isCategoryAllowed(catName, options.scope)) {
|
|
10511
|
+
continue;
|
|
10512
|
+
}
|
|
10513
|
+
if (options?.identities?.length) {
|
|
10514
|
+
const hasIdentity = options.identities.some((id) => id.connector === connectorName);
|
|
10515
|
+
if (!hasIdentity) continue;
|
|
10516
|
+
}
|
|
10517
|
+
const preRegistered = this.getCategory(catName);
|
|
10518
|
+
results.push({
|
|
10519
|
+
name: catName,
|
|
10520
|
+
displayName: preRegistered?.displayName ?? this.toDisplayName(connectorName),
|
|
10521
|
+
description: preRegistered?.description ?? `API tools for ${connectorName}`,
|
|
10522
|
+
toolCount: tools.length,
|
|
10523
|
+
tools
|
|
10524
|
+
});
|
|
10525
|
+
}
|
|
10526
|
+
return results;
|
|
10527
|
+
} catch {
|
|
10528
|
+
return [];
|
|
10529
|
+
}
|
|
10530
|
+
}
|
|
10531
|
+
/**
|
|
10532
|
+
* Resolve tools for a specific connector category.
|
|
10533
|
+
*
|
|
10534
|
+
* @param category - Category name in 'connector:<name>' format
|
|
10535
|
+
* @returns Array of resolved tools with names
|
|
10536
|
+
*/
|
|
10537
|
+
static resolveConnectorCategoryTools(category) {
|
|
10538
|
+
const connectorName = this.parseConnectorCategory(category);
|
|
10539
|
+
if (!connectorName) return [];
|
|
10540
|
+
const mod = this.getConnectorToolsModule();
|
|
10541
|
+
if (!mod) return [];
|
|
10542
|
+
try {
|
|
10543
|
+
const tools = mod.ConnectorTools.for(connectorName);
|
|
10544
|
+
return tools.map((t) => ({ tool: t, name: t.definition.function.name }));
|
|
10545
|
+
} catch {
|
|
10546
|
+
return [];
|
|
10547
|
+
}
|
|
10548
|
+
}
|
|
10549
|
+
// ========================================================================
|
|
10550
|
+
// Resolution
|
|
10551
|
+
// ========================================================================
|
|
10552
|
+
/**
|
|
10553
|
+
* Resolve tool names to ToolFunction[].
|
|
10554
|
+
*
|
|
10555
|
+
* Searches registered categories and (optionally) connector tools.
|
|
10556
|
+
* Used by app-level executors (e.g., V25's OneRingAgentExecutor).
|
|
10557
|
+
*
|
|
10558
|
+
* @param toolNames - Array of tool names to resolve
|
|
10559
|
+
* @param options - Resolution options
|
|
10560
|
+
* @returns Resolved tool functions (skips unresolvable names with warning)
|
|
10561
|
+
*/
|
|
10562
|
+
static resolveTools(toolNames, options) {
|
|
10563
|
+
this.ensureInitialized();
|
|
10564
|
+
const resolved = [];
|
|
10565
|
+
const missing = [];
|
|
10566
|
+
for (const name of toolNames) {
|
|
10567
|
+
const found = this.findTool(name);
|
|
10568
|
+
if (found) {
|
|
10569
|
+
const tool = this.resolveEntryTool(found.entry, options?.context);
|
|
10570
|
+
if (tool) {
|
|
10571
|
+
resolved.push(tool);
|
|
10572
|
+
continue;
|
|
10573
|
+
}
|
|
10574
|
+
}
|
|
10575
|
+
if (options?.includeConnectors) {
|
|
10576
|
+
const connectorTool = this.findConnectorTool(name);
|
|
10577
|
+
if (connectorTool) {
|
|
10578
|
+
resolved.push(connectorTool);
|
|
10579
|
+
continue;
|
|
10580
|
+
}
|
|
10581
|
+
}
|
|
10582
|
+
missing.push(name);
|
|
10583
|
+
}
|
|
10584
|
+
if (missing.length > 0) {
|
|
10585
|
+
exports.logger.warn(
|
|
10586
|
+
{ missing, resolved: resolved.length, total: toolNames.length },
|
|
10587
|
+
`[ToolCatalogRegistry.resolveTools] Could not resolve ${missing.length} tool(s): ${missing.join(", ")}`
|
|
10588
|
+
);
|
|
10589
|
+
}
|
|
10590
|
+
return resolved;
|
|
10591
|
+
}
|
|
10592
|
+
/**
|
|
10593
|
+
* Resolve tools grouped by connector name.
|
|
10594
|
+
*
|
|
10595
|
+
* Tools with a `connectorName` go into `byConnector`; all others go into `plain`.
|
|
10596
|
+
* Supports factory-based tool creation via `createTool` when context is provided.
|
|
10597
|
+
*
|
|
10598
|
+
* @param toolNames - Array of tool names to resolve
|
|
10599
|
+
* @param context - Optional context passed to createTool factories
|
|
10600
|
+
* @param options - Resolution options
|
|
10601
|
+
* @returns Grouped tools: plain + byConnector map
|
|
10602
|
+
*/
|
|
10603
|
+
static resolveToolsGrouped(toolNames, context, options) {
|
|
10604
|
+
this.ensureInitialized();
|
|
10605
|
+
const plain = [];
|
|
10606
|
+
const byConnector = /* @__PURE__ */ new Map();
|
|
10607
|
+
for (const name of toolNames) {
|
|
10608
|
+
const found = this.findTool(name);
|
|
10609
|
+
if (found) {
|
|
10610
|
+
const entry = found.entry;
|
|
10611
|
+
const tool = this.resolveEntryTool(entry, context);
|
|
10612
|
+
if (!tool) continue;
|
|
10613
|
+
if (entry.connectorName) {
|
|
10614
|
+
const list = byConnector.get(entry.connectorName) ?? [];
|
|
10615
|
+
list.push(tool);
|
|
10616
|
+
byConnector.set(entry.connectorName, list);
|
|
10617
|
+
} else {
|
|
10618
|
+
plain.push(tool);
|
|
10619
|
+
}
|
|
10620
|
+
continue;
|
|
10621
|
+
}
|
|
10622
|
+
if (options?.includeConnectors) {
|
|
10623
|
+
const connectorTool = this.findConnectorTool(name);
|
|
10624
|
+
if (connectorTool) {
|
|
10625
|
+
plain.push(connectorTool);
|
|
10626
|
+
continue;
|
|
10627
|
+
}
|
|
10628
|
+
}
|
|
10629
|
+
}
|
|
10630
|
+
return { plain, byConnector };
|
|
10631
|
+
}
|
|
10632
|
+
/**
|
|
10633
|
+
* Resolve a tool from a CatalogToolEntry, using factory if available.
|
|
10634
|
+
* Returns null if neither tool nor createTool is available.
|
|
10635
|
+
*/
|
|
10636
|
+
static resolveEntryTool(entry, context) {
|
|
10637
|
+
if (entry.createTool && context) {
|
|
10638
|
+
try {
|
|
10639
|
+
return entry.createTool(context);
|
|
10640
|
+
} catch (e) {
|
|
10641
|
+
exports.logger.warn(`[ToolCatalogRegistry] Factory failed for '${entry.name}': ${e}`);
|
|
10642
|
+
return null;
|
|
10643
|
+
}
|
|
10644
|
+
}
|
|
10645
|
+
return entry.tool ?? null;
|
|
10646
|
+
}
|
|
10647
|
+
/**
|
|
10648
|
+
* Search connector tools by name (uses lazy accessor).
|
|
10649
|
+
*/
|
|
10650
|
+
static findConnectorTool(name) {
|
|
10651
|
+
const mod = this.getConnectorToolsModule();
|
|
10652
|
+
if (!mod) return void 0;
|
|
10653
|
+
try {
|
|
10654
|
+
const allConnectorTools = mod.ConnectorTools.discoverAll();
|
|
10655
|
+
for (const [, tools] of allConnectorTools) {
|
|
10656
|
+
for (const tool of tools) {
|
|
10657
|
+
if (tool.definition.function.name === name) {
|
|
10658
|
+
return tool;
|
|
10659
|
+
}
|
|
10660
|
+
}
|
|
10661
|
+
}
|
|
10662
|
+
} catch {
|
|
10663
|
+
}
|
|
10664
|
+
return void 0;
|
|
10665
|
+
}
|
|
10666
|
+
// ========================================================================
|
|
10667
|
+
// Built-in initialization
|
|
10668
|
+
// ========================================================================
|
|
10669
|
+
/**
|
|
10670
|
+
* Ensure built-in tools from registry.generated.ts are registered.
|
|
10671
|
+
* Called lazily on first query.
|
|
10672
|
+
*
|
|
10673
|
+
* In ESM environments, call `initializeFromRegistry(toolRegistry)` explicitly
|
|
10674
|
+
* from your app startup instead of relying on auto-initialization.
|
|
10675
|
+
*/
|
|
10676
|
+
static ensureInitialized() {
|
|
10677
|
+
if (this._initialized) return;
|
|
10678
|
+
this._initialized = true;
|
|
10679
|
+
try {
|
|
10680
|
+
const mod = __require("../../tools/registry.generated.js");
|
|
10681
|
+
const registry = mod?.toolRegistry ?? mod?.default?.toolRegistry;
|
|
10682
|
+
if (Array.isArray(registry)) {
|
|
10683
|
+
this.registerFromToolRegistry(registry);
|
|
10684
|
+
}
|
|
10685
|
+
} catch {
|
|
10686
|
+
}
|
|
10687
|
+
}
|
|
10688
|
+
/**
|
|
10689
|
+
* Explicitly initialize from the generated tool registry.
|
|
10690
|
+
* Call this at app startup in ESM environments where lazy require() doesn't work.
|
|
10691
|
+
*
|
|
10692
|
+
* @example
|
|
10693
|
+
* ```typescript
|
|
10694
|
+
* import { toolRegistry } from './tools/registry.generated.js';
|
|
10695
|
+
* ToolCatalogRegistry.initializeFromRegistry(toolRegistry);
|
|
10696
|
+
* ```
|
|
10697
|
+
*/
|
|
10698
|
+
static initializeFromRegistry(registry) {
|
|
10699
|
+
this._initialized = true;
|
|
10700
|
+
this.registerFromToolRegistry(registry);
|
|
10701
|
+
}
|
|
10702
|
+
/**
|
|
10703
|
+
* Internal: register tools from a tool registry array.
|
|
10704
|
+
*/
|
|
10705
|
+
static registerFromToolRegistry(registry) {
|
|
10706
|
+
for (const entry of registry) {
|
|
10707
|
+
const category = entry.category;
|
|
10708
|
+
if (!this._categories.has(category)) {
|
|
10709
|
+
this.registerCategory({
|
|
10710
|
+
name: category,
|
|
10711
|
+
displayName: this.toDisplayName(category),
|
|
10712
|
+
description: this.BUILTIN_DESCRIPTIONS[category] ?? `Built-in ${category} tools`
|
|
10713
|
+
});
|
|
10714
|
+
}
|
|
10715
|
+
const catalogEntry = {
|
|
10716
|
+
tool: entry.tool,
|
|
10717
|
+
name: entry.name,
|
|
10718
|
+
displayName: entry.displayName,
|
|
10719
|
+
description: entry.description,
|
|
10720
|
+
safeByDefault: entry.safeByDefault,
|
|
10721
|
+
requiresConnector: entry.requiresConnector
|
|
10722
|
+
};
|
|
10723
|
+
const existing = this._tools.get(category) ?? [];
|
|
10724
|
+
if (!existing.some((t) => t.name === catalogEntry.name)) {
|
|
10725
|
+
existing.push(catalogEntry);
|
|
10726
|
+
this._tools.set(category, existing);
|
|
10727
|
+
}
|
|
10728
|
+
}
|
|
10729
|
+
}
|
|
10730
|
+
/**
|
|
10731
|
+
* Reset the registry. Primarily for testing.
|
|
10732
|
+
*/
|
|
10733
|
+
static reset() {
|
|
10734
|
+
this._categories.clear();
|
|
10735
|
+
this._tools.clear();
|
|
10736
|
+
this._initialized = false;
|
|
10737
|
+
this._connectorToolsModule = null;
|
|
10738
|
+
}
|
|
10739
|
+
};
|
|
10740
|
+
|
|
10289
10741
|
// src/core/BaseAgent.ts
|
|
10290
10742
|
init_Connector();
|
|
10291
10743
|
|
|
@@ -10323,6 +10775,14 @@ var DEFAULT_ALLOWLIST = [
|
|
|
10323
10775
|
"user_info_get",
|
|
10324
10776
|
"user_info_remove",
|
|
10325
10777
|
"user_info_clear",
|
|
10778
|
+
// TODO tools (user-specific data - safe)
|
|
10779
|
+
"todo_add",
|
|
10780
|
+
"todo_update",
|
|
10781
|
+
"todo_remove",
|
|
10782
|
+
// Tool catalog tools (browsing and loading — safe)
|
|
10783
|
+
"tool_catalog_search",
|
|
10784
|
+
"tool_catalog_load",
|
|
10785
|
+
"tool_catalog_unload",
|
|
10326
10786
|
// Meta-tools (internal coordination)
|
|
10327
10787
|
"_start_planning",
|
|
10328
10788
|
"_modify_plan",
|
|
@@ -11637,6 +12097,17 @@ var ToolManager = class extends eventemitter3.EventEmitter {
|
|
|
11637
12097
|
if (!toolNames) return [];
|
|
11638
12098
|
return Array.from(toolNames).map((name) => this.registry.get(name)).filter((reg) => reg.enabled).sort((a, b) => b.priority - a.priority).map((reg) => reg.tool);
|
|
11639
12099
|
}
|
|
12100
|
+
/**
|
|
12101
|
+
* Get all registered tool names in a category.
|
|
12102
|
+
* Used by ToolCatalogPlugin for bulk enable/disable.
|
|
12103
|
+
*/
|
|
12104
|
+
getByCategory(category) {
|
|
12105
|
+
const names = [];
|
|
12106
|
+
for (const [name, reg] of this.registry) {
|
|
12107
|
+
if (reg.category === category) names.push(name);
|
|
12108
|
+
}
|
|
12109
|
+
return names;
|
|
12110
|
+
}
|
|
11640
12111
|
/**
|
|
11641
12112
|
* Get tool registration info
|
|
11642
12113
|
*/
|
|
@@ -15802,7 +16273,35 @@ User info is automatically shown in context \u2014 no need to call user_info_get
|
|
|
15802
16273
|
|
|
15803
16274
|
**Important:** Do not store sensitive information (passwords, tokens, PII) in user info. It is not encrypted and may be accessible to other parts of the system. Always follow best practices for security.
|
|
15804
16275
|
|
|
15805
|
-
**Rules after each user message:** If the user provides new information about themselves, update user info accordingly. If they ask to change or remove existing information, do that as well. Always keep user info up to date with the latest information provided by the user. Learn about the user proactively
|
|
16276
|
+
**Rules after each user message:** If the user provides new information about themselves, update user info accordingly. If they ask to change or remove existing information, do that as well. Always keep user info up to date with the latest information provided by the user. Learn about the user proactively!
|
|
16277
|
+
|
|
16278
|
+
## TODO Management
|
|
16279
|
+
|
|
16280
|
+
TODOs are stored alongside user info and shown in a separate "Current TODOs" section in context.
|
|
16281
|
+
|
|
16282
|
+
**Tools:**
|
|
16283
|
+
- \`todo_add(title, description?, people?, dueDate?, tags?)\`: Create a new TODO item
|
|
16284
|
+
- \`todo_update(id, title?, description?, people?, dueDate?, tags?, status?)\`: Update an existing TODO
|
|
16285
|
+
- \`todo_remove(id)\`: Delete a TODO item
|
|
16286
|
+
|
|
16287
|
+
**Proactive creation \u2014 be helpful:**
|
|
16288
|
+
- If the user's message implies an action item, task, or deadline \u2192 ask "Would you like me to create a TODO for this?"
|
|
16289
|
+
- If the user explicitly says "remind me", "track this", "don't forget" \u2192 create a TODO immediately without asking.
|
|
16290
|
+
- When discussing plans with deadlines or deliverables \u2192 suggest relevant TODOs.
|
|
16291
|
+
- When the user mentions other people involved \u2192 include them in the \`people\` field.
|
|
16292
|
+
- Suggest appropriate tags based on context (e.g. "work", "personal", "urgent").
|
|
16293
|
+
|
|
16294
|
+
**Reminder rules:**
|
|
16295
|
+
- Check the \`_todo_last_reminded\` entry in user info. If its value is NOT today's date (YYYY-MM-DD) AND there are overdue or soon-due items (within 2 days), proactively remind the user ONCE at the start of the conversation, then set \`_todo_last_reminded\` to today's date via \`user_info_set\`.
|
|
16296
|
+
- Do NOT remind again in the same day unless the user explicitly asks about their TODOs.
|
|
16297
|
+
- When reminding, prioritize: overdue items first, then items due today, then items due tomorrow.
|
|
16298
|
+
- If the user asks about their TODOs or schedule, always answer regardless of reminder status.
|
|
16299
|
+
- After completing a TODO, mark it as done via \`todo_update(id, status: 'done')\`. Suggest marking items done when context indicates completion.
|
|
16300
|
+
|
|
16301
|
+
**Cleanup rules:**
|
|
16302
|
+
- Completed TODOs older than 48 hours (check updatedAt of done items) \u2192 auto-delete via \`todo_remove\` without asking.
|
|
16303
|
+
- Overdue pending TODOs (past due > 7 days) \u2192 ask the user: "This TODO is overdue by X days \u2014 still relevant or should I remove it?"
|
|
16304
|
+
- Run cleanup checks at the same time as reminders (once per day, using \`_todo_last_reminded\` marker).`;
|
|
15806
16305
|
var userInfoSetDefinition = {
|
|
15807
16306
|
type: "function",
|
|
15808
16307
|
function: {
|
|
@@ -15879,6 +16378,102 @@ var userInfoClearDefinition = {
|
|
|
15879
16378
|
}
|
|
15880
16379
|
}
|
|
15881
16380
|
};
|
|
16381
|
+
var todoAddDefinition = {
|
|
16382
|
+
type: "function",
|
|
16383
|
+
function: {
|
|
16384
|
+
name: "todo_add",
|
|
16385
|
+
description: "Create a new TODO item for the user. Returns the generated todo ID.",
|
|
16386
|
+
parameters: {
|
|
16387
|
+
type: "object",
|
|
16388
|
+
properties: {
|
|
16389
|
+
title: {
|
|
16390
|
+
type: "string",
|
|
16391
|
+
description: "Short title for the TODO (required)"
|
|
16392
|
+
},
|
|
16393
|
+
description: {
|
|
16394
|
+
type: "string",
|
|
16395
|
+
description: "Optional detailed description"
|
|
16396
|
+
},
|
|
16397
|
+
people: {
|
|
16398
|
+
type: "array",
|
|
16399
|
+
items: { type: "string" },
|
|
16400
|
+
description: "People involved besides the current user (optional)"
|
|
16401
|
+
},
|
|
16402
|
+
dueDate: {
|
|
16403
|
+
type: "string",
|
|
16404
|
+
description: "Due date in ISO format YYYY-MM-DD (optional)"
|
|
16405
|
+
},
|
|
16406
|
+
tags: {
|
|
16407
|
+
type: "array",
|
|
16408
|
+
items: { type: "string" },
|
|
16409
|
+
description: 'Categorization tags (optional, e.g. "work", "personal", "urgent")'
|
|
16410
|
+
}
|
|
16411
|
+
},
|
|
16412
|
+
required: ["title"]
|
|
16413
|
+
}
|
|
16414
|
+
}
|
|
16415
|
+
};
|
|
16416
|
+
var todoUpdateDefinition = {
|
|
16417
|
+
type: "function",
|
|
16418
|
+
function: {
|
|
16419
|
+
name: "todo_update",
|
|
16420
|
+
description: "Update an existing TODO item. Only provided fields are changed.",
|
|
16421
|
+
parameters: {
|
|
16422
|
+
type: "object",
|
|
16423
|
+
properties: {
|
|
16424
|
+
id: {
|
|
16425
|
+
type: "string",
|
|
16426
|
+
description: 'The todo ID (e.g. "todo_a1b2c3")'
|
|
16427
|
+
},
|
|
16428
|
+
title: {
|
|
16429
|
+
type: "string",
|
|
16430
|
+
description: "New title"
|
|
16431
|
+
},
|
|
16432
|
+
description: {
|
|
16433
|
+
type: "string",
|
|
16434
|
+
description: "New description (pass empty string to clear)"
|
|
16435
|
+
},
|
|
16436
|
+
people: {
|
|
16437
|
+
type: "array",
|
|
16438
|
+
items: { type: "string" },
|
|
16439
|
+
description: "New people list (replaces existing)"
|
|
16440
|
+
},
|
|
16441
|
+
dueDate: {
|
|
16442
|
+
type: "string",
|
|
16443
|
+
description: "New due date in ISO format YYYY-MM-DD (pass empty string to clear)"
|
|
16444
|
+
},
|
|
16445
|
+
tags: {
|
|
16446
|
+
type: "array",
|
|
16447
|
+
items: { type: "string" },
|
|
16448
|
+
description: "New tags list (replaces existing)"
|
|
16449
|
+
},
|
|
16450
|
+
status: {
|
|
16451
|
+
type: "string",
|
|
16452
|
+
enum: ["pending", "done"],
|
|
16453
|
+
description: "New status"
|
|
16454
|
+
}
|
|
16455
|
+
},
|
|
16456
|
+
required: ["id"]
|
|
16457
|
+
}
|
|
16458
|
+
}
|
|
16459
|
+
};
|
|
16460
|
+
var todoRemoveDefinition = {
|
|
16461
|
+
type: "function",
|
|
16462
|
+
function: {
|
|
16463
|
+
name: "todo_remove",
|
|
16464
|
+
description: "Delete a TODO item.",
|
|
16465
|
+
parameters: {
|
|
16466
|
+
type: "object",
|
|
16467
|
+
properties: {
|
|
16468
|
+
id: {
|
|
16469
|
+
type: "string",
|
|
16470
|
+
description: 'The todo ID to remove (e.g. "todo_a1b2c3")'
|
|
16471
|
+
}
|
|
16472
|
+
},
|
|
16473
|
+
required: ["id"]
|
|
16474
|
+
}
|
|
16475
|
+
}
|
|
16476
|
+
};
|
|
15882
16477
|
function validateKey2(key) {
|
|
15883
16478
|
if (typeof key !== "string") return "Key must be a string";
|
|
15884
16479
|
const trimmed = key.trim();
|
|
@@ -15902,6 +16497,37 @@ function buildStorageContext(toolContext) {
|
|
|
15902
16497
|
if (toolContext?.userId) return { userId: toolContext.userId };
|
|
15903
16498
|
return void 0;
|
|
15904
16499
|
}
|
|
16500
|
+
var TODO_KEY_PREFIX = "todo_";
|
|
16501
|
+
var INTERNAL_KEY_PREFIX = "_";
|
|
16502
|
+
function isTodoEntry(entry) {
|
|
16503
|
+
return entry.id.startsWith(TODO_KEY_PREFIX);
|
|
16504
|
+
}
|
|
16505
|
+
function isInternalEntry(entry) {
|
|
16506
|
+
return entry.id.startsWith(INTERNAL_KEY_PREFIX);
|
|
16507
|
+
}
|
|
16508
|
+
function generateTodoId() {
|
|
16509
|
+
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
16510
|
+
let id = "";
|
|
16511
|
+
for (let i = 0; i < 6; i++) {
|
|
16512
|
+
id += chars[Math.floor(Math.random() * chars.length)];
|
|
16513
|
+
}
|
|
16514
|
+
return `${TODO_KEY_PREFIX}${id}`;
|
|
16515
|
+
}
|
|
16516
|
+
function renderTodoEntry(entry) {
|
|
16517
|
+
const val = entry.value;
|
|
16518
|
+
const checkbox = val.status === "done" ? "[x]" : "[ ]";
|
|
16519
|
+
const parts = [];
|
|
16520
|
+
if (val.dueDate) parts.push(`due: ${val.dueDate}`);
|
|
16521
|
+
if (val.people && val.people.length > 0) parts.push(`people: ${val.people.join(", ")}`);
|
|
16522
|
+
const meta = parts.length > 0 ? ` (${parts.join(", ")})` : "";
|
|
16523
|
+
const tags = val.tags && val.tags.length > 0 ? ` [${val.tags.join(", ")}]` : "";
|
|
16524
|
+
let line = `- ${checkbox} ${entry.id}: ${val.title}${meta}${tags}`;
|
|
16525
|
+
if (val.description) {
|
|
16526
|
+
line += `
|
|
16527
|
+
${val.description}`;
|
|
16528
|
+
}
|
|
16529
|
+
return line;
|
|
16530
|
+
}
|
|
15905
16531
|
function formatValue(value) {
|
|
15906
16532
|
if (value === null) return "null";
|
|
15907
16533
|
if (typeof value === "string") return value;
|
|
@@ -15969,7 +16595,10 @@ var UserInfoPluginNextGen = class {
|
|
|
15969
16595
|
this.createUserInfoSetTool(),
|
|
15970
16596
|
this.createUserInfoGetTool(),
|
|
15971
16597
|
this.createUserInfoRemoveTool(),
|
|
15972
|
-
this.createUserInfoClearTool()
|
|
16598
|
+
this.createUserInfoClearTool(),
|
|
16599
|
+
this.createTodoAddTool(),
|
|
16600
|
+
this.createTodoUpdateTool(),
|
|
16601
|
+
this.createTodoRemoveTool()
|
|
15973
16602
|
];
|
|
15974
16603
|
}
|
|
15975
16604
|
destroy() {
|
|
@@ -16040,9 +16669,38 @@ var UserInfoPluginNextGen = class {
|
|
|
16040
16669
|
* Render entries as markdown for context injection
|
|
16041
16670
|
*/
|
|
16042
16671
|
renderContent() {
|
|
16043
|
-
const
|
|
16044
|
-
|
|
16045
|
-
|
|
16672
|
+
const userEntries = [];
|
|
16673
|
+
const todoEntries = [];
|
|
16674
|
+
for (const entry of this._entries.values()) {
|
|
16675
|
+
if (isTodoEntry(entry)) {
|
|
16676
|
+
todoEntries.push(entry);
|
|
16677
|
+
} else if (!isInternalEntry(entry)) {
|
|
16678
|
+
userEntries.push(entry);
|
|
16679
|
+
}
|
|
16680
|
+
}
|
|
16681
|
+
const sections = [];
|
|
16682
|
+
if (userEntries.length > 0) {
|
|
16683
|
+
userEntries.sort((a, b) => a.createdAt - b.createdAt);
|
|
16684
|
+
sections.push(
|
|
16685
|
+
userEntries.map((entry) => `### ${entry.id}
|
|
16686
|
+
${formatValue(entry.value)}`).join("\n\n")
|
|
16687
|
+
);
|
|
16688
|
+
}
|
|
16689
|
+
if (todoEntries.length > 0) {
|
|
16690
|
+
todoEntries.sort((a, b) => {
|
|
16691
|
+
const aVal = a.value;
|
|
16692
|
+
const bVal = b.value;
|
|
16693
|
+
if (aVal.status !== bVal.status) return aVal.status === "pending" ? -1 : 1;
|
|
16694
|
+
if (aVal.dueDate && bVal.dueDate) return aVal.dueDate.localeCompare(bVal.dueDate);
|
|
16695
|
+
if (aVal.dueDate) return -1;
|
|
16696
|
+
if (bVal.dueDate) return 1;
|
|
16697
|
+
return a.createdAt - b.createdAt;
|
|
16698
|
+
});
|
|
16699
|
+
sections.push(
|
|
16700
|
+
"## Current TODOs\n" + todoEntries.map(renderTodoEntry).join("\n")
|
|
16701
|
+
);
|
|
16702
|
+
}
|
|
16703
|
+
return sections.join("\n\n");
|
|
16046
16704
|
}
|
|
16047
16705
|
/**
|
|
16048
16706
|
* Resolve storage instance (lazy singleton)
|
|
@@ -16223,6 +16881,619 @@ ${formatValue(entry.value)}`).join("\n\n");
|
|
|
16223
16881
|
describeCall: () => "clear user info"
|
|
16224
16882
|
};
|
|
16225
16883
|
}
|
|
16884
|
+
// ============================================================================
|
|
16885
|
+
// TODO Tool Factories
|
|
16886
|
+
// ============================================================================
|
|
16887
|
+
createTodoAddTool() {
|
|
16888
|
+
return {
|
|
16889
|
+
definition: todoAddDefinition,
|
|
16890
|
+
execute: async (args, context) => {
|
|
16891
|
+
this.assertNotDestroyed();
|
|
16892
|
+
await this.ensureInitialized();
|
|
16893
|
+
const userId = context?.userId ?? this.userId;
|
|
16894
|
+
const title = args.title;
|
|
16895
|
+
if (!title || typeof title !== "string" || title.trim().length === 0) {
|
|
16896
|
+
return { error: "Title is required" };
|
|
16897
|
+
}
|
|
16898
|
+
if (this._entries.size >= this.maxEntries) {
|
|
16899
|
+
return { error: `Maximum number of entries reached (${this.maxEntries})` };
|
|
16900
|
+
}
|
|
16901
|
+
let todoId = generateTodoId();
|
|
16902
|
+
while (this._entries.has(todoId)) {
|
|
16903
|
+
todoId = generateTodoId();
|
|
16904
|
+
}
|
|
16905
|
+
const todoValue = {
|
|
16906
|
+
type: "todo",
|
|
16907
|
+
title: title.trim(),
|
|
16908
|
+
description: args.description ? String(args.description).trim() : void 0,
|
|
16909
|
+
people: Array.isArray(args.people) ? args.people.filter((p) => typeof p === "string") : void 0,
|
|
16910
|
+
dueDate: typeof args.dueDate === "string" && args.dueDate.trim() ? args.dueDate.trim() : void 0,
|
|
16911
|
+
tags: Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string") : void 0,
|
|
16912
|
+
status: "pending"
|
|
16913
|
+
};
|
|
16914
|
+
const valueSize = calculateValueSize(todoValue);
|
|
16915
|
+
let currentTotal = 0;
|
|
16916
|
+
for (const e of this._entries.values()) {
|
|
16917
|
+
currentTotal += calculateValueSize(e.value);
|
|
16918
|
+
}
|
|
16919
|
+
if (currentTotal + valueSize > this.maxTotalSize) {
|
|
16920
|
+
return { error: `Total size would exceed maximum (${this.maxTotalSize} bytes)` };
|
|
16921
|
+
}
|
|
16922
|
+
const now = Date.now();
|
|
16923
|
+
const entry = {
|
|
16924
|
+
id: todoId,
|
|
16925
|
+
value: todoValue,
|
|
16926
|
+
valueType: "object",
|
|
16927
|
+
description: title.trim(),
|
|
16928
|
+
createdAt: now,
|
|
16929
|
+
updatedAt: now
|
|
16930
|
+
};
|
|
16931
|
+
this._entries.set(todoId, entry);
|
|
16932
|
+
this._tokenCache = null;
|
|
16933
|
+
await this.persistToStorage(userId);
|
|
16934
|
+
return {
|
|
16935
|
+
success: true,
|
|
16936
|
+
message: `TODO '${title.trim()}' created`,
|
|
16937
|
+
id: todoId,
|
|
16938
|
+
todo: todoValue
|
|
16939
|
+
};
|
|
16940
|
+
},
|
|
16941
|
+
permission: { scope: "always", riskLevel: "low" },
|
|
16942
|
+
describeCall: (args) => `add todo '${args.title}'`
|
|
16943
|
+
};
|
|
16944
|
+
}
|
|
16945
|
+
createTodoUpdateTool() {
|
|
16946
|
+
return {
|
|
16947
|
+
definition: todoUpdateDefinition,
|
|
16948
|
+
execute: async (args, context) => {
|
|
16949
|
+
this.assertNotDestroyed();
|
|
16950
|
+
await this.ensureInitialized();
|
|
16951
|
+
const userId = context?.userId ?? this.userId;
|
|
16952
|
+
const id = args.id;
|
|
16953
|
+
if (!id || typeof id !== "string") {
|
|
16954
|
+
return { error: "Todo ID is required" };
|
|
16955
|
+
}
|
|
16956
|
+
const entry = this._entries.get(id);
|
|
16957
|
+
if (!entry || !isTodoEntry(entry)) {
|
|
16958
|
+
return { error: `TODO '${id}' not found` };
|
|
16959
|
+
}
|
|
16960
|
+
const currentValue = entry.value;
|
|
16961
|
+
const updatedValue = { ...currentValue };
|
|
16962
|
+
if (typeof args.title === "string" && args.title.trim()) {
|
|
16963
|
+
updatedValue.title = args.title.trim();
|
|
16964
|
+
}
|
|
16965
|
+
if (args.description !== void 0) {
|
|
16966
|
+
updatedValue.description = typeof args.description === "string" && args.description.trim() ? args.description.trim() : void 0;
|
|
16967
|
+
}
|
|
16968
|
+
if (args.people !== void 0) {
|
|
16969
|
+
updatedValue.people = Array.isArray(args.people) ? args.people.filter((p) => typeof p === "string") : void 0;
|
|
16970
|
+
}
|
|
16971
|
+
if (args.dueDate !== void 0) {
|
|
16972
|
+
updatedValue.dueDate = typeof args.dueDate === "string" && args.dueDate.trim() ? args.dueDate.trim() : void 0;
|
|
16973
|
+
}
|
|
16974
|
+
if (args.tags !== void 0) {
|
|
16975
|
+
updatedValue.tags = Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string") : void 0;
|
|
16976
|
+
}
|
|
16977
|
+
if (args.status === "pending" || args.status === "done") {
|
|
16978
|
+
updatedValue.status = args.status;
|
|
16979
|
+
}
|
|
16980
|
+
const valueSize = calculateValueSize(updatedValue);
|
|
16981
|
+
let currentTotal = 0;
|
|
16982
|
+
for (const e of this._entries.values()) {
|
|
16983
|
+
currentTotal += calculateValueSize(e.value);
|
|
16984
|
+
}
|
|
16985
|
+
const existingSize = calculateValueSize(currentValue);
|
|
16986
|
+
if (currentTotal - existingSize + valueSize > this.maxTotalSize) {
|
|
16987
|
+
return { error: `Total size would exceed maximum (${this.maxTotalSize} bytes)` };
|
|
16988
|
+
}
|
|
16989
|
+
const now = Date.now();
|
|
16990
|
+
const updatedEntry = {
|
|
16991
|
+
...entry,
|
|
16992
|
+
value: updatedValue,
|
|
16993
|
+
description: updatedValue.title,
|
|
16994
|
+
updatedAt: now
|
|
16995
|
+
};
|
|
16996
|
+
this._entries.set(id, updatedEntry);
|
|
16997
|
+
this._tokenCache = null;
|
|
16998
|
+
await this.persistToStorage(userId);
|
|
16999
|
+
return {
|
|
17000
|
+
success: true,
|
|
17001
|
+
message: `TODO '${id}' updated`,
|
|
17002
|
+
id,
|
|
17003
|
+
todo: updatedValue
|
|
17004
|
+
};
|
|
17005
|
+
},
|
|
17006
|
+
permission: { scope: "always", riskLevel: "low" },
|
|
17007
|
+
describeCall: (args) => `update todo '${args.id}'`
|
|
17008
|
+
};
|
|
17009
|
+
}
|
|
17010
|
+
createTodoRemoveTool() {
|
|
17011
|
+
return {
|
|
17012
|
+
definition: todoRemoveDefinition,
|
|
17013
|
+
execute: async (args, context) => {
|
|
17014
|
+
this.assertNotDestroyed();
|
|
17015
|
+
await this.ensureInitialized();
|
|
17016
|
+
const userId = context?.userId ?? this.userId;
|
|
17017
|
+
const id = args.id;
|
|
17018
|
+
if (!id || typeof id !== "string") {
|
|
17019
|
+
return { error: "Todo ID is required" };
|
|
17020
|
+
}
|
|
17021
|
+
const entry = this._entries.get(id);
|
|
17022
|
+
if (!entry || !isTodoEntry(entry)) {
|
|
17023
|
+
return { error: `TODO '${id}' not found` };
|
|
17024
|
+
}
|
|
17025
|
+
this._entries.delete(id);
|
|
17026
|
+
this._tokenCache = null;
|
|
17027
|
+
await this.persistToStorage(userId);
|
|
17028
|
+
return {
|
|
17029
|
+
success: true,
|
|
17030
|
+
message: `TODO '${id}' removed`,
|
|
17031
|
+
id
|
|
17032
|
+
};
|
|
17033
|
+
},
|
|
17034
|
+
permission: { scope: "always", riskLevel: "low" },
|
|
17035
|
+
describeCall: (args) => `remove todo '${args.id}'`
|
|
17036
|
+
};
|
|
17037
|
+
}
|
|
17038
|
+
};
|
|
17039
|
+
|
|
17040
|
+
// src/core/context-nextgen/plugins/ToolCatalogPluginNextGen.ts
|
|
17041
|
+
init_Logger();
|
|
17042
|
+
var DEFAULT_MAX_LOADED = 10;
|
|
17043
|
+
var TOOL_CATALOG_INSTRUCTIONS = `## Tool Catalog
|
|
17044
|
+
|
|
17045
|
+
You have access to a dynamic tool catalog. Not all tools are loaded at once \u2014 use these metatools to discover and load what you need:
|
|
17046
|
+
|
|
17047
|
+
**tool_catalog_search** \u2014 Browse available tool categories and search for specific tools.
|
|
17048
|
+
- No params \u2192 list all available categories with descriptions
|
|
17049
|
+
- \`category\` \u2192 list tools in that category
|
|
17050
|
+
- \`query\` \u2192 keyword search across categories and tools
|
|
17051
|
+
|
|
17052
|
+
**tool_catalog_load** \u2014 Load a category's tools so you can use them.
|
|
17053
|
+
- Tools become available immediately after loading.
|
|
17054
|
+
- If you need tools from a category, load it first.
|
|
17055
|
+
|
|
17056
|
+
**tool_catalog_unload** \u2014 Unload a category to free token budget.
|
|
17057
|
+
- Unloaded tools are no longer sent to you.
|
|
17058
|
+
- Use when you're done with a category.
|
|
17059
|
+
|
|
17060
|
+
**Best practices:**
|
|
17061
|
+
- Search first to find the right category before loading.
|
|
17062
|
+
- Unload categories you no longer need to keep context lean.
|
|
17063
|
+
- Categories marked [LOADED] are already available.`;
|
|
17064
|
+
var catalogSearchDefinition = {
|
|
17065
|
+
type: "function",
|
|
17066
|
+
function: {
|
|
17067
|
+
name: "tool_catalog_search",
|
|
17068
|
+
description: "Search the tool catalog. No params lists categories. Use category to list tools in it, or query to keyword-search.",
|
|
17069
|
+
parameters: {
|
|
17070
|
+
type: "object",
|
|
17071
|
+
properties: {
|
|
17072
|
+
query: {
|
|
17073
|
+
type: "string",
|
|
17074
|
+
description: "Keyword to search across category names, descriptions, and tool names"
|
|
17075
|
+
},
|
|
17076
|
+
category: {
|
|
17077
|
+
type: "string",
|
|
17078
|
+
description: "Category name to list its tools"
|
|
17079
|
+
}
|
|
17080
|
+
}
|
|
17081
|
+
}
|
|
17082
|
+
}
|
|
17083
|
+
};
|
|
17084
|
+
var catalogLoadDefinition = {
|
|
17085
|
+
type: "function",
|
|
17086
|
+
function: {
|
|
17087
|
+
name: "tool_catalog_load",
|
|
17088
|
+
description: "Load all tools from a category so they become available for use.",
|
|
17089
|
+
parameters: {
|
|
17090
|
+
type: "object",
|
|
17091
|
+
properties: {
|
|
17092
|
+
category: {
|
|
17093
|
+
type: "string",
|
|
17094
|
+
description: "Category name to load"
|
|
17095
|
+
}
|
|
17096
|
+
},
|
|
17097
|
+
required: ["category"]
|
|
17098
|
+
}
|
|
17099
|
+
}
|
|
17100
|
+
};
|
|
17101
|
+
var catalogUnloadDefinition = {
|
|
17102
|
+
type: "function",
|
|
17103
|
+
function: {
|
|
17104
|
+
name: "tool_catalog_unload",
|
|
17105
|
+
description: "Unload a category to free token budget. Tools from this category will no longer be available.",
|
|
17106
|
+
parameters: {
|
|
17107
|
+
type: "object",
|
|
17108
|
+
properties: {
|
|
17109
|
+
category: {
|
|
17110
|
+
type: "string",
|
|
17111
|
+
description: "Category name to unload"
|
|
17112
|
+
}
|
|
17113
|
+
},
|
|
17114
|
+
required: ["category"]
|
|
17115
|
+
}
|
|
17116
|
+
}
|
|
17117
|
+
};
|
|
17118
|
+
var ToolCatalogPluginNextGen = class extends BasePluginNextGen {
|
|
17119
|
+
name = "tool_catalog";
|
|
17120
|
+
/** category name → array of tool names that were loaded */
|
|
17121
|
+
_loadedCategories = /* @__PURE__ */ new Map();
|
|
17122
|
+
/** Reference to the ToolManager for registering/disabling tools */
|
|
17123
|
+
_toolManager = null;
|
|
17124
|
+
/** Cached connector categories — discovered once in setToolManager() */
|
|
17125
|
+
_connectorCategories = null;
|
|
17126
|
+
/** Whether this plugin has been destroyed */
|
|
17127
|
+
_destroyed = false;
|
|
17128
|
+
/** WeakMap cache for tool definition token estimates */
|
|
17129
|
+
_toolTokenCache = /* @__PURE__ */ new WeakMap();
|
|
17130
|
+
_config;
|
|
17131
|
+
constructor(config) {
|
|
17132
|
+
super();
|
|
17133
|
+
this._config = {
|
|
17134
|
+
maxLoadedCategories: DEFAULT_MAX_LOADED,
|
|
17135
|
+
...config
|
|
17136
|
+
};
|
|
17137
|
+
}
|
|
17138
|
+
// ========================================================================
|
|
17139
|
+
// Plugin Interface
|
|
17140
|
+
// ========================================================================
|
|
17141
|
+
getInstructions() {
|
|
17142
|
+
return TOOL_CATALOG_INSTRUCTIONS;
|
|
17143
|
+
}
|
|
17144
|
+
async getContent() {
|
|
17145
|
+
const categories = this.getAllowedCategories();
|
|
17146
|
+
if (categories.length === 0 && this.getConnectorCategories().length === 0) return null;
|
|
17147
|
+
const lines = ["## Tool Catalog"];
|
|
17148
|
+
lines.push("");
|
|
17149
|
+
const loaded = Array.from(this._loadedCategories.keys());
|
|
17150
|
+
if (loaded.length > 0) {
|
|
17151
|
+
lines.push(`**Loaded:** ${loaded.join(", ")}`);
|
|
17152
|
+
}
|
|
17153
|
+
lines.push(`**Available categories:** ${categories.length}`);
|
|
17154
|
+
for (const cat of categories) {
|
|
17155
|
+
const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
|
|
17156
|
+
const marker = this._loadedCategories.has(cat.name) ? " [LOADED]" : "";
|
|
17157
|
+
lines.push(`- **${cat.displayName}** (${tools.length} tools)${marker}: ${cat.description}`);
|
|
17158
|
+
}
|
|
17159
|
+
for (const cc of this.getConnectorCategories()) {
|
|
17160
|
+
const marker = this._loadedCategories.has(cc.name) ? " [LOADED]" : "";
|
|
17161
|
+
lines.push(`- **${cc.displayName}** (${cc.toolCount} tools)${marker}: ${cc.description}`);
|
|
17162
|
+
}
|
|
17163
|
+
const content = lines.join("\n");
|
|
17164
|
+
this.updateTokenCache(this.estimator.estimateTokens(content));
|
|
17165
|
+
return content;
|
|
17166
|
+
}
|
|
17167
|
+
getContents() {
|
|
17168
|
+
return {
|
|
17169
|
+
loadedCategories: Array.from(this._loadedCategories.entries()).map(([name, tools]) => ({
|
|
17170
|
+
category: name,
|
|
17171
|
+
toolCount: tools.length,
|
|
17172
|
+
tools
|
|
17173
|
+
}))
|
|
17174
|
+
};
|
|
17175
|
+
}
|
|
17176
|
+
getTools() {
|
|
17177
|
+
const plugin = this;
|
|
17178
|
+
const searchTool = {
|
|
17179
|
+
definition: catalogSearchDefinition,
|
|
17180
|
+
execute: async (args) => {
|
|
17181
|
+
return plugin.executeSearch(args.query, args.category);
|
|
17182
|
+
}
|
|
17183
|
+
};
|
|
17184
|
+
const loadTool = {
|
|
17185
|
+
definition: catalogLoadDefinition,
|
|
17186
|
+
execute: async (args) => {
|
|
17187
|
+
return plugin.executeLoad(args.category);
|
|
17188
|
+
}
|
|
17189
|
+
};
|
|
17190
|
+
const unloadTool = {
|
|
17191
|
+
definition: catalogUnloadDefinition,
|
|
17192
|
+
execute: async (args) => {
|
|
17193
|
+
return plugin.executeUnload(args.category);
|
|
17194
|
+
}
|
|
17195
|
+
};
|
|
17196
|
+
return [searchTool, loadTool, unloadTool];
|
|
17197
|
+
}
|
|
17198
|
+
isCompactable() {
|
|
17199
|
+
return this._loadedCategories.size > 0;
|
|
17200
|
+
}
|
|
17201
|
+
async compact(targetTokensToFree) {
|
|
17202
|
+
if (!this._toolManager || this._loadedCategories.size === 0) return 0;
|
|
17203
|
+
const categoriesByLastUsed = this.getCategoriesSortedByLastUsed();
|
|
17204
|
+
let freed = 0;
|
|
17205
|
+
for (const category of categoriesByLastUsed) {
|
|
17206
|
+
if (freed >= targetTokensToFree) break;
|
|
17207
|
+
const toolNames = this._loadedCategories.get(category);
|
|
17208
|
+
if (!toolNames) continue;
|
|
17209
|
+
const toolTokens = this.estimateToolDefinitionTokens(toolNames);
|
|
17210
|
+
this._toolManager.setEnabled(toolNames, false);
|
|
17211
|
+
this._loadedCategories.delete(category);
|
|
17212
|
+
freed += toolTokens;
|
|
17213
|
+
exports.logger.debug(
|
|
17214
|
+
{ category, toolCount: toolNames.length, freed: toolTokens },
|
|
17215
|
+
`[ToolCatalogPlugin] Compacted category '${category}'`
|
|
17216
|
+
);
|
|
17217
|
+
}
|
|
17218
|
+
this.invalidateTokenCache();
|
|
17219
|
+
return freed;
|
|
17220
|
+
}
|
|
17221
|
+
getState() {
|
|
17222
|
+
return {
|
|
17223
|
+
loadedCategories: Array.from(this._loadedCategories.keys())
|
|
17224
|
+
};
|
|
17225
|
+
}
|
|
17226
|
+
restoreState(state) {
|
|
17227
|
+
if (!state || typeof state !== "object") return;
|
|
17228
|
+
const s = state;
|
|
17229
|
+
if (!Array.isArray(s.loadedCategories) || s.loadedCategories.length === 0) return;
|
|
17230
|
+
for (const category of s.loadedCategories) {
|
|
17231
|
+
if (typeof category !== "string" || !category) continue;
|
|
17232
|
+
const result = this.executeLoad(category);
|
|
17233
|
+
if (result.error) {
|
|
17234
|
+
exports.logger.warn(
|
|
17235
|
+
{ category, error: result.error },
|
|
17236
|
+
`[ToolCatalogPlugin] Failed to restore category '${category}'`
|
|
17237
|
+
);
|
|
17238
|
+
}
|
|
17239
|
+
}
|
|
17240
|
+
this.invalidateTokenCache();
|
|
17241
|
+
}
|
|
17242
|
+
destroy() {
|
|
17243
|
+
this._loadedCategories.clear();
|
|
17244
|
+
this._toolManager = null;
|
|
17245
|
+
this._connectorCategories = null;
|
|
17246
|
+
this._destroyed = true;
|
|
17247
|
+
}
|
|
17248
|
+
// ========================================================================
|
|
17249
|
+
// Public API
|
|
17250
|
+
// ========================================================================
|
|
17251
|
+
/**
|
|
17252
|
+
* Set the ToolManager reference. Called by AgentContextNextGen after plugin registration.
|
|
17253
|
+
*/
|
|
17254
|
+
setToolManager(tm) {
|
|
17255
|
+
this._toolManager = tm;
|
|
17256
|
+
this._connectorCategories = ToolCatalogRegistry.discoverConnectorCategories({
|
|
17257
|
+
scope: this._config.categoryScope,
|
|
17258
|
+
identities: this._config.identities
|
|
17259
|
+
});
|
|
17260
|
+
if (this._config.autoLoadCategories?.length) {
|
|
17261
|
+
for (const category of this._config.autoLoadCategories) {
|
|
17262
|
+
const result = this.executeLoad(category);
|
|
17263
|
+
if (result.error) {
|
|
17264
|
+
exports.logger.warn(
|
|
17265
|
+
{ category, error: result.error },
|
|
17266
|
+
`[ToolCatalogPlugin] Failed to auto-load category '${category}'`
|
|
17267
|
+
);
|
|
17268
|
+
}
|
|
17269
|
+
}
|
|
17270
|
+
}
|
|
17271
|
+
}
|
|
17272
|
+
/** Get list of currently loaded category names */
|
|
17273
|
+
get loadedCategories() {
|
|
17274
|
+
return Array.from(this._loadedCategories.keys());
|
|
17275
|
+
}
|
|
17276
|
+
// ========================================================================
|
|
17277
|
+
// Metatool Implementations
|
|
17278
|
+
// ========================================================================
|
|
17279
|
+
executeSearch(query, category) {
|
|
17280
|
+
if (this._destroyed) return { error: "Plugin destroyed" };
|
|
17281
|
+
if (category) {
|
|
17282
|
+
if (ToolCatalogRegistry.parseConnectorCategory(category) !== null) {
|
|
17283
|
+
return this.searchConnectorCategory(category);
|
|
17284
|
+
}
|
|
17285
|
+
if (!ToolCatalogRegistry.hasCategory(category)) {
|
|
17286
|
+
return { error: `Category '${category}' not found. Use tool_catalog_search with no params to see available categories.` };
|
|
17287
|
+
}
|
|
17288
|
+
if (!ToolCatalogRegistry.isCategoryAllowed(category, this._config.categoryScope)) {
|
|
17289
|
+
return { error: `Category '${category}' is not available for this agent.` };
|
|
17290
|
+
}
|
|
17291
|
+
const tools = ToolCatalogRegistry.getToolsInCategory(category);
|
|
17292
|
+
const loaded = this._loadedCategories.has(category);
|
|
17293
|
+
return {
|
|
17294
|
+
category,
|
|
17295
|
+
loaded,
|
|
17296
|
+
tools: tools.map((t) => ({
|
|
17297
|
+
name: t.name,
|
|
17298
|
+
displayName: t.displayName,
|
|
17299
|
+
description: t.description,
|
|
17300
|
+
safeByDefault: t.safeByDefault
|
|
17301
|
+
}))
|
|
17302
|
+
};
|
|
17303
|
+
}
|
|
17304
|
+
if (query) {
|
|
17305
|
+
return this.keywordSearch(query);
|
|
17306
|
+
}
|
|
17307
|
+
const categories = this.getAllowedCategories();
|
|
17308
|
+
const connectorCats = this.getConnectorCategories();
|
|
17309
|
+
const result = [];
|
|
17310
|
+
for (const cat of categories) {
|
|
17311
|
+
const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
|
|
17312
|
+
result.push({
|
|
17313
|
+
name: cat.name,
|
|
17314
|
+
displayName: cat.displayName,
|
|
17315
|
+
description: cat.description,
|
|
17316
|
+
toolCount: tools.length,
|
|
17317
|
+
loaded: this._loadedCategories.has(cat.name)
|
|
17318
|
+
});
|
|
17319
|
+
}
|
|
17320
|
+
for (const cc of connectorCats) {
|
|
17321
|
+
result.push({
|
|
17322
|
+
name: cc.name,
|
|
17323
|
+
displayName: cc.displayName,
|
|
17324
|
+
description: cc.description,
|
|
17325
|
+
toolCount: cc.toolCount,
|
|
17326
|
+
loaded: this._loadedCategories.has(cc.name)
|
|
17327
|
+
});
|
|
17328
|
+
}
|
|
17329
|
+
return { categories: result };
|
|
17330
|
+
}
|
|
17331
|
+
executeLoad(category) {
|
|
17332
|
+
if (this._destroyed) return { error: "Plugin destroyed" };
|
|
17333
|
+
if (!this._toolManager) {
|
|
17334
|
+
return { error: "ToolManager not connected. Plugin not properly initialized." };
|
|
17335
|
+
}
|
|
17336
|
+
if (!ToolCatalogRegistry.isCategoryAllowed(category, this._config.categoryScope)) {
|
|
17337
|
+
return { error: `Category '${category}' is not available for this agent.` };
|
|
17338
|
+
}
|
|
17339
|
+
if (this._loadedCategories.has(category)) {
|
|
17340
|
+
const toolNames2 = this._loadedCategories.get(category);
|
|
17341
|
+
return { loaded: toolNames2.length, tools: toolNames2, alreadyLoaded: true };
|
|
17342
|
+
}
|
|
17343
|
+
if (this._loadedCategories.size >= this._config.maxLoadedCategories) {
|
|
17344
|
+
return {
|
|
17345
|
+
error: `Maximum loaded categories (${this._config.maxLoadedCategories}) reached. Unload a category first.`,
|
|
17346
|
+
loaded: Array.from(this._loadedCategories.keys())
|
|
17347
|
+
};
|
|
17348
|
+
}
|
|
17349
|
+
const isConnector = ToolCatalogRegistry.parseConnectorCategory(category) !== null;
|
|
17350
|
+
let tools;
|
|
17351
|
+
if (isConnector) {
|
|
17352
|
+
tools = ToolCatalogRegistry.resolveConnectorCategoryTools(category);
|
|
17353
|
+
} else {
|
|
17354
|
+
const entries = ToolCatalogRegistry.getToolsInCategory(category);
|
|
17355
|
+
if (entries.length === 0) {
|
|
17356
|
+
return { error: `Category '${category}' has no tools or does not exist.` };
|
|
17357
|
+
}
|
|
17358
|
+
tools = entries.filter((e) => e.tool != null).map((e) => ({ tool: e.tool, name: e.name }));
|
|
17359
|
+
}
|
|
17360
|
+
if (tools.length === 0) {
|
|
17361
|
+
return { error: `No tools found for category '${category}'.` };
|
|
17362
|
+
}
|
|
17363
|
+
const toolNames = [];
|
|
17364
|
+
for (const { tool, name } of tools) {
|
|
17365
|
+
const existing = this._toolManager.getRegistration(name);
|
|
17366
|
+
if (existing) {
|
|
17367
|
+
this._toolManager.setEnabled([name], true);
|
|
17368
|
+
} else {
|
|
17369
|
+
this._toolManager.register(tool, { category, source: `catalog:${category}` });
|
|
17370
|
+
}
|
|
17371
|
+
toolNames.push(name);
|
|
17372
|
+
}
|
|
17373
|
+
this._loadedCategories.set(category, toolNames);
|
|
17374
|
+
this.invalidateTokenCache();
|
|
17375
|
+
exports.logger.debug(
|
|
17376
|
+
{ category, toolCount: toolNames.length, tools: toolNames },
|
|
17377
|
+
`[ToolCatalogPlugin] Loaded category '${category}'`
|
|
17378
|
+
);
|
|
17379
|
+
return { loaded: toolNames.length, tools: toolNames };
|
|
17380
|
+
}
|
|
17381
|
+
executeUnload(category) {
|
|
17382
|
+
if (this._destroyed) return { error: "Plugin destroyed" };
|
|
17383
|
+
if (!this._toolManager) {
|
|
17384
|
+
return { error: "ToolManager not connected." };
|
|
17385
|
+
}
|
|
17386
|
+
const toolNames = this._loadedCategories.get(category);
|
|
17387
|
+
if (!toolNames) {
|
|
17388
|
+
return { unloaded: 0, message: `Category '${category}' is not loaded.` };
|
|
17389
|
+
}
|
|
17390
|
+
this._toolManager.setEnabled(toolNames, false);
|
|
17391
|
+
this._loadedCategories.delete(category);
|
|
17392
|
+
this.invalidateTokenCache();
|
|
17393
|
+
exports.logger.debug(
|
|
17394
|
+
{ category, toolCount: toolNames.length },
|
|
17395
|
+
`[ToolCatalogPlugin] Unloaded category '${category}'`
|
|
17396
|
+
);
|
|
17397
|
+
return { unloaded: toolNames.length };
|
|
17398
|
+
}
|
|
17399
|
+
// ========================================================================
|
|
17400
|
+
// Helpers
|
|
17401
|
+
// ========================================================================
|
|
17402
|
+
getAllowedCategories() {
|
|
17403
|
+
return ToolCatalogRegistry.filterCategories(this._config.categoryScope);
|
|
17404
|
+
}
|
|
17405
|
+
/**
|
|
17406
|
+
* Get connector categories from cache (populated once in setToolManager).
|
|
17407
|
+
*/
|
|
17408
|
+
getConnectorCategories() {
|
|
17409
|
+
return this._connectorCategories ?? [];
|
|
17410
|
+
}
|
|
17411
|
+
keywordSearch(query) {
|
|
17412
|
+
const lq = query.toLowerCase();
|
|
17413
|
+
const results = [];
|
|
17414
|
+
for (const cat of this.getAllowedCategories()) {
|
|
17415
|
+
const catMatch = cat.name.toLowerCase().includes(lq) || cat.displayName.toLowerCase().includes(lq) || cat.description.toLowerCase().includes(lq);
|
|
17416
|
+
const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
|
|
17417
|
+
const matchingTools = tools.filter(
|
|
17418
|
+
(t) => t.name.toLowerCase().includes(lq) || t.displayName.toLowerCase().includes(lq) || t.description.toLowerCase().includes(lq)
|
|
17419
|
+
);
|
|
17420
|
+
if (catMatch || matchingTools.length > 0) {
|
|
17421
|
+
results.push({
|
|
17422
|
+
category: cat.name,
|
|
17423
|
+
categoryDisplayName: cat.displayName,
|
|
17424
|
+
tools: (catMatch ? tools : matchingTools).map((t) => ({
|
|
17425
|
+
name: t.name,
|
|
17426
|
+
displayName: t.displayName,
|
|
17427
|
+
description: t.description
|
|
17428
|
+
}))
|
|
17429
|
+
});
|
|
17430
|
+
}
|
|
17431
|
+
}
|
|
17432
|
+
for (const cc of this.getConnectorCategories()) {
|
|
17433
|
+
if (cc.name.toLowerCase().includes(lq) || cc.displayName.toLowerCase().includes(lq) || cc.description.toLowerCase().includes(lq)) {
|
|
17434
|
+
results.push({
|
|
17435
|
+
category: cc.name,
|
|
17436
|
+
categoryDisplayName: cc.displayName,
|
|
17437
|
+
tools: cc.tools.map((t) => ({
|
|
17438
|
+
name: t.definition.function.name,
|
|
17439
|
+
displayName: t.definition.function.name.replace(/_/g, " "),
|
|
17440
|
+
description: t.definition.function.description || ""
|
|
17441
|
+
}))
|
|
17442
|
+
});
|
|
17443
|
+
}
|
|
17444
|
+
}
|
|
17445
|
+
return { query, results, totalMatches: results.length };
|
|
17446
|
+
}
|
|
17447
|
+
searchConnectorCategory(category) {
|
|
17448
|
+
const connectorName = ToolCatalogRegistry.parseConnectorCategory(category);
|
|
17449
|
+
const tools = ToolCatalogRegistry.resolveConnectorCategoryTools(category);
|
|
17450
|
+
const loaded = this._loadedCategories.has(category);
|
|
17451
|
+
return {
|
|
17452
|
+
category,
|
|
17453
|
+
loaded,
|
|
17454
|
+
connectorName,
|
|
17455
|
+
tools: tools.map((t) => ({
|
|
17456
|
+
name: t.name,
|
|
17457
|
+
description: t.tool.definition.function.description || ""
|
|
17458
|
+
}))
|
|
17459
|
+
};
|
|
17460
|
+
}
|
|
17461
|
+
getCategoriesSortedByLastUsed() {
|
|
17462
|
+
if (!this._toolManager) return Array.from(this._loadedCategories.keys());
|
|
17463
|
+
const categoryLastUsed = [];
|
|
17464
|
+
for (const [category, toolNames] of this._loadedCategories) {
|
|
17465
|
+
let maxLastUsed = 0;
|
|
17466
|
+
for (const name of toolNames) {
|
|
17467
|
+
const reg = this._toolManager.getRegistration(name);
|
|
17468
|
+
if (reg?.metadata?.lastUsed) {
|
|
17469
|
+
const ts = reg.metadata.lastUsed instanceof Date ? reg.metadata.lastUsed.getTime() : 0;
|
|
17470
|
+
if (ts > maxLastUsed) maxLastUsed = ts;
|
|
17471
|
+
}
|
|
17472
|
+
}
|
|
17473
|
+
categoryLastUsed.push({ category, lastUsed: maxLastUsed });
|
|
17474
|
+
}
|
|
17475
|
+
categoryLastUsed.sort((a, b) => a.lastUsed - b.lastUsed);
|
|
17476
|
+
return categoryLastUsed.map((c) => c.category);
|
|
17477
|
+
}
|
|
17478
|
+
estimateToolDefinitionTokens(toolNames) {
|
|
17479
|
+
let total = 0;
|
|
17480
|
+
for (const name of toolNames) {
|
|
17481
|
+
const reg = this._toolManager?.getRegistration(name);
|
|
17482
|
+
if (reg) {
|
|
17483
|
+
const defObj = reg.tool.definition;
|
|
17484
|
+
const cached = this._toolTokenCache.get(defObj);
|
|
17485
|
+
if (cached !== void 0) {
|
|
17486
|
+
total += cached;
|
|
17487
|
+
} else {
|
|
17488
|
+
const defStr = JSON.stringify(defObj);
|
|
17489
|
+
const tokens = this.estimator.estimateTokens(defStr);
|
|
17490
|
+
this._toolTokenCache.set(defObj, tokens);
|
|
17491
|
+
total += tokens;
|
|
17492
|
+
}
|
|
17493
|
+
}
|
|
17494
|
+
}
|
|
17495
|
+
return total;
|
|
17496
|
+
}
|
|
16226
17497
|
};
|
|
16227
17498
|
|
|
16228
17499
|
// src/core/context-nextgen/AgentContextNextGen.ts
|
|
@@ -16878,7 +18149,8 @@ var DEFAULT_FEATURES = {
|
|
|
16878
18149
|
workingMemory: true,
|
|
16879
18150
|
inContextMemory: true,
|
|
16880
18151
|
persistentInstructions: false,
|
|
16881
|
-
userInfo: false
|
|
18152
|
+
userInfo: false,
|
|
18153
|
+
toolCatalog: false
|
|
16882
18154
|
};
|
|
16883
18155
|
var DEFAULT_CONFIG2 = {
|
|
16884
18156
|
responseReserve: 4096,
|
|
@@ -16950,6 +18222,7 @@ var AgentContextNextGen = class _AgentContextNextGen extends eventemitter3.Event
|
|
|
16950
18222
|
strategy: config.strategy ?? DEFAULT_CONFIG2.strategy,
|
|
16951
18223
|
features: { ...DEFAULT_FEATURES, ...config.features },
|
|
16952
18224
|
agentId: config.agentId ?? this.generateId(),
|
|
18225
|
+
toolCategories: config.toolCategories,
|
|
16953
18226
|
storage: config.storage
|
|
16954
18227
|
};
|
|
16955
18228
|
this._systemPrompt = config.systemPrompt;
|
|
@@ -17005,6 +18278,16 @@ var AgentContextNextGen = class _AgentContextNextGen extends eventemitter3.Event
|
|
|
17005
18278
|
...uiConfig
|
|
17006
18279
|
}));
|
|
17007
18280
|
}
|
|
18281
|
+
if (features.toolCatalog) {
|
|
18282
|
+
const tcConfig = configs.toolCatalog;
|
|
18283
|
+
const plugin = new ToolCatalogPluginNextGen({
|
|
18284
|
+
categoryScope: this._config.toolCategories,
|
|
18285
|
+
identities: this._identities,
|
|
18286
|
+
...tcConfig
|
|
18287
|
+
});
|
|
18288
|
+
this.registerPlugin(plugin);
|
|
18289
|
+
plugin.setToolManager(this._tools);
|
|
18290
|
+
}
|
|
17008
18291
|
this.validateStrategyDependencies(this._compactionStrategy);
|
|
17009
18292
|
}
|
|
17010
18293
|
/**
|
|
@@ -24726,7 +26009,9 @@ var ROUTINE_KEYS = {
|
|
|
24726
26009
|
/** Running fold accumulator (ICM) */
|
|
24727
26010
|
FOLD_ACCUMULATOR: "__fold_accumulator",
|
|
24728
26011
|
/** Prefix for large dep results stored in WM findings tier */
|
|
24729
|
-
WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_"
|
|
26012
|
+
WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_",
|
|
26013
|
+
/** Prefix for auto-stored task outputs (set by output contracts) */
|
|
26014
|
+
TASK_OUTPUT_PREFIX: "__task_output_"
|
|
24730
26015
|
};
|
|
24731
26016
|
function resolveTemplates(text, inputs, icmPlugin) {
|
|
24732
26017
|
return text.replace(/\{\{(\w+)\.(\w+)\}\}/g, (_match, namespace, key) => {
|
|
@@ -24751,13 +26036,45 @@ function resolveTemplates(text, inputs, icmPlugin) {
|
|
|
24751
26036
|
function resolveTaskTemplates(task, inputs, icmPlugin) {
|
|
24752
26037
|
const resolvedDescription = resolveTemplates(task.description, inputs, icmPlugin);
|
|
24753
26038
|
const resolvedExpectedOutput = task.expectedOutput ? resolveTemplates(task.expectedOutput, inputs, icmPlugin) : task.expectedOutput;
|
|
24754
|
-
|
|
26039
|
+
let resolvedControlFlow = task.controlFlow;
|
|
26040
|
+
if (task.controlFlow && "source" in task.controlFlow) {
|
|
26041
|
+
const flow = task.controlFlow;
|
|
26042
|
+
const source = flow.source;
|
|
26043
|
+
if (typeof source === "string") {
|
|
26044
|
+
const r = resolveTemplates(source, inputs, icmPlugin);
|
|
26045
|
+
if (r !== source) {
|
|
26046
|
+
resolvedControlFlow = { ...flow, source: r };
|
|
26047
|
+
}
|
|
26048
|
+
} else if (source) {
|
|
26049
|
+
let changed = false;
|
|
26050
|
+
const resolved = { ...source };
|
|
26051
|
+
if (resolved.task) {
|
|
26052
|
+
const r = resolveTemplates(resolved.task, inputs, icmPlugin);
|
|
26053
|
+
if (r !== resolved.task) {
|
|
26054
|
+
resolved.task = r;
|
|
26055
|
+
changed = true;
|
|
26056
|
+
}
|
|
26057
|
+
}
|
|
26058
|
+
if (resolved.key) {
|
|
26059
|
+
const r = resolveTemplates(resolved.key, inputs, icmPlugin);
|
|
26060
|
+
if (r !== resolved.key) {
|
|
26061
|
+
resolved.key = r;
|
|
26062
|
+
changed = true;
|
|
26063
|
+
}
|
|
26064
|
+
}
|
|
26065
|
+
if (changed) {
|
|
26066
|
+
resolvedControlFlow = { ...flow, source: resolved };
|
|
26067
|
+
}
|
|
26068
|
+
}
|
|
26069
|
+
}
|
|
26070
|
+
if (resolvedDescription === task.description && resolvedExpectedOutput === task.expectedOutput && resolvedControlFlow === task.controlFlow) {
|
|
24755
26071
|
return task;
|
|
24756
26072
|
}
|
|
24757
26073
|
return {
|
|
24758
26074
|
...task,
|
|
24759
26075
|
description: resolvedDescription,
|
|
24760
|
-
expectedOutput: resolvedExpectedOutput
|
|
26076
|
+
expectedOutput: resolvedExpectedOutput,
|
|
26077
|
+
controlFlow: resolvedControlFlow
|
|
24761
26078
|
};
|
|
24762
26079
|
}
|
|
24763
26080
|
function validateAndResolveInputs(parameters, inputs) {
|
|
@@ -24825,17 +26142,6 @@ function cleanFoldKeys(icmPlugin) {
|
|
|
24825
26142
|
cleanMapKeys(icmPlugin);
|
|
24826
26143
|
icmPlugin.delete(ROUTINE_KEYS.FOLD_ACCUMULATOR);
|
|
24827
26144
|
}
|
|
24828
|
-
async function readSourceArray(flow, flowType, icmPlugin, wmPlugin) {
|
|
24829
|
-
const sourceValue = await readMemoryValue(flow.sourceKey, icmPlugin, wmPlugin);
|
|
24830
|
-
if (!Array.isArray(sourceValue)) {
|
|
24831
|
-
return {
|
|
24832
|
-
completed: false,
|
|
24833
|
-
error: `${flowType} sourceKey "${flow.sourceKey}" is not an array (got ${typeof sourceValue})`
|
|
24834
|
-
};
|
|
24835
|
-
}
|
|
24836
|
-
const maxIter = Math.min(sourceValue.length, flow.maxIterations ?? sourceValue.length, HARD_MAX_ITERATIONS);
|
|
24837
|
-
return { array: sourceValue, maxIter };
|
|
24838
|
-
}
|
|
24839
26145
|
function prepareSubRoutine(tasks, parentTaskName) {
|
|
24840
26146
|
const subRoutine = resolveSubRoutine(tasks, parentTaskName);
|
|
24841
26147
|
return {
|
|
@@ -24870,10 +26176,141 @@ async function withTimeout(promise, timeoutMs, label) {
|
|
|
24870
26176
|
clearTimeout(timer);
|
|
24871
26177
|
}
|
|
24872
26178
|
}
|
|
24873
|
-
|
|
26179
|
+
var COMMON_ARRAY_FIELDS = ["data", "items", "results", "entries", "list", "records", "values", "elements"];
|
|
26180
|
+
function extractByPath(value, path6) {
|
|
26181
|
+
let current = value;
|
|
26182
|
+
if (typeof current === "string") {
|
|
26183
|
+
try {
|
|
26184
|
+
current = JSON.parse(current);
|
|
26185
|
+
} catch {
|
|
26186
|
+
return void 0;
|
|
26187
|
+
}
|
|
26188
|
+
}
|
|
26189
|
+
const segments = path6.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
|
|
26190
|
+
for (const segment of segments) {
|
|
26191
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
26192
|
+
current = current[segment];
|
|
26193
|
+
}
|
|
26194
|
+
return current;
|
|
26195
|
+
}
|
|
26196
|
+
function tryCoerceToArray(value) {
|
|
26197
|
+
if (value === void 0 || value === null) return value;
|
|
26198
|
+
if (Array.isArray(value)) return value;
|
|
26199
|
+
if (typeof value === "string") {
|
|
26200
|
+
try {
|
|
26201
|
+
const parsed = JSON.parse(value);
|
|
26202
|
+
if (Array.isArray(parsed)) return parsed;
|
|
26203
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
26204
|
+
value = parsed;
|
|
26205
|
+
} else {
|
|
26206
|
+
return value;
|
|
26207
|
+
}
|
|
26208
|
+
} catch {
|
|
26209
|
+
return value;
|
|
26210
|
+
}
|
|
26211
|
+
}
|
|
26212
|
+
if (typeof value === "object" && value !== null) {
|
|
26213
|
+
for (const field of COMMON_ARRAY_FIELDS) {
|
|
26214
|
+
const candidate = value[field];
|
|
26215
|
+
if (Array.isArray(candidate)) return candidate;
|
|
26216
|
+
}
|
|
26217
|
+
}
|
|
26218
|
+
return value;
|
|
26219
|
+
}
|
|
26220
|
+
async function llmExtractArray(agent, rawValue) {
|
|
26221
|
+
const serialized = typeof rawValue === "string" ? rawValue : JSON.stringify(rawValue);
|
|
26222
|
+
const truncated = serialized.length > 8e3 ? serialized.slice(0, 8e3) + "\n...(truncated)" : serialized;
|
|
26223
|
+
const response = await agent.runDirect(
|
|
26224
|
+
[
|
|
26225
|
+
"Extract a JSON array from the data below for iteration.",
|
|
26226
|
+
"Return ONLY a valid JSON array. No explanation, no markdown fences, no extra text.",
|
|
26227
|
+
"If the data contains a list in any format (JSON, markdown, numbered list, comma-separated), convert it to a JSON array of items.",
|
|
26228
|
+
"",
|
|
26229
|
+
"Data:",
|
|
26230
|
+
truncated
|
|
26231
|
+
].join("\n"),
|
|
26232
|
+
{ temperature: 0, maxOutputTokens: 4096 }
|
|
26233
|
+
);
|
|
26234
|
+
const text = response.output_text?.trim() ?? "";
|
|
26235
|
+
const cleaned = text.replace(/^```(?:json|JSON)?\s*\n?/, "").replace(/\n?\s*```$/, "").trim();
|
|
26236
|
+
let parsed;
|
|
26237
|
+
try {
|
|
26238
|
+
parsed = JSON.parse(cleaned);
|
|
26239
|
+
} catch (parseErr) {
|
|
26240
|
+
throw new Error(`LLM returned invalid JSON: ${parseErr.message}. Raw: "${text.slice(0, 200)}"`);
|
|
26241
|
+
}
|
|
26242
|
+
if (!Array.isArray(parsed)) {
|
|
26243
|
+
throw new Error(`LLM extraction produced ${typeof parsed}, expected array`);
|
|
26244
|
+
}
|
|
26245
|
+
return parsed;
|
|
26246
|
+
}
|
|
26247
|
+
async function resolveFlowSource(flow, flowType, agent, execution, icmPlugin, wmPlugin) {
|
|
26248
|
+
const log = exports.logger.child({ fn: "resolveFlowSource", flowType });
|
|
26249
|
+
const source = flow.source;
|
|
26250
|
+
const lookups = [];
|
|
26251
|
+
if (typeof source === "string") {
|
|
26252
|
+
lookups.push({ key: source, label: `key "${source}"` });
|
|
26253
|
+
} else if (source.task) {
|
|
26254
|
+
lookups.push({
|
|
26255
|
+
key: `${ROUTINE_KEYS.TASK_OUTPUT_PREFIX}${source.task}`,
|
|
26256
|
+
path: source.path,
|
|
26257
|
+
label: `task output "${source.task}"`
|
|
26258
|
+
});
|
|
26259
|
+
if (execution) {
|
|
26260
|
+
const depTask = execution.plan.tasks.find((t) => t.name === source.task);
|
|
26261
|
+
if (depTask) {
|
|
26262
|
+
lookups.push({
|
|
26263
|
+
key: `${ROUTINE_KEYS.DEP_RESULT_PREFIX}${depTask.id}`,
|
|
26264
|
+
path: source.path,
|
|
26265
|
+
label: `dep result "${source.task}"`
|
|
26266
|
+
});
|
|
26267
|
+
}
|
|
26268
|
+
}
|
|
26269
|
+
} else if (source.key) {
|
|
26270
|
+
lookups.push({ key: source.key, path: source.path, label: `key "${source.key}"` });
|
|
26271
|
+
}
|
|
26272
|
+
if (lookups.length === 0) {
|
|
26273
|
+
return { completed: false, error: `${flowType}: source has no task, key, or string value` };
|
|
26274
|
+
}
|
|
26275
|
+
let rawValue;
|
|
26276
|
+
let resolvedVia;
|
|
26277
|
+
for (const { key, path: path6, label } of lookups) {
|
|
26278
|
+
const value2 = await readMemoryValue(key, icmPlugin, wmPlugin);
|
|
26279
|
+
if (value2 !== void 0) {
|
|
26280
|
+
rawValue = path6 ? extractByPath(value2, path6) : value2;
|
|
26281
|
+
resolvedVia = label;
|
|
26282
|
+
break;
|
|
26283
|
+
}
|
|
26284
|
+
}
|
|
26285
|
+
if (rawValue === void 0) {
|
|
26286
|
+
const tried = lookups.map((l) => l.label).join(", ");
|
|
26287
|
+
return { completed: false, error: `${flowType}: source not found (tried: ${tried})` };
|
|
26288
|
+
}
|
|
26289
|
+
log.debug({ resolvedVia }, "Source value found");
|
|
26290
|
+
let value = tryCoerceToArray(rawValue);
|
|
26291
|
+
if (!Array.isArray(value)) {
|
|
26292
|
+
log.info({ resolvedVia, valueType: typeof value }, "Source not an array, attempting LLM extraction");
|
|
26293
|
+
try {
|
|
26294
|
+
value = await llmExtractArray(agent, rawValue);
|
|
26295
|
+
log.info({ extractedLength: value.length }, "LLM extraction succeeded");
|
|
26296
|
+
} catch (err) {
|
|
26297
|
+
return {
|
|
26298
|
+
completed: false,
|
|
26299
|
+
error: `${flowType}: source value is not an array and LLM extraction failed: ${err.message}`
|
|
26300
|
+
};
|
|
26301
|
+
}
|
|
26302
|
+
}
|
|
26303
|
+
const arr = value;
|
|
26304
|
+
if (arr.length === 0) {
|
|
26305
|
+
log.warn("Source array is empty");
|
|
26306
|
+
}
|
|
26307
|
+
const maxIter = Math.min(arr.length, flow.maxIterations ?? arr.length, HARD_MAX_ITERATIONS);
|
|
26308
|
+
return { array: arr, maxIter };
|
|
26309
|
+
}
|
|
26310
|
+
async function handleMap(agent, flow, task, inputs, execution) {
|
|
24874
26311
|
const { icmPlugin, wmPlugin } = getPlugins(agent);
|
|
24875
26312
|
const log = exports.logger.child({ controlFlow: "map", task: task.name });
|
|
24876
|
-
const sourceResult = await
|
|
26313
|
+
const sourceResult = await resolveFlowSource(flow, "Map", agent, execution, icmPlugin, wmPlugin);
|
|
24877
26314
|
if ("completed" in sourceResult) return sourceResult;
|
|
24878
26315
|
const { array: array3, maxIter } = sourceResult;
|
|
24879
26316
|
const results = [];
|
|
@@ -24911,10 +26348,10 @@ async function handleMap(agent, flow, task, inputs) {
|
|
|
24911
26348
|
log.info({ resultCount: results.length }, "Map completed");
|
|
24912
26349
|
return { completed: true, result: results };
|
|
24913
26350
|
}
|
|
24914
|
-
async function handleFold(agent, flow, task, inputs) {
|
|
26351
|
+
async function handleFold(agent, flow, task, inputs, execution) {
|
|
24915
26352
|
const { icmPlugin, wmPlugin } = getPlugins(agent);
|
|
24916
26353
|
const log = exports.logger.child({ controlFlow: "fold", task: task.name });
|
|
24917
|
-
const sourceResult = await
|
|
26354
|
+
const sourceResult = await resolveFlowSource(flow, "Fold", agent, execution, icmPlugin, wmPlugin);
|
|
24918
26355
|
if ("completed" in sourceResult) return sourceResult;
|
|
24919
26356
|
const { array: array3, maxIter } = sourceResult;
|
|
24920
26357
|
let accumulator = flow.initialValue;
|
|
@@ -25005,13 +26442,13 @@ async function handleUntil(agent, flow, task, inputs) {
|
|
|
25005
26442
|
}
|
|
25006
26443
|
return { completed: false, error: `Until loop: maxIterations (${flow.maxIterations}) exceeded` };
|
|
25007
26444
|
}
|
|
25008
|
-
async function executeControlFlow(agent, task, inputs) {
|
|
26445
|
+
async function executeControlFlow(agent, task, inputs, execution) {
|
|
25009
26446
|
const flow = task.controlFlow;
|
|
25010
26447
|
switch (flow.type) {
|
|
25011
26448
|
case "map":
|
|
25012
|
-
return handleMap(agent, flow, task, inputs);
|
|
26449
|
+
return handleMap(agent, flow, task, inputs, execution);
|
|
25013
26450
|
case "fold":
|
|
25014
|
-
return handleFold(agent, flow, task, inputs);
|
|
26451
|
+
return handleFold(agent, flow, task, inputs, execution);
|
|
25015
26452
|
case "until":
|
|
25016
26453
|
return handleUntil(agent, flow, task, inputs);
|
|
25017
26454
|
default:
|
|
@@ -25040,7 +26477,26 @@ function defaultSystemPrompt(definition) {
|
|
|
25040
26477
|
);
|
|
25041
26478
|
return parts.join("\n");
|
|
25042
26479
|
}
|
|
25043
|
-
function
|
|
26480
|
+
function getOutputContracts(execution, currentTask) {
|
|
26481
|
+
const contracts = [];
|
|
26482
|
+
for (const task of execution.plan.tasks) {
|
|
26483
|
+
if (task.status !== "pending" || !task.controlFlow) continue;
|
|
26484
|
+
const flow = task.controlFlow;
|
|
26485
|
+
if (flow.type === "until") continue;
|
|
26486
|
+
const source = flow.source;
|
|
26487
|
+
const sourceTaskName = typeof source === "string" ? void 0 : source.task;
|
|
26488
|
+
if (sourceTaskName === currentTask.name) {
|
|
26489
|
+
contracts.push({
|
|
26490
|
+
storageKey: `${ROUTINE_KEYS.TASK_OUTPUT_PREFIX}${currentTask.name}`,
|
|
26491
|
+
format: "array",
|
|
26492
|
+
consumingTaskName: task.name,
|
|
26493
|
+
flowType: flow.type
|
|
26494
|
+
});
|
|
26495
|
+
}
|
|
26496
|
+
}
|
|
26497
|
+
return contracts;
|
|
26498
|
+
}
|
|
26499
|
+
function defaultTaskPrompt(task, execution) {
|
|
25044
26500
|
const parts = [];
|
|
25045
26501
|
parts.push(`## Current Task: ${task.name}`, "");
|
|
25046
26502
|
parts.push(task.description, "");
|
|
@@ -25065,6 +26521,21 @@ function defaultTaskPrompt(task) {
|
|
|
25065
26521
|
parts.push("Review the plan overview and dependency results before starting.");
|
|
25066
26522
|
parts.push("");
|
|
25067
26523
|
}
|
|
26524
|
+
if (execution) {
|
|
26525
|
+
const contracts = getOutputContracts(execution, task);
|
|
26526
|
+
if (contracts.length > 0) {
|
|
26527
|
+
parts.push("### Output Storage");
|
|
26528
|
+
for (const contract of contracts) {
|
|
26529
|
+
parts.push(
|
|
26530
|
+
`A downstream task ("${contract.consumingTaskName}") will ${contract.flowType} over your results.`,
|
|
26531
|
+
`Store your result as a JSON ${contract.format} using:`,
|
|
26532
|
+
` context_set("${contract.storageKey}", <your JSON ${contract.format}>)`,
|
|
26533
|
+
"Each array element should represent one item to process independently.",
|
|
26534
|
+
""
|
|
26535
|
+
);
|
|
26536
|
+
}
|
|
26537
|
+
}
|
|
26538
|
+
}
|
|
25068
26539
|
parts.push("After completing the work, store key results in memory once, then respond with a text summary (no more tool calls).");
|
|
25069
26540
|
return parts.join("\n");
|
|
25070
26541
|
}
|
|
@@ -25221,8 +26692,8 @@ var DEP_CLEANUP_CONFIG = {
|
|
|
25221
26692
|
wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX]
|
|
25222
26693
|
};
|
|
25223
26694
|
var FULL_CLEANUP_CONFIG = {
|
|
25224
|
-
icmPrefixes: ["__routine_", ROUTINE_KEYS.DEP_RESULT_PREFIX, "__map_", "__fold_"],
|
|
25225
|
-
wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX]
|
|
26695
|
+
icmPrefixes: ["__routine_", ROUTINE_KEYS.DEP_RESULT_PREFIX, "__map_", "__fold_", ROUTINE_KEYS.TASK_OUTPUT_PREFIX],
|
|
26696
|
+
wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX, ROUTINE_KEYS.TASK_OUTPUT_PREFIX]
|
|
25226
26697
|
};
|
|
25227
26698
|
async function injectRoutineContext(agent, execution, definition, currentTask) {
|
|
25228
26699
|
const { icmPlugin, wmPlugin } = getPlugins(agent);
|
|
@@ -25333,7 +26804,8 @@ async function executeRoutine(options) {
|
|
|
25333
26804
|
execution.startedAt = Date.now();
|
|
25334
26805
|
execution.lastUpdatedAt = Date.now();
|
|
25335
26806
|
const buildSystemPrompt = prompts?.system ?? defaultSystemPrompt;
|
|
25336
|
-
const
|
|
26807
|
+
const userTaskPromptBuilder = prompts?.task ?? defaultTaskPrompt;
|
|
26808
|
+
const buildTaskPrompt = (task) => userTaskPromptBuilder(task, execution);
|
|
25337
26809
|
const buildValidationPrompt = prompts?.validation ?? defaultValidationPrompt;
|
|
25338
26810
|
let agent;
|
|
25339
26811
|
const registeredHooks = [];
|
|
@@ -25424,7 +26896,7 @@ async function executeRoutine(options) {
|
|
|
25424
26896
|
const { icmPlugin } = getPlugins(agent);
|
|
25425
26897
|
if (getTask().controlFlow) {
|
|
25426
26898
|
try {
|
|
25427
|
-
const cfResult = await executeControlFlow(agent, getTask(), resolvedInputs);
|
|
26899
|
+
const cfResult = await executeControlFlow(agent, getTask(), resolvedInputs, execution);
|
|
25428
26900
|
if (cfResult.completed) {
|
|
25429
26901
|
execution.plan.tasks[taskIndex] = updateTaskStatus(getTask(), "completed");
|
|
25430
26902
|
execution.plan.tasks[taskIndex].result = { success: true, output: cfResult.result };
|
|
@@ -25574,6 +27046,261 @@ async function executeRoutine(options) {
|
|
|
25574
27046
|
}
|
|
25575
27047
|
}
|
|
25576
27048
|
|
|
27049
|
+
// src/core/createExecutionRecorder.ts
|
|
27050
|
+
init_Logger();
|
|
27051
|
+
function truncate(value, maxLen) {
|
|
27052
|
+
const str = typeof value === "string" ? value : JSON.stringify(value);
|
|
27053
|
+
if (!str) return "";
|
|
27054
|
+
return str.length > maxLen ? str.slice(0, maxLen) + "...(truncated)" : str;
|
|
27055
|
+
}
|
|
27056
|
+
function safeCall(fn, prefix) {
|
|
27057
|
+
try {
|
|
27058
|
+
const result = fn();
|
|
27059
|
+
if (result && typeof result.catch === "function") {
|
|
27060
|
+
result.catch((err) => {
|
|
27061
|
+
exports.logger.debug({ error: err.message }, `${prefix} async error`);
|
|
27062
|
+
});
|
|
27063
|
+
}
|
|
27064
|
+
} catch (err) {
|
|
27065
|
+
exports.logger.debug({ error: err.message }, `${prefix} sync error`);
|
|
27066
|
+
}
|
|
27067
|
+
}
|
|
27068
|
+
function createExecutionRecorder(options) {
|
|
27069
|
+
const { storage, executionId, logPrefix = "[Recorder]", maxTruncateLength = 500 } = options;
|
|
27070
|
+
const log = exports.logger.child({ executionId });
|
|
27071
|
+
let currentTaskName = "(unknown)";
|
|
27072
|
+
function pushStep(step) {
|
|
27073
|
+
safeCall(() => storage.pushStep(executionId, step), `${logPrefix} pushStep`);
|
|
27074
|
+
}
|
|
27075
|
+
function heartbeat() {
|
|
27076
|
+
safeCall(
|
|
27077
|
+
() => storage.update(executionId, { lastActivityAt: Date.now() }),
|
|
27078
|
+
`${logPrefix} heartbeat`
|
|
27079
|
+
);
|
|
27080
|
+
}
|
|
27081
|
+
const hooks = {
|
|
27082
|
+
"before:llm": (ctx) => {
|
|
27083
|
+
pushStep({
|
|
27084
|
+
timestamp: Date.now(),
|
|
27085
|
+
taskName: currentTaskName,
|
|
27086
|
+
type: "llm.start",
|
|
27087
|
+
data: { iteration: ctx.iteration }
|
|
27088
|
+
});
|
|
27089
|
+
return {};
|
|
27090
|
+
},
|
|
27091
|
+
"after:llm": (ctx) => {
|
|
27092
|
+
pushStep({
|
|
27093
|
+
timestamp: Date.now(),
|
|
27094
|
+
taskName: currentTaskName,
|
|
27095
|
+
type: "llm.complete",
|
|
27096
|
+
data: {
|
|
27097
|
+
iteration: ctx.iteration,
|
|
27098
|
+
duration: ctx.duration,
|
|
27099
|
+
tokens: ctx.response?.usage
|
|
27100
|
+
}
|
|
27101
|
+
});
|
|
27102
|
+
return {};
|
|
27103
|
+
},
|
|
27104
|
+
"before:tool": (ctx) => {
|
|
27105
|
+
pushStep({
|
|
27106
|
+
timestamp: Date.now(),
|
|
27107
|
+
taskName: currentTaskName,
|
|
27108
|
+
type: "tool.start",
|
|
27109
|
+
data: {
|
|
27110
|
+
toolName: ctx.toolCall.function.name,
|
|
27111
|
+
args: truncate(ctx.toolCall.function.arguments, maxTruncateLength)
|
|
27112
|
+
}
|
|
27113
|
+
});
|
|
27114
|
+
return {};
|
|
27115
|
+
},
|
|
27116
|
+
"after:tool": (ctx) => {
|
|
27117
|
+
pushStep({
|
|
27118
|
+
timestamp: Date.now(),
|
|
27119
|
+
taskName: currentTaskName,
|
|
27120
|
+
type: "tool.call",
|
|
27121
|
+
data: {
|
|
27122
|
+
toolName: ctx.toolCall.function.name,
|
|
27123
|
+
args: truncate(ctx.toolCall.function.arguments, maxTruncateLength),
|
|
27124
|
+
result: truncate(ctx.result?.content, maxTruncateLength),
|
|
27125
|
+
error: ctx.result?.error ? true : void 0
|
|
27126
|
+
}
|
|
27127
|
+
});
|
|
27128
|
+
return {};
|
|
27129
|
+
},
|
|
27130
|
+
"after:execution": () => {
|
|
27131
|
+
pushStep({
|
|
27132
|
+
timestamp: Date.now(),
|
|
27133
|
+
taskName: currentTaskName,
|
|
27134
|
+
type: "iteration.complete"
|
|
27135
|
+
});
|
|
27136
|
+
},
|
|
27137
|
+
"pause:check": () => {
|
|
27138
|
+
heartbeat();
|
|
27139
|
+
return { shouldPause: false };
|
|
27140
|
+
}
|
|
27141
|
+
};
|
|
27142
|
+
const onTaskStarted = (task, execution) => {
|
|
27143
|
+
currentTaskName = task.name;
|
|
27144
|
+
const now = Date.now();
|
|
27145
|
+
safeCall(
|
|
27146
|
+
() => storage.updateTask(executionId, task.name, {
|
|
27147
|
+
status: "in_progress",
|
|
27148
|
+
startedAt: now,
|
|
27149
|
+
attempts: task.attempts
|
|
27150
|
+
}),
|
|
27151
|
+
`${logPrefix} onTaskStarted`
|
|
27152
|
+
);
|
|
27153
|
+
pushStep({
|
|
27154
|
+
timestamp: now,
|
|
27155
|
+
taskName: task.name,
|
|
27156
|
+
type: "task.started",
|
|
27157
|
+
data: { taskId: task.id }
|
|
27158
|
+
});
|
|
27159
|
+
if (task.controlFlow) {
|
|
27160
|
+
pushStep({
|
|
27161
|
+
timestamp: now,
|
|
27162
|
+
taskName: task.name,
|
|
27163
|
+
type: "control_flow.started",
|
|
27164
|
+
data: { flowType: task.controlFlow.type }
|
|
27165
|
+
});
|
|
27166
|
+
}
|
|
27167
|
+
safeCall(
|
|
27168
|
+
() => storage.update(executionId, {
|
|
27169
|
+
progress: execution.progress,
|
|
27170
|
+
lastActivityAt: now
|
|
27171
|
+
}),
|
|
27172
|
+
`${logPrefix} onTaskStarted progress`
|
|
27173
|
+
);
|
|
27174
|
+
};
|
|
27175
|
+
const onTaskComplete = (task, execution) => {
|
|
27176
|
+
const now = Date.now();
|
|
27177
|
+
safeCall(
|
|
27178
|
+
() => storage.updateTask(executionId, task.name, {
|
|
27179
|
+
status: "completed",
|
|
27180
|
+
completedAt: now,
|
|
27181
|
+
attempts: task.attempts,
|
|
27182
|
+
result: task.result ? {
|
|
27183
|
+
success: true,
|
|
27184
|
+
output: truncate(task.result.output, maxTruncateLength),
|
|
27185
|
+
validationScore: task.result.validationScore,
|
|
27186
|
+
validationExplanation: task.result.validationExplanation
|
|
27187
|
+
} : void 0
|
|
27188
|
+
}),
|
|
27189
|
+
`${logPrefix} onTaskComplete`
|
|
27190
|
+
);
|
|
27191
|
+
pushStep({
|
|
27192
|
+
timestamp: now,
|
|
27193
|
+
taskName: task.name,
|
|
27194
|
+
type: "task.completed",
|
|
27195
|
+
data: {
|
|
27196
|
+
taskId: task.id,
|
|
27197
|
+
validationScore: task.result?.validationScore
|
|
27198
|
+
}
|
|
27199
|
+
});
|
|
27200
|
+
if (task.controlFlow) {
|
|
27201
|
+
pushStep({
|
|
27202
|
+
timestamp: now,
|
|
27203
|
+
taskName: task.name,
|
|
27204
|
+
type: "control_flow.completed",
|
|
27205
|
+
data: { flowType: task.controlFlow.type }
|
|
27206
|
+
});
|
|
27207
|
+
}
|
|
27208
|
+
safeCall(
|
|
27209
|
+
() => storage.update(executionId, {
|
|
27210
|
+
progress: execution.progress,
|
|
27211
|
+
lastActivityAt: now
|
|
27212
|
+
}),
|
|
27213
|
+
`${logPrefix} onTaskComplete progress`
|
|
27214
|
+
);
|
|
27215
|
+
};
|
|
27216
|
+
const onTaskFailed = (task, execution) => {
|
|
27217
|
+
const now = Date.now();
|
|
27218
|
+
safeCall(
|
|
27219
|
+
() => storage.updateTask(executionId, task.name, {
|
|
27220
|
+
status: "failed",
|
|
27221
|
+
completedAt: now,
|
|
27222
|
+
attempts: task.attempts,
|
|
27223
|
+
result: task.result ? {
|
|
27224
|
+
success: false,
|
|
27225
|
+
error: task.result.error,
|
|
27226
|
+
validationScore: task.result.validationScore,
|
|
27227
|
+
validationExplanation: task.result.validationExplanation
|
|
27228
|
+
} : void 0
|
|
27229
|
+
}),
|
|
27230
|
+
`${logPrefix} onTaskFailed`
|
|
27231
|
+
);
|
|
27232
|
+
pushStep({
|
|
27233
|
+
timestamp: now,
|
|
27234
|
+
taskName: task.name,
|
|
27235
|
+
type: "task.failed",
|
|
27236
|
+
data: {
|
|
27237
|
+
taskId: task.id,
|
|
27238
|
+
error: task.result?.error,
|
|
27239
|
+
attempts: task.attempts
|
|
27240
|
+
}
|
|
27241
|
+
});
|
|
27242
|
+
safeCall(
|
|
27243
|
+
() => storage.update(executionId, {
|
|
27244
|
+
progress: execution.progress,
|
|
27245
|
+
lastActivityAt: now
|
|
27246
|
+
}),
|
|
27247
|
+
`${logPrefix} onTaskFailed progress`
|
|
27248
|
+
);
|
|
27249
|
+
};
|
|
27250
|
+
const onTaskValidation = (task, result, _execution) => {
|
|
27251
|
+
pushStep({
|
|
27252
|
+
timestamp: Date.now(),
|
|
27253
|
+
taskName: task.name,
|
|
27254
|
+
type: "task.validation",
|
|
27255
|
+
data: {
|
|
27256
|
+
taskId: task.id,
|
|
27257
|
+
isComplete: result.isComplete,
|
|
27258
|
+
completionScore: result.completionScore,
|
|
27259
|
+
explanation: truncate(result.explanation, maxTruncateLength)
|
|
27260
|
+
}
|
|
27261
|
+
});
|
|
27262
|
+
};
|
|
27263
|
+
const finalize = async (execution, error) => {
|
|
27264
|
+
const now = Date.now();
|
|
27265
|
+
try {
|
|
27266
|
+
if (error || !execution) {
|
|
27267
|
+
await storage.update(executionId, {
|
|
27268
|
+
status: "failed",
|
|
27269
|
+
error: error?.message ?? "Unknown error",
|
|
27270
|
+
completedAt: now,
|
|
27271
|
+
lastActivityAt: now
|
|
27272
|
+
});
|
|
27273
|
+
if (error) {
|
|
27274
|
+
await storage.pushStep(executionId, {
|
|
27275
|
+
timestamp: now,
|
|
27276
|
+
taskName: currentTaskName,
|
|
27277
|
+
type: "execution.error",
|
|
27278
|
+
data: { error: error.message }
|
|
27279
|
+
});
|
|
27280
|
+
}
|
|
27281
|
+
} else {
|
|
27282
|
+
await storage.update(executionId, {
|
|
27283
|
+
status: execution.status,
|
|
27284
|
+
progress: execution.progress,
|
|
27285
|
+
error: execution.error,
|
|
27286
|
+
completedAt: execution.completedAt ?? now,
|
|
27287
|
+
lastActivityAt: now
|
|
27288
|
+
});
|
|
27289
|
+
}
|
|
27290
|
+
} catch (err) {
|
|
27291
|
+
log.error({ error: err.message }, `${logPrefix} finalize error`);
|
|
27292
|
+
}
|
|
27293
|
+
};
|
|
27294
|
+
return {
|
|
27295
|
+
hooks,
|
|
27296
|
+
onTaskStarted,
|
|
27297
|
+
onTaskComplete,
|
|
27298
|
+
onTaskFailed,
|
|
27299
|
+
onTaskValidation,
|
|
27300
|
+
finalize
|
|
27301
|
+
};
|
|
27302
|
+
}
|
|
27303
|
+
|
|
25577
27304
|
// src/core/index.ts
|
|
25578
27305
|
init_constants();
|
|
25579
27306
|
(class {
|
|
@@ -38898,6 +40625,38 @@ var InMemoryHistoryStorage = class {
|
|
|
38898
40625
|
this.summaries = state.summaries ? [...state.summaries] : [];
|
|
38899
40626
|
}
|
|
38900
40627
|
};
|
|
40628
|
+
|
|
40629
|
+
// src/domain/entities/RoutineExecutionRecord.ts
|
|
40630
|
+
function createTaskSnapshots(definition) {
|
|
40631
|
+
return definition.tasks.map((task) => ({
|
|
40632
|
+
taskId: task.id ?? task.name,
|
|
40633
|
+
name: task.name,
|
|
40634
|
+
description: task.description,
|
|
40635
|
+
status: "pending",
|
|
40636
|
+
attempts: 0,
|
|
40637
|
+
maxAttempts: task.maxAttempts ?? 3,
|
|
40638
|
+
controlFlowType: task.controlFlow?.type
|
|
40639
|
+
}));
|
|
40640
|
+
}
|
|
40641
|
+
function createRoutineExecutionRecord(definition, connectorName, model, trigger) {
|
|
40642
|
+
const now = Date.now();
|
|
40643
|
+
const executionId = `rexec-${now}-${Math.random().toString(36).substr(2, 9)}`;
|
|
40644
|
+
return {
|
|
40645
|
+
executionId,
|
|
40646
|
+
routineId: definition.id,
|
|
40647
|
+
routineName: definition.name,
|
|
40648
|
+
status: "running",
|
|
40649
|
+
progress: 0,
|
|
40650
|
+
tasks: createTaskSnapshots(definition),
|
|
40651
|
+
steps: [],
|
|
40652
|
+
taskCount: definition.tasks.length,
|
|
40653
|
+
connectorName,
|
|
40654
|
+
model,
|
|
40655
|
+
startedAt: now,
|
|
40656
|
+
lastActivityAt: now,
|
|
40657
|
+
trigger: trigger ?? { type: "manual" }
|
|
40658
|
+
};
|
|
40659
|
+
}
|
|
38901
40660
|
function getDefaultBaseDirectory3() {
|
|
38902
40661
|
const platform2 = process.platform;
|
|
38903
40662
|
if (platform2 === "win32") {
|
|
@@ -44741,6 +46500,7 @@ __export(tools_exports, {
|
|
|
44741
46500
|
createEditMeetingTool: () => createEditMeetingTool,
|
|
44742
46501
|
createExecuteJavaScriptTool: () => createExecuteJavaScriptTool,
|
|
44743
46502
|
createFindMeetingSlotsTool: () => createFindMeetingSlotsTool,
|
|
46503
|
+
createGenerateRoutine: () => createGenerateRoutine,
|
|
44744
46504
|
createGetMeetingTranscriptTool: () => createGetMeetingTranscriptTool,
|
|
44745
46505
|
createGetPRTool: () => createGetPRTool,
|
|
44746
46506
|
createGitHubReadFileTool: () => createGitHubReadFileTool,
|
|
@@ -44749,6 +46509,9 @@ __export(tools_exports, {
|
|
|
44749
46509
|
createImageGenerationTool: () => createImageGenerationTool,
|
|
44750
46510
|
createListDirectoryTool: () => createListDirectoryTool,
|
|
44751
46511
|
createMeetingTool: () => createMeetingTool,
|
|
46512
|
+
createMicrosoftListFilesTool: () => createMicrosoftListFilesTool,
|
|
46513
|
+
createMicrosoftReadFileTool: () => createMicrosoftReadFileTool,
|
|
46514
|
+
createMicrosoftSearchFilesTool: () => createMicrosoftSearchFilesTool,
|
|
44752
46515
|
createPRCommentsTool: () => createPRCommentsTool,
|
|
44753
46516
|
createPRFilesTool: () => createPRFilesTool,
|
|
44754
46517
|
createReadFileTool: () => createReadFileTool,
|
|
@@ -44781,14 +46544,18 @@ __export(tools_exports, {
|
|
|
44781
46544
|
desktopWindowList: () => desktopWindowList,
|
|
44782
46545
|
developerTools: () => developerTools,
|
|
44783
46546
|
editFile: () => editFile,
|
|
46547
|
+
encodeSharingUrl: () => encodeSharingUrl,
|
|
44784
46548
|
executeInVM: () => executeInVM,
|
|
44785
46549
|
executeJavaScript: () => executeJavaScript,
|
|
44786
46550
|
expandTilde: () => expandTilde,
|
|
44787
46551
|
formatAttendees: () => formatAttendees,
|
|
46552
|
+
formatFileSize: () => formatFileSize,
|
|
44788
46553
|
formatRecipients: () => formatRecipients,
|
|
46554
|
+
generateRoutine: () => generateRoutine,
|
|
44789
46555
|
getAllBuiltInTools: () => getAllBuiltInTools,
|
|
44790
46556
|
getBackgroundOutput: () => getBackgroundOutput,
|
|
44791
46557
|
getDesktopDriver: () => getDesktopDriver,
|
|
46558
|
+
getDrivePrefix: () => getDrivePrefix,
|
|
44792
46559
|
getMediaOutputHandler: () => getMediaOutputHandler,
|
|
44793
46560
|
getMediaStorage: () => getMediaStorage,
|
|
44794
46561
|
getToolByName: () => getToolByName,
|
|
@@ -44802,7 +46569,9 @@ __export(tools_exports, {
|
|
|
44802
46569
|
hydrateCustomTool: () => hydrateCustomTool,
|
|
44803
46570
|
isBlockedCommand: () => isBlockedCommand,
|
|
44804
46571
|
isExcludedExtension: () => isExcludedExtension,
|
|
46572
|
+
isMicrosoftFileUrl: () => isMicrosoftFileUrl,
|
|
44805
46573
|
isTeamsMeetingUrl: () => isTeamsMeetingUrl,
|
|
46574
|
+
isWebUrl: () => isWebUrl,
|
|
44806
46575
|
jsonManipulator: () => jsonManipulator,
|
|
44807
46576
|
killBackgroundProcess: () => killBackgroundProcess,
|
|
44808
46577
|
listDirectory: () => listDirectory,
|
|
@@ -44813,6 +46582,7 @@ __export(tools_exports, {
|
|
|
44813
46582
|
parseRepository: () => parseRepository,
|
|
44814
46583
|
readFile: () => readFile5,
|
|
44815
46584
|
resetDefaultDriver: () => resetDefaultDriver,
|
|
46585
|
+
resolveFileEndpoints: () => resolveFileEndpoints,
|
|
44816
46586
|
resolveMeetingId: () => resolveMeetingId,
|
|
44817
46587
|
resolveRepository: () => resolveRepository,
|
|
44818
46588
|
setMediaOutputHandler: () => setMediaOutputHandler,
|
|
@@ -49065,6 +50835,87 @@ async function resolveMeetingId(connector, input, prefix, effectiveUserId, effec
|
|
|
49065
50835
|
subject: meetings.value[0].subject
|
|
49066
50836
|
};
|
|
49067
50837
|
}
|
|
50838
|
+
var DEFAULT_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024;
|
|
50839
|
+
var DEFAULT_FILE_SIZE_LIMITS = {
|
|
50840
|
+
".pptx": 100 * 1024 * 1024,
|
|
50841
|
+
// 100 MB — presentations are image-heavy
|
|
50842
|
+
".ppt": 100 * 1024 * 1024,
|
|
50843
|
+
".odp": 100 * 1024 * 1024
|
|
50844
|
+
};
|
|
50845
|
+
function getFileSizeLimit(ext, overrides, defaultLimit) {
|
|
50846
|
+
const merged = { ...DEFAULT_FILE_SIZE_LIMITS, ...overrides };
|
|
50847
|
+
return merged[ext.toLowerCase()] ?? defaultLimit ?? DEFAULT_MAX_FILE_SIZE_BYTES;
|
|
50848
|
+
}
|
|
50849
|
+
var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
50850
|
+
".docx",
|
|
50851
|
+
".pptx",
|
|
50852
|
+
".xlsx",
|
|
50853
|
+
".csv",
|
|
50854
|
+
".pdf",
|
|
50855
|
+
".odt",
|
|
50856
|
+
".odp",
|
|
50857
|
+
".ods",
|
|
50858
|
+
".rtf",
|
|
50859
|
+
".html",
|
|
50860
|
+
".htm",
|
|
50861
|
+
".txt",
|
|
50862
|
+
".md",
|
|
50863
|
+
".json",
|
|
50864
|
+
".xml",
|
|
50865
|
+
".yaml",
|
|
50866
|
+
".yml"
|
|
50867
|
+
]);
|
|
50868
|
+
function encodeSharingUrl(webUrl) {
|
|
50869
|
+
const base64 = Buffer.from(webUrl, "utf-8").toString("base64").replace(/=+$/, "").replace(/\//g, "_").replace(/\+/g, "-");
|
|
50870
|
+
return `u!${base64}`;
|
|
50871
|
+
}
|
|
50872
|
+
function isWebUrl(source) {
|
|
50873
|
+
return /^https?:\/\//i.test(source.trim());
|
|
50874
|
+
}
|
|
50875
|
+
function isMicrosoftFileUrl(source) {
|
|
50876
|
+
try {
|
|
50877
|
+
const url2 = new URL(source.trim());
|
|
50878
|
+
const host = url2.hostname.toLowerCase();
|
|
50879
|
+
return host.endsWith(".sharepoint.com") || host.endsWith(".sharepoint-df.com") || host === "onedrive.live.com" || host === "1drv.ms";
|
|
50880
|
+
} catch {
|
|
50881
|
+
return false;
|
|
50882
|
+
}
|
|
50883
|
+
}
|
|
50884
|
+
function getDrivePrefix(userPrefix, options) {
|
|
50885
|
+
if (options?.siteId) return `/sites/${options.siteId}/drive`;
|
|
50886
|
+
if (options?.driveId) return `/drives/${options.driveId}`;
|
|
50887
|
+
return `${userPrefix}/drive`;
|
|
50888
|
+
}
|
|
50889
|
+
function resolveFileEndpoints(source, drivePrefix) {
|
|
50890
|
+
const trimmed = source.trim();
|
|
50891
|
+
if (isWebUrl(trimmed)) {
|
|
50892
|
+
const token = encodeSharingUrl(trimmed);
|
|
50893
|
+
return {
|
|
50894
|
+
metadataEndpoint: `/shares/${token}/driveItem`,
|
|
50895
|
+
contentEndpoint: `/shares/${token}/driveItem/content`,
|
|
50896
|
+
isSharedUrl: true
|
|
50897
|
+
};
|
|
50898
|
+
}
|
|
50899
|
+
if (trimmed.startsWith("/")) {
|
|
50900
|
+
const path6 = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
|
|
50901
|
+
return {
|
|
50902
|
+
metadataEndpoint: `${drivePrefix}/root:${path6}:`,
|
|
50903
|
+
contentEndpoint: `${drivePrefix}/root:${path6}:/content`,
|
|
50904
|
+
isSharedUrl: false
|
|
50905
|
+
};
|
|
50906
|
+
}
|
|
50907
|
+
return {
|
|
50908
|
+
metadataEndpoint: `${drivePrefix}/items/${trimmed}`,
|
|
50909
|
+
contentEndpoint: `${drivePrefix}/items/${trimmed}/content`,
|
|
50910
|
+
isSharedUrl: false
|
|
50911
|
+
};
|
|
50912
|
+
}
|
|
50913
|
+
function formatFileSize(bytes) {
|
|
50914
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
50915
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
|
50916
|
+
if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
50917
|
+
return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
|
50918
|
+
}
|
|
49068
50919
|
|
|
49069
50920
|
// src/tools/microsoft/createDraftEmail.ts
|
|
49070
50921
|
function createDraftEmailTool(connector, userId) {
|
|
@@ -49770,16 +51621,539 @@ EXAMPLES:
|
|
|
49770
51621
|
};
|
|
49771
51622
|
}
|
|
49772
51623
|
|
|
51624
|
+
// src/tools/microsoft/readFile.ts
|
|
51625
|
+
function createMicrosoftReadFileTool(connector, userId, config) {
|
|
51626
|
+
const reader = DocumentReader.create();
|
|
51627
|
+
const defaultLimit = config?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES;
|
|
51628
|
+
const sizeOverrides = config?.fileSizeLimits;
|
|
51629
|
+
return {
|
|
51630
|
+
definition: {
|
|
51631
|
+
type: "function",
|
|
51632
|
+
function: {
|
|
51633
|
+
name: "read_file",
|
|
51634
|
+
description: `Read a file from Microsoft OneDrive or SharePoint and return its content as **markdown text**.
|
|
51635
|
+
|
|
51636
|
+
Use this tool when you need to read the contents of a document stored in OneDrive or SharePoint. The file is downloaded and automatically converted to clean markdown \u2014 you will never receive raw binary data.
|
|
51637
|
+
|
|
51638
|
+
**Supported formats:** .docx, .pptx, .xlsx, .csv, .pdf, .odt, .odp, .ods, .rtf, .html, .txt, .md, .json, .xml, .yaml
|
|
51639
|
+
**Not supported:** .doc, .xls, .ppt (legacy Office formats), images, videos, executables.
|
|
51640
|
+
|
|
51641
|
+
**The \`source\` parameter is flexible \u2014 you can provide any of these:**
|
|
51642
|
+
- A SharePoint or OneDrive **web URL**: \`https://contoso.sharepoint.com/sites/team/Shared Documents/report.docx\`
|
|
51643
|
+
- A OneDrive **sharing link**: \`https://1drv.ms/w/s!AmVg...\`
|
|
51644
|
+
- A **file path** within the drive: \`/Documents/Q4 Report.docx\`
|
|
51645
|
+
- A Graph API **item ID**: \`01ABCDEF123456\`
|
|
51646
|
+
|
|
51647
|
+
When given a web URL, the tool automatically resolves it to the correct Graph API call \u2014 no need to manually extract drive or item IDs.
|
|
51648
|
+
|
|
51649
|
+
**Maximum file size:** 50 MB (100 MB for presentations). For larger files, use the search or list tools to find smaller alternatives.
|
|
51650
|
+
|
|
51651
|
+
**Returns:** The file content as markdown text, along with metadata (filename, size, MIME type, webUrl). For spreadsheets, each sheet becomes a markdown table. For presentations, each slide becomes a section.`,
|
|
51652
|
+
parameters: {
|
|
51653
|
+
type: "object",
|
|
51654
|
+
properties: {
|
|
51655
|
+
source: {
|
|
51656
|
+
type: "string",
|
|
51657
|
+
description: 'The file to read. Accepts a web URL (SharePoint/OneDrive link), a file path within the drive (e.g., "/Documents/report.docx"), or a Graph API item ID.'
|
|
51658
|
+
},
|
|
51659
|
+
driveId: {
|
|
51660
|
+
type: "string",
|
|
51661
|
+
description: "Optional drive ID. Omit to use the default drive. Only needed when accessing a specific non-default drive."
|
|
51662
|
+
},
|
|
51663
|
+
siteId: {
|
|
51664
|
+
type: "string",
|
|
51665
|
+
description: "Optional SharePoint site ID. Use this instead of driveId to access files in a specific SharePoint site's default drive."
|
|
51666
|
+
},
|
|
51667
|
+
targetUser: {
|
|
51668
|
+
type: "string",
|
|
51669
|
+
description: `User ID or email (e.g., "user@contoso.com"). Only needed with application-only (client_credentials) auth to specify which user's drive to access.`
|
|
51670
|
+
}
|
|
51671
|
+
},
|
|
51672
|
+
required: ["source"]
|
|
51673
|
+
}
|
|
51674
|
+
},
|
|
51675
|
+
blocking: true,
|
|
51676
|
+
timeout: 6e4
|
|
51677
|
+
},
|
|
51678
|
+
describeCall: (args) => {
|
|
51679
|
+
const src = args.source.length > 80 ? args.source.slice(0, 77) + "..." : args.source;
|
|
51680
|
+
return `Read: ${src}`;
|
|
51681
|
+
},
|
|
51682
|
+
permission: {
|
|
51683
|
+
scope: "session",
|
|
51684
|
+
riskLevel: "low",
|
|
51685
|
+
approvalMessage: `Read a file from OneDrive/SharePoint via ${connector.displayName}`
|
|
51686
|
+
},
|
|
51687
|
+
execute: async (args, context) => {
|
|
51688
|
+
const effectiveUserId = context?.userId ?? userId;
|
|
51689
|
+
const effectiveAccountId = context?.accountId;
|
|
51690
|
+
if (!args.source || !args.source.trim()) {
|
|
51691
|
+
return {
|
|
51692
|
+
success: false,
|
|
51693
|
+
error: 'The "source" parameter is required. Provide a file URL, path, or item ID.'
|
|
51694
|
+
};
|
|
51695
|
+
}
|
|
51696
|
+
if (isWebUrl(args.source) && !isMicrosoftFileUrl(args.source)) {
|
|
51697
|
+
return {
|
|
51698
|
+
success: false,
|
|
51699
|
+
error: `The URL "${args.source}" does not appear to be a SharePoint or OneDrive link. This tool only supports URLs from *.sharepoint.com, onedrive.live.com, or 1drv.ms. For other URLs, use the web_fetch tool instead.`
|
|
51700
|
+
};
|
|
51701
|
+
}
|
|
51702
|
+
try {
|
|
51703
|
+
const userPrefix = getUserPathPrefix(connector, args.targetUser);
|
|
51704
|
+
const drivePrefix = getDrivePrefix(userPrefix, {
|
|
51705
|
+
siteId: args.siteId,
|
|
51706
|
+
driveId: args.driveId
|
|
51707
|
+
});
|
|
51708
|
+
const { metadataEndpoint, contentEndpoint, isSharedUrl } = resolveFileEndpoints(
|
|
51709
|
+
args.source,
|
|
51710
|
+
drivePrefix
|
|
51711
|
+
);
|
|
51712
|
+
const metadataQueryParams = isSharedUrl ? {} : { "$select": "id,name,size,file,folder,webUrl,parentReference" };
|
|
51713
|
+
const metadata = await microsoftFetch(connector, metadataEndpoint, {
|
|
51714
|
+
userId: effectiveUserId,
|
|
51715
|
+
accountId: effectiveAccountId,
|
|
51716
|
+
queryParams: metadataQueryParams
|
|
51717
|
+
});
|
|
51718
|
+
if (metadata.folder) {
|
|
51719
|
+
return {
|
|
51720
|
+
success: false,
|
|
51721
|
+
error: `"${metadata.name}" is a folder, not a file. Use the list_files tool to browse folder contents.`
|
|
51722
|
+
};
|
|
51723
|
+
}
|
|
51724
|
+
const ext = getExtension(metadata.name);
|
|
51725
|
+
const sizeLimit = getFileSizeLimit(ext, sizeOverrides, defaultLimit);
|
|
51726
|
+
if (metadata.size > sizeLimit) {
|
|
51727
|
+
return {
|
|
51728
|
+
success: false,
|
|
51729
|
+
filename: metadata.name,
|
|
51730
|
+
sizeBytes: metadata.size,
|
|
51731
|
+
error: `File "${metadata.name}" is ${formatFileSize(metadata.size)}, which exceeds the ${formatFileSize(sizeLimit)} limit for ${ext || "this file type"}. Consider downloading a smaller version or using the search tool to find an alternative.`
|
|
51732
|
+
};
|
|
51733
|
+
}
|
|
51734
|
+
if (ext && !SUPPORTED_EXTENSIONS.has(ext) && !FormatDetector.isBinaryDocumentFormat(ext)) {
|
|
51735
|
+
return {
|
|
51736
|
+
success: false,
|
|
51737
|
+
filename: metadata.name,
|
|
51738
|
+
mimeType: metadata.file?.mimeType,
|
|
51739
|
+
error: `File format "${ext}" is not supported for text extraction. Supported formats: ${[...SUPPORTED_EXTENSIONS].join(", ")}`
|
|
51740
|
+
};
|
|
51741
|
+
}
|
|
51742
|
+
const response = await connector.fetch(
|
|
51743
|
+
contentEndpoint,
|
|
51744
|
+
{ method: "GET" },
|
|
51745
|
+
effectiveUserId,
|
|
51746
|
+
effectiveAccountId
|
|
51747
|
+
);
|
|
51748
|
+
if (!response.ok) {
|
|
51749
|
+
throw new MicrosoftAPIError(response.status, response.statusText, await response.text());
|
|
51750
|
+
}
|
|
51751
|
+
const arrayBuffer = await response.arrayBuffer();
|
|
51752
|
+
const buffer = Buffer.from(arrayBuffer);
|
|
51753
|
+
const result = await reader.read(
|
|
51754
|
+
{ type: "buffer", buffer, filename: metadata.name },
|
|
51755
|
+
{ extractImages: false }
|
|
51756
|
+
);
|
|
51757
|
+
if (!result.success) {
|
|
51758
|
+
return {
|
|
51759
|
+
success: false,
|
|
51760
|
+
filename: metadata.name,
|
|
51761
|
+
error: `Failed to convert "${metadata.name}" to markdown: ${result.error ?? "unknown error"}`
|
|
51762
|
+
};
|
|
51763
|
+
}
|
|
51764
|
+
const markdown = mergeTextPieces(result.pieces);
|
|
51765
|
+
if (!markdown || markdown.trim().length === 0) {
|
|
51766
|
+
return {
|
|
51767
|
+
success: true,
|
|
51768
|
+
filename: metadata.name,
|
|
51769
|
+
sizeBytes: metadata.size,
|
|
51770
|
+
mimeType: metadata.file?.mimeType,
|
|
51771
|
+
webUrl: metadata.webUrl,
|
|
51772
|
+
markdown: "*(empty document \u2014 no text content found)*"
|
|
51773
|
+
};
|
|
51774
|
+
}
|
|
51775
|
+
return {
|
|
51776
|
+
success: true,
|
|
51777
|
+
filename: metadata.name,
|
|
51778
|
+
sizeBytes: metadata.size,
|
|
51779
|
+
mimeType: metadata.file?.mimeType,
|
|
51780
|
+
webUrl: metadata.webUrl,
|
|
51781
|
+
markdown
|
|
51782
|
+
};
|
|
51783
|
+
} catch (error) {
|
|
51784
|
+
if (error instanceof MicrosoftAPIError) {
|
|
51785
|
+
if (error.status === 404) {
|
|
51786
|
+
return {
|
|
51787
|
+
success: false,
|
|
51788
|
+
error: `File not found. Check that the source "${args.source}" is correct and you have access.`
|
|
51789
|
+
};
|
|
51790
|
+
}
|
|
51791
|
+
if (error.status === 403 || error.status === 401) {
|
|
51792
|
+
return {
|
|
51793
|
+
success: false,
|
|
51794
|
+
error: `Access denied. The connector may not have sufficient permissions (Files.Read or Sites.Read.All required).`
|
|
51795
|
+
};
|
|
51796
|
+
}
|
|
51797
|
+
}
|
|
51798
|
+
return {
|
|
51799
|
+
success: false,
|
|
51800
|
+
error: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`
|
|
51801
|
+
};
|
|
51802
|
+
}
|
|
51803
|
+
}
|
|
51804
|
+
};
|
|
51805
|
+
}
|
|
51806
|
+
function getExtension(filename) {
|
|
51807
|
+
const dot = filename.lastIndexOf(".");
|
|
51808
|
+
if (dot < 0) return "";
|
|
51809
|
+
return filename.slice(dot).toLowerCase();
|
|
51810
|
+
}
|
|
51811
|
+
|
|
51812
|
+
// src/tools/microsoft/listFiles.ts
|
|
51813
|
+
var DEFAULT_LIMIT = 50;
|
|
51814
|
+
var MAX_LIMIT = 200;
|
|
51815
|
+
var SELECT_FIELDS = "id,name,size,lastModifiedDateTime,file,folder,webUrl";
|
|
51816
|
+
function createMicrosoftListFilesTool(connector, userId) {
|
|
51817
|
+
return {
|
|
51818
|
+
definition: {
|
|
51819
|
+
type: "function",
|
|
51820
|
+
function: {
|
|
51821
|
+
name: "list_files",
|
|
51822
|
+
description: `List files and folders in a Microsoft OneDrive or SharePoint directory.
|
|
51823
|
+
|
|
51824
|
+
Use this tool to browse the contents of a folder, discover available files before reading them, or search within a specific folder. Returns file/folder metadata (name, size, type, last modified, URL) \u2014 **never returns file contents**.
|
|
51825
|
+
|
|
51826
|
+
**The \`path\` parameter is flexible \u2014 you can provide:**
|
|
51827
|
+
- A **folder path** within the drive: \`/Documents/Projects\` or \`/\` for root
|
|
51828
|
+
- A SharePoint/OneDrive **folder URL**: \`https://contoso.sharepoint.com/sites/team/Shared Documents/Projects\`
|
|
51829
|
+
- Omit entirely to list the root of the drive
|
|
51830
|
+
|
|
51831
|
+
**Optional search:** Use the \`search\` parameter to filter by filename within the folder tree. This uses Microsoft's server-side search (fast, works across subfolders).
|
|
51832
|
+
|
|
51833
|
+
**Tip:** To read a file's content after finding it, use the read_file tool with the file's webUrl or id from these results.`,
|
|
51834
|
+
parameters: {
|
|
51835
|
+
type: "object",
|
|
51836
|
+
properties: {
|
|
51837
|
+
path: {
|
|
51838
|
+
type: "string",
|
|
51839
|
+
description: 'Folder path (e.g., "/Documents/Projects") or a web URL to a SharePoint/OneDrive folder. Omit to list root.'
|
|
51840
|
+
},
|
|
51841
|
+
driveId: {
|
|
51842
|
+
type: "string",
|
|
51843
|
+
description: "Optional drive ID for a specific non-default drive."
|
|
51844
|
+
},
|
|
51845
|
+
siteId: {
|
|
51846
|
+
type: "string",
|
|
51847
|
+
description: "Optional SharePoint site ID to access that site's default document library."
|
|
51848
|
+
},
|
|
51849
|
+
search: {
|
|
51850
|
+
type: "string",
|
|
51851
|
+
description: "Optional search query to filter results by filename or content. Searches within the specified folder and all subfolders."
|
|
51852
|
+
},
|
|
51853
|
+
limit: {
|
|
51854
|
+
type: "number",
|
|
51855
|
+
description: `Maximum number of items to return (default: ${DEFAULT_LIMIT}, max: ${MAX_LIMIT}).`
|
|
51856
|
+
},
|
|
51857
|
+
targetUser: {
|
|
51858
|
+
type: "string",
|
|
51859
|
+
description: "User ID or email. Only needed with application-only (client_credentials) auth."
|
|
51860
|
+
}
|
|
51861
|
+
}
|
|
51862
|
+
}
|
|
51863
|
+
},
|
|
51864
|
+
blocking: true,
|
|
51865
|
+
timeout: 3e4
|
|
51866
|
+
},
|
|
51867
|
+
describeCall: (args) => {
|
|
51868
|
+
const loc = args.path || "/";
|
|
51869
|
+
const suffix = args.search ? ` (search: "${args.search}")` : "";
|
|
51870
|
+
return `List: ${loc}${suffix}`;
|
|
51871
|
+
},
|
|
51872
|
+
permission: {
|
|
51873
|
+
scope: "session",
|
|
51874
|
+
riskLevel: "low",
|
|
51875
|
+
approvalMessage: `List files in OneDrive/SharePoint via ${connector.displayName}`
|
|
51876
|
+
},
|
|
51877
|
+
execute: async (args, context) => {
|
|
51878
|
+
const effectiveUserId = context?.userId ?? userId;
|
|
51879
|
+
const effectiveAccountId = context?.accountId;
|
|
51880
|
+
const limit = Math.min(Math.max(1, args.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
|
|
51881
|
+
try {
|
|
51882
|
+
const userPrefix = getUserPathPrefix(connector, args.targetUser);
|
|
51883
|
+
const drivePrefix = getDrivePrefix(userPrefix, {
|
|
51884
|
+
siteId: args.siteId,
|
|
51885
|
+
driveId: args.driveId
|
|
51886
|
+
});
|
|
51887
|
+
let endpoint;
|
|
51888
|
+
if (args.search) {
|
|
51889
|
+
const folderBase = args.path && !isWebUrl(args.path) ? `${drivePrefix}/root:${normalizePath(args.path)}:` : drivePrefix;
|
|
51890
|
+
endpoint = `${folderBase}/search(q='${encodeSearchQuery(args.search)}')`;
|
|
51891
|
+
} else if (args.path) {
|
|
51892
|
+
if (isWebUrl(args.path)) {
|
|
51893
|
+
const token = encodeSharingUrl(args.path.trim());
|
|
51894
|
+
endpoint = `/shares/${token}/driveItem/children`;
|
|
51895
|
+
} else {
|
|
51896
|
+
const path6 = normalizePath(args.path);
|
|
51897
|
+
endpoint = path6 === "/" ? `${drivePrefix}/root/children` : `${drivePrefix}/root:${path6}:/children`;
|
|
51898
|
+
}
|
|
51899
|
+
} else {
|
|
51900
|
+
endpoint = `${drivePrefix}/root/children`;
|
|
51901
|
+
}
|
|
51902
|
+
const queryParams = {
|
|
51903
|
+
"$top": limit,
|
|
51904
|
+
"$select": SELECT_FIELDS
|
|
51905
|
+
};
|
|
51906
|
+
if (!args.search) {
|
|
51907
|
+
queryParams["$orderby"] = "name asc";
|
|
51908
|
+
}
|
|
51909
|
+
const data = await microsoftFetch(connector, endpoint, {
|
|
51910
|
+
userId: effectiveUserId,
|
|
51911
|
+
accountId: effectiveAccountId,
|
|
51912
|
+
queryParams
|
|
51913
|
+
});
|
|
51914
|
+
const items = (data.value || []).map(mapDriveItem);
|
|
51915
|
+
return {
|
|
51916
|
+
success: true,
|
|
51917
|
+
items,
|
|
51918
|
+
totalCount: items.length,
|
|
51919
|
+
hasMore: !!data["@odata.nextLink"]
|
|
51920
|
+
};
|
|
51921
|
+
} catch (error) {
|
|
51922
|
+
return {
|
|
51923
|
+
success: false,
|
|
51924
|
+
error: `Failed to list files: ${error instanceof Error ? error.message : String(error)}`
|
|
51925
|
+
};
|
|
51926
|
+
}
|
|
51927
|
+
}
|
|
51928
|
+
};
|
|
51929
|
+
}
|
|
51930
|
+
function mapDriveItem(item) {
|
|
51931
|
+
return {
|
|
51932
|
+
name: item.name,
|
|
51933
|
+
type: item.folder ? "folder" : "file",
|
|
51934
|
+
size: item.size,
|
|
51935
|
+
sizeFormatted: formatFileSize(item.size),
|
|
51936
|
+
mimeType: item.file?.mimeType,
|
|
51937
|
+
lastModified: item.lastModifiedDateTime,
|
|
51938
|
+
webUrl: item.webUrl,
|
|
51939
|
+
id: item.id,
|
|
51940
|
+
childCount: item.folder?.childCount
|
|
51941
|
+
};
|
|
51942
|
+
}
|
|
51943
|
+
function normalizePath(path6) {
|
|
51944
|
+
let p = path6.trim();
|
|
51945
|
+
if (!p.startsWith("/")) p = "/" + p;
|
|
51946
|
+
if (p.endsWith("/") && p.length > 1) p = p.slice(0, -1);
|
|
51947
|
+
return p;
|
|
51948
|
+
}
|
|
51949
|
+
function encodeSearchQuery(query) {
|
|
51950
|
+
return query.replace(/\\/g, "\\\\").replace(/'/g, "''");
|
|
51951
|
+
}
|
|
51952
|
+
|
|
51953
|
+
// src/tools/microsoft/searchFiles.ts
|
|
51954
|
+
var DEFAULT_LIMIT2 = 25;
|
|
51955
|
+
var MAX_LIMIT2 = 100;
|
|
51956
|
+
function createMicrosoftSearchFilesTool(connector, userId) {
|
|
51957
|
+
return {
|
|
51958
|
+
definition: {
|
|
51959
|
+
type: "function",
|
|
51960
|
+
function: {
|
|
51961
|
+
name: "search_files",
|
|
51962
|
+
description: `Search for files across Microsoft OneDrive and SharePoint.
|
|
51963
|
+
|
|
51964
|
+
Use this tool when you need to **find** files by name, content, or metadata across all of the user's OneDrive and SharePoint sites. This is a powerful full-text search \u2014 it searches inside document content, not just filenames.
|
|
51965
|
+
|
|
51966
|
+
**Supports Microsoft's KQL (Keyword Query Language):**
|
|
51967
|
+
- Simple text: \`"quarterly report"\`
|
|
51968
|
+
- By filename: \`filename:budget.xlsx\`
|
|
51969
|
+
- By author: \`author:"Jane Smith"\`
|
|
51970
|
+
- By date: \`lastModifiedTime>2024-01-01\`
|
|
51971
|
+
- Combined: \`project proposal filetype:docx\`
|
|
51972
|
+
|
|
51973
|
+
**Filter by file type:** Use the \`fileTypes\` parameter (e.g., \`["docx", "pdf"]\`) to restrict results to specific formats.
|
|
51974
|
+
|
|
51975
|
+
**Limit to a SharePoint site:** Provide the \`siteId\` parameter to search only within a specific site.
|
|
51976
|
+
|
|
51977
|
+
**Returns:** A list of matching files with name, path, site, snippet (text preview), size, and webUrl. Does NOT return file contents \u2014 use the read_file tool to read a specific result.
|
|
51978
|
+
|
|
51979
|
+
**Tip:** Start with a broad search, then use read_file on the most relevant results.`,
|
|
51980
|
+
parameters: {
|
|
51981
|
+
type: "object",
|
|
51982
|
+
properties: {
|
|
51983
|
+
query: {
|
|
51984
|
+
type: "string",
|
|
51985
|
+
description: 'Search query. Supports plain text and KQL syntax (e.g., "budget report", "filename:spec.docx", "author:john filetype:pptx").'
|
|
51986
|
+
},
|
|
51987
|
+
siteId: {
|
|
51988
|
+
type: "string",
|
|
51989
|
+
description: "Optional SharePoint site ID to limit search to a specific site."
|
|
51990
|
+
},
|
|
51991
|
+
fileTypes: {
|
|
51992
|
+
type: "array",
|
|
51993
|
+
items: { type: "string" },
|
|
51994
|
+
description: 'Optional file type filter. Array of extensions without dots (e.g., ["docx", "pdf", "xlsx"]).'
|
|
51995
|
+
},
|
|
51996
|
+
limit: {
|
|
51997
|
+
type: "number",
|
|
51998
|
+
description: `Maximum number of results (default: ${DEFAULT_LIMIT2}, max: ${MAX_LIMIT2}).`
|
|
51999
|
+
},
|
|
52000
|
+
targetUser: {
|
|
52001
|
+
type: "string",
|
|
52002
|
+
description: "User ID or email. Only needed with application-only (client_credentials) auth."
|
|
52003
|
+
}
|
|
52004
|
+
},
|
|
52005
|
+
required: ["query"]
|
|
52006
|
+
}
|
|
52007
|
+
},
|
|
52008
|
+
blocking: true,
|
|
52009
|
+
timeout: 3e4
|
|
52010
|
+
},
|
|
52011
|
+
describeCall: (args) => {
|
|
52012
|
+
const types = args.fileTypes?.length ? ` [${args.fileTypes.join(",")}]` : "";
|
|
52013
|
+
return `Search: "${args.query}"${types}`;
|
|
52014
|
+
},
|
|
52015
|
+
permission: {
|
|
52016
|
+
scope: "session",
|
|
52017
|
+
riskLevel: "low",
|
|
52018
|
+
approvalMessage: `Search files in OneDrive/SharePoint via ${connector.displayName}`
|
|
52019
|
+
},
|
|
52020
|
+
execute: async (args, context) => {
|
|
52021
|
+
const effectiveUserId = context?.userId ?? userId;
|
|
52022
|
+
const effectiveAccountId = context?.accountId;
|
|
52023
|
+
const limit = Math.min(Math.max(1, args.limit ?? DEFAULT_LIMIT2), MAX_LIMIT2);
|
|
52024
|
+
try {
|
|
52025
|
+
if (args.siteId) {
|
|
52026
|
+
return await searchViaDriveEndpoint(
|
|
52027
|
+
connector,
|
|
52028
|
+
args,
|
|
52029
|
+
limit,
|
|
52030
|
+
effectiveUserId,
|
|
52031
|
+
effectiveAccountId
|
|
52032
|
+
);
|
|
52033
|
+
}
|
|
52034
|
+
let queryString = args.query;
|
|
52035
|
+
if (args.fileTypes?.length) {
|
|
52036
|
+
const typeFilter = args.fileTypes.map((t) => `filetype:${t.replace(/^\./, "")}`).join(" OR ");
|
|
52037
|
+
queryString = `(${queryString}) (${typeFilter})`;
|
|
52038
|
+
}
|
|
52039
|
+
const searchRequest = {
|
|
52040
|
+
requests: [
|
|
52041
|
+
{
|
|
52042
|
+
entityTypes: ["driveItem"],
|
|
52043
|
+
query: { queryString },
|
|
52044
|
+
from: 0,
|
|
52045
|
+
size: limit,
|
|
52046
|
+
fields: [
|
|
52047
|
+
"id",
|
|
52048
|
+
"name",
|
|
52049
|
+
"size",
|
|
52050
|
+
"webUrl",
|
|
52051
|
+
"lastModifiedDateTime",
|
|
52052
|
+
"parentReference",
|
|
52053
|
+
"file"
|
|
52054
|
+
]
|
|
52055
|
+
}
|
|
52056
|
+
]
|
|
52057
|
+
};
|
|
52058
|
+
const data = await microsoftFetch(connector, "/search/query", {
|
|
52059
|
+
method: "POST",
|
|
52060
|
+
body: searchRequest,
|
|
52061
|
+
userId: effectiveUserId,
|
|
52062
|
+
accountId: effectiveAccountId
|
|
52063
|
+
});
|
|
52064
|
+
const container = data.value?.[0]?.hitsContainers?.[0];
|
|
52065
|
+
if (!container?.hits?.length) {
|
|
52066
|
+
return {
|
|
52067
|
+
success: true,
|
|
52068
|
+
results: [],
|
|
52069
|
+
totalCount: 0,
|
|
52070
|
+
hasMore: false
|
|
52071
|
+
};
|
|
52072
|
+
}
|
|
52073
|
+
const results = container.hits.map((hit) => {
|
|
52074
|
+
const resource = hit.resource;
|
|
52075
|
+
return {
|
|
52076
|
+
name: resource.name,
|
|
52077
|
+
path: resource.parentReference?.path?.replace(/\/drive\/root:/, "") || void 0,
|
|
52078
|
+
site: resource.parentReference?.siteId || void 0,
|
|
52079
|
+
snippet: hit.summary || void 0,
|
|
52080
|
+
size: resource.size,
|
|
52081
|
+
sizeFormatted: formatFileSize(resource.size),
|
|
52082
|
+
webUrl: resource.webUrl,
|
|
52083
|
+
id: resource.id,
|
|
52084
|
+
lastModified: resource.lastModifiedDateTime
|
|
52085
|
+
};
|
|
52086
|
+
});
|
|
52087
|
+
return {
|
|
52088
|
+
success: true,
|
|
52089
|
+
results,
|
|
52090
|
+
totalCount: container.total,
|
|
52091
|
+
hasMore: container.moreResultsAvailable
|
|
52092
|
+
};
|
|
52093
|
+
} catch (error) {
|
|
52094
|
+
return {
|
|
52095
|
+
success: false,
|
|
52096
|
+
error: `Search failed: ${error instanceof Error ? error.message : String(error)}`
|
|
52097
|
+
};
|
|
52098
|
+
}
|
|
52099
|
+
}
|
|
52100
|
+
};
|
|
52101
|
+
}
|
|
52102
|
+
async function searchViaDriveEndpoint(connector, args, limit, effectiveUserId, effectiveAccountId) {
|
|
52103
|
+
const drivePrefix = `/sites/${args.siteId}/drive`;
|
|
52104
|
+
const escapedQuery = args.query.replace(/'/g, "''");
|
|
52105
|
+
const endpoint = `${drivePrefix}/root/search(q='${escapedQuery}')`;
|
|
52106
|
+
const data = await microsoftFetch(connector, endpoint, {
|
|
52107
|
+
userId: effectiveUserId,
|
|
52108
|
+
accountId: effectiveAccountId,
|
|
52109
|
+
queryParams: {
|
|
52110
|
+
"$top": limit,
|
|
52111
|
+
"$select": "id,name,size,webUrl,lastModifiedDateTime,parentReference,file"
|
|
52112
|
+
}
|
|
52113
|
+
});
|
|
52114
|
+
let items = data.value || [];
|
|
52115
|
+
if (args.fileTypes?.length) {
|
|
52116
|
+
const extSet = new Set(args.fileTypes.map((t) => t.replace(/^\./, "").toLowerCase()));
|
|
52117
|
+
items = items.filter((item) => {
|
|
52118
|
+
const ext = item.name.split(".").pop()?.toLowerCase();
|
|
52119
|
+
return ext && extSet.has(ext);
|
|
52120
|
+
});
|
|
52121
|
+
}
|
|
52122
|
+
const results = items.map((item) => ({
|
|
52123
|
+
name: item.name,
|
|
52124
|
+
path: item.parentReference?.path?.replace(/\/drive\/root:/, "") || void 0,
|
|
52125
|
+
site: item.parentReference?.siteId || void 0,
|
|
52126
|
+
snippet: void 0,
|
|
52127
|
+
size: item.size,
|
|
52128
|
+
sizeFormatted: formatFileSize(item.size),
|
|
52129
|
+
webUrl: item.webUrl,
|
|
52130
|
+
id: item.id,
|
|
52131
|
+
lastModified: item.lastModifiedDateTime
|
|
52132
|
+
}));
|
|
52133
|
+
return {
|
|
52134
|
+
success: true,
|
|
52135
|
+
results,
|
|
52136
|
+
totalCount: results.length,
|
|
52137
|
+
hasMore: !!data["@odata.nextLink"]
|
|
52138
|
+
};
|
|
52139
|
+
}
|
|
52140
|
+
|
|
49773
52141
|
// src/tools/microsoft/register.ts
|
|
49774
52142
|
function registerMicrosoftTools() {
|
|
49775
52143
|
ConnectorTools.registerService("microsoft", (connector, userId) => {
|
|
49776
52144
|
return [
|
|
52145
|
+
// Email
|
|
49777
52146
|
createDraftEmailTool(connector, userId),
|
|
49778
52147
|
createSendEmailTool(connector, userId),
|
|
52148
|
+
// Meetings
|
|
49779
52149
|
createMeetingTool(connector, userId),
|
|
49780
52150
|
createEditMeetingTool(connector, userId),
|
|
49781
52151
|
createGetMeetingTranscriptTool(connector, userId),
|
|
49782
|
-
createFindMeetingSlotsTool(connector, userId)
|
|
52152
|
+
createFindMeetingSlotsTool(connector, userId),
|
|
52153
|
+
// Files (OneDrive / SharePoint)
|
|
52154
|
+
createMicrosoftReadFileTool(connector, userId),
|
|
52155
|
+
createMicrosoftListFilesTool(connector, userId),
|
|
52156
|
+
createMicrosoftSearchFilesTool(connector, userId)
|
|
49783
52157
|
];
|
|
49784
52158
|
});
|
|
49785
52159
|
}
|
|
@@ -51133,6 +53507,311 @@ function createCustomToolTest() {
|
|
|
51133
53507
|
}
|
|
51134
53508
|
var customToolTest = createCustomToolTest();
|
|
51135
53509
|
|
|
53510
|
+
// src/tools/routines/resolveStorage.ts
|
|
53511
|
+
init_StorageRegistry();
|
|
53512
|
+
function buildStorageContext3(toolContext) {
|
|
53513
|
+
const global2 = exports.StorageRegistry.getContext();
|
|
53514
|
+
if (global2) return global2;
|
|
53515
|
+
if (toolContext?.userId) return { userId: toolContext.userId };
|
|
53516
|
+
return void 0;
|
|
53517
|
+
}
|
|
53518
|
+
function resolveRoutineDefinitionStorage(explicit, toolContext) {
|
|
53519
|
+
if (explicit) return explicit;
|
|
53520
|
+
const factory = exports.StorageRegistry.get("routineDefinitions");
|
|
53521
|
+
if (factory) {
|
|
53522
|
+
return factory(buildStorageContext3(toolContext));
|
|
53523
|
+
}
|
|
53524
|
+
return new FileRoutineDefinitionStorage();
|
|
53525
|
+
}
|
|
53526
|
+
|
|
53527
|
+
// src/tools/routines/generateRoutine.ts
|
|
53528
|
+
var TOOL_DESCRIPTION = `Generate and save a complete routine definition to persistent storage. A routine is a reusable, parameterized workflow template composed of tasks with dependencies, control flow, and validation.
|
|
53529
|
+
|
|
53530
|
+
## Routine Structure
|
|
53531
|
+
|
|
53532
|
+
A routine definition has these fields:
|
|
53533
|
+
- **name** (required): Human-readable name (e.g., "Research and Summarize Topic")
|
|
53534
|
+
- **description** (required): What this routine accomplishes
|
|
53535
|
+
- **version**: Semver string for tracking evolution (e.g., "1.0.0")
|
|
53536
|
+
- **author**: Creator name or identifier
|
|
53537
|
+
- **tags**: Array of strings for categorization and filtering (e.g., ["research", "analysis"])
|
|
53538
|
+
- **instructions**: Additional text injected into the agent's system prompt when executing this routine. Use for behavioral guidance, tone, constraints.
|
|
53539
|
+
- **parameters**: Array of input parameters that make the routine reusable. Each has: name, description, required (default false), default. Use {{param.NAME}} in task descriptions/expectedOutput to reference them.
|
|
53540
|
+
- **requiredTools**: Tool names that must be available before starting (e.g., ["web_fetch", "memory_store"])
|
|
53541
|
+
- **requiredPlugins**: Plugin names that must be enabled (e.g., ["working_memory"])
|
|
53542
|
+
- **concurrency**: { maxParallelTasks: number, strategy: "fifo"|"priority"|"shortest-first", failureMode?: "fail-fast"|"continue"|"fail-all" }
|
|
53543
|
+
- **allowDynamicTasks**: If true, the LLM can add/modify tasks during execution (default: false)
|
|
53544
|
+
- **tasks** (required): Array of TaskInput objects defining the workflow steps
|
|
53545
|
+
|
|
53546
|
+
## Task Structure
|
|
53547
|
+
|
|
53548
|
+
Each task in the tasks array has:
|
|
53549
|
+
- **name** (required): Unique name within the routine (used for dependency references)
|
|
53550
|
+
- **description** (required): What this task should accomplish \u2014 the agent uses this as its goal
|
|
53551
|
+
- **dependsOn**: Array of task names that must complete before this task starts (e.g., ["Gather Data", "Validate Input"])
|
|
53552
|
+
- **suggestedTools**: Tool names the agent should prefer for this task (advisory, not enforced)
|
|
53553
|
+
- **expectedOutput**: Description of what the task should produce \u2014 helps the agent know when it's done
|
|
53554
|
+
- **maxAttempts**: Max retry count on failure (default: 3)
|
|
53555
|
+
- **condition**: Execute only if a condition is met (see Conditions below)
|
|
53556
|
+
- **controlFlow**: Map, fold, or until loop (see Control Flow below)
|
|
53557
|
+
- **validation**: Completion validation settings (see Validation below)
|
|
53558
|
+
- **execution**: { parallel?: boolean, maxConcurrency?: number, priority?: number, maxIterations?: number }
|
|
53559
|
+
- **metadata**: Arbitrary key-value pairs for extensions
|
|
53560
|
+
|
|
53561
|
+
## Control Flow Types
|
|
53562
|
+
|
|
53563
|
+
Tasks can have a controlFlow field for iteration patterns:
|
|
53564
|
+
|
|
53565
|
+
### map \u2014 Iterate over an array, run sub-tasks per element
|
|
53566
|
+
\`\`\`json
|
|
53567
|
+
{
|
|
53568
|
+
"type": "map",
|
|
53569
|
+
"source": { "task": "Fetch Items" },
|
|
53570
|
+
"tasks": [
|
|
53571
|
+
{ "name": "Process Item", "description": "Process {{map.item}} ({{map.index}}/{{map.total}})" }
|
|
53572
|
+
],
|
|
53573
|
+
"resultKey": "processed_items",
|
|
53574
|
+
"maxIterations": 100,
|
|
53575
|
+
"iterationTimeoutMs": 30000
|
|
53576
|
+
}
|
|
53577
|
+
\`\`\`
|
|
53578
|
+
|
|
53579
|
+
### fold \u2014 Accumulate a result across array elements
|
|
53580
|
+
\`\`\`json
|
|
53581
|
+
{
|
|
53582
|
+
"type": "fold",
|
|
53583
|
+
"source": { "key": "data_points", "path": "results" },
|
|
53584
|
+
"tasks": [
|
|
53585
|
+
{ "name": "Merge Entry", "description": "Merge {{map.item}} into {{fold.accumulator}}" }
|
|
53586
|
+
],
|
|
53587
|
+
"initialValue": "",
|
|
53588
|
+
"resultKey": "merged_result",
|
|
53589
|
+
"maxIterations": 50
|
|
53590
|
+
}
|
|
53591
|
+
\`\`\`
|
|
53592
|
+
|
|
53593
|
+
### until \u2014 Loop until a condition is met
|
|
53594
|
+
\`\`\`json
|
|
53595
|
+
{
|
|
53596
|
+
"type": "until",
|
|
53597
|
+
"tasks": [
|
|
53598
|
+
{ "name": "Refine Draft", "description": "Improve the current draft based on feedback" }
|
|
53599
|
+
],
|
|
53600
|
+
"condition": { "memoryKey": "quality_score", "operator": "greater_than", "value": 80, "onFalse": "skip" },
|
|
53601
|
+
"maxIterations": 5,
|
|
53602
|
+
"iterationKey": "refinement_round"
|
|
53603
|
+
}
|
|
53604
|
+
\`\`\`
|
|
53605
|
+
|
|
53606
|
+
### Source field
|
|
53607
|
+
The \`source\` field in map/fold can be:
|
|
53608
|
+
- A string: direct memory key lookup (e.g., "my_items")
|
|
53609
|
+
- \`{ task: "TaskName" }\`: resolves the output of a completed dependency task
|
|
53610
|
+
- \`{ key: "memoryKey" }\`: direct memory key lookup
|
|
53611
|
+
- \`{ key: "memoryKey", path: "data.items" }\`: memory key with JSON path extraction
|
|
53612
|
+
|
|
53613
|
+
### Sub-routine tasks
|
|
53614
|
+
Tasks inside controlFlow.tasks have the same shape as regular tasks (name, description, dependsOn, suggestedTools, etc.) but execute within the control flow context.
|
|
53615
|
+
|
|
53616
|
+
## Template Placeholders
|
|
53617
|
+
|
|
53618
|
+
Use these in task descriptions and expectedOutput:
|
|
53619
|
+
- \`{{param.NAME}}\` \u2014 routine parameter value
|
|
53620
|
+
- \`{{map.item}}\` \u2014 current element in map/fold iteration
|
|
53621
|
+
- \`{{map.index}}\` \u2014 current 0-based iteration index
|
|
53622
|
+
- \`{{map.total}}\` \u2014 total number of elements
|
|
53623
|
+
- \`{{fold.accumulator}}\` \u2014 current accumulated value in fold
|
|
53624
|
+
|
|
53625
|
+
## Task Conditions
|
|
53626
|
+
|
|
53627
|
+
Execute a task conditionally based on memory state:
|
|
53628
|
+
\`\`\`json
|
|
53629
|
+
{
|
|
53630
|
+
"memoryKey": "user_preference",
|
|
53631
|
+
"operator": "equals",
|
|
53632
|
+
"value": "detailed",
|
|
53633
|
+
"onFalse": "skip"
|
|
53634
|
+
}
|
|
53635
|
+
\`\`\`
|
|
53636
|
+
|
|
53637
|
+
Operators: "exists", "not_exists", "equals", "contains", "truthy", "greater_than", "less_than"
|
|
53638
|
+
onFalse actions: "skip" (mark skipped), "fail" (mark failed), "wait" (block until condition met)
|
|
53639
|
+
|
|
53640
|
+
## Validation
|
|
53641
|
+
|
|
53642
|
+
Enable completion validation to verify task quality:
|
|
53643
|
+
\`\`\`json
|
|
53644
|
+
{
|
|
53645
|
+
"skipReflection": false,
|
|
53646
|
+
"completionCriteria": [
|
|
53647
|
+
"Response contains at least 3 specific examples",
|
|
53648
|
+
"All requested sections are present"
|
|
53649
|
+
],
|
|
53650
|
+
"minCompletionScore": 80,
|
|
53651
|
+
"requiredMemoryKeys": ["result_data"],
|
|
53652
|
+
"mode": "strict"
|
|
53653
|
+
}
|
|
53654
|
+
\`\`\`
|
|
53655
|
+
|
|
53656
|
+
By default, skipReflection is true (validation auto-passes). Set to false and provide completionCriteria to enable LLM self-reflection validation.
|
|
53657
|
+
|
|
53658
|
+
## Best Practices
|
|
53659
|
+
|
|
53660
|
+
1. **Task naming**: Use clear, action-oriented names (e.g., "Research Topic", "Generate Summary"). Names are used in dependsOn references.
|
|
53661
|
+
2. **Dependency chaining**: Build pipelines by having each task depend on the previous one. Independent tasks can run in parallel.
|
|
53662
|
+
3. **Control flow vs sequential**: Use map/fold when iterating over dynamic data. Use sequential tasks for fixed multi-step workflows.
|
|
53663
|
+
4. **Parameters**: Define parameters for any value that should vary between executions. Always provide a description.
|
|
53664
|
+
5. **Instructions**: Use the instructions field for behavioral guidance that applies to all tasks in the routine.
|
|
53665
|
+
6. **Keep tasks focused**: Each task should have a single clear goal. Break complex work into multiple dependent tasks.
|
|
53666
|
+
7. **Expected output**: Always specify expectedOutput \u2014 it helps the agent know when it's done and what format to produce.`;
|
|
53667
|
+
function createGenerateRoutine(storage) {
|
|
53668
|
+
return {
|
|
53669
|
+
definition: {
|
|
53670
|
+
type: "function",
|
|
53671
|
+
function: {
|
|
53672
|
+
name: "generate_routine",
|
|
53673
|
+
description: TOOL_DESCRIPTION,
|
|
53674
|
+
parameters: {
|
|
53675
|
+
type: "object",
|
|
53676
|
+
properties: {
|
|
53677
|
+
definition: {
|
|
53678
|
+
type: "object",
|
|
53679
|
+
description: "Complete routine definition input",
|
|
53680
|
+
properties: {
|
|
53681
|
+
name: { type: "string", description: "Human-readable routine name" },
|
|
53682
|
+
description: { type: "string", description: "What this routine accomplishes" },
|
|
53683
|
+
version: { type: "string", description: 'Semver version string (e.g., "1.0.0")' },
|
|
53684
|
+
author: { type: "string", description: "Creator name or identifier" },
|
|
53685
|
+
tags: { type: "array", items: { type: "string" }, description: "Tags for categorization" },
|
|
53686
|
+
instructions: { type: "string", description: "Additional instructions injected into system prompt during execution" },
|
|
53687
|
+
parameters: {
|
|
53688
|
+
type: "array",
|
|
53689
|
+
description: "Input parameters for reusable routines",
|
|
53690
|
+
items: {
|
|
53691
|
+
type: "object",
|
|
53692
|
+
properties: {
|
|
53693
|
+
name: { type: "string", description: "Parameter name (referenced as {{param.name}})" },
|
|
53694
|
+
description: { type: "string", description: "Human-readable description" },
|
|
53695
|
+
required: { type: "boolean", description: "Whether this parameter must be provided (default: false)" },
|
|
53696
|
+
default: { description: "Default value when not provided" }
|
|
53697
|
+
},
|
|
53698
|
+
required: ["name", "description"]
|
|
53699
|
+
}
|
|
53700
|
+
},
|
|
53701
|
+
requiredTools: { type: "array", items: { type: "string" }, description: "Tool names that must be available" },
|
|
53702
|
+
requiredPlugins: { type: "array", items: { type: "string" }, description: "Plugin names that must be enabled" },
|
|
53703
|
+
concurrency: {
|
|
53704
|
+
type: "object",
|
|
53705
|
+
description: "Concurrency settings for parallel task execution",
|
|
53706
|
+
properties: {
|
|
53707
|
+
maxParallelTasks: { type: "number", description: "Maximum tasks running in parallel" },
|
|
53708
|
+
strategy: { type: "string", enum: ["fifo", "priority", "shortest-first"], description: "Task selection strategy" },
|
|
53709
|
+
failureMode: { type: "string", enum: ["fail-fast", "continue", "fail-all"], description: "How to handle failures in parallel" }
|
|
53710
|
+
},
|
|
53711
|
+
required: ["maxParallelTasks", "strategy"]
|
|
53712
|
+
},
|
|
53713
|
+
allowDynamicTasks: { type: "boolean", description: "Allow LLM to add/modify tasks during execution (default: false)" },
|
|
53714
|
+
tasks: {
|
|
53715
|
+
type: "array",
|
|
53716
|
+
description: "Array of task definitions forming the workflow",
|
|
53717
|
+
items: {
|
|
53718
|
+
type: "object",
|
|
53719
|
+
properties: {
|
|
53720
|
+
name: { type: "string", description: "Unique task name (used in dependsOn references)" },
|
|
53721
|
+
description: { type: "string", description: "What this task should accomplish" },
|
|
53722
|
+
dependsOn: { type: "array", items: { type: "string" }, description: "Task names that must complete first" },
|
|
53723
|
+
suggestedTools: { type: "array", items: { type: "string" }, description: "Preferred tool names for this task" },
|
|
53724
|
+
expectedOutput: { type: "string", description: "Description of expected task output" },
|
|
53725
|
+
maxAttempts: { type: "number", description: "Max retries on failure (default: 3)" },
|
|
53726
|
+
condition: {
|
|
53727
|
+
type: "object",
|
|
53728
|
+
description: "Conditional execution based on memory state",
|
|
53729
|
+
properties: {
|
|
53730
|
+
memoryKey: { type: "string", description: "Memory key to check" },
|
|
53731
|
+
operator: { type: "string", enum: ["exists", "not_exists", "equals", "contains", "truthy", "greater_than", "less_than"] },
|
|
53732
|
+
value: { description: "Value to compare against" },
|
|
53733
|
+
onFalse: { type: "string", enum: ["skip", "fail", "wait"], description: "Action when condition is false" }
|
|
53734
|
+
},
|
|
53735
|
+
required: ["memoryKey", "operator", "onFalse"]
|
|
53736
|
+
},
|
|
53737
|
+
controlFlow: {
|
|
53738
|
+
type: "object",
|
|
53739
|
+
description: "Control flow for iteration (map, fold, or until)",
|
|
53740
|
+
properties: {
|
|
53741
|
+
type: { type: "string", enum: ["map", "fold", "until"], description: "Control flow type" },
|
|
53742
|
+
source: { description: 'Source data: string key, { task: "name" }, { key: "key" }, or { key: "key", path: "json.path" }' },
|
|
53743
|
+
tasks: { type: "array", description: "Sub-routine tasks to execute per iteration", items: { type: "object" } },
|
|
53744
|
+
resultKey: { type: "string", description: "Memory key for collected results" },
|
|
53745
|
+
initialValue: { description: "Starting accumulator value (fold only)" },
|
|
53746
|
+
condition: { type: "object", description: "Exit condition (until only)" },
|
|
53747
|
+
maxIterations: { type: "number", description: "Cap on iterations" },
|
|
53748
|
+
iterationKey: { type: "string", description: "Memory key for iteration index (until only)" },
|
|
53749
|
+
iterationTimeoutMs: { type: "number", description: "Timeout per iteration in ms" }
|
|
53750
|
+
},
|
|
53751
|
+
required: ["type", "tasks"]
|
|
53752
|
+
},
|
|
53753
|
+
validation: {
|
|
53754
|
+
type: "object",
|
|
53755
|
+
description: "Completion validation settings",
|
|
53756
|
+
properties: {
|
|
53757
|
+
skipReflection: { type: "boolean", description: "Set to false to enable LLM self-reflection validation" },
|
|
53758
|
+
completionCriteria: { type: "array", items: { type: "string" }, description: "Natural language criteria for completion" },
|
|
53759
|
+
minCompletionScore: { type: "number", description: "Minimum score (0-100) to pass (default: 80)" },
|
|
53760
|
+
requiredMemoryKeys: { type: "array", items: { type: "string" }, description: "Memory keys that must exist after completion" },
|
|
53761
|
+
mode: { type: "string", enum: ["strict", "warn"], description: "Validation failure mode (default: strict)" },
|
|
53762
|
+
requireUserApproval: { type: "string", enum: ["never", "uncertain", "always"], description: "When to ask user for approval" },
|
|
53763
|
+
customValidator: { type: "string", description: "Custom validation hook name" }
|
|
53764
|
+
}
|
|
53765
|
+
},
|
|
53766
|
+
execution: {
|
|
53767
|
+
type: "object",
|
|
53768
|
+
description: "Execution settings",
|
|
53769
|
+
properties: {
|
|
53770
|
+
parallel: { type: "boolean", description: "Can run in parallel with other parallel tasks" },
|
|
53771
|
+
maxConcurrency: { type: "number", description: "Max concurrent sub-work" },
|
|
53772
|
+
priority: { type: "number", description: "Higher = executed first" },
|
|
53773
|
+
maxIterations: { type: "number", description: "Max LLM iterations per task (default: 50)" }
|
|
53774
|
+
}
|
|
53775
|
+
},
|
|
53776
|
+
metadata: { type: "object", description: "Arbitrary key-value metadata" }
|
|
53777
|
+
},
|
|
53778
|
+
required: ["name", "description"]
|
|
53779
|
+
}
|
|
53780
|
+
},
|
|
53781
|
+
metadata: { type: "object", description: "Arbitrary routine-level metadata" }
|
|
53782
|
+
},
|
|
53783
|
+
required: ["name", "description", "tasks"]
|
|
53784
|
+
}
|
|
53785
|
+
},
|
|
53786
|
+
required: ["definition"]
|
|
53787
|
+
}
|
|
53788
|
+
}
|
|
53789
|
+
},
|
|
53790
|
+
permission: { scope: "session", riskLevel: "medium" },
|
|
53791
|
+
execute: async (args, context) => {
|
|
53792
|
+
try {
|
|
53793
|
+
const userId = context?.userId;
|
|
53794
|
+
const s = resolveRoutineDefinitionStorage(storage, context);
|
|
53795
|
+
const routineDefinition = createRoutineDefinition(args.definition);
|
|
53796
|
+
await s.save(userId, routineDefinition);
|
|
53797
|
+
return {
|
|
53798
|
+
success: true,
|
|
53799
|
+
id: routineDefinition.id,
|
|
53800
|
+
name: routineDefinition.name,
|
|
53801
|
+
storagePath: s.getPath(userId)
|
|
53802
|
+
};
|
|
53803
|
+
} catch (error) {
|
|
53804
|
+
return {
|
|
53805
|
+
success: false,
|
|
53806
|
+
error: error.message
|
|
53807
|
+
};
|
|
53808
|
+
}
|
|
53809
|
+
},
|
|
53810
|
+
describeCall: (args) => args.definition?.name ?? "routine"
|
|
53811
|
+
};
|
|
53812
|
+
}
|
|
53813
|
+
var generateRoutine = createGenerateRoutine();
|
|
53814
|
+
|
|
51136
53815
|
// src/tools/registry.generated.ts
|
|
51137
53816
|
var toolRegistry = [
|
|
51138
53817
|
{
|
|
@@ -51360,6 +54039,15 @@ var toolRegistry = [
|
|
|
51360
54039
|
tool: jsonManipulator,
|
|
51361
54040
|
safeByDefault: true
|
|
51362
54041
|
},
|
|
54042
|
+
{
|
|
54043
|
+
name: "generate_routine",
|
|
54044
|
+
exportName: "generateRoutine",
|
|
54045
|
+
displayName: "Generate Routine",
|
|
54046
|
+
category: "routines",
|
|
54047
|
+
description: "Complete routine definition input",
|
|
54048
|
+
tool: generateRoutine,
|
|
54049
|
+
safeByDefault: false
|
|
54050
|
+
},
|
|
51363
54051
|
{
|
|
51364
54052
|
name: "bash",
|
|
51365
54053
|
exportName: "bash",
|
|
@@ -51789,6 +54477,127 @@ REMEMBER: Keep it conversational, ask one question at a time, and only output th
|
|
|
51789
54477
|
}
|
|
51790
54478
|
};
|
|
51791
54479
|
|
|
54480
|
+
// src/infrastructure/scheduling/SimpleScheduler.ts
|
|
54481
|
+
var SimpleScheduler = class {
|
|
54482
|
+
timers = /* @__PURE__ */ new Map();
|
|
54483
|
+
_isDestroyed = false;
|
|
54484
|
+
schedule(id, spec, callback) {
|
|
54485
|
+
if (this._isDestroyed) throw new Error("Scheduler has been destroyed");
|
|
54486
|
+
if (spec.cron) {
|
|
54487
|
+
throw new Error(
|
|
54488
|
+
`SimpleScheduler does not support cron expressions. Use a cron-capable scheduler implementation (e.g. node-cron, croner) or convert to intervalMs.`
|
|
54489
|
+
);
|
|
54490
|
+
}
|
|
54491
|
+
if (this.timers.has(id)) {
|
|
54492
|
+
this.cancel(id);
|
|
54493
|
+
}
|
|
54494
|
+
if (spec.intervalMs != null) {
|
|
54495
|
+
const timer = setInterval(() => {
|
|
54496
|
+
try {
|
|
54497
|
+
const result = callback();
|
|
54498
|
+
if (result && typeof result.catch === "function") {
|
|
54499
|
+
result.catch(() => {
|
|
54500
|
+
});
|
|
54501
|
+
}
|
|
54502
|
+
} catch {
|
|
54503
|
+
}
|
|
54504
|
+
}, spec.intervalMs);
|
|
54505
|
+
this.timers.set(id, { timer, type: "interval" });
|
|
54506
|
+
} else if (spec.once != null) {
|
|
54507
|
+
const delay = Math.max(0, spec.once - Date.now());
|
|
54508
|
+
const timer = setTimeout(() => {
|
|
54509
|
+
this.timers.delete(id);
|
|
54510
|
+
try {
|
|
54511
|
+
const result = callback();
|
|
54512
|
+
if (result && typeof result.catch === "function") {
|
|
54513
|
+
result.catch(() => {
|
|
54514
|
+
});
|
|
54515
|
+
}
|
|
54516
|
+
} catch {
|
|
54517
|
+
}
|
|
54518
|
+
}, delay);
|
|
54519
|
+
this.timers.set(id, { timer, type: "timeout" });
|
|
54520
|
+
} else {
|
|
54521
|
+
throw new Error("ScheduleSpec must have at least one of: cron, intervalMs, once");
|
|
54522
|
+
}
|
|
54523
|
+
return {
|
|
54524
|
+
id,
|
|
54525
|
+
cancel: () => this.cancel(id)
|
|
54526
|
+
};
|
|
54527
|
+
}
|
|
54528
|
+
cancel(id) {
|
|
54529
|
+
const entry = this.timers.get(id);
|
|
54530
|
+
if (!entry) return;
|
|
54531
|
+
if (entry.type === "interval") {
|
|
54532
|
+
clearInterval(entry.timer);
|
|
54533
|
+
} else {
|
|
54534
|
+
clearTimeout(entry.timer);
|
|
54535
|
+
}
|
|
54536
|
+
this.timers.delete(id);
|
|
54537
|
+
}
|
|
54538
|
+
cancelAll() {
|
|
54539
|
+
for (const [id] of this.timers) {
|
|
54540
|
+
this.cancel(id);
|
|
54541
|
+
}
|
|
54542
|
+
}
|
|
54543
|
+
has(id) {
|
|
54544
|
+
return this.timers.has(id);
|
|
54545
|
+
}
|
|
54546
|
+
destroy() {
|
|
54547
|
+
if (this._isDestroyed) return;
|
|
54548
|
+
this.cancelAll();
|
|
54549
|
+
this._isDestroyed = true;
|
|
54550
|
+
}
|
|
54551
|
+
get isDestroyed() {
|
|
54552
|
+
return this._isDestroyed;
|
|
54553
|
+
}
|
|
54554
|
+
};
|
|
54555
|
+
|
|
54556
|
+
// src/infrastructure/triggers/EventEmitterTrigger.ts
|
|
54557
|
+
var EventEmitterTrigger = class {
|
|
54558
|
+
listeners = /* @__PURE__ */ new Map();
|
|
54559
|
+
_isDestroyed = false;
|
|
54560
|
+
/**
|
|
54561
|
+
* Register a listener for an event. Returns an unsubscribe function.
|
|
54562
|
+
*/
|
|
54563
|
+
on(event, callback) {
|
|
54564
|
+
if (this._isDestroyed) throw new Error("EventEmitterTrigger has been destroyed");
|
|
54565
|
+
if (!this.listeners.has(event)) {
|
|
54566
|
+
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
54567
|
+
}
|
|
54568
|
+
this.listeners.get(event).add(callback);
|
|
54569
|
+
return () => {
|
|
54570
|
+
this.listeners.get(event)?.delete(callback);
|
|
54571
|
+
};
|
|
54572
|
+
}
|
|
54573
|
+
/**
|
|
54574
|
+
* Emit an event to all registered listeners.
|
|
54575
|
+
*/
|
|
54576
|
+
emit(event, payload) {
|
|
54577
|
+
if (this._isDestroyed) return;
|
|
54578
|
+
const callbacks = this.listeners.get(event);
|
|
54579
|
+
if (!callbacks) return;
|
|
54580
|
+
for (const cb of callbacks) {
|
|
54581
|
+
try {
|
|
54582
|
+
const result = cb(payload);
|
|
54583
|
+
if (result && typeof result.catch === "function") {
|
|
54584
|
+
result.catch(() => {
|
|
54585
|
+
});
|
|
54586
|
+
}
|
|
54587
|
+
} catch {
|
|
54588
|
+
}
|
|
54589
|
+
}
|
|
54590
|
+
}
|
|
54591
|
+
destroy() {
|
|
54592
|
+
if (this._isDestroyed) return;
|
|
54593
|
+
this.listeners.clear();
|
|
54594
|
+
this._isDestroyed = true;
|
|
54595
|
+
}
|
|
54596
|
+
get isDestroyed() {
|
|
54597
|
+
return this._isDestroyed;
|
|
54598
|
+
}
|
|
54599
|
+
};
|
|
54600
|
+
|
|
51792
54601
|
exports.AGENT_DEFINITION_FORMAT_VERSION = AGENT_DEFINITION_FORMAT_VERSION;
|
|
51793
54602
|
exports.AIError = AIError;
|
|
51794
54603
|
exports.APPROVAL_STATE_VERSION = APPROVAL_STATE_VERSION;
|
|
@@ -51825,6 +54634,7 @@ exports.DefaultCompactionStrategy = DefaultCompactionStrategy;
|
|
|
51825
54634
|
exports.DependencyCycleError = DependencyCycleError;
|
|
51826
54635
|
exports.DocumentReader = DocumentReader;
|
|
51827
54636
|
exports.ErrorHandler = ErrorHandler;
|
|
54637
|
+
exports.EventEmitterTrigger = EventEmitterTrigger;
|
|
51828
54638
|
exports.ExecutionContext = ExecutionContext;
|
|
51829
54639
|
exports.ExternalDependencyHandler = ExternalDependencyHandler;
|
|
51830
54640
|
exports.FileAgentDefinitionStorage = FileAgentDefinitionStorage;
|
|
@@ -51890,6 +54700,7 @@ exports.ScrapeProvider = ScrapeProvider;
|
|
|
51890
54700
|
exports.SearchProvider = SearchProvider;
|
|
51891
54701
|
exports.SerperProvider = SerperProvider;
|
|
51892
54702
|
exports.Services = Services;
|
|
54703
|
+
exports.SimpleScheduler = SimpleScheduler;
|
|
51893
54704
|
exports.SpeechToText = SpeechToText;
|
|
51894
54705
|
exports.StrategyRegistry = StrategyRegistry;
|
|
51895
54706
|
exports.StreamEventType = StreamEventType;
|
|
@@ -51905,6 +54716,8 @@ exports.TavilyProvider = TavilyProvider;
|
|
|
51905
54716
|
exports.TextToSpeech = TextToSpeech;
|
|
51906
54717
|
exports.TokenBucketRateLimiter = TokenBucketRateLimiter;
|
|
51907
54718
|
exports.ToolCallState = ToolCallState;
|
|
54719
|
+
exports.ToolCatalogPluginNextGen = ToolCatalogPluginNextGen;
|
|
54720
|
+
exports.ToolCatalogRegistry = ToolCatalogRegistry;
|
|
51908
54721
|
exports.ToolExecutionError = ToolExecutionError;
|
|
51909
54722
|
exports.ToolExecutionPipeline = ToolExecutionPipeline;
|
|
51910
54723
|
exports.ToolManager = ToolManager;
|
|
@@ -51968,6 +54781,7 @@ exports.createEditFileTool = createEditFileTool;
|
|
|
51968
54781
|
exports.createEditMeetingTool = createEditMeetingTool;
|
|
51969
54782
|
exports.createEstimator = createEstimator;
|
|
51970
54783
|
exports.createExecuteJavaScriptTool = createExecuteJavaScriptTool;
|
|
54784
|
+
exports.createExecutionRecorder = createExecutionRecorder;
|
|
51971
54785
|
exports.createFileAgentDefinitionStorage = createFileAgentDefinitionStorage;
|
|
51972
54786
|
exports.createFileContextStorage = createFileContextStorage;
|
|
51973
54787
|
exports.createFileCustomToolStorage = createFileCustomToolStorage;
|
|
@@ -51985,6 +54799,9 @@ exports.createListDirectoryTool = createListDirectoryTool;
|
|
|
51985
54799
|
exports.createMeetingTool = createMeetingTool;
|
|
51986
54800
|
exports.createMessageWithImages = createMessageWithImages;
|
|
51987
54801
|
exports.createMetricsCollector = createMetricsCollector;
|
|
54802
|
+
exports.createMicrosoftListFilesTool = createMicrosoftListFilesTool;
|
|
54803
|
+
exports.createMicrosoftReadFileTool = createMicrosoftReadFileTool;
|
|
54804
|
+
exports.createMicrosoftSearchFilesTool = createMicrosoftSearchFilesTool;
|
|
51988
54805
|
exports.createPRCommentsTool = createPRCommentsTool;
|
|
51989
54806
|
exports.createPRFilesTool = createPRFilesTool;
|
|
51990
54807
|
exports.createPlan = createPlan;
|
|
@@ -51992,11 +54809,13 @@ exports.createProvider = createProvider;
|
|
|
51992
54809
|
exports.createReadFileTool = createReadFileTool;
|
|
51993
54810
|
exports.createRoutineDefinition = createRoutineDefinition;
|
|
51994
54811
|
exports.createRoutineExecution = createRoutineExecution;
|
|
54812
|
+
exports.createRoutineExecutionRecord = createRoutineExecutionRecord;
|
|
51995
54813
|
exports.createSearchCodeTool = createSearchCodeTool;
|
|
51996
54814
|
exports.createSearchFilesTool = createSearchFilesTool;
|
|
51997
54815
|
exports.createSendEmailTool = createSendEmailTool;
|
|
51998
54816
|
exports.createSpeechToTextTool = createSpeechToTextTool;
|
|
51999
54817
|
exports.createTask = createTask;
|
|
54818
|
+
exports.createTaskSnapshots = createTaskSnapshots;
|
|
52000
54819
|
exports.createTextMessage = createTextMessage;
|
|
52001
54820
|
exports.createTextToSpeechTool = createTextToSpeechTool;
|
|
52002
54821
|
exports.createVideoProvider = createVideoProvider;
|
|
@@ -52026,6 +54845,7 @@ exports.detectServiceFromURL = detectServiceFromURL;
|
|
|
52026
54845
|
exports.developerTools = developerTools;
|
|
52027
54846
|
exports.documentToContent = documentToContent;
|
|
52028
54847
|
exports.editFile = editFile;
|
|
54848
|
+
exports.encodeSharingUrl = encodeSharingUrl;
|
|
52029
54849
|
exports.evaluateCondition = evaluateCondition;
|
|
52030
54850
|
exports.executeRoutine = executeRoutine;
|
|
52031
54851
|
exports.extractJSON = extractJSON;
|
|
@@ -52035,6 +54855,7 @@ exports.findConnectorByServiceTypes = findConnectorByServiceTypes;
|
|
|
52035
54855
|
exports.forPlan = forPlan;
|
|
52036
54856
|
exports.forTasks = forTasks;
|
|
52037
54857
|
exports.formatAttendees = formatAttendees;
|
|
54858
|
+
exports.formatFileSize = formatFileSize;
|
|
52038
54859
|
exports.formatPluginDisplayName = formatPluginDisplayName;
|
|
52039
54860
|
exports.formatRecipients = formatRecipients;
|
|
52040
54861
|
exports.generateEncryptionKey = generateEncryptionKey;
|
|
@@ -52054,6 +54875,7 @@ exports.getConnectorTools = getConnectorTools;
|
|
|
52054
54875
|
exports.getCredentialsSetupURL = getCredentialsSetupURL;
|
|
52055
54876
|
exports.getDesktopDriver = getDesktopDriver;
|
|
52056
54877
|
exports.getDocsURL = getDocsURL;
|
|
54878
|
+
exports.getDrivePrefix = getDrivePrefix;
|
|
52057
54879
|
exports.getImageModelInfo = getImageModelInfo;
|
|
52058
54880
|
exports.getImageModelsByVendor = getImageModelsByVendor;
|
|
52059
54881
|
exports.getImageModelsWithFeature = getImageModelsWithFeature;
|
|
@@ -52103,6 +54925,7 @@ exports.isBlockedCommand = isBlockedCommand;
|
|
|
52103
54925
|
exports.isErrorEvent = isErrorEvent;
|
|
52104
54926
|
exports.isExcludedExtension = isExcludedExtension;
|
|
52105
54927
|
exports.isKnownService = isKnownService;
|
|
54928
|
+
exports.isMicrosoftFileUrl = isMicrosoftFileUrl;
|
|
52106
54929
|
exports.isOutputTextDelta = isOutputTextDelta;
|
|
52107
54930
|
exports.isReasoningDelta = isReasoningDelta;
|
|
52108
54931
|
exports.isReasoningDone = isReasoningDone;
|
|
@@ -52118,6 +54941,7 @@ exports.isToolCallArgumentsDelta = isToolCallArgumentsDelta;
|
|
|
52118
54941
|
exports.isToolCallArgumentsDone = isToolCallArgumentsDone;
|
|
52119
54942
|
exports.isToolCallStart = isToolCallStart;
|
|
52120
54943
|
exports.isVendor = isVendor;
|
|
54944
|
+
exports.isWebUrl = isWebUrl;
|
|
52121
54945
|
exports.killBackgroundProcess = killBackgroundProcess;
|
|
52122
54946
|
exports.listConnectorsByServiceTypes = listConnectorsByServiceTypes;
|
|
52123
54947
|
exports.listDirectory = listDirectory;
|
|
@@ -52138,6 +54962,8 @@ exports.registerScrapeProvider = registerScrapeProvider;
|
|
|
52138
54962
|
exports.resetDefaultDriver = resetDefaultDriver;
|
|
52139
54963
|
exports.resolveConnector = resolveConnector;
|
|
52140
54964
|
exports.resolveDependencies = resolveDependencies;
|
|
54965
|
+
exports.resolveFileEndpoints = resolveFileEndpoints;
|
|
54966
|
+
exports.resolveFlowSource = resolveFlowSource;
|
|
52141
54967
|
exports.resolveMaxContextTokens = resolveMaxContextTokens;
|
|
52142
54968
|
exports.resolveMeetingId = resolveMeetingId;
|
|
52143
54969
|
exports.resolveModelCapabilities = resolveModelCapabilities;
|