@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/dist/index.js CHANGED
@@ -9960,15 +9960,16 @@ var init_PDFHandler = __esm({
9960
9960
  const unpdf = await getUnpdf();
9961
9961
  const pieces = [];
9962
9962
  let pieceIndex = 0;
9963
+ const data = new Uint8Array(buffer);
9963
9964
  let metadata = {};
9964
9965
  const includeMetadata = options.formatOptions?.pdf?.includeMetadata !== false;
9965
9966
  if (includeMetadata) {
9966
9967
  try {
9967
- metadata = await unpdf.getMeta(buffer);
9968
+ metadata = await unpdf.getMeta(data);
9968
9969
  } catch {
9969
9970
  }
9970
9971
  }
9971
- const textResult = await unpdf.extractText(buffer, { mergePages: false });
9972
+ const textResult = await unpdf.extractText(data, { mergePages: false });
9972
9973
  const pages = textResult?.pages || textResult?.text ? Array.isArray(textResult.text) ? textResult.text : [textResult.text] : [];
9973
9974
  const requestedPages = options.pages;
9974
9975
  const pageEntries = pages.map((text, i) => ({ text, pageNum: i + 1 }));
@@ -10021,7 +10022,7 @@ var init_PDFHandler = __esm({
10021
10022
  }
10022
10023
  if (options.extractImages !== false) {
10023
10024
  try {
10024
- const imagesResult = await unpdf.extractImages(buffer, {});
10025
+ const imagesResult = await unpdf.extractImages(data, {});
10025
10026
  const images = imagesResult?.images || [];
10026
10027
  for (const img of images) {
10027
10028
  if (!img.data) continue;
@@ -10254,6 +10255,457 @@ init_Connector();
10254
10255
  init_ScopedConnectorRegistry();
10255
10256
  init_StorageRegistry();
10256
10257
 
10258
+ // src/core/ToolCatalogRegistry.ts
10259
+ init_Logger();
10260
+ var ToolCatalogRegistry = class {
10261
+ /** Category definitions: name → definition */
10262
+ static _categories = /* @__PURE__ */ new Map();
10263
+ /** Tools per category: category name → tool entries */
10264
+ static _tools = /* @__PURE__ */ new Map();
10265
+ /** Whether built-in tools have been registered */
10266
+ static _initialized = false;
10267
+ /** Lazy-loaded ConnectorTools module. null = not attempted, false = failed */
10268
+ static _connectorToolsModule = null;
10269
+ // --- Built-in category descriptions ---
10270
+ static BUILTIN_DESCRIPTIONS = {
10271
+ filesystem: "Read, write, edit, search, and list files and directories",
10272
+ shell: "Execute bash/shell commands",
10273
+ web: "Fetch and process web content",
10274
+ code: "Execute JavaScript code in sandboxed VM",
10275
+ json: "Parse, query, and transform JSON data",
10276
+ desktop: "Screenshot, mouse, keyboard, and window desktop automation",
10277
+ "custom-tools": "Create, save, load, and test custom tool definitions",
10278
+ routines: "Generate and manage agent routines",
10279
+ other: "Miscellaneous tools"
10280
+ };
10281
+ // ========================================================================
10282
+ // Static Helpers (DRY)
10283
+ // ========================================================================
10284
+ /**
10285
+ * Convert a hyphenated or plain name to a display name.
10286
+ * E.g., 'custom-tools' → 'Custom Tools', 'filesystem' → 'Filesystem'
10287
+ */
10288
+ static toDisplayName(name) {
10289
+ return name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
10290
+ }
10291
+ /**
10292
+ * Parse a connector category name, returning the connector name or null.
10293
+ * E.g., 'connector:github' → 'github', 'filesystem' → null
10294
+ */
10295
+ static parseConnectorCategory(category) {
10296
+ return category.startsWith("connector:") ? category.slice("connector:".length) : null;
10297
+ }
10298
+ /**
10299
+ * Get the ConnectorTools module (lazy-loaded, cached).
10300
+ * Returns null if ConnectorTools is not available.
10301
+ * Uses false sentinel to prevent retrying after first failure.
10302
+ */
10303
+ static getConnectorToolsModule() {
10304
+ if (this._connectorToolsModule === null) {
10305
+ try {
10306
+ this._connectorToolsModule = __require("../../tools/connector/ConnectorTools.js");
10307
+ } catch {
10308
+ this._connectorToolsModule = false;
10309
+ }
10310
+ }
10311
+ return this._connectorToolsModule || null;
10312
+ }
10313
+ // ========================================================================
10314
+ // Registration
10315
+ // ========================================================================
10316
+ /**
10317
+ * Register a tool category.
10318
+ * If the category already exists, updates its metadata.
10319
+ * @throws Error if name is empty or whitespace
10320
+ */
10321
+ static registerCategory(def) {
10322
+ if (!def.name || !def.name.trim()) {
10323
+ throw new Error("[ToolCatalogRegistry] Category name cannot be empty");
10324
+ }
10325
+ this._categories.set(def.name, def);
10326
+ if (!this._tools.has(def.name)) {
10327
+ this._tools.set(def.name, []);
10328
+ }
10329
+ }
10330
+ /**
10331
+ * Register multiple tools in a category.
10332
+ * The category is auto-created if it doesn't exist (with a generic description).
10333
+ * @throws Error if category name is empty or whitespace
10334
+ */
10335
+ static registerTools(category, tools) {
10336
+ if (!category || !category.trim()) {
10337
+ throw new Error("[ToolCatalogRegistry] Category name cannot be empty");
10338
+ }
10339
+ if (!this._categories.has(category)) {
10340
+ this._categories.set(category, {
10341
+ name: category,
10342
+ displayName: this.toDisplayName(category),
10343
+ description: this.BUILTIN_DESCRIPTIONS[category] ?? `Tools in the ${category} category`
10344
+ });
10345
+ }
10346
+ const existing = this._tools.get(category) ?? [];
10347
+ const existingNames = new Set(existing.map((t) => t.name));
10348
+ const newTools = tools.filter((t) => !existingNames.has(t.name));
10349
+ const updated = existing.map((t) => {
10350
+ const replacement = tools.find((nt) => nt.name === t.name);
10351
+ return replacement ?? t;
10352
+ });
10353
+ this._tools.set(category, [...updated, ...newTools]);
10354
+ }
10355
+ /**
10356
+ * Register a single tool in a category.
10357
+ */
10358
+ static registerTool(category, tool) {
10359
+ this.registerTools(category, [tool]);
10360
+ }
10361
+ /**
10362
+ * Unregister a category and all its tools.
10363
+ */
10364
+ static unregisterCategory(category) {
10365
+ const hadCategory = this._categories.delete(category);
10366
+ this._tools.delete(category);
10367
+ return hadCategory;
10368
+ }
10369
+ /**
10370
+ * Unregister a single tool from a category.
10371
+ */
10372
+ static unregisterTool(category, toolName) {
10373
+ const tools = this._tools.get(category);
10374
+ if (!tools) return false;
10375
+ const idx = tools.findIndex((t) => t.name === toolName);
10376
+ if (idx === -1) return false;
10377
+ tools.splice(idx, 1);
10378
+ return true;
10379
+ }
10380
+ // ========================================================================
10381
+ // Query
10382
+ // ========================================================================
10383
+ /**
10384
+ * Get all registered categories.
10385
+ */
10386
+ static getCategories() {
10387
+ this.ensureInitialized();
10388
+ return Array.from(this._categories.values());
10389
+ }
10390
+ /**
10391
+ * Get a single category by name.
10392
+ */
10393
+ static getCategory(name) {
10394
+ this.ensureInitialized();
10395
+ return this._categories.get(name);
10396
+ }
10397
+ /**
10398
+ * Check if a category exists.
10399
+ */
10400
+ static hasCategory(name) {
10401
+ this.ensureInitialized();
10402
+ return this._categories.has(name);
10403
+ }
10404
+ /**
10405
+ * Get all tools in a category.
10406
+ */
10407
+ static getToolsInCategory(category) {
10408
+ this.ensureInitialized();
10409
+ return this._tools.get(category) ?? [];
10410
+ }
10411
+ /**
10412
+ * Get all catalog tools across all categories.
10413
+ */
10414
+ static getAllCatalogTools() {
10415
+ this.ensureInitialized();
10416
+ const all = [];
10417
+ for (const tools of this._tools.values()) {
10418
+ all.push(...tools);
10419
+ }
10420
+ return all;
10421
+ }
10422
+ /**
10423
+ * Find a tool by name across all categories.
10424
+ */
10425
+ static findTool(name) {
10426
+ this.ensureInitialized();
10427
+ for (const [category, tools] of this._tools) {
10428
+ const entry = tools.find((t) => t.name === name);
10429
+ if (entry) return { category, entry };
10430
+ }
10431
+ return void 0;
10432
+ }
10433
+ // ========================================================================
10434
+ // Filtering
10435
+ // ========================================================================
10436
+ /**
10437
+ * Filter categories by scope.
10438
+ */
10439
+ static filterCategories(scope) {
10440
+ const all = this.getCategories();
10441
+ if (!scope) return all;
10442
+ return all.filter((cat) => this.isCategoryAllowed(cat.name, scope));
10443
+ }
10444
+ /**
10445
+ * Check if a category is allowed by a scope.
10446
+ */
10447
+ static isCategoryAllowed(name, scope) {
10448
+ if (!scope) return true;
10449
+ if (Array.isArray(scope)) {
10450
+ return scope.includes(name);
10451
+ }
10452
+ if ("include" in scope) {
10453
+ return scope.include.includes(name);
10454
+ }
10455
+ if ("exclude" in scope) {
10456
+ return !scope.exclude.includes(name);
10457
+ }
10458
+ return true;
10459
+ }
10460
+ // ========================================================================
10461
+ // Connector Discovery
10462
+ // ========================================================================
10463
+ /**
10464
+ * Discover all connector categories with their tools.
10465
+ * Calls ConnectorTools.discoverAll() and filters by scope/identities.
10466
+ *
10467
+ * @param options - Optional filtering
10468
+ * @returns Array of connector category info
10469
+ */
10470
+ static discoverConnectorCategories(options) {
10471
+ const mod = this.getConnectorToolsModule();
10472
+ if (!mod) return [];
10473
+ try {
10474
+ const discovered = mod.ConnectorTools.discoverAll();
10475
+ const results = [];
10476
+ for (const [connectorName, tools] of discovered) {
10477
+ const catName = `connector:${connectorName}`;
10478
+ if (options?.scope && !this.isCategoryAllowed(catName, options.scope)) {
10479
+ continue;
10480
+ }
10481
+ if (options?.identities?.length) {
10482
+ const hasIdentity = options.identities.some((id) => id.connector === connectorName);
10483
+ if (!hasIdentity) continue;
10484
+ }
10485
+ const preRegistered = this.getCategory(catName);
10486
+ results.push({
10487
+ name: catName,
10488
+ displayName: preRegistered?.displayName ?? this.toDisplayName(connectorName),
10489
+ description: preRegistered?.description ?? `API tools for ${connectorName}`,
10490
+ toolCount: tools.length,
10491
+ tools
10492
+ });
10493
+ }
10494
+ return results;
10495
+ } catch {
10496
+ return [];
10497
+ }
10498
+ }
10499
+ /**
10500
+ * Resolve tools for a specific connector category.
10501
+ *
10502
+ * @param category - Category name in 'connector:<name>' format
10503
+ * @returns Array of resolved tools with names
10504
+ */
10505
+ static resolveConnectorCategoryTools(category) {
10506
+ const connectorName = this.parseConnectorCategory(category);
10507
+ if (!connectorName) return [];
10508
+ const mod = this.getConnectorToolsModule();
10509
+ if (!mod) return [];
10510
+ try {
10511
+ const tools = mod.ConnectorTools.for(connectorName);
10512
+ return tools.map((t) => ({ tool: t, name: t.definition.function.name }));
10513
+ } catch {
10514
+ return [];
10515
+ }
10516
+ }
10517
+ // ========================================================================
10518
+ // Resolution
10519
+ // ========================================================================
10520
+ /**
10521
+ * Resolve tool names to ToolFunction[].
10522
+ *
10523
+ * Searches registered categories and (optionally) connector tools.
10524
+ * Used by app-level executors (e.g., V25's OneRingAgentExecutor).
10525
+ *
10526
+ * @param toolNames - Array of tool names to resolve
10527
+ * @param options - Resolution options
10528
+ * @returns Resolved tool functions (skips unresolvable names with warning)
10529
+ */
10530
+ static resolveTools(toolNames, options) {
10531
+ this.ensureInitialized();
10532
+ const resolved = [];
10533
+ const missing = [];
10534
+ for (const name of toolNames) {
10535
+ const found = this.findTool(name);
10536
+ if (found) {
10537
+ const tool = this.resolveEntryTool(found.entry, options?.context);
10538
+ if (tool) {
10539
+ resolved.push(tool);
10540
+ continue;
10541
+ }
10542
+ }
10543
+ if (options?.includeConnectors) {
10544
+ const connectorTool = this.findConnectorTool(name);
10545
+ if (connectorTool) {
10546
+ resolved.push(connectorTool);
10547
+ continue;
10548
+ }
10549
+ }
10550
+ missing.push(name);
10551
+ }
10552
+ if (missing.length > 0) {
10553
+ logger.warn(
10554
+ { missing, resolved: resolved.length, total: toolNames.length },
10555
+ `[ToolCatalogRegistry.resolveTools] Could not resolve ${missing.length} tool(s): ${missing.join(", ")}`
10556
+ );
10557
+ }
10558
+ return resolved;
10559
+ }
10560
+ /**
10561
+ * Resolve tools grouped by connector name.
10562
+ *
10563
+ * Tools with a `connectorName` go into `byConnector`; all others go into `plain`.
10564
+ * Supports factory-based tool creation via `createTool` when context is provided.
10565
+ *
10566
+ * @param toolNames - Array of tool names to resolve
10567
+ * @param context - Optional context passed to createTool factories
10568
+ * @param options - Resolution options
10569
+ * @returns Grouped tools: plain + byConnector map
10570
+ */
10571
+ static resolveToolsGrouped(toolNames, context, options) {
10572
+ this.ensureInitialized();
10573
+ const plain = [];
10574
+ const byConnector = /* @__PURE__ */ new Map();
10575
+ for (const name of toolNames) {
10576
+ const found = this.findTool(name);
10577
+ if (found) {
10578
+ const entry = found.entry;
10579
+ const tool = this.resolveEntryTool(entry, context);
10580
+ if (!tool) continue;
10581
+ if (entry.connectorName) {
10582
+ const list = byConnector.get(entry.connectorName) ?? [];
10583
+ list.push(tool);
10584
+ byConnector.set(entry.connectorName, list);
10585
+ } else {
10586
+ plain.push(tool);
10587
+ }
10588
+ continue;
10589
+ }
10590
+ if (options?.includeConnectors) {
10591
+ const connectorTool = this.findConnectorTool(name);
10592
+ if (connectorTool) {
10593
+ plain.push(connectorTool);
10594
+ continue;
10595
+ }
10596
+ }
10597
+ }
10598
+ return { plain, byConnector };
10599
+ }
10600
+ /**
10601
+ * Resolve a tool from a CatalogToolEntry, using factory if available.
10602
+ * Returns null if neither tool nor createTool is available.
10603
+ */
10604
+ static resolveEntryTool(entry, context) {
10605
+ if (entry.createTool && context) {
10606
+ try {
10607
+ return entry.createTool(context);
10608
+ } catch (e) {
10609
+ logger.warn(`[ToolCatalogRegistry] Factory failed for '${entry.name}': ${e}`);
10610
+ return null;
10611
+ }
10612
+ }
10613
+ return entry.tool ?? null;
10614
+ }
10615
+ /**
10616
+ * Search connector tools by name (uses lazy accessor).
10617
+ */
10618
+ static findConnectorTool(name) {
10619
+ const mod = this.getConnectorToolsModule();
10620
+ if (!mod) return void 0;
10621
+ try {
10622
+ const allConnectorTools = mod.ConnectorTools.discoverAll();
10623
+ for (const [, tools] of allConnectorTools) {
10624
+ for (const tool of tools) {
10625
+ if (tool.definition.function.name === name) {
10626
+ return tool;
10627
+ }
10628
+ }
10629
+ }
10630
+ } catch {
10631
+ }
10632
+ return void 0;
10633
+ }
10634
+ // ========================================================================
10635
+ // Built-in initialization
10636
+ // ========================================================================
10637
+ /**
10638
+ * Ensure built-in tools from registry.generated.ts are registered.
10639
+ * Called lazily on first query.
10640
+ *
10641
+ * In ESM environments, call `initializeFromRegistry(toolRegistry)` explicitly
10642
+ * from your app startup instead of relying on auto-initialization.
10643
+ */
10644
+ static ensureInitialized() {
10645
+ if (this._initialized) return;
10646
+ this._initialized = true;
10647
+ try {
10648
+ const mod = __require("../../tools/registry.generated.js");
10649
+ const registry = mod?.toolRegistry ?? mod?.default?.toolRegistry;
10650
+ if (Array.isArray(registry)) {
10651
+ this.registerFromToolRegistry(registry);
10652
+ }
10653
+ } catch {
10654
+ }
10655
+ }
10656
+ /**
10657
+ * Explicitly initialize from the generated tool registry.
10658
+ * Call this at app startup in ESM environments where lazy require() doesn't work.
10659
+ *
10660
+ * @example
10661
+ * ```typescript
10662
+ * import { toolRegistry } from './tools/registry.generated.js';
10663
+ * ToolCatalogRegistry.initializeFromRegistry(toolRegistry);
10664
+ * ```
10665
+ */
10666
+ static initializeFromRegistry(registry) {
10667
+ this._initialized = true;
10668
+ this.registerFromToolRegistry(registry);
10669
+ }
10670
+ /**
10671
+ * Internal: register tools from a tool registry array.
10672
+ */
10673
+ static registerFromToolRegistry(registry) {
10674
+ for (const entry of registry) {
10675
+ const category = entry.category;
10676
+ if (!this._categories.has(category)) {
10677
+ this.registerCategory({
10678
+ name: category,
10679
+ displayName: this.toDisplayName(category),
10680
+ description: this.BUILTIN_DESCRIPTIONS[category] ?? `Built-in ${category} tools`
10681
+ });
10682
+ }
10683
+ const catalogEntry = {
10684
+ tool: entry.tool,
10685
+ name: entry.name,
10686
+ displayName: entry.displayName,
10687
+ description: entry.description,
10688
+ safeByDefault: entry.safeByDefault,
10689
+ requiresConnector: entry.requiresConnector
10690
+ };
10691
+ const existing = this._tools.get(category) ?? [];
10692
+ if (!existing.some((t) => t.name === catalogEntry.name)) {
10693
+ existing.push(catalogEntry);
10694
+ this._tools.set(category, existing);
10695
+ }
10696
+ }
10697
+ }
10698
+ /**
10699
+ * Reset the registry. Primarily for testing.
10700
+ */
10701
+ static reset() {
10702
+ this._categories.clear();
10703
+ this._tools.clear();
10704
+ this._initialized = false;
10705
+ this._connectorToolsModule = null;
10706
+ }
10707
+ };
10708
+
10257
10709
  // src/core/BaseAgent.ts
10258
10710
  init_Connector();
10259
10711
 
@@ -10291,6 +10743,14 @@ var DEFAULT_ALLOWLIST = [
10291
10743
  "user_info_get",
10292
10744
  "user_info_remove",
10293
10745
  "user_info_clear",
10746
+ // TODO tools (user-specific data - safe)
10747
+ "todo_add",
10748
+ "todo_update",
10749
+ "todo_remove",
10750
+ // Tool catalog tools (browsing and loading — safe)
10751
+ "tool_catalog_search",
10752
+ "tool_catalog_load",
10753
+ "tool_catalog_unload",
10294
10754
  // Meta-tools (internal coordination)
10295
10755
  "_start_planning",
10296
10756
  "_modify_plan",
@@ -11605,6 +12065,17 @@ var ToolManager = class extends EventEmitter {
11605
12065
  if (!toolNames) return [];
11606
12066
  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);
11607
12067
  }
12068
+ /**
12069
+ * Get all registered tool names in a category.
12070
+ * Used by ToolCatalogPlugin for bulk enable/disable.
12071
+ */
12072
+ getByCategory(category) {
12073
+ const names = [];
12074
+ for (const [name, reg] of this.registry) {
12075
+ if (reg.category === category) names.push(name);
12076
+ }
12077
+ return names;
12078
+ }
11608
12079
  /**
11609
12080
  * Get tool registration info
11610
12081
  */
@@ -15770,7 +16241,35 @@ User info is automatically shown in context \u2014 no need to call user_info_get
15770
16241
 
15771
16242
  **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.
15772
16243
 
15773
- **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!`;
16244
+ **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!
16245
+
16246
+ ## TODO Management
16247
+
16248
+ TODOs are stored alongside user info and shown in a separate "Current TODOs" section in context.
16249
+
16250
+ **Tools:**
16251
+ - \`todo_add(title, description?, people?, dueDate?, tags?)\`: Create a new TODO item
16252
+ - \`todo_update(id, title?, description?, people?, dueDate?, tags?, status?)\`: Update an existing TODO
16253
+ - \`todo_remove(id)\`: Delete a TODO item
16254
+
16255
+ **Proactive creation \u2014 be helpful:**
16256
+ - If the user's message implies an action item, task, or deadline \u2192 ask "Would you like me to create a TODO for this?"
16257
+ - If the user explicitly says "remind me", "track this", "don't forget" \u2192 create a TODO immediately without asking.
16258
+ - When discussing plans with deadlines or deliverables \u2192 suggest relevant TODOs.
16259
+ - When the user mentions other people involved \u2192 include them in the \`people\` field.
16260
+ - Suggest appropriate tags based on context (e.g. "work", "personal", "urgent").
16261
+
16262
+ **Reminder rules:**
16263
+ - 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\`.
16264
+ - Do NOT remind again in the same day unless the user explicitly asks about their TODOs.
16265
+ - When reminding, prioritize: overdue items first, then items due today, then items due tomorrow.
16266
+ - If the user asks about their TODOs or schedule, always answer regardless of reminder status.
16267
+ - After completing a TODO, mark it as done via \`todo_update(id, status: 'done')\`. Suggest marking items done when context indicates completion.
16268
+
16269
+ **Cleanup rules:**
16270
+ - Completed TODOs older than 48 hours (check updatedAt of done items) \u2192 auto-delete via \`todo_remove\` without asking.
16271
+ - 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?"
16272
+ - Run cleanup checks at the same time as reminders (once per day, using \`_todo_last_reminded\` marker).`;
15774
16273
  var userInfoSetDefinition = {
15775
16274
  type: "function",
15776
16275
  function: {
@@ -15847,6 +16346,102 @@ var userInfoClearDefinition = {
15847
16346
  }
15848
16347
  }
15849
16348
  };
16349
+ var todoAddDefinition = {
16350
+ type: "function",
16351
+ function: {
16352
+ name: "todo_add",
16353
+ description: "Create a new TODO item for the user. Returns the generated todo ID.",
16354
+ parameters: {
16355
+ type: "object",
16356
+ properties: {
16357
+ title: {
16358
+ type: "string",
16359
+ description: "Short title for the TODO (required)"
16360
+ },
16361
+ description: {
16362
+ type: "string",
16363
+ description: "Optional detailed description"
16364
+ },
16365
+ people: {
16366
+ type: "array",
16367
+ items: { type: "string" },
16368
+ description: "People involved besides the current user (optional)"
16369
+ },
16370
+ dueDate: {
16371
+ type: "string",
16372
+ description: "Due date in ISO format YYYY-MM-DD (optional)"
16373
+ },
16374
+ tags: {
16375
+ type: "array",
16376
+ items: { type: "string" },
16377
+ description: 'Categorization tags (optional, e.g. "work", "personal", "urgent")'
16378
+ }
16379
+ },
16380
+ required: ["title"]
16381
+ }
16382
+ }
16383
+ };
16384
+ var todoUpdateDefinition = {
16385
+ type: "function",
16386
+ function: {
16387
+ name: "todo_update",
16388
+ description: "Update an existing TODO item. Only provided fields are changed.",
16389
+ parameters: {
16390
+ type: "object",
16391
+ properties: {
16392
+ id: {
16393
+ type: "string",
16394
+ description: 'The todo ID (e.g. "todo_a1b2c3")'
16395
+ },
16396
+ title: {
16397
+ type: "string",
16398
+ description: "New title"
16399
+ },
16400
+ description: {
16401
+ type: "string",
16402
+ description: "New description (pass empty string to clear)"
16403
+ },
16404
+ people: {
16405
+ type: "array",
16406
+ items: { type: "string" },
16407
+ description: "New people list (replaces existing)"
16408
+ },
16409
+ dueDate: {
16410
+ type: "string",
16411
+ description: "New due date in ISO format YYYY-MM-DD (pass empty string to clear)"
16412
+ },
16413
+ tags: {
16414
+ type: "array",
16415
+ items: { type: "string" },
16416
+ description: "New tags list (replaces existing)"
16417
+ },
16418
+ status: {
16419
+ type: "string",
16420
+ enum: ["pending", "done"],
16421
+ description: "New status"
16422
+ }
16423
+ },
16424
+ required: ["id"]
16425
+ }
16426
+ }
16427
+ };
16428
+ var todoRemoveDefinition = {
16429
+ type: "function",
16430
+ function: {
16431
+ name: "todo_remove",
16432
+ description: "Delete a TODO item.",
16433
+ parameters: {
16434
+ type: "object",
16435
+ properties: {
16436
+ id: {
16437
+ type: "string",
16438
+ description: 'The todo ID to remove (e.g. "todo_a1b2c3")'
16439
+ }
16440
+ },
16441
+ required: ["id"]
16442
+ }
16443
+ }
16444
+ };
15850
16445
  function validateKey2(key) {
15851
16446
  if (typeof key !== "string") return "Key must be a string";
15852
16447
  const trimmed = key.trim();
@@ -15870,6 +16465,37 @@ function buildStorageContext(toolContext) {
15870
16465
  if (toolContext?.userId) return { userId: toolContext.userId };
15871
16466
  return void 0;
15872
16467
  }
16468
+ var TODO_KEY_PREFIX = "todo_";
16469
+ var INTERNAL_KEY_PREFIX = "_";
16470
+ function isTodoEntry(entry) {
16471
+ return entry.id.startsWith(TODO_KEY_PREFIX);
16472
+ }
16473
+ function isInternalEntry(entry) {
16474
+ return entry.id.startsWith(INTERNAL_KEY_PREFIX);
16475
+ }
16476
+ function generateTodoId() {
16477
+ const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
16478
+ let id = "";
16479
+ for (let i = 0; i < 6; i++) {
16480
+ id += chars[Math.floor(Math.random() * chars.length)];
16481
+ }
16482
+ return `${TODO_KEY_PREFIX}${id}`;
16483
+ }
16484
+ function renderTodoEntry(entry) {
16485
+ const val = entry.value;
16486
+ const checkbox = val.status === "done" ? "[x]" : "[ ]";
16487
+ const parts = [];
16488
+ if (val.dueDate) parts.push(`due: ${val.dueDate}`);
16489
+ if (val.people && val.people.length > 0) parts.push(`people: ${val.people.join(", ")}`);
16490
+ const meta = parts.length > 0 ? ` (${parts.join(", ")})` : "";
16491
+ const tags = val.tags && val.tags.length > 0 ? ` [${val.tags.join(", ")}]` : "";
16492
+ let line = `- ${checkbox} ${entry.id}: ${val.title}${meta}${tags}`;
16493
+ if (val.description) {
16494
+ line += `
16495
+ ${val.description}`;
16496
+ }
16497
+ return line;
16498
+ }
15873
16499
  function formatValue(value) {
15874
16500
  if (value === null) return "null";
15875
16501
  if (typeof value === "string") return value;
@@ -15937,7 +16563,10 @@ var UserInfoPluginNextGen = class {
15937
16563
  this.createUserInfoSetTool(),
15938
16564
  this.createUserInfoGetTool(),
15939
16565
  this.createUserInfoRemoveTool(),
15940
- this.createUserInfoClearTool()
16566
+ this.createUserInfoClearTool(),
16567
+ this.createTodoAddTool(),
16568
+ this.createTodoUpdateTool(),
16569
+ this.createTodoRemoveTool()
15941
16570
  ];
15942
16571
  }
15943
16572
  destroy() {
@@ -16008,9 +16637,38 @@ var UserInfoPluginNextGen = class {
16008
16637
  * Render entries as markdown for context injection
16009
16638
  */
16010
16639
  renderContent() {
16011
- const sorted = Array.from(this._entries.values()).sort((a, b) => a.createdAt - b.createdAt);
16012
- return sorted.map((entry) => `### ${entry.id}
16013
- ${formatValue(entry.value)}`).join("\n\n");
16640
+ const userEntries = [];
16641
+ const todoEntries = [];
16642
+ for (const entry of this._entries.values()) {
16643
+ if (isTodoEntry(entry)) {
16644
+ todoEntries.push(entry);
16645
+ } else if (!isInternalEntry(entry)) {
16646
+ userEntries.push(entry);
16647
+ }
16648
+ }
16649
+ const sections = [];
16650
+ if (userEntries.length > 0) {
16651
+ userEntries.sort((a, b) => a.createdAt - b.createdAt);
16652
+ sections.push(
16653
+ userEntries.map((entry) => `### ${entry.id}
16654
+ ${formatValue(entry.value)}`).join("\n\n")
16655
+ );
16656
+ }
16657
+ if (todoEntries.length > 0) {
16658
+ todoEntries.sort((a, b) => {
16659
+ const aVal = a.value;
16660
+ const bVal = b.value;
16661
+ if (aVal.status !== bVal.status) return aVal.status === "pending" ? -1 : 1;
16662
+ if (aVal.dueDate && bVal.dueDate) return aVal.dueDate.localeCompare(bVal.dueDate);
16663
+ if (aVal.dueDate) return -1;
16664
+ if (bVal.dueDate) return 1;
16665
+ return a.createdAt - b.createdAt;
16666
+ });
16667
+ sections.push(
16668
+ "## Current TODOs\n" + todoEntries.map(renderTodoEntry).join("\n")
16669
+ );
16670
+ }
16671
+ return sections.join("\n\n");
16014
16672
  }
16015
16673
  /**
16016
16674
  * Resolve storage instance (lazy singleton)
@@ -16191,6 +16849,619 @@ ${formatValue(entry.value)}`).join("\n\n");
16191
16849
  describeCall: () => "clear user info"
16192
16850
  };
16193
16851
  }
16852
+ // ============================================================================
16853
+ // TODO Tool Factories
16854
+ // ============================================================================
16855
+ createTodoAddTool() {
16856
+ return {
16857
+ definition: todoAddDefinition,
16858
+ execute: async (args, context) => {
16859
+ this.assertNotDestroyed();
16860
+ await this.ensureInitialized();
16861
+ const userId = context?.userId ?? this.userId;
16862
+ const title = args.title;
16863
+ if (!title || typeof title !== "string" || title.trim().length === 0) {
16864
+ return { error: "Title is required" };
16865
+ }
16866
+ if (this._entries.size >= this.maxEntries) {
16867
+ return { error: `Maximum number of entries reached (${this.maxEntries})` };
16868
+ }
16869
+ let todoId = generateTodoId();
16870
+ while (this._entries.has(todoId)) {
16871
+ todoId = generateTodoId();
16872
+ }
16873
+ const todoValue = {
16874
+ type: "todo",
16875
+ title: title.trim(),
16876
+ description: args.description ? String(args.description).trim() : void 0,
16877
+ people: Array.isArray(args.people) ? args.people.filter((p) => typeof p === "string") : void 0,
16878
+ dueDate: typeof args.dueDate === "string" && args.dueDate.trim() ? args.dueDate.trim() : void 0,
16879
+ tags: Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string") : void 0,
16880
+ status: "pending"
16881
+ };
16882
+ const valueSize = calculateValueSize(todoValue);
16883
+ let currentTotal = 0;
16884
+ for (const e of this._entries.values()) {
16885
+ currentTotal += calculateValueSize(e.value);
16886
+ }
16887
+ if (currentTotal + valueSize > this.maxTotalSize) {
16888
+ return { error: `Total size would exceed maximum (${this.maxTotalSize} bytes)` };
16889
+ }
16890
+ const now = Date.now();
16891
+ const entry = {
16892
+ id: todoId,
16893
+ value: todoValue,
16894
+ valueType: "object",
16895
+ description: title.trim(),
16896
+ createdAt: now,
16897
+ updatedAt: now
16898
+ };
16899
+ this._entries.set(todoId, entry);
16900
+ this._tokenCache = null;
16901
+ await this.persistToStorage(userId);
16902
+ return {
16903
+ success: true,
16904
+ message: `TODO '${title.trim()}' created`,
16905
+ id: todoId,
16906
+ todo: todoValue
16907
+ };
16908
+ },
16909
+ permission: { scope: "always", riskLevel: "low" },
16910
+ describeCall: (args) => `add todo '${args.title}'`
16911
+ };
16912
+ }
16913
+ createTodoUpdateTool() {
16914
+ return {
16915
+ definition: todoUpdateDefinition,
16916
+ execute: async (args, context) => {
16917
+ this.assertNotDestroyed();
16918
+ await this.ensureInitialized();
16919
+ const userId = context?.userId ?? this.userId;
16920
+ const id = args.id;
16921
+ if (!id || typeof id !== "string") {
16922
+ return { error: "Todo ID is required" };
16923
+ }
16924
+ const entry = this._entries.get(id);
16925
+ if (!entry || !isTodoEntry(entry)) {
16926
+ return { error: `TODO '${id}' not found` };
16927
+ }
16928
+ const currentValue = entry.value;
16929
+ const updatedValue = { ...currentValue };
16930
+ if (typeof args.title === "string" && args.title.trim()) {
16931
+ updatedValue.title = args.title.trim();
16932
+ }
16933
+ if (args.description !== void 0) {
16934
+ updatedValue.description = typeof args.description === "string" && args.description.trim() ? args.description.trim() : void 0;
16935
+ }
16936
+ if (args.people !== void 0) {
16937
+ updatedValue.people = Array.isArray(args.people) ? args.people.filter((p) => typeof p === "string") : void 0;
16938
+ }
16939
+ if (args.dueDate !== void 0) {
16940
+ updatedValue.dueDate = typeof args.dueDate === "string" && args.dueDate.trim() ? args.dueDate.trim() : void 0;
16941
+ }
16942
+ if (args.tags !== void 0) {
16943
+ updatedValue.tags = Array.isArray(args.tags) ? args.tags.filter((t) => typeof t === "string") : void 0;
16944
+ }
16945
+ if (args.status === "pending" || args.status === "done") {
16946
+ updatedValue.status = args.status;
16947
+ }
16948
+ const valueSize = calculateValueSize(updatedValue);
16949
+ let currentTotal = 0;
16950
+ for (const e of this._entries.values()) {
16951
+ currentTotal += calculateValueSize(e.value);
16952
+ }
16953
+ const existingSize = calculateValueSize(currentValue);
16954
+ if (currentTotal - existingSize + valueSize > this.maxTotalSize) {
16955
+ return { error: `Total size would exceed maximum (${this.maxTotalSize} bytes)` };
16956
+ }
16957
+ const now = Date.now();
16958
+ const updatedEntry = {
16959
+ ...entry,
16960
+ value: updatedValue,
16961
+ description: updatedValue.title,
16962
+ updatedAt: now
16963
+ };
16964
+ this._entries.set(id, updatedEntry);
16965
+ this._tokenCache = null;
16966
+ await this.persistToStorage(userId);
16967
+ return {
16968
+ success: true,
16969
+ message: `TODO '${id}' updated`,
16970
+ id,
16971
+ todo: updatedValue
16972
+ };
16973
+ },
16974
+ permission: { scope: "always", riskLevel: "low" },
16975
+ describeCall: (args) => `update todo '${args.id}'`
16976
+ };
16977
+ }
16978
+ createTodoRemoveTool() {
16979
+ return {
16980
+ definition: todoRemoveDefinition,
16981
+ execute: async (args, context) => {
16982
+ this.assertNotDestroyed();
16983
+ await this.ensureInitialized();
16984
+ const userId = context?.userId ?? this.userId;
16985
+ const id = args.id;
16986
+ if (!id || typeof id !== "string") {
16987
+ return { error: "Todo ID is required" };
16988
+ }
16989
+ const entry = this._entries.get(id);
16990
+ if (!entry || !isTodoEntry(entry)) {
16991
+ return { error: `TODO '${id}' not found` };
16992
+ }
16993
+ this._entries.delete(id);
16994
+ this._tokenCache = null;
16995
+ await this.persistToStorage(userId);
16996
+ return {
16997
+ success: true,
16998
+ message: `TODO '${id}' removed`,
16999
+ id
17000
+ };
17001
+ },
17002
+ permission: { scope: "always", riskLevel: "low" },
17003
+ describeCall: (args) => `remove todo '${args.id}'`
17004
+ };
17005
+ }
17006
+ };
17007
+
17008
+ // src/core/context-nextgen/plugins/ToolCatalogPluginNextGen.ts
17009
+ init_Logger();
17010
+ var DEFAULT_MAX_LOADED = 10;
17011
+ var TOOL_CATALOG_INSTRUCTIONS = `## Tool Catalog
17012
+
17013
+ 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:
17014
+
17015
+ **tool_catalog_search** \u2014 Browse available tool categories and search for specific tools.
17016
+ - No params \u2192 list all available categories with descriptions
17017
+ - \`category\` \u2192 list tools in that category
17018
+ - \`query\` \u2192 keyword search across categories and tools
17019
+
17020
+ **tool_catalog_load** \u2014 Load a category's tools so you can use them.
17021
+ - Tools become available immediately after loading.
17022
+ - If you need tools from a category, load it first.
17023
+
17024
+ **tool_catalog_unload** \u2014 Unload a category to free token budget.
17025
+ - Unloaded tools are no longer sent to you.
17026
+ - Use when you're done with a category.
17027
+
17028
+ **Best practices:**
17029
+ - Search first to find the right category before loading.
17030
+ - Unload categories you no longer need to keep context lean.
17031
+ - Categories marked [LOADED] are already available.`;
17032
+ var catalogSearchDefinition = {
17033
+ type: "function",
17034
+ function: {
17035
+ name: "tool_catalog_search",
17036
+ description: "Search the tool catalog. No params lists categories. Use category to list tools in it, or query to keyword-search.",
17037
+ parameters: {
17038
+ type: "object",
17039
+ properties: {
17040
+ query: {
17041
+ type: "string",
17042
+ description: "Keyword to search across category names, descriptions, and tool names"
17043
+ },
17044
+ category: {
17045
+ type: "string",
17046
+ description: "Category name to list its tools"
17047
+ }
17048
+ }
17049
+ }
17050
+ }
17051
+ };
17052
+ var catalogLoadDefinition = {
17053
+ type: "function",
17054
+ function: {
17055
+ name: "tool_catalog_load",
17056
+ description: "Load all tools from a category so they become available for use.",
17057
+ parameters: {
17058
+ type: "object",
17059
+ properties: {
17060
+ category: {
17061
+ type: "string",
17062
+ description: "Category name to load"
17063
+ }
17064
+ },
17065
+ required: ["category"]
17066
+ }
17067
+ }
17068
+ };
17069
+ var catalogUnloadDefinition = {
17070
+ type: "function",
17071
+ function: {
17072
+ name: "tool_catalog_unload",
17073
+ description: "Unload a category to free token budget. Tools from this category will no longer be available.",
17074
+ parameters: {
17075
+ type: "object",
17076
+ properties: {
17077
+ category: {
17078
+ type: "string",
17079
+ description: "Category name to unload"
17080
+ }
17081
+ },
17082
+ required: ["category"]
17083
+ }
17084
+ }
17085
+ };
17086
+ var ToolCatalogPluginNextGen = class extends BasePluginNextGen {
17087
+ name = "tool_catalog";
17088
+ /** category name → array of tool names that were loaded */
17089
+ _loadedCategories = /* @__PURE__ */ new Map();
17090
+ /** Reference to the ToolManager for registering/disabling tools */
17091
+ _toolManager = null;
17092
+ /** Cached connector categories — discovered once in setToolManager() */
17093
+ _connectorCategories = null;
17094
+ /** Whether this plugin has been destroyed */
17095
+ _destroyed = false;
17096
+ /** WeakMap cache for tool definition token estimates */
17097
+ _toolTokenCache = /* @__PURE__ */ new WeakMap();
17098
+ _config;
17099
+ constructor(config) {
17100
+ super();
17101
+ this._config = {
17102
+ maxLoadedCategories: DEFAULT_MAX_LOADED,
17103
+ ...config
17104
+ };
17105
+ }
17106
+ // ========================================================================
17107
+ // Plugin Interface
17108
+ // ========================================================================
17109
+ getInstructions() {
17110
+ return TOOL_CATALOG_INSTRUCTIONS;
17111
+ }
17112
+ async getContent() {
17113
+ const categories = this.getAllowedCategories();
17114
+ if (categories.length === 0 && this.getConnectorCategories().length === 0) return null;
17115
+ const lines = ["## Tool Catalog"];
17116
+ lines.push("");
17117
+ const loaded = Array.from(this._loadedCategories.keys());
17118
+ if (loaded.length > 0) {
17119
+ lines.push(`**Loaded:** ${loaded.join(", ")}`);
17120
+ }
17121
+ lines.push(`**Available categories:** ${categories.length}`);
17122
+ for (const cat of categories) {
17123
+ const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
17124
+ const marker = this._loadedCategories.has(cat.name) ? " [LOADED]" : "";
17125
+ lines.push(`- **${cat.displayName}** (${tools.length} tools)${marker}: ${cat.description}`);
17126
+ }
17127
+ for (const cc of this.getConnectorCategories()) {
17128
+ const marker = this._loadedCategories.has(cc.name) ? " [LOADED]" : "";
17129
+ lines.push(`- **${cc.displayName}** (${cc.toolCount} tools)${marker}: ${cc.description}`);
17130
+ }
17131
+ const content = lines.join("\n");
17132
+ this.updateTokenCache(this.estimator.estimateTokens(content));
17133
+ return content;
17134
+ }
17135
+ getContents() {
17136
+ return {
17137
+ loadedCategories: Array.from(this._loadedCategories.entries()).map(([name, tools]) => ({
17138
+ category: name,
17139
+ toolCount: tools.length,
17140
+ tools
17141
+ }))
17142
+ };
17143
+ }
17144
+ getTools() {
17145
+ const plugin = this;
17146
+ const searchTool = {
17147
+ definition: catalogSearchDefinition,
17148
+ execute: async (args) => {
17149
+ return plugin.executeSearch(args.query, args.category);
17150
+ }
17151
+ };
17152
+ const loadTool = {
17153
+ definition: catalogLoadDefinition,
17154
+ execute: async (args) => {
17155
+ return plugin.executeLoad(args.category);
17156
+ }
17157
+ };
17158
+ const unloadTool = {
17159
+ definition: catalogUnloadDefinition,
17160
+ execute: async (args) => {
17161
+ return plugin.executeUnload(args.category);
17162
+ }
17163
+ };
17164
+ return [searchTool, loadTool, unloadTool];
17165
+ }
17166
+ isCompactable() {
17167
+ return this._loadedCategories.size > 0;
17168
+ }
17169
+ async compact(targetTokensToFree) {
17170
+ if (!this._toolManager || this._loadedCategories.size === 0) return 0;
17171
+ const categoriesByLastUsed = this.getCategoriesSortedByLastUsed();
17172
+ let freed = 0;
17173
+ for (const category of categoriesByLastUsed) {
17174
+ if (freed >= targetTokensToFree) break;
17175
+ const toolNames = this._loadedCategories.get(category);
17176
+ if (!toolNames) continue;
17177
+ const toolTokens = this.estimateToolDefinitionTokens(toolNames);
17178
+ this._toolManager.setEnabled(toolNames, false);
17179
+ this._loadedCategories.delete(category);
17180
+ freed += toolTokens;
17181
+ logger.debug(
17182
+ { category, toolCount: toolNames.length, freed: toolTokens },
17183
+ `[ToolCatalogPlugin] Compacted category '${category}'`
17184
+ );
17185
+ }
17186
+ this.invalidateTokenCache();
17187
+ return freed;
17188
+ }
17189
+ getState() {
17190
+ return {
17191
+ loadedCategories: Array.from(this._loadedCategories.keys())
17192
+ };
17193
+ }
17194
+ restoreState(state) {
17195
+ if (!state || typeof state !== "object") return;
17196
+ const s = state;
17197
+ if (!Array.isArray(s.loadedCategories) || s.loadedCategories.length === 0) return;
17198
+ for (const category of s.loadedCategories) {
17199
+ if (typeof category !== "string" || !category) continue;
17200
+ const result = this.executeLoad(category);
17201
+ if (result.error) {
17202
+ logger.warn(
17203
+ { category, error: result.error },
17204
+ `[ToolCatalogPlugin] Failed to restore category '${category}'`
17205
+ );
17206
+ }
17207
+ }
17208
+ this.invalidateTokenCache();
17209
+ }
17210
+ destroy() {
17211
+ this._loadedCategories.clear();
17212
+ this._toolManager = null;
17213
+ this._connectorCategories = null;
17214
+ this._destroyed = true;
17215
+ }
17216
+ // ========================================================================
17217
+ // Public API
17218
+ // ========================================================================
17219
+ /**
17220
+ * Set the ToolManager reference. Called by AgentContextNextGen after plugin registration.
17221
+ */
17222
+ setToolManager(tm) {
17223
+ this._toolManager = tm;
17224
+ this._connectorCategories = ToolCatalogRegistry.discoverConnectorCategories({
17225
+ scope: this._config.categoryScope,
17226
+ identities: this._config.identities
17227
+ });
17228
+ if (this._config.autoLoadCategories?.length) {
17229
+ for (const category of this._config.autoLoadCategories) {
17230
+ const result = this.executeLoad(category);
17231
+ if (result.error) {
17232
+ logger.warn(
17233
+ { category, error: result.error },
17234
+ `[ToolCatalogPlugin] Failed to auto-load category '${category}'`
17235
+ );
17236
+ }
17237
+ }
17238
+ }
17239
+ }
17240
+ /** Get list of currently loaded category names */
17241
+ get loadedCategories() {
17242
+ return Array.from(this._loadedCategories.keys());
17243
+ }
17244
+ // ========================================================================
17245
+ // Metatool Implementations
17246
+ // ========================================================================
17247
+ executeSearch(query, category) {
17248
+ if (this._destroyed) return { error: "Plugin destroyed" };
17249
+ if (category) {
17250
+ if (ToolCatalogRegistry.parseConnectorCategory(category) !== null) {
17251
+ return this.searchConnectorCategory(category);
17252
+ }
17253
+ if (!ToolCatalogRegistry.hasCategory(category)) {
17254
+ return { error: `Category '${category}' not found. Use tool_catalog_search with no params to see available categories.` };
17255
+ }
17256
+ if (!ToolCatalogRegistry.isCategoryAllowed(category, this._config.categoryScope)) {
17257
+ return { error: `Category '${category}' is not available for this agent.` };
17258
+ }
17259
+ const tools = ToolCatalogRegistry.getToolsInCategory(category);
17260
+ const loaded = this._loadedCategories.has(category);
17261
+ return {
17262
+ category,
17263
+ loaded,
17264
+ tools: tools.map((t) => ({
17265
+ name: t.name,
17266
+ displayName: t.displayName,
17267
+ description: t.description,
17268
+ safeByDefault: t.safeByDefault
17269
+ }))
17270
+ };
17271
+ }
17272
+ if (query) {
17273
+ return this.keywordSearch(query);
17274
+ }
17275
+ const categories = this.getAllowedCategories();
17276
+ const connectorCats = this.getConnectorCategories();
17277
+ const result = [];
17278
+ for (const cat of categories) {
17279
+ const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
17280
+ result.push({
17281
+ name: cat.name,
17282
+ displayName: cat.displayName,
17283
+ description: cat.description,
17284
+ toolCount: tools.length,
17285
+ loaded: this._loadedCategories.has(cat.name)
17286
+ });
17287
+ }
17288
+ for (const cc of connectorCats) {
17289
+ result.push({
17290
+ name: cc.name,
17291
+ displayName: cc.displayName,
17292
+ description: cc.description,
17293
+ toolCount: cc.toolCount,
17294
+ loaded: this._loadedCategories.has(cc.name)
17295
+ });
17296
+ }
17297
+ return { categories: result };
17298
+ }
17299
+ executeLoad(category) {
17300
+ if (this._destroyed) return { error: "Plugin destroyed" };
17301
+ if (!this._toolManager) {
17302
+ return { error: "ToolManager not connected. Plugin not properly initialized." };
17303
+ }
17304
+ if (!ToolCatalogRegistry.isCategoryAllowed(category, this._config.categoryScope)) {
17305
+ return { error: `Category '${category}' is not available for this agent.` };
17306
+ }
17307
+ if (this._loadedCategories.has(category)) {
17308
+ const toolNames2 = this._loadedCategories.get(category);
17309
+ return { loaded: toolNames2.length, tools: toolNames2, alreadyLoaded: true };
17310
+ }
17311
+ if (this._loadedCategories.size >= this._config.maxLoadedCategories) {
17312
+ return {
17313
+ error: `Maximum loaded categories (${this._config.maxLoadedCategories}) reached. Unload a category first.`,
17314
+ loaded: Array.from(this._loadedCategories.keys())
17315
+ };
17316
+ }
17317
+ const isConnector = ToolCatalogRegistry.parseConnectorCategory(category) !== null;
17318
+ let tools;
17319
+ if (isConnector) {
17320
+ tools = ToolCatalogRegistry.resolveConnectorCategoryTools(category);
17321
+ } else {
17322
+ const entries = ToolCatalogRegistry.getToolsInCategory(category);
17323
+ if (entries.length === 0) {
17324
+ return { error: `Category '${category}' has no tools or does not exist.` };
17325
+ }
17326
+ tools = entries.filter((e) => e.tool != null).map((e) => ({ tool: e.tool, name: e.name }));
17327
+ }
17328
+ if (tools.length === 0) {
17329
+ return { error: `No tools found for category '${category}'.` };
17330
+ }
17331
+ const toolNames = [];
17332
+ for (const { tool, name } of tools) {
17333
+ const existing = this._toolManager.getRegistration(name);
17334
+ if (existing) {
17335
+ this._toolManager.setEnabled([name], true);
17336
+ } else {
17337
+ this._toolManager.register(tool, { category, source: `catalog:${category}` });
17338
+ }
17339
+ toolNames.push(name);
17340
+ }
17341
+ this._loadedCategories.set(category, toolNames);
17342
+ this.invalidateTokenCache();
17343
+ logger.debug(
17344
+ { category, toolCount: toolNames.length, tools: toolNames },
17345
+ `[ToolCatalogPlugin] Loaded category '${category}'`
17346
+ );
17347
+ return { loaded: toolNames.length, tools: toolNames };
17348
+ }
17349
+ executeUnload(category) {
17350
+ if (this._destroyed) return { error: "Plugin destroyed" };
17351
+ if (!this._toolManager) {
17352
+ return { error: "ToolManager not connected." };
17353
+ }
17354
+ const toolNames = this._loadedCategories.get(category);
17355
+ if (!toolNames) {
17356
+ return { unloaded: 0, message: `Category '${category}' is not loaded.` };
17357
+ }
17358
+ this._toolManager.setEnabled(toolNames, false);
17359
+ this._loadedCategories.delete(category);
17360
+ this.invalidateTokenCache();
17361
+ logger.debug(
17362
+ { category, toolCount: toolNames.length },
17363
+ `[ToolCatalogPlugin] Unloaded category '${category}'`
17364
+ );
17365
+ return { unloaded: toolNames.length };
17366
+ }
17367
+ // ========================================================================
17368
+ // Helpers
17369
+ // ========================================================================
17370
+ getAllowedCategories() {
17371
+ return ToolCatalogRegistry.filterCategories(this._config.categoryScope);
17372
+ }
17373
+ /**
17374
+ * Get connector categories from cache (populated once in setToolManager).
17375
+ */
17376
+ getConnectorCategories() {
17377
+ return this._connectorCategories ?? [];
17378
+ }
17379
+ keywordSearch(query) {
17380
+ const lq = query.toLowerCase();
17381
+ const results = [];
17382
+ for (const cat of this.getAllowedCategories()) {
17383
+ const catMatch = cat.name.toLowerCase().includes(lq) || cat.displayName.toLowerCase().includes(lq) || cat.description.toLowerCase().includes(lq);
17384
+ const tools = ToolCatalogRegistry.getToolsInCategory(cat.name);
17385
+ const matchingTools = tools.filter(
17386
+ (t) => t.name.toLowerCase().includes(lq) || t.displayName.toLowerCase().includes(lq) || t.description.toLowerCase().includes(lq)
17387
+ );
17388
+ if (catMatch || matchingTools.length > 0) {
17389
+ results.push({
17390
+ category: cat.name,
17391
+ categoryDisplayName: cat.displayName,
17392
+ tools: (catMatch ? tools : matchingTools).map((t) => ({
17393
+ name: t.name,
17394
+ displayName: t.displayName,
17395
+ description: t.description
17396
+ }))
17397
+ });
17398
+ }
17399
+ }
17400
+ for (const cc of this.getConnectorCategories()) {
17401
+ if (cc.name.toLowerCase().includes(lq) || cc.displayName.toLowerCase().includes(lq) || cc.description.toLowerCase().includes(lq)) {
17402
+ results.push({
17403
+ category: cc.name,
17404
+ categoryDisplayName: cc.displayName,
17405
+ tools: cc.tools.map((t) => ({
17406
+ name: t.definition.function.name,
17407
+ displayName: t.definition.function.name.replace(/_/g, " "),
17408
+ description: t.definition.function.description || ""
17409
+ }))
17410
+ });
17411
+ }
17412
+ }
17413
+ return { query, results, totalMatches: results.length };
17414
+ }
17415
+ searchConnectorCategory(category) {
17416
+ const connectorName = ToolCatalogRegistry.parseConnectorCategory(category);
17417
+ const tools = ToolCatalogRegistry.resolveConnectorCategoryTools(category);
17418
+ const loaded = this._loadedCategories.has(category);
17419
+ return {
17420
+ category,
17421
+ loaded,
17422
+ connectorName,
17423
+ tools: tools.map((t) => ({
17424
+ name: t.name,
17425
+ description: t.tool.definition.function.description || ""
17426
+ }))
17427
+ };
17428
+ }
17429
+ getCategoriesSortedByLastUsed() {
17430
+ if (!this._toolManager) return Array.from(this._loadedCategories.keys());
17431
+ const categoryLastUsed = [];
17432
+ for (const [category, toolNames] of this._loadedCategories) {
17433
+ let maxLastUsed = 0;
17434
+ for (const name of toolNames) {
17435
+ const reg = this._toolManager.getRegistration(name);
17436
+ if (reg?.metadata?.lastUsed) {
17437
+ const ts = reg.metadata.lastUsed instanceof Date ? reg.metadata.lastUsed.getTime() : 0;
17438
+ if (ts > maxLastUsed) maxLastUsed = ts;
17439
+ }
17440
+ }
17441
+ categoryLastUsed.push({ category, lastUsed: maxLastUsed });
17442
+ }
17443
+ categoryLastUsed.sort((a, b) => a.lastUsed - b.lastUsed);
17444
+ return categoryLastUsed.map((c) => c.category);
17445
+ }
17446
+ estimateToolDefinitionTokens(toolNames) {
17447
+ let total = 0;
17448
+ for (const name of toolNames) {
17449
+ const reg = this._toolManager?.getRegistration(name);
17450
+ if (reg) {
17451
+ const defObj = reg.tool.definition;
17452
+ const cached = this._toolTokenCache.get(defObj);
17453
+ if (cached !== void 0) {
17454
+ total += cached;
17455
+ } else {
17456
+ const defStr = JSON.stringify(defObj);
17457
+ const tokens = this.estimator.estimateTokens(defStr);
17458
+ this._toolTokenCache.set(defObj, tokens);
17459
+ total += tokens;
17460
+ }
17461
+ }
17462
+ }
17463
+ return total;
17464
+ }
16194
17465
  };
16195
17466
 
16196
17467
  // src/core/context-nextgen/AgentContextNextGen.ts
@@ -16846,7 +18117,8 @@ var DEFAULT_FEATURES = {
16846
18117
  workingMemory: true,
16847
18118
  inContextMemory: true,
16848
18119
  persistentInstructions: false,
16849
- userInfo: false
18120
+ userInfo: false,
18121
+ toolCatalog: false
16850
18122
  };
16851
18123
  var DEFAULT_CONFIG2 = {
16852
18124
  responseReserve: 4096,
@@ -16918,6 +18190,7 @@ var AgentContextNextGen = class _AgentContextNextGen extends EventEmitter {
16918
18190
  strategy: config.strategy ?? DEFAULT_CONFIG2.strategy,
16919
18191
  features: { ...DEFAULT_FEATURES, ...config.features },
16920
18192
  agentId: config.agentId ?? this.generateId(),
18193
+ toolCategories: config.toolCategories,
16921
18194
  storage: config.storage
16922
18195
  };
16923
18196
  this._systemPrompt = config.systemPrompt;
@@ -16973,6 +18246,16 @@ var AgentContextNextGen = class _AgentContextNextGen extends EventEmitter {
16973
18246
  ...uiConfig
16974
18247
  }));
16975
18248
  }
18249
+ if (features.toolCatalog) {
18250
+ const tcConfig = configs.toolCatalog;
18251
+ const plugin = new ToolCatalogPluginNextGen({
18252
+ categoryScope: this._config.toolCategories,
18253
+ identities: this._identities,
18254
+ ...tcConfig
18255
+ });
18256
+ this.registerPlugin(plugin);
18257
+ plugin.setToolManager(this._tools);
18258
+ }
16976
18259
  this.validateStrategyDependencies(this._compactionStrategy);
16977
18260
  }
16978
18261
  /**
@@ -24694,7 +25977,9 @@ var ROUTINE_KEYS = {
24694
25977
  /** Running fold accumulator (ICM) */
24695
25978
  FOLD_ACCUMULATOR: "__fold_accumulator",
24696
25979
  /** Prefix for large dep results stored in WM findings tier */
24697
- WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_"
25980
+ WM_DEP_FINDINGS_PREFIX: "findings/__dep_result_",
25981
+ /** Prefix for auto-stored task outputs (set by output contracts) */
25982
+ TASK_OUTPUT_PREFIX: "__task_output_"
24698
25983
  };
24699
25984
  function resolveTemplates(text, inputs, icmPlugin) {
24700
25985
  return text.replace(/\{\{(\w+)\.(\w+)\}\}/g, (_match, namespace, key) => {
@@ -24719,13 +26004,45 @@ function resolveTemplates(text, inputs, icmPlugin) {
24719
26004
  function resolveTaskTemplates(task, inputs, icmPlugin) {
24720
26005
  const resolvedDescription = resolveTemplates(task.description, inputs, icmPlugin);
24721
26006
  const resolvedExpectedOutput = task.expectedOutput ? resolveTemplates(task.expectedOutput, inputs, icmPlugin) : task.expectedOutput;
24722
- if (resolvedDescription === task.description && resolvedExpectedOutput === task.expectedOutput) {
26007
+ let resolvedControlFlow = task.controlFlow;
26008
+ if (task.controlFlow && "source" in task.controlFlow) {
26009
+ const flow = task.controlFlow;
26010
+ const source = flow.source;
26011
+ if (typeof source === "string") {
26012
+ const r = resolveTemplates(source, inputs, icmPlugin);
26013
+ if (r !== source) {
26014
+ resolvedControlFlow = { ...flow, source: r };
26015
+ }
26016
+ } else if (source) {
26017
+ let changed = false;
26018
+ const resolved = { ...source };
26019
+ if (resolved.task) {
26020
+ const r = resolveTemplates(resolved.task, inputs, icmPlugin);
26021
+ if (r !== resolved.task) {
26022
+ resolved.task = r;
26023
+ changed = true;
26024
+ }
26025
+ }
26026
+ if (resolved.key) {
26027
+ const r = resolveTemplates(resolved.key, inputs, icmPlugin);
26028
+ if (r !== resolved.key) {
26029
+ resolved.key = r;
26030
+ changed = true;
26031
+ }
26032
+ }
26033
+ if (changed) {
26034
+ resolvedControlFlow = { ...flow, source: resolved };
26035
+ }
26036
+ }
26037
+ }
26038
+ if (resolvedDescription === task.description && resolvedExpectedOutput === task.expectedOutput && resolvedControlFlow === task.controlFlow) {
24723
26039
  return task;
24724
26040
  }
24725
26041
  return {
24726
26042
  ...task,
24727
26043
  description: resolvedDescription,
24728
- expectedOutput: resolvedExpectedOutput
26044
+ expectedOutput: resolvedExpectedOutput,
26045
+ controlFlow: resolvedControlFlow
24729
26046
  };
24730
26047
  }
24731
26048
  function validateAndResolveInputs(parameters, inputs) {
@@ -24793,17 +26110,6 @@ function cleanFoldKeys(icmPlugin) {
24793
26110
  cleanMapKeys(icmPlugin);
24794
26111
  icmPlugin.delete(ROUTINE_KEYS.FOLD_ACCUMULATOR);
24795
26112
  }
24796
- async function readSourceArray(flow, flowType, icmPlugin, wmPlugin) {
24797
- const sourceValue = await readMemoryValue(flow.sourceKey, icmPlugin, wmPlugin);
24798
- if (!Array.isArray(sourceValue)) {
24799
- return {
24800
- completed: false,
24801
- error: `${flowType} sourceKey "${flow.sourceKey}" is not an array (got ${typeof sourceValue})`
24802
- };
24803
- }
24804
- const maxIter = Math.min(sourceValue.length, flow.maxIterations ?? sourceValue.length, HARD_MAX_ITERATIONS);
24805
- return { array: sourceValue, maxIter };
24806
- }
24807
26113
  function prepareSubRoutine(tasks, parentTaskName) {
24808
26114
  const subRoutine = resolveSubRoutine(tasks, parentTaskName);
24809
26115
  return {
@@ -24838,10 +26144,141 @@ async function withTimeout(promise, timeoutMs, label) {
24838
26144
  clearTimeout(timer);
24839
26145
  }
24840
26146
  }
24841
- async function handleMap(agent, flow, task, inputs) {
26147
+ var COMMON_ARRAY_FIELDS = ["data", "items", "results", "entries", "list", "records", "values", "elements"];
26148
+ function extractByPath(value, path6) {
26149
+ let current = value;
26150
+ if (typeof current === "string") {
26151
+ try {
26152
+ current = JSON.parse(current);
26153
+ } catch {
26154
+ return void 0;
26155
+ }
26156
+ }
26157
+ const segments = path6.replace(/\[(\d+)\]/g, ".$1").split(".").filter(Boolean);
26158
+ for (const segment of segments) {
26159
+ if (current == null || typeof current !== "object") return void 0;
26160
+ current = current[segment];
26161
+ }
26162
+ return current;
26163
+ }
26164
+ function tryCoerceToArray(value) {
26165
+ if (value === void 0 || value === null) return value;
26166
+ if (Array.isArray(value)) return value;
26167
+ if (typeof value === "string") {
26168
+ try {
26169
+ const parsed = JSON.parse(value);
26170
+ if (Array.isArray(parsed)) return parsed;
26171
+ if (typeof parsed === "object" && parsed !== null) {
26172
+ value = parsed;
26173
+ } else {
26174
+ return value;
26175
+ }
26176
+ } catch {
26177
+ return value;
26178
+ }
26179
+ }
26180
+ if (typeof value === "object" && value !== null) {
26181
+ for (const field of COMMON_ARRAY_FIELDS) {
26182
+ const candidate = value[field];
26183
+ if (Array.isArray(candidate)) return candidate;
26184
+ }
26185
+ }
26186
+ return value;
26187
+ }
26188
+ async function llmExtractArray(agent, rawValue) {
26189
+ const serialized = typeof rawValue === "string" ? rawValue : JSON.stringify(rawValue);
26190
+ const truncated = serialized.length > 8e3 ? serialized.slice(0, 8e3) + "\n...(truncated)" : serialized;
26191
+ const response = await agent.runDirect(
26192
+ [
26193
+ "Extract a JSON array from the data below for iteration.",
26194
+ "Return ONLY a valid JSON array. No explanation, no markdown fences, no extra text.",
26195
+ "If the data contains a list in any format (JSON, markdown, numbered list, comma-separated), convert it to a JSON array of items.",
26196
+ "",
26197
+ "Data:",
26198
+ truncated
26199
+ ].join("\n"),
26200
+ { temperature: 0, maxOutputTokens: 4096 }
26201
+ );
26202
+ const text = response.output_text?.trim() ?? "";
26203
+ const cleaned = text.replace(/^```(?:json|JSON)?\s*\n?/, "").replace(/\n?\s*```$/, "").trim();
26204
+ let parsed;
26205
+ try {
26206
+ parsed = JSON.parse(cleaned);
26207
+ } catch (parseErr) {
26208
+ throw new Error(`LLM returned invalid JSON: ${parseErr.message}. Raw: "${text.slice(0, 200)}"`);
26209
+ }
26210
+ if (!Array.isArray(parsed)) {
26211
+ throw new Error(`LLM extraction produced ${typeof parsed}, expected array`);
26212
+ }
26213
+ return parsed;
26214
+ }
26215
+ async function resolveFlowSource(flow, flowType, agent, execution, icmPlugin, wmPlugin) {
26216
+ const log = logger.child({ fn: "resolveFlowSource", flowType });
26217
+ const source = flow.source;
26218
+ const lookups = [];
26219
+ if (typeof source === "string") {
26220
+ lookups.push({ key: source, label: `key "${source}"` });
26221
+ } else if (source.task) {
26222
+ lookups.push({
26223
+ key: `${ROUTINE_KEYS.TASK_OUTPUT_PREFIX}${source.task}`,
26224
+ path: source.path,
26225
+ label: `task output "${source.task}"`
26226
+ });
26227
+ if (execution) {
26228
+ const depTask = execution.plan.tasks.find((t) => t.name === source.task);
26229
+ if (depTask) {
26230
+ lookups.push({
26231
+ key: `${ROUTINE_KEYS.DEP_RESULT_PREFIX}${depTask.id}`,
26232
+ path: source.path,
26233
+ label: `dep result "${source.task}"`
26234
+ });
26235
+ }
26236
+ }
26237
+ } else if (source.key) {
26238
+ lookups.push({ key: source.key, path: source.path, label: `key "${source.key}"` });
26239
+ }
26240
+ if (lookups.length === 0) {
26241
+ return { completed: false, error: `${flowType}: source has no task, key, or string value` };
26242
+ }
26243
+ let rawValue;
26244
+ let resolvedVia;
26245
+ for (const { key, path: path6, label } of lookups) {
26246
+ const value2 = await readMemoryValue(key, icmPlugin, wmPlugin);
26247
+ if (value2 !== void 0) {
26248
+ rawValue = path6 ? extractByPath(value2, path6) : value2;
26249
+ resolvedVia = label;
26250
+ break;
26251
+ }
26252
+ }
26253
+ if (rawValue === void 0) {
26254
+ const tried = lookups.map((l) => l.label).join(", ");
26255
+ return { completed: false, error: `${flowType}: source not found (tried: ${tried})` };
26256
+ }
26257
+ log.debug({ resolvedVia }, "Source value found");
26258
+ let value = tryCoerceToArray(rawValue);
26259
+ if (!Array.isArray(value)) {
26260
+ log.info({ resolvedVia, valueType: typeof value }, "Source not an array, attempting LLM extraction");
26261
+ try {
26262
+ value = await llmExtractArray(agent, rawValue);
26263
+ log.info({ extractedLength: value.length }, "LLM extraction succeeded");
26264
+ } catch (err) {
26265
+ return {
26266
+ completed: false,
26267
+ error: `${flowType}: source value is not an array and LLM extraction failed: ${err.message}`
26268
+ };
26269
+ }
26270
+ }
26271
+ const arr = value;
26272
+ if (arr.length === 0) {
26273
+ log.warn("Source array is empty");
26274
+ }
26275
+ const maxIter = Math.min(arr.length, flow.maxIterations ?? arr.length, HARD_MAX_ITERATIONS);
26276
+ return { array: arr, maxIter };
26277
+ }
26278
+ async function handleMap(agent, flow, task, inputs, execution) {
24842
26279
  const { icmPlugin, wmPlugin } = getPlugins(agent);
24843
26280
  const log = logger.child({ controlFlow: "map", task: task.name });
24844
- const sourceResult = await readSourceArray(flow, "Map", icmPlugin, wmPlugin);
26281
+ const sourceResult = await resolveFlowSource(flow, "Map", agent, execution, icmPlugin, wmPlugin);
24845
26282
  if ("completed" in sourceResult) return sourceResult;
24846
26283
  const { array: array3, maxIter } = sourceResult;
24847
26284
  const results = [];
@@ -24879,10 +26316,10 @@ async function handleMap(agent, flow, task, inputs) {
24879
26316
  log.info({ resultCount: results.length }, "Map completed");
24880
26317
  return { completed: true, result: results };
24881
26318
  }
24882
- async function handleFold(agent, flow, task, inputs) {
26319
+ async function handleFold(agent, flow, task, inputs, execution) {
24883
26320
  const { icmPlugin, wmPlugin } = getPlugins(agent);
24884
26321
  const log = logger.child({ controlFlow: "fold", task: task.name });
24885
- const sourceResult = await readSourceArray(flow, "Fold", icmPlugin, wmPlugin);
26322
+ const sourceResult = await resolveFlowSource(flow, "Fold", agent, execution, icmPlugin, wmPlugin);
24886
26323
  if ("completed" in sourceResult) return sourceResult;
24887
26324
  const { array: array3, maxIter } = sourceResult;
24888
26325
  let accumulator = flow.initialValue;
@@ -24973,13 +26410,13 @@ async function handleUntil(agent, flow, task, inputs) {
24973
26410
  }
24974
26411
  return { completed: false, error: `Until loop: maxIterations (${flow.maxIterations}) exceeded` };
24975
26412
  }
24976
- async function executeControlFlow(agent, task, inputs) {
26413
+ async function executeControlFlow(agent, task, inputs, execution) {
24977
26414
  const flow = task.controlFlow;
24978
26415
  switch (flow.type) {
24979
26416
  case "map":
24980
- return handleMap(agent, flow, task, inputs);
26417
+ return handleMap(agent, flow, task, inputs, execution);
24981
26418
  case "fold":
24982
- return handleFold(agent, flow, task, inputs);
26419
+ return handleFold(agent, flow, task, inputs, execution);
24983
26420
  case "until":
24984
26421
  return handleUntil(agent, flow, task, inputs);
24985
26422
  default:
@@ -25008,7 +26445,26 @@ function defaultSystemPrompt(definition) {
25008
26445
  );
25009
26446
  return parts.join("\n");
25010
26447
  }
25011
- function defaultTaskPrompt(task) {
26448
+ function getOutputContracts(execution, currentTask) {
26449
+ const contracts = [];
26450
+ for (const task of execution.plan.tasks) {
26451
+ if (task.status !== "pending" || !task.controlFlow) continue;
26452
+ const flow = task.controlFlow;
26453
+ if (flow.type === "until") continue;
26454
+ const source = flow.source;
26455
+ const sourceTaskName = typeof source === "string" ? void 0 : source.task;
26456
+ if (sourceTaskName === currentTask.name) {
26457
+ contracts.push({
26458
+ storageKey: `${ROUTINE_KEYS.TASK_OUTPUT_PREFIX}${currentTask.name}`,
26459
+ format: "array",
26460
+ consumingTaskName: task.name,
26461
+ flowType: flow.type
26462
+ });
26463
+ }
26464
+ }
26465
+ return contracts;
26466
+ }
26467
+ function defaultTaskPrompt(task, execution) {
25012
26468
  const parts = [];
25013
26469
  parts.push(`## Current Task: ${task.name}`, "");
25014
26470
  parts.push(task.description, "");
@@ -25033,6 +26489,21 @@ function defaultTaskPrompt(task) {
25033
26489
  parts.push("Review the plan overview and dependency results before starting.");
25034
26490
  parts.push("");
25035
26491
  }
26492
+ if (execution) {
26493
+ const contracts = getOutputContracts(execution, task);
26494
+ if (contracts.length > 0) {
26495
+ parts.push("### Output Storage");
26496
+ for (const contract of contracts) {
26497
+ parts.push(
26498
+ `A downstream task ("${contract.consumingTaskName}") will ${contract.flowType} over your results.`,
26499
+ `Store your result as a JSON ${contract.format} using:`,
26500
+ ` context_set("${contract.storageKey}", <your JSON ${contract.format}>)`,
26501
+ "Each array element should represent one item to process independently.",
26502
+ ""
26503
+ );
26504
+ }
26505
+ }
26506
+ }
25036
26507
  parts.push("After completing the work, store key results in memory once, then respond with a text summary (no more tool calls).");
25037
26508
  return parts.join("\n");
25038
26509
  }
@@ -25189,8 +26660,8 @@ var DEP_CLEANUP_CONFIG = {
25189
26660
  wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX]
25190
26661
  };
25191
26662
  var FULL_CLEANUP_CONFIG = {
25192
- icmPrefixes: ["__routine_", ROUTINE_KEYS.DEP_RESULT_PREFIX, "__map_", "__fold_"],
25193
- wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX]
26663
+ icmPrefixes: ["__routine_", ROUTINE_KEYS.DEP_RESULT_PREFIX, "__map_", "__fold_", ROUTINE_KEYS.TASK_OUTPUT_PREFIX],
26664
+ wmPrefixes: [ROUTINE_KEYS.DEP_RESULT_PREFIX, ROUTINE_KEYS.WM_DEP_FINDINGS_PREFIX, ROUTINE_KEYS.TASK_OUTPUT_PREFIX]
25194
26665
  };
25195
26666
  async function injectRoutineContext(agent, execution, definition, currentTask) {
25196
26667
  const { icmPlugin, wmPlugin } = getPlugins(agent);
@@ -25301,7 +26772,8 @@ async function executeRoutine(options) {
25301
26772
  execution.startedAt = Date.now();
25302
26773
  execution.lastUpdatedAt = Date.now();
25303
26774
  const buildSystemPrompt = prompts?.system ?? defaultSystemPrompt;
25304
- const buildTaskPrompt = prompts?.task ?? defaultTaskPrompt;
26775
+ const userTaskPromptBuilder = prompts?.task ?? defaultTaskPrompt;
26776
+ const buildTaskPrompt = (task) => userTaskPromptBuilder(task, execution);
25305
26777
  const buildValidationPrompt = prompts?.validation ?? defaultValidationPrompt;
25306
26778
  let agent;
25307
26779
  const registeredHooks = [];
@@ -25392,7 +26864,7 @@ async function executeRoutine(options) {
25392
26864
  const { icmPlugin } = getPlugins(agent);
25393
26865
  if (getTask().controlFlow) {
25394
26866
  try {
25395
- const cfResult = await executeControlFlow(agent, getTask(), resolvedInputs);
26867
+ const cfResult = await executeControlFlow(agent, getTask(), resolvedInputs, execution);
25396
26868
  if (cfResult.completed) {
25397
26869
  execution.plan.tasks[taskIndex] = updateTaskStatus(getTask(), "completed");
25398
26870
  execution.plan.tasks[taskIndex].result = { success: true, output: cfResult.result };
@@ -25542,6 +27014,261 @@ async function executeRoutine(options) {
25542
27014
  }
25543
27015
  }
25544
27016
 
27017
+ // src/core/createExecutionRecorder.ts
27018
+ init_Logger();
27019
+ function truncate(value, maxLen) {
27020
+ const str = typeof value === "string" ? value : JSON.stringify(value);
27021
+ if (!str) return "";
27022
+ return str.length > maxLen ? str.slice(0, maxLen) + "...(truncated)" : str;
27023
+ }
27024
+ function safeCall(fn, prefix) {
27025
+ try {
27026
+ const result = fn();
27027
+ if (result && typeof result.catch === "function") {
27028
+ result.catch((err) => {
27029
+ logger.debug({ error: err.message }, `${prefix} async error`);
27030
+ });
27031
+ }
27032
+ } catch (err) {
27033
+ logger.debug({ error: err.message }, `${prefix} sync error`);
27034
+ }
27035
+ }
27036
+ function createExecutionRecorder(options) {
27037
+ const { storage, executionId, logPrefix = "[Recorder]", maxTruncateLength = 500 } = options;
27038
+ const log = logger.child({ executionId });
27039
+ let currentTaskName = "(unknown)";
27040
+ function pushStep(step) {
27041
+ safeCall(() => storage.pushStep(executionId, step), `${logPrefix} pushStep`);
27042
+ }
27043
+ function heartbeat() {
27044
+ safeCall(
27045
+ () => storage.update(executionId, { lastActivityAt: Date.now() }),
27046
+ `${logPrefix} heartbeat`
27047
+ );
27048
+ }
27049
+ const hooks = {
27050
+ "before:llm": (ctx) => {
27051
+ pushStep({
27052
+ timestamp: Date.now(),
27053
+ taskName: currentTaskName,
27054
+ type: "llm.start",
27055
+ data: { iteration: ctx.iteration }
27056
+ });
27057
+ return {};
27058
+ },
27059
+ "after:llm": (ctx) => {
27060
+ pushStep({
27061
+ timestamp: Date.now(),
27062
+ taskName: currentTaskName,
27063
+ type: "llm.complete",
27064
+ data: {
27065
+ iteration: ctx.iteration,
27066
+ duration: ctx.duration,
27067
+ tokens: ctx.response?.usage
27068
+ }
27069
+ });
27070
+ return {};
27071
+ },
27072
+ "before:tool": (ctx) => {
27073
+ pushStep({
27074
+ timestamp: Date.now(),
27075
+ taskName: currentTaskName,
27076
+ type: "tool.start",
27077
+ data: {
27078
+ toolName: ctx.toolCall.function.name,
27079
+ args: truncate(ctx.toolCall.function.arguments, maxTruncateLength)
27080
+ }
27081
+ });
27082
+ return {};
27083
+ },
27084
+ "after:tool": (ctx) => {
27085
+ pushStep({
27086
+ timestamp: Date.now(),
27087
+ taskName: currentTaskName,
27088
+ type: "tool.call",
27089
+ data: {
27090
+ toolName: ctx.toolCall.function.name,
27091
+ args: truncate(ctx.toolCall.function.arguments, maxTruncateLength),
27092
+ result: truncate(ctx.result?.content, maxTruncateLength),
27093
+ error: ctx.result?.error ? true : void 0
27094
+ }
27095
+ });
27096
+ return {};
27097
+ },
27098
+ "after:execution": () => {
27099
+ pushStep({
27100
+ timestamp: Date.now(),
27101
+ taskName: currentTaskName,
27102
+ type: "iteration.complete"
27103
+ });
27104
+ },
27105
+ "pause:check": () => {
27106
+ heartbeat();
27107
+ return { shouldPause: false };
27108
+ }
27109
+ };
27110
+ const onTaskStarted = (task, execution) => {
27111
+ currentTaskName = task.name;
27112
+ const now = Date.now();
27113
+ safeCall(
27114
+ () => storage.updateTask(executionId, task.name, {
27115
+ status: "in_progress",
27116
+ startedAt: now,
27117
+ attempts: task.attempts
27118
+ }),
27119
+ `${logPrefix} onTaskStarted`
27120
+ );
27121
+ pushStep({
27122
+ timestamp: now,
27123
+ taskName: task.name,
27124
+ type: "task.started",
27125
+ data: { taskId: task.id }
27126
+ });
27127
+ if (task.controlFlow) {
27128
+ pushStep({
27129
+ timestamp: now,
27130
+ taskName: task.name,
27131
+ type: "control_flow.started",
27132
+ data: { flowType: task.controlFlow.type }
27133
+ });
27134
+ }
27135
+ safeCall(
27136
+ () => storage.update(executionId, {
27137
+ progress: execution.progress,
27138
+ lastActivityAt: now
27139
+ }),
27140
+ `${logPrefix} onTaskStarted progress`
27141
+ );
27142
+ };
27143
+ const onTaskComplete = (task, execution) => {
27144
+ const now = Date.now();
27145
+ safeCall(
27146
+ () => storage.updateTask(executionId, task.name, {
27147
+ status: "completed",
27148
+ completedAt: now,
27149
+ attempts: task.attempts,
27150
+ result: task.result ? {
27151
+ success: true,
27152
+ output: truncate(task.result.output, maxTruncateLength),
27153
+ validationScore: task.result.validationScore,
27154
+ validationExplanation: task.result.validationExplanation
27155
+ } : void 0
27156
+ }),
27157
+ `${logPrefix} onTaskComplete`
27158
+ );
27159
+ pushStep({
27160
+ timestamp: now,
27161
+ taskName: task.name,
27162
+ type: "task.completed",
27163
+ data: {
27164
+ taskId: task.id,
27165
+ validationScore: task.result?.validationScore
27166
+ }
27167
+ });
27168
+ if (task.controlFlow) {
27169
+ pushStep({
27170
+ timestamp: now,
27171
+ taskName: task.name,
27172
+ type: "control_flow.completed",
27173
+ data: { flowType: task.controlFlow.type }
27174
+ });
27175
+ }
27176
+ safeCall(
27177
+ () => storage.update(executionId, {
27178
+ progress: execution.progress,
27179
+ lastActivityAt: now
27180
+ }),
27181
+ `${logPrefix} onTaskComplete progress`
27182
+ );
27183
+ };
27184
+ const onTaskFailed = (task, execution) => {
27185
+ const now = Date.now();
27186
+ safeCall(
27187
+ () => storage.updateTask(executionId, task.name, {
27188
+ status: "failed",
27189
+ completedAt: now,
27190
+ attempts: task.attempts,
27191
+ result: task.result ? {
27192
+ success: false,
27193
+ error: task.result.error,
27194
+ validationScore: task.result.validationScore,
27195
+ validationExplanation: task.result.validationExplanation
27196
+ } : void 0
27197
+ }),
27198
+ `${logPrefix} onTaskFailed`
27199
+ );
27200
+ pushStep({
27201
+ timestamp: now,
27202
+ taskName: task.name,
27203
+ type: "task.failed",
27204
+ data: {
27205
+ taskId: task.id,
27206
+ error: task.result?.error,
27207
+ attempts: task.attempts
27208
+ }
27209
+ });
27210
+ safeCall(
27211
+ () => storage.update(executionId, {
27212
+ progress: execution.progress,
27213
+ lastActivityAt: now
27214
+ }),
27215
+ `${logPrefix} onTaskFailed progress`
27216
+ );
27217
+ };
27218
+ const onTaskValidation = (task, result, _execution) => {
27219
+ pushStep({
27220
+ timestamp: Date.now(),
27221
+ taskName: task.name,
27222
+ type: "task.validation",
27223
+ data: {
27224
+ taskId: task.id,
27225
+ isComplete: result.isComplete,
27226
+ completionScore: result.completionScore,
27227
+ explanation: truncate(result.explanation, maxTruncateLength)
27228
+ }
27229
+ });
27230
+ };
27231
+ const finalize = async (execution, error) => {
27232
+ const now = Date.now();
27233
+ try {
27234
+ if (error || !execution) {
27235
+ await storage.update(executionId, {
27236
+ status: "failed",
27237
+ error: error?.message ?? "Unknown error",
27238
+ completedAt: now,
27239
+ lastActivityAt: now
27240
+ });
27241
+ if (error) {
27242
+ await storage.pushStep(executionId, {
27243
+ timestamp: now,
27244
+ taskName: currentTaskName,
27245
+ type: "execution.error",
27246
+ data: { error: error.message }
27247
+ });
27248
+ }
27249
+ } else {
27250
+ await storage.update(executionId, {
27251
+ status: execution.status,
27252
+ progress: execution.progress,
27253
+ error: execution.error,
27254
+ completedAt: execution.completedAt ?? now,
27255
+ lastActivityAt: now
27256
+ });
27257
+ }
27258
+ } catch (err) {
27259
+ log.error({ error: err.message }, `${logPrefix} finalize error`);
27260
+ }
27261
+ };
27262
+ return {
27263
+ hooks,
27264
+ onTaskStarted,
27265
+ onTaskComplete,
27266
+ onTaskFailed,
27267
+ onTaskValidation,
27268
+ finalize
27269
+ };
27270
+ }
27271
+
25545
27272
  // src/core/index.ts
25546
27273
  init_constants();
25547
27274
  (class {
@@ -38866,6 +40593,38 @@ var InMemoryHistoryStorage = class {
38866
40593
  this.summaries = state.summaries ? [...state.summaries] : [];
38867
40594
  }
38868
40595
  };
40596
+
40597
+ // src/domain/entities/RoutineExecutionRecord.ts
40598
+ function createTaskSnapshots(definition) {
40599
+ return definition.tasks.map((task) => ({
40600
+ taskId: task.id ?? task.name,
40601
+ name: task.name,
40602
+ description: task.description,
40603
+ status: "pending",
40604
+ attempts: 0,
40605
+ maxAttempts: task.maxAttempts ?? 3,
40606
+ controlFlowType: task.controlFlow?.type
40607
+ }));
40608
+ }
40609
+ function createRoutineExecutionRecord(definition, connectorName, model, trigger) {
40610
+ const now = Date.now();
40611
+ const executionId = `rexec-${now}-${Math.random().toString(36).substr(2, 9)}`;
40612
+ return {
40613
+ executionId,
40614
+ routineId: definition.id,
40615
+ routineName: definition.name,
40616
+ status: "running",
40617
+ progress: 0,
40618
+ tasks: createTaskSnapshots(definition),
40619
+ steps: [],
40620
+ taskCount: definition.tasks.length,
40621
+ connectorName,
40622
+ model,
40623
+ startedAt: now,
40624
+ lastActivityAt: now,
40625
+ trigger: trigger ?? { type: "manual" }
40626
+ };
40627
+ }
38869
40628
  function getDefaultBaseDirectory3() {
38870
40629
  const platform2 = process.platform;
38871
40630
  if (platform2 === "win32") {
@@ -44709,6 +46468,7 @@ __export(tools_exports, {
44709
46468
  createEditMeetingTool: () => createEditMeetingTool,
44710
46469
  createExecuteJavaScriptTool: () => createExecuteJavaScriptTool,
44711
46470
  createFindMeetingSlotsTool: () => createFindMeetingSlotsTool,
46471
+ createGenerateRoutine: () => createGenerateRoutine,
44712
46472
  createGetMeetingTranscriptTool: () => createGetMeetingTranscriptTool,
44713
46473
  createGetPRTool: () => createGetPRTool,
44714
46474
  createGitHubReadFileTool: () => createGitHubReadFileTool,
@@ -44717,6 +46477,9 @@ __export(tools_exports, {
44717
46477
  createImageGenerationTool: () => createImageGenerationTool,
44718
46478
  createListDirectoryTool: () => createListDirectoryTool,
44719
46479
  createMeetingTool: () => createMeetingTool,
46480
+ createMicrosoftListFilesTool: () => createMicrosoftListFilesTool,
46481
+ createMicrosoftReadFileTool: () => createMicrosoftReadFileTool,
46482
+ createMicrosoftSearchFilesTool: () => createMicrosoftSearchFilesTool,
44720
46483
  createPRCommentsTool: () => createPRCommentsTool,
44721
46484
  createPRFilesTool: () => createPRFilesTool,
44722
46485
  createReadFileTool: () => createReadFileTool,
@@ -44749,14 +46512,18 @@ __export(tools_exports, {
44749
46512
  desktopWindowList: () => desktopWindowList,
44750
46513
  developerTools: () => developerTools,
44751
46514
  editFile: () => editFile,
46515
+ encodeSharingUrl: () => encodeSharingUrl,
44752
46516
  executeInVM: () => executeInVM,
44753
46517
  executeJavaScript: () => executeJavaScript,
44754
46518
  expandTilde: () => expandTilde,
44755
46519
  formatAttendees: () => formatAttendees,
46520
+ formatFileSize: () => formatFileSize,
44756
46521
  formatRecipients: () => formatRecipients,
46522
+ generateRoutine: () => generateRoutine,
44757
46523
  getAllBuiltInTools: () => getAllBuiltInTools,
44758
46524
  getBackgroundOutput: () => getBackgroundOutput,
44759
46525
  getDesktopDriver: () => getDesktopDriver,
46526
+ getDrivePrefix: () => getDrivePrefix,
44760
46527
  getMediaOutputHandler: () => getMediaOutputHandler,
44761
46528
  getMediaStorage: () => getMediaStorage,
44762
46529
  getToolByName: () => getToolByName,
@@ -44770,7 +46537,9 @@ __export(tools_exports, {
44770
46537
  hydrateCustomTool: () => hydrateCustomTool,
44771
46538
  isBlockedCommand: () => isBlockedCommand,
44772
46539
  isExcludedExtension: () => isExcludedExtension,
46540
+ isMicrosoftFileUrl: () => isMicrosoftFileUrl,
44773
46541
  isTeamsMeetingUrl: () => isTeamsMeetingUrl,
46542
+ isWebUrl: () => isWebUrl,
44774
46543
  jsonManipulator: () => jsonManipulator,
44775
46544
  killBackgroundProcess: () => killBackgroundProcess,
44776
46545
  listDirectory: () => listDirectory,
@@ -44781,6 +46550,7 @@ __export(tools_exports, {
44781
46550
  parseRepository: () => parseRepository,
44782
46551
  readFile: () => readFile5,
44783
46552
  resetDefaultDriver: () => resetDefaultDriver,
46553
+ resolveFileEndpoints: () => resolveFileEndpoints,
44784
46554
  resolveMeetingId: () => resolveMeetingId,
44785
46555
  resolveRepository: () => resolveRepository,
44786
46556
  setMediaOutputHandler: () => setMediaOutputHandler,
@@ -49033,6 +50803,87 @@ async function resolveMeetingId(connector, input, prefix, effectiveUserId, effec
49033
50803
  subject: meetings.value[0].subject
49034
50804
  };
49035
50805
  }
50806
+ var DEFAULT_MAX_FILE_SIZE_BYTES = 50 * 1024 * 1024;
50807
+ var DEFAULT_FILE_SIZE_LIMITS = {
50808
+ ".pptx": 100 * 1024 * 1024,
50809
+ // 100 MB — presentations are image-heavy
50810
+ ".ppt": 100 * 1024 * 1024,
50811
+ ".odp": 100 * 1024 * 1024
50812
+ };
50813
+ function getFileSizeLimit(ext, overrides, defaultLimit) {
50814
+ const merged = { ...DEFAULT_FILE_SIZE_LIMITS, ...overrides };
50815
+ return merged[ext.toLowerCase()] ?? defaultLimit ?? DEFAULT_MAX_FILE_SIZE_BYTES;
50816
+ }
50817
+ var SUPPORTED_EXTENSIONS = /* @__PURE__ */ new Set([
50818
+ ".docx",
50819
+ ".pptx",
50820
+ ".xlsx",
50821
+ ".csv",
50822
+ ".pdf",
50823
+ ".odt",
50824
+ ".odp",
50825
+ ".ods",
50826
+ ".rtf",
50827
+ ".html",
50828
+ ".htm",
50829
+ ".txt",
50830
+ ".md",
50831
+ ".json",
50832
+ ".xml",
50833
+ ".yaml",
50834
+ ".yml"
50835
+ ]);
50836
+ function encodeSharingUrl(webUrl) {
50837
+ const base64 = Buffer.from(webUrl, "utf-8").toString("base64").replace(/=+$/, "").replace(/\//g, "_").replace(/\+/g, "-");
50838
+ return `u!${base64}`;
50839
+ }
50840
+ function isWebUrl(source) {
50841
+ return /^https?:\/\//i.test(source.trim());
50842
+ }
50843
+ function isMicrosoftFileUrl(source) {
50844
+ try {
50845
+ const url2 = new URL(source.trim());
50846
+ const host = url2.hostname.toLowerCase();
50847
+ return host.endsWith(".sharepoint.com") || host.endsWith(".sharepoint-df.com") || host === "onedrive.live.com" || host === "1drv.ms";
50848
+ } catch {
50849
+ return false;
50850
+ }
50851
+ }
50852
+ function getDrivePrefix(userPrefix, options) {
50853
+ if (options?.siteId) return `/sites/${options.siteId}/drive`;
50854
+ if (options?.driveId) return `/drives/${options.driveId}`;
50855
+ return `${userPrefix}/drive`;
50856
+ }
50857
+ function resolveFileEndpoints(source, drivePrefix) {
50858
+ const trimmed = source.trim();
50859
+ if (isWebUrl(trimmed)) {
50860
+ const token = encodeSharingUrl(trimmed);
50861
+ return {
50862
+ metadataEndpoint: `/shares/${token}/driveItem`,
50863
+ contentEndpoint: `/shares/${token}/driveItem/content`,
50864
+ isSharedUrl: true
50865
+ };
50866
+ }
50867
+ if (trimmed.startsWith("/")) {
50868
+ const path6 = trimmed.endsWith("/") ? trimmed.slice(0, -1) : trimmed;
50869
+ return {
50870
+ metadataEndpoint: `${drivePrefix}/root:${path6}:`,
50871
+ contentEndpoint: `${drivePrefix}/root:${path6}:/content`,
50872
+ isSharedUrl: false
50873
+ };
50874
+ }
50875
+ return {
50876
+ metadataEndpoint: `${drivePrefix}/items/${trimmed}`,
50877
+ contentEndpoint: `${drivePrefix}/items/${trimmed}/content`,
50878
+ isSharedUrl: false
50879
+ };
50880
+ }
50881
+ function formatFileSize(bytes) {
50882
+ if (bytes < 1024) return `${bytes} B`;
50883
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
50884
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
50885
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
50886
+ }
49036
50887
 
49037
50888
  // src/tools/microsoft/createDraftEmail.ts
49038
50889
  function createDraftEmailTool(connector, userId) {
@@ -49738,16 +51589,539 @@ EXAMPLES:
49738
51589
  };
49739
51590
  }
49740
51591
 
51592
+ // src/tools/microsoft/readFile.ts
51593
+ function createMicrosoftReadFileTool(connector, userId, config) {
51594
+ const reader = DocumentReader.create();
51595
+ const defaultLimit = config?.maxFileSizeBytes ?? DEFAULT_MAX_FILE_SIZE_BYTES;
51596
+ const sizeOverrides = config?.fileSizeLimits;
51597
+ return {
51598
+ definition: {
51599
+ type: "function",
51600
+ function: {
51601
+ name: "read_file",
51602
+ description: `Read a file from Microsoft OneDrive or SharePoint and return its content as **markdown text**.
51603
+
51604
+ 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.
51605
+
51606
+ **Supported formats:** .docx, .pptx, .xlsx, .csv, .pdf, .odt, .odp, .ods, .rtf, .html, .txt, .md, .json, .xml, .yaml
51607
+ **Not supported:** .doc, .xls, .ppt (legacy Office formats), images, videos, executables.
51608
+
51609
+ **The \`source\` parameter is flexible \u2014 you can provide any of these:**
51610
+ - A SharePoint or OneDrive **web URL**: \`https://contoso.sharepoint.com/sites/team/Shared Documents/report.docx\`
51611
+ - A OneDrive **sharing link**: \`https://1drv.ms/w/s!AmVg...\`
51612
+ - A **file path** within the drive: \`/Documents/Q4 Report.docx\`
51613
+ - A Graph API **item ID**: \`01ABCDEF123456\`
51614
+
51615
+ 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.
51616
+
51617
+ **Maximum file size:** 50 MB (100 MB for presentations). For larger files, use the search or list tools to find smaller alternatives.
51618
+
51619
+ **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.`,
51620
+ parameters: {
51621
+ type: "object",
51622
+ properties: {
51623
+ source: {
51624
+ type: "string",
51625
+ 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.'
51626
+ },
51627
+ driveId: {
51628
+ type: "string",
51629
+ description: "Optional drive ID. Omit to use the default drive. Only needed when accessing a specific non-default drive."
51630
+ },
51631
+ siteId: {
51632
+ type: "string",
51633
+ description: "Optional SharePoint site ID. Use this instead of driveId to access files in a specific SharePoint site's default drive."
51634
+ },
51635
+ targetUser: {
51636
+ type: "string",
51637
+ 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.`
51638
+ }
51639
+ },
51640
+ required: ["source"]
51641
+ }
51642
+ },
51643
+ blocking: true,
51644
+ timeout: 6e4
51645
+ },
51646
+ describeCall: (args) => {
51647
+ const src = args.source.length > 80 ? args.source.slice(0, 77) + "..." : args.source;
51648
+ return `Read: ${src}`;
51649
+ },
51650
+ permission: {
51651
+ scope: "session",
51652
+ riskLevel: "low",
51653
+ approvalMessage: `Read a file from OneDrive/SharePoint via ${connector.displayName}`
51654
+ },
51655
+ execute: async (args, context) => {
51656
+ const effectiveUserId = context?.userId ?? userId;
51657
+ const effectiveAccountId = context?.accountId;
51658
+ if (!args.source || !args.source.trim()) {
51659
+ return {
51660
+ success: false,
51661
+ error: 'The "source" parameter is required. Provide a file URL, path, or item ID.'
51662
+ };
51663
+ }
51664
+ if (isWebUrl(args.source) && !isMicrosoftFileUrl(args.source)) {
51665
+ return {
51666
+ success: false,
51667
+ 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.`
51668
+ };
51669
+ }
51670
+ try {
51671
+ const userPrefix = getUserPathPrefix(connector, args.targetUser);
51672
+ const drivePrefix = getDrivePrefix(userPrefix, {
51673
+ siteId: args.siteId,
51674
+ driveId: args.driveId
51675
+ });
51676
+ const { metadataEndpoint, contentEndpoint, isSharedUrl } = resolveFileEndpoints(
51677
+ args.source,
51678
+ drivePrefix
51679
+ );
51680
+ const metadataQueryParams = isSharedUrl ? {} : { "$select": "id,name,size,file,folder,webUrl,parentReference" };
51681
+ const metadata = await microsoftFetch(connector, metadataEndpoint, {
51682
+ userId: effectiveUserId,
51683
+ accountId: effectiveAccountId,
51684
+ queryParams: metadataQueryParams
51685
+ });
51686
+ if (metadata.folder) {
51687
+ return {
51688
+ success: false,
51689
+ error: `"${metadata.name}" is a folder, not a file. Use the list_files tool to browse folder contents.`
51690
+ };
51691
+ }
51692
+ const ext = getExtension(metadata.name);
51693
+ const sizeLimit = getFileSizeLimit(ext, sizeOverrides, defaultLimit);
51694
+ if (metadata.size > sizeLimit) {
51695
+ return {
51696
+ success: false,
51697
+ filename: metadata.name,
51698
+ sizeBytes: metadata.size,
51699
+ 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.`
51700
+ };
51701
+ }
51702
+ if (ext && !SUPPORTED_EXTENSIONS.has(ext) && !FormatDetector.isBinaryDocumentFormat(ext)) {
51703
+ return {
51704
+ success: false,
51705
+ filename: metadata.name,
51706
+ mimeType: metadata.file?.mimeType,
51707
+ error: `File format "${ext}" is not supported for text extraction. Supported formats: ${[...SUPPORTED_EXTENSIONS].join(", ")}`
51708
+ };
51709
+ }
51710
+ const response = await connector.fetch(
51711
+ contentEndpoint,
51712
+ { method: "GET" },
51713
+ effectiveUserId,
51714
+ effectiveAccountId
51715
+ );
51716
+ if (!response.ok) {
51717
+ throw new MicrosoftAPIError(response.status, response.statusText, await response.text());
51718
+ }
51719
+ const arrayBuffer = await response.arrayBuffer();
51720
+ const buffer = Buffer.from(arrayBuffer);
51721
+ const result = await reader.read(
51722
+ { type: "buffer", buffer, filename: metadata.name },
51723
+ { extractImages: false }
51724
+ );
51725
+ if (!result.success) {
51726
+ return {
51727
+ success: false,
51728
+ filename: metadata.name,
51729
+ error: `Failed to convert "${metadata.name}" to markdown: ${result.error ?? "unknown error"}`
51730
+ };
51731
+ }
51732
+ const markdown = mergeTextPieces(result.pieces);
51733
+ if (!markdown || markdown.trim().length === 0) {
51734
+ return {
51735
+ success: true,
51736
+ filename: metadata.name,
51737
+ sizeBytes: metadata.size,
51738
+ mimeType: metadata.file?.mimeType,
51739
+ webUrl: metadata.webUrl,
51740
+ markdown: "*(empty document \u2014 no text content found)*"
51741
+ };
51742
+ }
51743
+ return {
51744
+ success: true,
51745
+ filename: metadata.name,
51746
+ sizeBytes: metadata.size,
51747
+ mimeType: metadata.file?.mimeType,
51748
+ webUrl: metadata.webUrl,
51749
+ markdown
51750
+ };
51751
+ } catch (error) {
51752
+ if (error instanceof MicrosoftAPIError) {
51753
+ if (error.status === 404) {
51754
+ return {
51755
+ success: false,
51756
+ error: `File not found. Check that the source "${args.source}" is correct and you have access.`
51757
+ };
51758
+ }
51759
+ if (error.status === 403 || error.status === 401) {
51760
+ return {
51761
+ success: false,
51762
+ error: `Access denied. The connector may not have sufficient permissions (Files.Read or Sites.Read.All required).`
51763
+ };
51764
+ }
51765
+ }
51766
+ return {
51767
+ success: false,
51768
+ error: `Failed to read file: ${error instanceof Error ? error.message : String(error)}`
51769
+ };
51770
+ }
51771
+ }
51772
+ };
51773
+ }
51774
+ function getExtension(filename) {
51775
+ const dot = filename.lastIndexOf(".");
51776
+ if (dot < 0) return "";
51777
+ return filename.slice(dot).toLowerCase();
51778
+ }
51779
+
51780
+ // src/tools/microsoft/listFiles.ts
51781
+ var DEFAULT_LIMIT = 50;
51782
+ var MAX_LIMIT = 200;
51783
+ var SELECT_FIELDS = "id,name,size,lastModifiedDateTime,file,folder,webUrl";
51784
+ function createMicrosoftListFilesTool(connector, userId) {
51785
+ return {
51786
+ definition: {
51787
+ type: "function",
51788
+ function: {
51789
+ name: "list_files",
51790
+ description: `List files and folders in a Microsoft OneDrive or SharePoint directory.
51791
+
51792
+ 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**.
51793
+
51794
+ **The \`path\` parameter is flexible \u2014 you can provide:**
51795
+ - A **folder path** within the drive: \`/Documents/Projects\` or \`/\` for root
51796
+ - A SharePoint/OneDrive **folder URL**: \`https://contoso.sharepoint.com/sites/team/Shared Documents/Projects\`
51797
+ - Omit entirely to list the root of the drive
51798
+
51799
+ **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).
51800
+
51801
+ **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.`,
51802
+ parameters: {
51803
+ type: "object",
51804
+ properties: {
51805
+ path: {
51806
+ type: "string",
51807
+ description: 'Folder path (e.g., "/Documents/Projects") or a web URL to a SharePoint/OneDrive folder. Omit to list root.'
51808
+ },
51809
+ driveId: {
51810
+ type: "string",
51811
+ description: "Optional drive ID for a specific non-default drive."
51812
+ },
51813
+ siteId: {
51814
+ type: "string",
51815
+ description: "Optional SharePoint site ID to access that site's default document library."
51816
+ },
51817
+ search: {
51818
+ type: "string",
51819
+ description: "Optional search query to filter results by filename or content. Searches within the specified folder and all subfolders."
51820
+ },
51821
+ limit: {
51822
+ type: "number",
51823
+ description: `Maximum number of items to return (default: ${DEFAULT_LIMIT}, max: ${MAX_LIMIT}).`
51824
+ },
51825
+ targetUser: {
51826
+ type: "string",
51827
+ description: "User ID or email. Only needed with application-only (client_credentials) auth."
51828
+ }
51829
+ }
51830
+ }
51831
+ },
51832
+ blocking: true,
51833
+ timeout: 3e4
51834
+ },
51835
+ describeCall: (args) => {
51836
+ const loc = args.path || "/";
51837
+ const suffix = args.search ? ` (search: "${args.search}")` : "";
51838
+ return `List: ${loc}${suffix}`;
51839
+ },
51840
+ permission: {
51841
+ scope: "session",
51842
+ riskLevel: "low",
51843
+ approvalMessage: `List files in OneDrive/SharePoint via ${connector.displayName}`
51844
+ },
51845
+ execute: async (args, context) => {
51846
+ const effectiveUserId = context?.userId ?? userId;
51847
+ const effectiveAccountId = context?.accountId;
51848
+ const limit = Math.min(Math.max(1, args.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
51849
+ try {
51850
+ const userPrefix = getUserPathPrefix(connector, args.targetUser);
51851
+ const drivePrefix = getDrivePrefix(userPrefix, {
51852
+ siteId: args.siteId,
51853
+ driveId: args.driveId
51854
+ });
51855
+ let endpoint;
51856
+ if (args.search) {
51857
+ const folderBase = args.path && !isWebUrl(args.path) ? `${drivePrefix}/root:${normalizePath(args.path)}:` : drivePrefix;
51858
+ endpoint = `${folderBase}/search(q='${encodeSearchQuery(args.search)}')`;
51859
+ } else if (args.path) {
51860
+ if (isWebUrl(args.path)) {
51861
+ const token = encodeSharingUrl(args.path.trim());
51862
+ endpoint = `/shares/${token}/driveItem/children`;
51863
+ } else {
51864
+ const path6 = normalizePath(args.path);
51865
+ endpoint = path6 === "/" ? `${drivePrefix}/root/children` : `${drivePrefix}/root:${path6}:/children`;
51866
+ }
51867
+ } else {
51868
+ endpoint = `${drivePrefix}/root/children`;
51869
+ }
51870
+ const queryParams = {
51871
+ "$top": limit,
51872
+ "$select": SELECT_FIELDS
51873
+ };
51874
+ if (!args.search) {
51875
+ queryParams["$orderby"] = "name asc";
51876
+ }
51877
+ const data = await microsoftFetch(connector, endpoint, {
51878
+ userId: effectiveUserId,
51879
+ accountId: effectiveAccountId,
51880
+ queryParams
51881
+ });
51882
+ const items = (data.value || []).map(mapDriveItem);
51883
+ return {
51884
+ success: true,
51885
+ items,
51886
+ totalCount: items.length,
51887
+ hasMore: !!data["@odata.nextLink"]
51888
+ };
51889
+ } catch (error) {
51890
+ return {
51891
+ success: false,
51892
+ error: `Failed to list files: ${error instanceof Error ? error.message : String(error)}`
51893
+ };
51894
+ }
51895
+ }
51896
+ };
51897
+ }
51898
+ function mapDriveItem(item) {
51899
+ return {
51900
+ name: item.name,
51901
+ type: item.folder ? "folder" : "file",
51902
+ size: item.size,
51903
+ sizeFormatted: formatFileSize(item.size),
51904
+ mimeType: item.file?.mimeType,
51905
+ lastModified: item.lastModifiedDateTime,
51906
+ webUrl: item.webUrl,
51907
+ id: item.id,
51908
+ childCount: item.folder?.childCount
51909
+ };
51910
+ }
51911
+ function normalizePath(path6) {
51912
+ let p = path6.trim();
51913
+ if (!p.startsWith("/")) p = "/" + p;
51914
+ if (p.endsWith("/") && p.length > 1) p = p.slice(0, -1);
51915
+ return p;
51916
+ }
51917
+ function encodeSearchQuery(query) {
51918
+ return query.replace(/\\/g, "\\\\").replace(/'/g, "''");
51919
+ }
51920
+
51921
+ // src/tools/microsoft/searchFiles.ts
51922
+ var DEFAULT_LIMIT2 = 25;
51923
+ var MAX_LIMIT2 = 100;
51924
+ function createMicrosoftSearchFilesTool(connector, userId) {
51925
+ return {
51926
+ definition: {
51927
+ type: "function",
51928
+ function: {
51929
+ name: "search_files",
51930
+ description: `Search for files across Microsoft OneDrive and SharePoint.
51931
+
51932
+ 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.
51933
+
51934
+ **Supports Microsoft's KQL (Keyword Query Language):**
51935
+ - Simple text: \`"quarterly report"\`
51936
+ - By filename: \`filename:budget.xlsx\`
51937
+ - By author: \`author:"Jane Smith"\`
51938
+ - By date: \`lastModifiedTime>2024-01-01\`
51939
+ - Combined: \`project proposal filetype:docx\`
51940
+
51941
+ **Filter by file type:** Use the \`fileTypes\` parameter (e.g., \`["docx", "pdf"]\`) to restrict results to specific formats.
51942
+
51943
+ **Limit to a SharePoint site:** Provide the \`siteId\` parameter to search only within a specific site.
51944
+
51945
+ **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.
51946
+
51947
+ **Tip:** Start with a broad search, then use read_file on the most relevant results.`,
51948
+ parameters: {
51949
+ type: "object",
51950
+ properties: {
51951
+ query: {
51952
+ type: "string",
51953
+ description: 'Search query. Supports plain text and KQL syntax (e.g., "budget report", "filename:spec.docx", "author:john filetype:pptx").'
51954
+ },
51955
+ siteId: {
51956
+ type: "string",
51957
+ description: "Optional SharePoint site ID to limit search to a specific site."
51958
+ },
51959
+ fileTypes: {
51960
+ type: "array",
51961
+ items: { type: "string" },
51962
+ description: 'Optional file type filter. Array of extensions without dots (e.g., ["docx", "pdf", "xlsx"]).'
51963
+ },
51964
+ limit: {
51965
+ type: "number",
51966
+ description: `Maximum number of results (default: ${DEFAULT_LIMIT2}, max: ${MAX_LIMIT2}).`
51967
+ },
51968
+ targetUser: {
51969
+ type: "string",
51970
+ description: "User ID or email. Only needed with application-only (client_credentials) auth."
51971
+ }
51972
+ },
51973
+ required: ["query"]
51974
+ }
51975
+ },
51976
+ blocking: true,
51977
+ timeout: 3e4
51978
+ },
51979
+ describeCall: (args) => {
51980
+ const types = args.fileTypes?.length ? ` [${args.fileTypes.join(",")}]` : "";
51981
+ return `Search: "${args.query}"${types}`;
51982
+ },
51983
+ permission: {
51984
+ scope: "session",
51985
+ riskLevel: "low",
51986
+ approvalMessage: `Search files in OneDrive/SharePoint via ${connector.displayName}`
51987
+ },
51988
+ execute: async (args, context) => {
51989
+ const effectiveUserId = context?.userId ?? userId;
51990
+ const effectiveAccountId = context?.accountId;
51991
+ const limit = Math.min(Math.max(1, args.limit ?? DEFAULT_LIMIT2), MAX_LIMIT2);
51992
+ try {
51993
+ if (args.siteId) {
51994
+ return await searchViaDriveEndpoint(
51995
+ connector,
51996
+ args,
51997
+ limit,
51998
+ effectiveUserId,
51999
+ effectiveAccountId
52000
+ );
52001
+ }
52002
+ let queryString = args.query;
52003
+ if (args.fileTypes?.length) {
52004
+ const typeFilter = args.fileTypes.map((t) => `filetype:${t.replace(/^\./, "")}`).join(" OR ");
52005
+ queryString = `(${queryString}) (${typeFilter})`;
52006
+ }
52007
+ const searchRequest = {
52008
+ requests: [
52009
+ {
52010
+ entityTypes: ["driveItem"],
52011
+ query: { queryString },
52012
+ from: 0,
52013
+ size: limit,
52014
+ fields: [
52015
+ "id",
52016
+ "name",
52017
+ "size",
52018
+ "webUrl",
52019
+ "lastModifiedDateTime",
52020
+ "parentReference",
52021
+ "file"
52022
+ ]
52023
+ }
52024
+ ]
52025
+ };
52026
+ const data = await microsoftFetch(connector, "/search/query", {
52027
+ method: "POST",
52028
+ body: searchRequest,
52029
+ userId: effectiveUserId,
52030
+ accountId: effectiveAccountId
52031
+ });
52032
+ const container = data.value?.[0]?.hitsContainers?.[0];
52033
+ if (!container?.hits?.length) {
52034
+ return {
52035
+ success: true,
52036
+ results: [],
52037
+ totalCount: 0,
52038
+ hasMore: false
52039
+ };
52040
+ }
52041
+ const results = container.hits.map((hit) => {
52042
+ const resource = hit.resource;
52043
+ return {
52044
+ name: resource.name,
52045
+ path: resource.parentReference?.path?.replace(/\/drive\/root:/, "") || void 0,
52046
+ site: resource.parentReference?.siteId || void 0,
52047
+ snippet: hit.summary || void 0,
52048
+ size: resource.size,
52049
+ sizeFormatted: formatFileSize(resource.size),
52050
+ webUrl: resource.webUrl,
52051
+ id: resource.id,
52052
+ lastModified: resource.lastModifiedDateTime
52053
+ };
52054
+ });
52055
+ return {
52056
+ success: true,
52057
+ results,
52058
+ totalCount: container.total,
52059
+ hasMore: container.moreResultsAvailable
52060
+ };
52061
+ } catch (error) {
52062
+ return {
52063
+ success: false,
52064
+ error: `Search failed: ${error instanceof Error ? error.message : String(error)}`
52065
+ };
52066
+ }
52067
+ }
52068
+ };
52069
+ }
52070
+ async function searchViaDriveEndpoint(connector, args, limit, effectiveUserId, effectiveAccountId) {
52071
+ const drivePrefix = `/sites/${args.siteId}/drive`;
52072
+ const escapedQuery = args.query.replace(/'/g, "''");
52073
+ const endpoint = `${drivePrefix}/root/search(q='${escapedQuery}')`;
52074
+ const data = await microsoftFetch(connector, endpoint, {
52075
+ userId: effectiveUserId,
52076
+ accountId: effectiveAccountId,
52077
+ queryParams: {
52078
+ "$top": limit,
52079
+ "$select": "id,name,size,webUrl,lastModifiedDateTime,parentReference,file"
52080
+ }
52081
+ });
52082
+ let items = data.value || [];
52083
+ if (args.fileTypes?.length) {
52084
+ const extSet = new Set(args.fileTypes.map((t) => t.replace(/^\./, "").toLowerCase()));
52085
+ items = items.filter((item) => {
52086
+ const ext = item.name.split(".").pop()?.toLowerCase();
52087
+ return ext && extSet.has(ext);
52088
+ });
52089
+ }
52090
+ const results = items.map((item) => ({
52091
+ name: item.name,
52092
+ path: item.parentReference?.path?.replace(/\/drive\/root:/, "") || void 0,
52093
+ site: item.parentReference?.siteId || void 0,
52094
+ snippet: void 0,
52095
+ size: item.size,
52096
+ sizeFormatted: formatFileSize(item.size),
52097
+ webUrl: item.webUrl,
52098
+ id: item.id,
52099
+ lastModified: item.lastModifiedDateTime
52100
+ }));
52101
+ return {
52102
+ success: true,
52103
+ results,
52104
+ totalCount: results.length,
52105
+ hasMore: !!data["@odata.nextLink"]
52106
+ };
52107
+ }
52108
+
49741
52109
  // src/tools/microsoft/register.ts
49742
52110
  function registerMicrosoftTools() {
49743
52111
  ConnectorTools.registerService("microsoft", (connector, userId) => {
49744
52112
  return [
52113
+ // Email
49745
52114
  createDraftEmailTool(connector, userId),
49746
52115
  createSendEmailTool(connector, userId),
52116
+ // Meetings
49747
52117
  createMeetingTool(connector, userId),
49748
52118
  createEditMeetingTool(connector, userId),
49749
52119
  createGetMeetingTranscriptTool(connector, userId),
49750
- createFindMeetingSlotsTool(connector, userId)
52120
+ createFindMeetingSlotsTool(connector, userId),
52121
+ // Files (OneDrive / SharePoint)
52122
+ createMicrosoftReadFileTool(connector, userId),
52123
+ createMicrosoftListFilesTool(connector, userId),
52124
+ createMicrosoftSearchFilesTool(connector, userId)
49751
52125
  ];
49752
52126
  });
49753
52127
  }
@@ -51101,6 +53475,311 @@ function createCustomToolTest() {
51101
53475
  }
51102
53476
  var customToolTest = createCustomToolTest();
51103
53477
 
53478
+ // src/tools/routines/resolveStorage.ts
53479
+ init_StorageRegistry();
53480
+ function buildStorageContext3(toolContext) {
53481
+ const global2 = StorageRegistry.getContext();
53482
+ if (global2) return global2;
53483
+ if (toolContext?.userId) return { userId: toolContext.userId };
53484
+ return void 0;
53485
+ }
53486
+ function resolveRoutineDefinitionStorage(explicit, toolContext) {
53487
+ if (explicit) return explicit;
53488
+ const factory = StorageRegistry.get("routineDefinitions");
53489
+ if (factory) {
53490
+ return factory(buildStorageContext3(toolContext));
53491
+ }
53492
+ return new FileRoutineDefinitionStorage();
53493
+ }
53494
+
53495
+ // src/tools/routines/generateRoutine.ts
53496
+ 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.
53497
+
53498
+ ## Routine Structure
53499
+
53500
+ A routine definition has these fields:
53501
+ - **name** (required): Human-readable name (e.g., "Research and Summarize Topic")
53502
+ - **description** (required): What this routine accomplishes
53503
+ - **version**: Semver string for tracking evolution (e.g., "1.0.0")
53504
+ - **author**: Creator name or identifier
53505
+ - **tags**: Array of strings for categorization and filtering (e.g., ["research", "analysis"])
53506
+ - **instructions**: Additional text injected into the agent's system prompt when executing this routine. Use for behavioral guidance, tone, constraints.
53507
+ - **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.
53508
+ - **requiredTools**: Tool names that must be available before starting (e.g., ["web_fetch", "memory_store"])
53509
+ - **requiredPlugins**: Plugin names that must be enabled (e.g., ["working_memory"])
53510
+ - **concurrency**: { maxParallelTasks: number, strategy: "fifo"|"priority"|"shortest-first", failureMode?: "fail-fast"|"continue"|"fail-all" }
53511
+ - **allowDynamicTasks**: If true, the LLM can add/modify tasks during execution (default: false)
53512
+ - **tasks** (required): Array of TaskInput objects defining the workflow steps
53513
+
53514
+ ## Task Structure
53515
+
53516
+ Each task in the tasks array has:
53517
+ - **name** (required): Unique name within the routine (used for dependency references)
53518
+ - **description** (required): What this task should accomplish \u2014 the agent uses this as its goal
53519
+ - **dependsOn**: Array of task names that must complete before this task starts (e.g., ["Gather Data", "Validate Input"])
53520
+ - **suggestedTools**: Tool names the agent should prefer for this task (advisory, not enforced)
53521
+ - **expectedOutput**: Description of what the task should produce \u2014 helps the agent know when it's done
53522
+ - **maxAttempts**: Max retry count on failure (default: 3)
53523
+ - **condition**: Execute only if a condition is met (see Conditions below)
53524
+ - **controlFlow**: Map, fold, or until loop (see Control Flow below)
53525
+ - **validation**: Completion validation settings (see Validation below)
53526
+ - **execution**: { parallel?: boolean, maxConcurrency?: number, priority?: number, maxIterations?: number }
53527
+ - **metadata**: Arbitrary key-value pairs for extensions
53528
+
53529
+ ## Control Flow Types
53530
+
53531
+ Tasks can have a controlFlow field for iteration patterns:
53532
+
53533
+ ### map \u2014 Iterate over an array, run sub-tasks per element
53534
+ \`\`\`json
53535
+ {
53536
+ "type": "map",
53537
+ "source": { "task": "Fetch Items" },
53538
+ "tasks": [
53539
+ { "name": "Process Item", "description": "Process {{map.item}} ({{map.index}}/{{map.total}})" }
53540
+ ],
53541
+ "resultKey": "processed_items",
53542
+ "maxIterations": 100,
53543
+ "iterationTimeoutMs": 30000
53544
+ }
53545
+ \`\`\`
53546
+
53547
+ ### fold \u2014 Accumulate a result across array elements
53548
+ \`\`\`json
53549
+ {
53550
+ "type": "fold",
53551
+ "source": { "key": "data_points", "path": "results" },
53552
+ "tasks": [
53553
+ { "name": "Merge Entry", "description": "Merge {{map.item}} into {{fold.accumulator}}" }
53554
+ ],
53555
+ "initialValue": "",
53556
+ "resultKey": "merged_result",
53557
+ "maxIterations": 50
53558
+ }
53559
+ \`\`\`
53560
+
53561
+ ### until \u2014 Loop until a condition is met
53562
+ \`\`\`json
53563
+ {
53564
+ "type": "until",
53565
+ "tasks": [
53566
+ { "name": "Refine Draft", "description": "Improve the current draft based on feedback" }
53567
+ ],
53568
+ "condition": { "memoryKey": "quality_score", "operator": "greater_than", "value": 80, "onFalse": "skip" },
53569
+ "maxIterations": 5,
53570
+ "iterationKey": "refinement_round"
53571
+ }
53572
+ \`\`\`
53573
+
53574
+ ### Source field
53575
+ The \`source\` field in map/fold can be:
53576
+ - A string: direct memory key lookup (e.g., "my_items")
53577
+ - \`{ task: "TaskName" }\`: resolves the output of a completed dependency task
53578
+ - \`{ key: "memoryKey" }\`: direct memory key lookup
53579
+ - \`{ key: "memoryKey", path: "data.items" }\`: memory key with JSON path extraction
53580
+
53581
+ ### Sub-routine tasks
53582
+ Tasks inside controlFlow.tasks have the same shape as regular tasks (name, description, dependsOn, suggestedTools, etc.) but execute within the control flow context.
53583
+
53584
+ ## Template Placeholders
53585
+
53586
+ Use these in task descriptions and expectedOutput:
53587
+ - \`{{param.NAME}}\` \u2014 routine parameter value
53588
+ - \`{{map.item}}\` \u2014 current element in map/fold iteration
53589
+ - \`{{map.index}}\` \u2014 current 0-based iteration index
53590
+ - \`{{map.total}}\` \u2014 total number of elements
53591
+ - \`{{fold.accumulator}}\` \u2014 current accumulated value in fold
53592
+
53593
+ ## Task Conditions
53594
+
53595
+ Execute a task conditionally based on memory state:
53596
+ \`\`\`json
53597
+ {
53598
+ "memoryKey": "user_preference",
53599
+ "operator": "equals",
53600
+ "value": "detailed",
53601
+ "onFalse": "skip"
53602
+ }
53603
+ \`\`\`
53604
+
53605
+ Operators: "exists", "not_exists", "equals", "contains", "truthy", "greater_than", "less_than"
53606
+ onFalse actions: "skip" (mark skipped), "fail" (mark failed), "wait" (block until condition met)
53607
+
53608
+ ## Validation
53609
+
53610
+ Enable completion validation to verify task quality:
53611
+ \`\`\`json
53612
+ {
53613
+ "skipReflection": false,
53614
+ "completionCriteria": [
53615
+ "Response contains at least 3 specific examples",
53616
+ "All requested sections are present"
53617
+ ],
53618
+ "minCompletionScore": 80,
53619
+ "requiredMemoryKeys": ["result_data"],
53620
+ "mode": "strict"
53621
+ }
53622
+ \`\`\`
53623
+
53624
+ By default, skipReflection is true (validation auto-passes). Set to false and provide completionCriteria to enable LLM self-reflection validation.
53625
+
53626
+ ## Best Practices
53627
+
53628
+ 1. **Task naming**: Use clear, action-oriented names (e.g., "Research Topic", "Generate Summary"). Names are used in dependsOn references.
53629
+ 2. **Dependency chaining**: Build pipelines by having each task depend on the previous one. Independent tasks can run in parallel.
53630
+ 3. **Control flow vs sequential**: Use map/fold when iterating over dynamic data. Use sequential tasks for fixed multi-step workflows.
53631
+ 4. **Parameters**: Define parameters for any value that should vary between executions. Always provide a description.
53632
+ 5. **Instructions**: Use the instructions field for behavioral guidance that applies to all tasks in the routine.
53633
+ 6. **Keep tasks focused**: Each task should have a single clear goal. Break complex work into multiple dependent tasks.
53634
+ 7. **Expected output**: Always specify expectedOutput \u2014 it helps the agent know when it's done and what format to produce.`;
53635
+ function createGenerateRoutine(storage) {
53636
+ return {
53637
+ definition: {
53638
+ type: "function",
53639
+ function: {
53640
+ name: "generate_routine",
53641
+ description: TOOL_DESCRIPTION,
53642
+ parameters: {
53643
+ type: "object",
53644
+ properties: {
53645
+ definition: {
53646
+ type: "object",
53647
+ description: "Complete routine definition input",
53648
+ properties: {
53649
+ name: { type: "string", description: "Human-readable routine name" },
53650
+ description: { type: "string", description: "What this routine accomplishes" },
53651
+ version: { type: "string", description: 'Semver version string (e.g., "1.0.0")' },
53652
+ author: { type: "string", description: "Creator name or identifier" },
53653
+ tags: { type: "array", items: { type: "string" }, description: "Tags for categorization" },
53654
+ instructions: { type: "string", description: "Additional instructions injected into system prompt during execution" },
53655
+ parameters: {
53656
+ type: "array",
53657
+ description: "Input parameters for reusable routines",
53658
+ items: {
53659
+ type: "object",
53660
+ properties: {
53661
+ name: { type: "string", description: "Parameter name (referenced as {{param.name}})" },
53662
+ description: { type: "string", description: "Human-readable description" },
53663
+ required: { type: "boolean", description: "Whether this parameter must be provided (default: false)" },
53664
+ default: { description: "Default value when not provided" }
53665
+ },
53666
+ required: ["name", "description"]
53667
+ }
53668
+ },
53669
+ requiredTools: { type: "array", items: { type: "string" }, description: "Tool names that must be available" },
53670
+ requiredPlugins: { type: "array", items: { type: "string" }, description: "Plugin names that must be enabled" },
53671
+ concurrency: {
53672
+ type: "object",
53673
+ description: "Concurrency settings for parallel task execution",
53674
+ properties: {
53675
+ maxParallelTasks: { type: "number", description: "Maximum tasks running in parallel" },
53676
+ strategy: { type: "string", enum: ["fifo", "priority", "shortest-first"], description: "Task selection strategy" },
53677
+ failureMode: { type: "string", enum: ["fail-fast", "continue", "fail-all"], description: "How to handle failures in parallel" }
53678
+ },
53679
+ required: ["maxParallelTasks", "strategy"]
53680
+ },
53681
+ allowDynamicTasks: { type: "boolean", description: "Allow LLM to add/modify tasks during execution (default: false)" },
53682
+ tasks: {
53683
+ type: "array",
53684
+ description: "Array of task definitions forming the workflow",
53685
+ items: {
53686
+ type: "object",
53687
+ properties: {
53688
+ name: { type: "string", description: "Unique task name (used in dependsOn references)" },
53689
+ description: { type: "string", description: "What this task should accomplish" },
53690
+ dependsOn: { type: "array", items: { type: "string" }, description: "Task names that must complete first" },
53691
+ suggestedTools: { type: "array", items: { type: "string" }, description: "Preferred tool names for this task" },
53692
+ expectedOutput: { type: "string", description: "Description of expected task output" },
53693
+ maxAttempts: { type: "number", description: "Max retries on failure (default: 3)" },
53694
+ condition: {
53695
+ type: "object",
53696
+ description: "Conditional execution based on memory state",
53697
+ properties: {
53698
+ memoryKey: { type: "string", description: "Memory key to check" },
53699
+ operator: { type: "string", enum: ["exists", "not_exists", "equals", "contains", "truthy", "greater_than", "less_than"] },
53700
+ value: { description: "Value to compare against" },
53701
+ onFalse: { type: "string", enum: ["skip", "fail", "wait"], description: "Action when condition is false" }
53702
+ },
53703
+ required: ["memoryKey", "operator", "onFalse"]
53704
+ },
53705
+ controlFlow: {
53706
+ type: "object",
53707
+ description: "Control flow for iteration (map, fold, or until)",
53708
+ properties: {
53709
+ type: { type: "string", enum: ["map", "fold", "until"], description: "Control flow type" },
53710
+ source: { description: 'Source data: string key, { task: "name" }, { key: "key" }, or { key: "key", path: "json.path" }' },
53711
+ tasks: { type: "array", description: "Sub-routine tasks to execute per iteration", items: { type: "object" } },
53712
+ resultKey: { type: "string", description: "Memory key for collected results" },
53713
+ initialValue: { description: "Starting accumulator value (fold only)" },
53714
+ condition: { type: "object", description: "Exit condition (until only)" },
53715
+ maxIterations: { type: "number", description: "Cap on iterations" },
53716
+ iterationKey: { type: "string", description: "Memory key for iteration index (until only)" },
53717
+ iterationTimeoutMs: { type: "number", description: "Timeout per iteration in ms" }
53718
+ },
53719
+ required: ["type", "tasks"]
53720
+ },
53721
+ validation: {
53722
+ type: "object",
53723
+ description: "Completion validation settings",
53724
+ properties: {
53725
+ skipReflection: { type: "boolean", description: "Set to false to enable LLM self-reflection validation" },
53726
+ completionCriteria: { type: "array", items: { type: "string" }, description: "Natural language criteria for completion" },
53727
+ minCompletionScore: { type: "number", description: "Minimum score (0-100) to pass (default: 80)" },
53728
+ requiredMemoryKeys: { type: "array", items: { type: "string" }, description: "Memory keys that must exist after completion" },
53729
+ mode: { type: "string", enum: ["strict", "warn"], description: "Validation failure mode (default: strict)" },
53730
+ requireUserApproval: { type: "string", enum: ["never", "uncertain", "always"], description: "When to ask user for approval" },
53731
+ customValidator: { type: "string", description: "Custom validation hook name" }
53732
+ }
53733
+ },
53734
+ execution: {
53735
+ type: "object",
53736
+ description: "Execution settings",
53737
+ properties: {
53738
+ parallel: { type: "boolean", description: "Can run in parallel with other parallel tasks" },
53739
+ maxConcurrency: { type: "number", description: "Max concurrent sub-work" },
53740
+ priority: { type: "number", description: "Higher = executed first" },
53741
+ maxIterations: { type: "number", description: "Max LLM iterations per task (default: 50)" }
53742
+ }
53743
+ },
53744
+ metadata: { type: "object", description: "Arbitrary key-value metadata" }
53745
+ },
53746
+ required: ["name", "description"]
53747
+ }
53748
+ },
53749
+ metadata: { type: "object", description: "Arbitrary routine-level metadata" }
53750
+ },
53751
+ required: ["name", "description", "tasks"]
53752
+ }
53753
+ },
53754
+ required: ["definition"]
53755
+ }
53756
+ }
53757
+ },
53758
+ permission: { scope: "session", riskLevel: "medium" },
53759
+ execute: async (args, context) => {
53760
+ try {
53761
+ const userId = context?.userId;
53762
+ const s = resolveRoutineDefinitionStorage(storage, context);
53763
+ const routineDefinition = createRoutineDefinition(args.definition);
53764
+ await s.save(userId, routineDefinition);
53765
+ return {
53766
+ success: true,
53767
+ id: routineDefinition.id,
53768
+ name: routineDefinition.name,
53769
+ storagePath: s.getPath(userId)
53770
+ };
53771
+ } catch (error) {
53772
+ return {
53773
+ success: false,
53774
+ error: error.message
53775
+ };
53776
+ }
53777
+ },
53778
+ describeCall: (args) => args.definition?.name ?? "routine"
53779
+ };
53780
+ }
53781
+ var generateRoutine = createGenerateRoutine();
53782
+
51104
53783
  // src/tools/registry.generated.ts
51105
53784
  var toolRegistry = [
51106
53785
  {
@@ -51328,6 +54007,15 @@ var toolRegistry = [
51328
54007
  tool: jsonManipulator,
51329
54008
  safeByDefault: true
51330
54009
  },
54010
+ {
54011
+ name: "generate_routine",
54012
+ exportName: "generateRoutine",
54013
+ displayName: "Generate Routine",
54014
+ category: "routines",
54015
+ description: "Complete routine definition input",
54016
+ tool: generateRoutine,
54017
+ safeByDefault: false
54018
+ },
51331
54019
  {
51332
54020
  name: "bash",
51333
54021
  exportName: "bash",
@@ -51757,6 +54445,127 @@ REMEMBER: Keep it conversational, ask one question at a time, and only output th
51757
54445
  }
51758
54446
  };
51759
54447
 
51760
- export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, AgentContextNextGen, ApproximateTokenEstimator, BaseMediaProvider, BasePluginNextGen, BaseProvider, BaseTextProvider, BraveProvider, CONNECTOR_CONFIG_VERSION, CONTEXT_SESSION_FORMAT_VERSION, CUSTOM_TOOL_DEFINITION_VERSION, CheckpointManager, CircuitBreaker, CircuitOpenError, Connector, ConnectorConfigStore, ConnectorTools, ConsoleMetrics, ContentType, ContextOverflowError, DEFAULT_ALLOWLIST, DEFAULT_BACKOFF_CONFIG, DEFAULT_BASE_DELAY_MS, DEFAULT_CHECKPOINT_STRATEGY, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONFIG2 as DEFAULT_CONFIG, DEFAULT_CONNECTOR_TIMEOUT, DEFAULT_CONTEXT_CONFIG, DEFAULT_DESKTOP_CONFIG, DEFAULT_FEATURES, DEFAULT_FILESYSTEM_CONFIG, DEFAULT_HISTORY_MANAGER_CONFIG, DEFAULT_MAX_DELAY_MS, DEFAULT_MAX_RETRIES, DEFAULT_MEMORY_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_RATE_LIMITER_CONFIG, DEFAULT_RETRYABLE_STATUSES, DEFAULT_SHELL_CONFIG, DESKTOP_TOOL_NAMES, DefaultCompactionStrategy, DependencyCycleError, DocumentReader, ErrorHandler, ExecutionContext, ExternalDependencyHandler, FileAgentDefinitionStorage, FileConnectorStorage, FileContextStorage, FileCustomToolStorage, FileMediaStorage as FileMediaOutputHandler, FileMediaStorage, FilePersistentInstructionsStorage, FileRoutineDefinitionStorage, FileStorage, FileUserInfoStorage, FormatDetector, FrameworkLogger, HookManager, IMAGE_MODELS, IMAGE_MODEL_REGISTRY, ImageGeneration, InContextMemoryPluginNextGen, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, InvalidConfigError, InvalidToolArgumentsError, LLM_MODELS, LoggingPlugin, MCPClient, MCPConnectionError, MCPError, MCPProtocolError, MCPRegistry, MCPResourceError, MCPTimeoutError, MCPToolError, MEMORY_PRIORITY_VALUES, MODEL_REGISTRY, MemoryConnectorStorage, MemoryEvictionCompactor, MemoryStorage, MessageBuilder, MessageRole, ModelNotSupportedError, NoOpMetrics, NutTreeDriver, OAuthManager, ParallelTasksError, PersistentInstructionsPluginNextGen, PlanningAgent, ProviderAuthError, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, ROUTINE_KEYS, RapidAPIProvider, RateLimitError, SERVICE_DEFINITIONS, SERVICE_INFO, SERVICE_URL_PATTERNS, SIMPLE_ICONS_CDN, STT_MODELS, STT_MODEL_REGISTRY, ScopedConnectorRegistry, ScrapeProvider, SearchProvider, SerperProvider, Services, SpeechToText, StorageRegistry, StrategyRegistry, StreamEventType, StreamHelpers, StreamState, SummarizeCompactor, TERMINAL_TASK_STATUSES, TTS_MODELS, TTS_MODEL_REGISTRY, TaskTimeoutError, TaskValidationError, TavilyProvider, TextToSpeech, TokenBucketRateLimiter, ToolCallState, ToolExecutionError, ToolExecutionPipeline, ToolManager, ToolNotFoundError, ToolPermissionManager, ToolRegistry, ToolTimeoutError, TruncateCompactor, UserInfoPluginNextGen, VENDORS, VENDOR_ICON_MAP, VIDEO_MODELS, VIDEO_MODEL_REGISTRY, Vendor, VideoGeneration, WorkingMemory, WorkingMemoryPluginNextGen, addJitter, allVendorTemplates, assertNotDestroyed, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildQueryString, calculateBackoff, calculateCost, calculateEntrySize, calculateImageCost, calculateSTTCost, calculateTTSCost, calculateVideoCost, canTaskExecute, createAgentStorage, createAuthenticatedFetch, createBashTool, createConnectorFromTemplate, createCreatePRTool, createCustomToolDelete, createCustomToolDraft, createCustomToolList, createCustomToolLoad, createCustomToolMetaTools, createCustomToolSave, createCustomToolTest, createDesktopGetCursorTool, createDesktopGetScreenSizeTool, createDesktopKeyboardKeyTool, createDesktopKeyboardTypeTool, createDesktopMouseClickTool, createDesktopMouseDragTool, createDesktopMouseMoveTool, createDesktopMouseScrollTool, createDesktopScreenshotTool, createDesktopWindowFocusTool, createDesktopWindowListTool, createDraftEmailTool, createEditFileTool, createEditMeetingTool, createEstimator, createExecuteJavaScriptTool, createFileAgentDefinitionStorage, createFileContextStorage, createFileCustomToolStorage, createFileMediaStorage, createFileRoutineDefinitionStorage, createFindMeetingSlotsTool, createGetMeetingTranscriptTool, createGetPRTool, createGitHubReadFileTool, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListDirectoryTool, createMeetingTool, createMessageWithImages, createMetricsCollector, createPRCommentsTool, createPRFilesTool, createPlan, createProvider, createReadFileTool, createRoutineDefinition, createRoutineExecution, createSearchCodeTool, createSearchFilesTool, createSendEmailTool, createSpeechToTextTool, createTask, createTextMessage, createTextToSpeechTool, createVideoProvider, createVideoTools, createWriteFileTool, customToolDelete, customToolDraft, customToolList, customToolLoad, customToolSave, customToolTest, defaultDescribeCall, desktopGetCursor, desktopGetScreenSize, desktopKeyboardKey, desktopKeyboardType, desktopMouseClick, desktopMouseDrag, desktopMouseMove, desktopMouseScroll, desktopScreenshot, desktopTools, desktopWindowFocus, desktopWindowList, detectDependencyCycle, detectServiceFromURL, developerTools, documentToContent, editFile, evaluateCondition, executeRoutine, extractJSON, extractJSONField, extractNumber, findConnectorByServiceTypes, forPlan, forTasks, formatAttendees, formatPluginDisplayName, formatRecipients, generateEncryptionKey, generateSimplePlan, generateWebAPITool, getActiveImageModels, getActiveModels, getActiveSTTModels, getActiveTTSModels, getActiveVideoModels, getAllBuiltInTools, getAllServiceIds, getAllVendorLogos, getAllVendorTemplates, getBackgroundOutput, getConnectorTools, getCredentialsSetupURL, getDesktopDriver, getDocsURL, getImageModelInfo, getImageModelsByVendor, getImageModelsWithFeature, getMediaOutputHandler, getMediaStorage, getModelInfo, getModelsByVendor, getNextExecutableTasks, getRegisteredScrapeProviders, getRoutineProgress, getSTTModelInfo, getSTTModelsByVendor, getSTTModelsWithFeature, getServiceDefinition, getServiceInfo, getServicesByCategory, getTTSModelInfo, getTTSModelsByVendor, getTTSModelsWithFeature, getTaskDependencies, getToolByName, getToolCallDescription, getToolCategories, getToolRegistry, getToolsByCategory, getToolsRequiringConnector, getUserPathPrefix, getVendorAuthTemplate, getVendorColor, getVendorDefaultBaseURL, getVendorInfo, getVendorLogo, getVendorLogoCdnUrl, getVendorLogoSvg, getVendorTemplate, getVideoModelInfo, getVideoModelsByVendor, getVideoModelsWithAudio, getVideoModelsWithFeature, glob, globalErrorHandler, grep, hasClipboardImage, hasVendorLogo, hydrateCustomTool, isBlockedCommand, isErrorEvent, isExcludedExtension, isKnownService, isOutputTextDelta, isReasoningDelta, isReasoningDone, isResponseComplete, isSimpleScope, isStreamEvent, isTaskAwareScope, isTaskBlocked, isTeamsMeetingUrl, isTerminalMemoryStatus, isTerminalStatus, isToolCallArgumentsDelta, isToolCallArgumentsDone, isToolCallStart, isVendor, killBackgroundProcess, listConnectorsByServiceTypes, listDirectory, listVendorIds, listVendors, listVendorsByAuthType, listVendorsByCategory, listVendorsWithLogos, logger, mergeTextPieces, metrics, microsoftFetch, normalizeEmails, parseKeyCombo, parseRepository, readClipboardImage, readDocumentAsContent, readFile5 as readFile, registerScrapeProvider, resetDefaultDriver, resolveConnector, resolveDependencies, resolveMaxContextTokens, resolveMeetingId, resolveModelCapabilities, resolveRepository, resolveTemplates, retryWithBackoff, sanitizeToolName, scopeEquals, scopeMatches, setMediaOutputHandler, setMediaStorage, setMetricsCollector, simpleTokenEstimator, toConnectorOptions, toolRegistry, tools_exports as tools, updateTaskStatus, validatePath, writeFile5 as writeFile };
54448
+ // src/infrastructure/scheduling/SimpleScheduler.ts
54449
+ var SimpleScheduler = class {
54450
+ timers = /* @__PURE__ */ new Map();
54451
+ _isDestroyed = false;
54452
+ schedule(id, spec, callback) {
54453
+ if (this._isDestroyed) throw new Error("Scheduler has been destroyed");
54454
+ if (spec.cron) {
54455
+ throw new Error(
54456
+ `SimpleScheduler does not support cron expressions. Use a cron-capable scheduler implementation (e.g. node-cron, croner) or convert to intervalMs.`
54457
+ );
54458
+ }
54459
+ if (this.timers.has(id)) {
54460
+ this.cancel(id);
54461
+ }
54462
+ if (spec.intervalMs != null) {
54463
+ const timer = setInterval(() => {
54464
+ try {
54465
+ const result = callback();
54466
+ if (result && typeof result.catch === "function") {
54467
+ result.catch(() => {
54468
+ });
54469
+ }
54470
+ } catch {
54471
+ }
54472
+ }, spec.intervalMs);
54473
+ this.timers.set(id, { timer, type: "interval" });
54474
+ } else if (spec.once != null) {
54475
+ const delay = Math.max(0, spec.once - Date.now());
54476
+ const timer = setTimeout(() => {
54477
+ this.timers.delete(id);
54478
+ try {
54479
+ const result = callback();
54480
+ if (result && typeof result.catch === "function") {
54481
+ result.catch(() => {
54482
+ });
54483
+ }
54484
+ } catch {
54485
+ }
54486
+ }, delay);
54487
+ this.timers.set(id, { timer, type: "timeout" });
54488
+ } else {
54489
+ throw new Error("ScheduleSpec must have at least one of: cron, intervalMs, once");
54490
+ }
54491
+ return {
54492
+ id,
54493
+ cancel: () => this.cancel(id)
54494
+ };
54495
+ }
54496
+ cancel(id) {
54497
+ const entry = this.timers.get(id);
54498
+ if (!entry) return;
54499
+ if (entry.type === "interval") {
54500
+ clearInterval(entry.timer);
54501
+ } else {
54502
+ clearTimeout(entry.timer);
54503
+ }
54504
+ this.timers.delete(id);
54505
+ }
54506
+ cancelAll() {
54507
+ for (const [id] of this.timers) {
54508
+ this.cancel(id);
54509
+ }
54510
+ }
54511
+ has(id) {
54512
+ return this.timers.has(id);
54513
+ }
54514
+ destroy() {
54515
+ if (this._isDestroyed) return;
54516
+ this.cancelAll();
54517
+ this._isDestroyed = true;
54518
+ }
54519
+ get isDestroyed() {
54520
+ return this._isDestroyed;
54521
+ }
54522
+ };
54523
+
54524
+ // src/infrastructure/triggers/EventEmitterTrigger.ts
54525
+ var EventEmitterTrigger = class {
54526
+ listeners = /* @__PURE__ */ new Map();
54527
+ _isDestroyed = false;
54528
+ /**
54529
+ * Register a listener for an event. Returns an unsubscribe function.
54530
+ */
54531
+ on(event, callback) {
54532
+ if (this._isDestroyed) throw new Error("EventEmitterTrigger has been destroyed");
54533
+ if (!this.listeners.has(event)) {
54534
+ this.listeners.set(event, /* @__PURE__ */ new Set());
54535
+ }
54536
+ this.listeners.get(event).add(callback);
54537
+ return () => {
54538
+ this.listeners.get(event)?.delete(callback);
54539
+ };
54540
+ }
54541
+ /**
54542
+ * Emit an event to all registered listeners.
54543
+ */
54544
+ emit(event, payload) {
54545
+ if (this._isDestroyed) return;
54546
+ const callbacks = this.listeners.get(event);
54547
+ if (!callbacks) return;
54548
+ for (const cb of callbacks) {
54549
+ try {
54550
+ const result = cb(payload);
54551
+ if (result && typeof result.catch === "function") {
54552
+ result.catch(() => {
54553
+ });
54554
+ }
54555
+ } catch {
54556
+ }
54557
+ }
54558
+ }
54559
+ destroy() {
54560
+ if (this._isDestroyed) return;
54561
+ this.listeners.clear();
54562
+ this._isDestroyed = true;
54563
+ }
54564
+ get isDestroyed() {
54565
+ return this._isDestroyed;
54566
+ }
54567
+ };
54568
+
54569
+ export { AGENT_DEFINITION_FORMAT_VERSION, AIError, APPROVAL_STATE_VERSION, Agent, AgentContextNextGen, ApproximateTokenEstimator, BaseMediaProvider, BasePluginNextGen, BaseProvider, BaseTextProvider, BraveProvider, CONNECTOR_CONFIG_VERSION, CONTEXT_SESSION_FORMAT_VERSION, CUSTOM_TOOL_DEFINITION_VERSION, CheckpointManager, CircuitBreaker, CircuitOpenError, Connector, ConnectorConfigStore, ConnectorTools, ConsoleMetrics, ContentType, ContextOverflowError, DEFAULT_ALLOWLIST, DEFAULT_BACKOFF_CONFIG, DEFAULT_BASE_DELAY_MS, DEFAULT_CHECKPOINT_STRATEGY, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_CONFIG2 as DEFAULT_CONFIG, DEFAULT_CONNECTOR_TIMEOUT, DEFAULT_CONTEXT_CONFIG, DEFAULT_DESKTOP_CONFIG, DEFAULT_FEATURES, DEFAULT_FILESYSTEM_CONFIG, DEFAULT_HISTORY_MANAGER_CONFIG, DEFAULT_MAX_DELAY_MS, DEFAULT_MAX_RETRIES, DEFAULT_MEMORY_CONFIG, DEFAULT_PERMISSION_CONFIG, DEFAULT_RATE_LIMITER_CONFIG, DEFAULT_RETRYABLE_STATUSES, DEFAULT_SHELL_CONFIG, DESKTOP_TOOL_NAMES, DefaultCompactionStrategy, DependencyCycleError, DocumentReader, ErrorHandler, EventEmitterTrigger, ExecutionContext, ExternalDependencyHandler, FileAgentDefinitionStorage, FileConnectorStorage, FileContextStorage, FileCustomToolStorage, FileMediaStorage as FileMediaOutputHandler, FileMediaStorage, FilePersistentInstructionsStorage, FileRoutineDefinitionStorage, FileStorage, FileUserInfoStorage, FormatDetector, FrameworkLogger, HookManager, IMAGE_MODELS, IMAGE_MODEL_REGISTRY, ImageGeneration, InContextMemoryPluginNextGen, InMemoryAgentStateStorage, InMemoryHistoryStorage, InMemoryMetrics, InMemoryPlanStorage, InMemoryStorage, InvalidConfigError, InvalidToolArgumentsError, LLM_MODELS, LoggingPlugin, MCPClient, MCPConnectionError, MCPError, MCPProtocolError, MCPRegistry, MCPResourceError, MCPTimeoutError, MCPToolError, MEMORY_PRIORITY_VALUES, MODEL_REGISTRY, MemoryConnectorStorage, MemoryEvictionCompactor, MemoryStorage, MessageBuilder, MessageRole, ModelNotSupportedError, NoOpMetrics, NutTreeDriver, OAuthManager, ParallelTasksError, PersistentInstructionsPluginNextGen, PlanningAgent, ProviderAuthError, ProviderConfigAgent, ProviderContextLengthError, ProviderError, ProviderErrorMapper, ProviderNotFoundError, ProviderRateLimitError, ROUTINE_KEYS, RapidAPIProvider, RateLimitError, SERVICE_DEFINITIONS, SERVICE_INFO, SERVICE_URL_PATTERNS, SIMPLE_ICONS_CDN, STT_MODELS, STT_MODEL_REGISTRY, ScopedConnectorRegistry, ScrapeProvider, SearchProvider, SerperProvider, Services, SimpleScheduler, SpeechToText, StorageRegistry, StrategyRegistry, StreamEventType, StreamHelpers, StreamState, SummarizeCompactor, TERMINAL_TASK_STATUSES, TTS_MODELS, TTS_MODEL_REGISTRY, TaskTimeoutError, TaskValidationError, TavilyProvider, TextToSpeech, TokenBucketRateLimiter, ToolCallState, ToolCatalogPluginNextGen, ToolCatalogRegistry, ToolExecutionError, ToolExecutionPipeline, ToolManager, ToolNotFoundError, ToolPermissionManager, ToolRegistry, ToolTimeoutError, TruncateCompactor, UserInfoPluginNextGen, VENDORS, VENDOR_ICON_MAP, VIDEO_MODELS, VIDEO_MODEL_REGISTRY, Vendor, VideoGeneration, WorkingMemory, WorkingMemoryPluginNextGen, addJitter, allVendorTemplates, assertNotDestroyed, authenticatedFetch, backoffSequence, backoffWait, bash, buildAuthConfig, buildEndpointWithQuery, buildQueryString, calculateBackoff, calculateCost, calculateEntrySize, calculateImageCost, calculateSTTCost, calculateTTSCost, calculateVideoCost, canTaskExecute, createAgentStorage, createAuthenticatedFetch, createBashTool, createConnectorFromTemplate, createCreatePRTool, createCustomToolDelete, createCustomToolDraft, createCustomToolList, createCustomToolLoad, createCustomToolMetaTools, createCustomToolSave, createCustomToolTest, createDesktopGetCursorTool, createDesktopGetScreenSizeTool, createDesktopKeyboardKeyTool, createDesktopKeyboardTypeTool, createDesktopMouseClickTool, createDesktopMouseDragTool, createDesktopMouseMoveTool, createDesktopMouseScrollTool, createDesktopScreenshotTool, createDesktopWindowFocusTool, createDesktopWindowListTool, createDraftEmailTool, createEditFileTool, createEditMeetingTool, createEstimator, createExecuteJavaScriptTool, createExecutionRecorder, createFileAgentDefinitionStorage, createFileContextStorage, createFileCustomToolStorage, createFileMediaStorage, createFileRoutineDefinitionStorage, createFindMeetingSlotsTool, createGetMeetingTranscriptTool, createGetPRTool, createGitHubReadFileTool, createGlobTool, createGrepTool, createImageGenerationTool, createImageProvider, createListDirectoryTool, createMeetingTool, createMessageWithImages, createMetricsCollector, createMicrosoftListFilesTool, createMicrosoftReadFileTool, createMicrosoftSearchFilesTool, createPRCommentsTool, createPRFilesTool, createPlan, createProvider, createReadFileTool, createRoutineDefinition, createRoutineExecution, createRoutineExecutionRecord, createSearchCodeTool, createSearchFilesTool, createSendEmailTool, createSpeechToTextTool, createTask, createTaskSnapshots, createTextMessage, createTextToSpeechTool, createVideoProvider, createVideoTools, createWriteFileTool, customToolDelete, customToolDraft, customToolList, customToolLoad, customToolSave, customToolTest, defaultDescribeCall, desktopGetCursor, desktopGetScreenSize, desktopKeyboardKey, desktopKeyboardType, desktopMouseClick, desktopMouseDrag, desktopMouseMove, desktopMouseScroll, desktopScreenshot, desktopTools, desktopWindowFocus, desktopWindowList, detectDependencyCycle, detectServiceFromURL, developerTools, documentToContent, editFile, encodeSharingUrl, evaluateCondition, executeRoutine, extractJSON, extractJSONField, extractNumber, findConnectorByServiceTypes, forPlan, forTasks, formatAttendees, formatFileSize, formatPluginDisplayName, formatRecipients, generateEncryptionKey, generateSimplePlan, generateWebAPITool, getActiveImageModels, getActiveModels, getActiveSTTModels, getActiveTTSModels, getActiveVideoModels, getAllBuiltInTools, getAllServiceIds, getAllVendorLogos, getAllVendorTemplates, getBackgroundOutput, getConnectorTools, getCredentialsSetupURL, getDesktopDriver, getDocsURL, getDrivePrefix, getImageModelInfo, getImageModelsByVendor, getImageModelsWithFeature, getMediaOutputHandler, getMediaStorage, getModelInfo, getModelsByVendor, getNextExecutableTasks, getRegisteredScrapeProviders, getRoutineProgress, getSTTModelInfo, getSTTModelsByVendor, getSTTModelsWithFeature, getServiceDefinition, getServiceInfo, getServicesByCategory, getTTSModelInfo, getTTSModelsByVendor, getTTSModelsWithFeature, getTaskDependencies, getToolByName, getToolCallDescription, getToolCategories, getToolRegistry, getToolsByCategory, getToolsRequiringConnector, getUserPathPrefix, getVendorAuthTemplate, getVendorColor, getVendorDefaultBaseURL, getVendorInfo, getVendorLogo, getVendorLogoCdnUrl, getVendorLogoSvg, getVendorTemplate, getVideoModelInfo, getVideoModelsByVendor, getVideoModelsWithAudio, getVideoModelsWithFeature, glob, globalErrorHandler, grep, hasClipboardImage, hasVendorLogo, hydrateCustomTool, isBlockedCommand, isErrorEvent, isExcludedExtension, isKnownService, isMicrosoftFileUrl, isOutputTextDelta, isReasoningDelta, isReasoningDone, isResponseComplete, isSimpleScope, isStreamEvent, isTaskAwareScope, isTaskBlocked, isTeamsMeetingUrl, isTerminalMemoryStatus, isTerminalStatus, isToolCallArgumentsDelta, isToolCallArgumentsDone, isToolCallStart, isVendor, isWebUrl, killBackgroundProcess, listConnectorsByServiceTypes, listDirectory, listVendorIds, listVendors, listVendorsByAuthType, listVendorsByCategory, listVendorsWithLogos, logger, mergeTextPieces, metrics, microsoftFetch, normalizeEmails, parseKeyCombo, parseRepository, readClipboardImage, readDocumentAsContent, readFile5 as readFile, registerScrapeProvider, resetDefaultDriver, resolveConnector, resolveDependencies, resolveFileEndpoints, resolveFlowSource, resolveMaxContextTokens, resolveMeetingId, resolveModelCapabilities, resolveRepository, resolveTemplates, retryWithBackoff, sanitizeToolName, scopeEquals, scopeMatches, setMediaOutputHandler, setMediaStorage, setMetricsCollector, simpleTokenEstimator, toConnectorOptions, toolRegistry, tools_exports as tools, updateTaskStatus, validatePath, writeFile5 as writeFile };
51761
54570
  //# sourceMappingURL=index.js.map
51762
54571
  //# sourceMappingURL=index.js.map