plugin-agent-orchestrator 1.0.15 → 1.0.17

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.
Files changed (66) hide show
  1. package/README.md +96 -0
  2. package/dist/externalVersion.js +6 -6
  3. package/dist/server/plugin.js +11 -1
  4. package/dist/server/services/SkillManager.js +0 -39
  5. package/dist/server/skill-hub/plugin.js +3 -3
  6. package/dist/server/tools/delegate-task.js +60 -4
  7. package/dist/server/tools/external-rag-search.js +140 -0
  8. package/dist/server/tools/skill-execute.js +1 -2
  9. package/package.json +2 -2
  10. package/src/server/plugin.ts +104 -94
  11. package/src/server/services/SkillManager.ts +13 -53
  12. package/src/server/skill-hub/plugin.ts +3 -3
  13. package/src/server/tools/delegate-task.ts +77 -6
  14. package/src/server/tools/external-rag-search.ts +128 -0
  15. package/src/server/tools/skill-execute.ts +1 -2
  16. package/dist/client/AIEmployeeSelect.d.ts +0 -11
  17. package/dist/client/AIEmployeesContext.d.ts +0 -30
  18. package/dist/client/OrchestratorSettings.d.ts +0 -3
  19. package/dist/client/RulesTab.d.ts +0 -2
  20. package/dist/client/TracingTab.d.ts +0 -2
  21. package/dist/client/index.d.ts +0 -1
  22. package/dist/client/plugin.d.ts +0 -6
  23. package/dist/client/skill-hub/components/ExecutionHistory.d.ts +0 -2
  24. package/dist/client/skill-hub/components/ExecutionProgress.d.ts +0 -20
  25. package/dist/client/skill-hub/components/GitSkillImport.d.ts +0 -7
  26. package/dist/client/skill-hub/components/SkillEditor.d.ts +0 -7
  27. package/dist/client/skill-hub/components/SkillManager.d.ts +0 -2
  28. package/dist/client/skill-hub/components/SkillMetrics.d.ts +0 -2
  29. package/dist/client/skill-hub/components/SkillTestPanel.d.ts +0 -7
  30. package/dist/client/skill-hub/index.d.ts +0 -10
  31. package/dist/client/skill-hub/locale.d.ts +0 -3
  32. package/dist/client/skill-hub/tools/InteractionSchemasProvider.d.ts +0 -19
  33. package/dist/client/skill-hub/tools/SkillHubCard.d.ts +0 -3
  34. package/dist/client/skill-hub/utils/jsonFields.d.ts +0 -3
  35. package/dist/index.d.ts +0 -2
  36. package/dist/server/collections/agent-execution-spans.d.ts +0 -9
  37. package/dist/server/collections/orchestrator-config.d.ts +0 -2
  38. package/dist/server/collections/orchestrator-logs.d.ts +0 -8
  39. package/dist/server/collections/skill-definitions.d.ts +0 -2
  40. package/dist/server/collections/skill-executions.d.ts +0 -2
  41. package/dist/server/collections/skill-worker-configs.d.ts +0 -2
  42. package/dist/server/index.d.ts +0 -1
  43. package/dist/server/migrations/20260423000000-add-progress-fields.d.ts +0 -4
  44. package/dist/server/migrations/20260425000000-add-interaction-schema.d.ts +0 -4
  45. package/dist/server/migrations/20260427000000-add-tracing-detail-fields.d.ts +0 -7
  46. package/dist/server/migrations/20260427000000-change-packages-to-text.d.ts +0 -4
  47. package/dist/server/migrations/20260427000001-change-other-json-to-text.d.ts +0 -4
  48. package/dist/server/migrations/20260429000000-add-llm-fields.d.ts +0 -7
  49. package/dist/server/migrations/20260429000000-fix-inputargs-json-to-text.d.ts +0 -16
  50. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.d.ts +0 -7
  51. package/dist/server/plugin.d.ts +0 -14
  52. package/dist/server/resources/tracing.d.ts +0 -7
  53. package/dist/server/services/CodeValidator.d.ts +0 -32
  54. package/dist/server/services/ExecutionSpanService.d.ts +0 -44
  55. package/dist/server/services/FileManager.d.ts +0 -28
  56. package/dist/server/services/SandboxRunner.d.ts +0 -41
  57. package/dist/server/services/SkillManager.d.ts +0 -6
  58. package/dist/server/services/SkillRepositoryService.d.ts +0 -22
  59. package/dist/server/services/WorkerEnvManager.d.ts +0 -26
  60. package/dist/server/skill-hub/actions/git-import.d.ts +0 -21
  61. package/dist/server/skill-hub/mcp/McpController.d.ts +0 -15
  62. package/dist/server/skill-hub/plugin.d.ts +0 -58
  63. package/dist/server/skill-hub/tasks/SkillExecutionTask.d.ts +0 -16
  64. package/dist/server/skill-hub/utils/json-fields.d.ts +0 -7
  65. package/dist/server/tools/delegate-task.d.ts +0 -19
  66. package/dist/server/tools/skill-execute.d.ts +0 -36
package/README.md CHANGED
@@ -7,6 +7,7 @@ Hierarchical Multi-Agent orchestration for NocoBase AI Employees. Enables Leader
7
7
  - **Hierarchical Delegation**: Allows AI Leader agents to break down complex tasks and assign them to specialized sub-agents.
8
8
  - **Seamless Integration**: Plugs directly into the existing AI Employee framework.
9
9
  - **Execution Tracking**: Monitor sub-agent task execution and responses within the main chat interface.
10
+ - **External RAG Search**: Exposes `external_rag_search` so leaders and sub-agents can retrieve context from NocoBase knowledge bases, including external RAG services.
10
11
 
11
12
  ## Usage
12
13
  1. Enable the plugin in the NocoBase Plugin Manager.
@@ -14,3 +15,98 @@ Hierarchical Multi-Agent orchestration for NocoBase AI Employees. Enables Leader
14
15
  3. Configure a primary "Leader" agent.
15
16
  4. Add available "Sub-Agents" as tools or skills to the Leader agent.
16
17
  5. Interact with the Leader agent; it will automatically delegate tasks when necessary.
18
+
19
+ ## External RAG / Embedding service
20
+
21
+ Recommended approach: keep source ownership in NocoBase and move chunking, embedding, vector storage, and retrieval to an external lightweight RAG service. This plugin should not own vector infrastructure directly. It delegates search to `plugin-knowledge-base`, which already supports knowledge bases of type `EXTERNAL_RAG`.
22
+
23
+ ### Architecture
24
+
25
+ 1. NocoBase stores the source metadata:
26
+ - uploaded file attachment id, filename, storage id, URL, owner/role access, or
27
+ - datasource/collection/record id for database-backed knowledge.
28
+ 2. The external RAG service owns:
29
+ - document fetching or receiving source payloads,
30
+ - parsing/chunking,
31
+ - embedding,
32
+ - vector index,
33
+ - retrieval.
34
+ 3. NocoBase creates a knowledge base with `type = EXTERNAL_RAG` and `options` such as:
35
+ - `ragProvider: "external-http"`
36
+ - `ragApiUrl: "https://rag.example.com/search"`
37
+ - `ragApiKey`
38
+ - `ragNamespace`
39
+ - `ragTopK`
40
+ - `ragScoreThreshold`
41
+ 4. Agents use the `external_rag_search` tool. The tool calls `plugin-knowledge-base.searchKnowledgeBases()`, so access control and mixed local/external search remain centralized.
42
+
43
+ ### External search contract
44
+
45
+ The built-in `external-http` strategy expects:
46
+
47
+ ```http
48
+ POST /search
49
+ Authorization: Bearer <ragApiKey>
50
+ Content-Type: application/json
51
+ ```
52
+
53
+ ```json
54
+ {
55
+ "query": "search text",
56
+ "topK": 5,
57
+ "scoreThreshold": 0.3,
58
+ "namespace": "optional-kb-namespace",
59
+ "filter": {}
60
+ }
61
+ ```
62
+
63
+ Response:
64
+
65
+ ```json
66
+ {
67
+ "results": [
68
+ {
69
+ "id": "chunk-or-source-id",
70
+ "content": "matched text",
71
+ "score": 0.82,
72
+ "metadata": {
73
+ "fileId": "123",
74
+ "filename": "contract.pdf",
75
+ "collection": "orders",
76
+ "recordId": "456",
77
+ "sourceUrl": "/api/attachments/123:download"
78
+ }
79
+ }
80
+ ]
81
+ }
82
+ ```
83
+
84
+ The important rule is that every result should return enough metadata for NocoBase to resolve the original source: `fileId`/`filename` for files, or `collection`/`recordId` for datasource records.
85
+
86
+ ### Lightweight open-source service target
87
+
88
+ For a small but useful deployment, use a standalone service with:
89
+
90
+ - Qdrant or LanceDB for vector search.
91
+ - FastAPI or Express for `/ingest`, `/delete`, and `/search`.
92
+ - A small embedding model such as `BAAI/bge-small-en-v1.5`, `intfloat/multilingual-e5-small`, or another model matching the deployment language.
93
+ - A namespace per NocoBase knowledge base.
94
+
95
+ Minimum API surface:
96
+
97
+ - `POST /ingest`: receive `{ namespace, source, content | fileUrl | storageRef, metadata }`.
98
+ - `POST /delete`: receive `{ namespace, sourceId }`.
99
+ - `POST /search`: implement the contract above.
100
+
101
+ For NocoBase datasource knowledge, send each record as a source document with metadata `{ collection, recordId, fields, updatedAt }`; the RAG service chunks and embeds the selected text fields, then returns `collection` and `recordId` in search results.
102
+
103
+ ### E5/OpenAI-compatible embedding
104
+
105
+ If the external RAG service uses an E5 family model behind an OpenAI-compatible `/v1/embeddings` API, configure the NocoBase knowledge base with `ragProvider: "e5-http"`. `plugin-knowledge-base` will read the selected embedding LLM service and forward its `baseURL`, `apiKey`, and model to the RAG service.
106
+
107
+ - embed user queries as `query: <question>`;
108
+ - embed document chunks as `passage: <chunk>`;
109
+ - use the same model for ingest and search;
110
+ - recreate the vector collection when changing models or vector dimensions.
111
+
112
+ The RAG service still owns chunking, embedding calls, vector storage, and metadata mapping. NocoBase owns the LLM service configuration and search authorization path.
@@ -9,14 +9,14 @@
9
9
 
10
10
  module.exports = {
11
11
  "react": "18.2.0",
12
- "@nocobase/client": "2.0.49",
12
+ "@nocobase/client": "2.0.55",
13
13
  "antd": "5.24.2",
14
14
  "@ant-design/icons": "5.6.1",
15
- "@nocobase/server": "2.0.49",
16
- "@nocobase/database": "2.0.49",
17
- "@nocobase/actions": "2.0.49",
15
+ "@nocobase/server": "2.0.55",
16
+ "@nocobase/database": "2.0.55",
17
+ "@nocobase/actions": "2.0.55",
18
18
  "@langchain/langgraph": "0.2.74",
19
19
  "@langchain/core": "0.3.80",
20
- "@nocobase/plugin-ai": "2.0.49",
21
- "@nocobase/ai": "2.0.49"
20
+ "@nocobase/plugin-ai": "2.0.55",
21
+ "@nocobase/ai": "2.0.55"
22
22
  };
@@ -43,6 +43,7 @@ module.exports = __toCommonJS(plugin_exports);
43
43
  var import_server = require("@nocobase/server");
44
44
  var import_path = __toESM(require("path"));
45
45
  var import_delegate_task = require("./tools/delegate-task");
46
+ var import_external_rag_search = require("./tools/external-rag-search");
46
47
  var import_tracing = require("./resources/tracing");
47
48
  var import_plugin = __toESM(require("./skill-hub/plugin"));
48
49
  class PluginAgentOrchestratorServer extends import_server.Plugin {
@@ -62,9 +63,18 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
62
63
  await this.skillHub.load();
63
64
  this.app.acl.registerSnippet({
64
65
  name: `pm.${this.name}`,
65
- actions: ["orchestratorConfig:*", "orchestratorTracing:*", "agentExecutionSpans:*", "skillDefinitions:*", "skillExecutions:*", "skillHub:*", "skillWorkerConfigs:*"]
66
+ actions: [
67
+ "orchestratorConfig:*",
68
+ "orchestratorTracing:*",
69
+ "agentExecutionSpans:*",
70
+ "skillDefinitions:*",
71
+ "skillExecutions:*",
72
+ "skillHub:*",
73
+ "skillWorkerConfigs:*"
74
+ ]
66
75
  });
67
76
  const toolsManager = this.app.aiManager.toolsManager;
77
+ toolsManager.registerTools((0, import_external_rag_search.createExternalRagSearchTool)(this));
68
78
  toolsManager.registerDynamicTools((0, import_delegate_task.createDelegateToolsProvider)(this));
69
79
  (0, import_tracing.registerTracingResource)(this);
70
80
  this.app.cronJobManager.addJob({
@@ -347,45 +347,6 @@ if table_data_raw and table_data_raw != '{{' + 'tableData}}':
347
347
  doc.build(story)
348
348
  print('Generated: report.pdf')
349
349
  `;
350
- const SEED_PPTX = `import os, json
351
- from pptx import Presentation
352
- from pptx.util import Inches, Pt
353
- from pptx.enum.text import PP_ALIGN
354
-
355
- title = json.loads('''{{title}}''') if '{{title}}'.startswith('"') else '{{title}}'
356
- subtitle_raw = '''{{subtitle}}'''
357
- subtitle = json.loads(subtitle_raw) if subtitle_raw.startswith('"') else subtitle_raw if subtitle_raw != '{{' + 'subtitle}}' else ''
358
- slides_data = json.loads('''{{slides}}''')
359
-
360
- prs = Presentation()
361
- prs.slide_width = Inches(13.333)
362
- prs.slide_height = Inches(7.5)
363
-
364
- # Title slide
365
- slide = prs.slides.add_slide(prs.slide_layouts[0])
366
- slide.shapes.title.text = title
367
- if subtitle and slide.placeholders[1]:
368
- slide.placeholders[1].text = subtitle
369
-
370
- # Content slides
371
- for s in slides_data:
372
- slide = prs.slides.add_slide(prs.slide_layouts[1])
373
- slide.shapes.title.text = s.get('title', '')
374
- body = slide.placeholders[1].text_frame
375
- body.clear()
376
- for i, bullet in enumerate(s.get('bullets', [])):
377
- if i == 0:
378
- body.paragraphs[0].text = bullet
379
- else:
380
- p = body.add_paragraph()
381
- p.text = bullet
382
- body.paragraphs[-1].font.size = Pt(18)
383
-
384
- output_dir = os.environ.get('OUTPUT_DIR', '/output')
385
- filepath = os.path.join(output_dir, 'presentation.pptx')
386
- prs.save(filepath)
387
- print('Generated: presentation.pptx')
388
- `;
389
350
  const SEED_CHART = `import os, json
390
351
  import matplotlib
391
352
  matplotlib.use('Agg')
@@ -498,7 +498,7 @@ IMPORTANT: This skill requires human confirmation. Pass best-effort args; the us
498
498
  filter: { id: skill.get("id"), enabled: true }
499
499
  });
500
500
  if (!latestSkill) {
501
- return { error: `Skill "${skill.get("name")}" is no longer available` };
501
+ return { status: "error", content: `Skill "${skill.get("name")}" is no longer available` };
502
502
  }
503
503
  const result = await this.executeSkill(latestSkill, args, toolCtx);
504
504
  return {
@@ -530,7 +530,7 @@ IMPORTANT: This skill requires human confirmation. Pass best-effort args; the us
530
530
  const cutoff = new Date(Date.now() - MAX_AGE_MS);
531
531
  const repo = this.db.getRepository("skillExecutions");
532
532
  const outdated = await repo.find({
533
- where: { createdAt: { $lt: cutoff } }
533
+ filter: { createdAt: { $lt: cutoff } }
534
534
  });
535
535
  if (outdated.length > 0) {
536
536
  for (const record of outdated) {
@@ -579,7 +579,7 @@ IMPORTANT: This skill requires human confirmation. Pass best-effort args; the us
579
579
  const hours = config ? config.get("retentionHours") : 24;
580
580
  if (hours > 0) {
581
581
  const cutoff = new Date(Date.now() - hours * 60 * 60 * 1e3);
582
- const results = await repo.find({ where: { createdAt: { $lt: cutoff } }, fields: ["id"] });
582
+ const results = await repo.find({ filter: { createdAt: { $lt: cutoff } }, fields: ["id"] });
583
583
  for (const rec of results) {
584
584
  await rec.destroy();
585
585
  }
@@ -37,6 +37,7 @@ var import_tools = require("@langchain/core/tools");
37
37
  var import_messages = require("@langchain/core/messages");
38
38
  var import_ExecutionSpanService = require("../services/ExecutionSpanService");
39
39
  const ORCHESTRATOR_DEPTH_KEY = "__orchestratorDepth";
40
+ const ORCHESTRATOR_PATH_KEY = "__orchestratorPath";
40
41
  const MAX_DISPATCH_CONCURRENCY = 5;
41
42
  const MAX_DISPATCH_TASKS = 20;
42
43
  const MAX_TOOL_NAME_LENGTH = 64;
@@ -554,7 +555,7 @@ function invalidateDelegateToolsCache() {
554
555
  registeredDelegateNamesByPlugin = /* @__PURE__ */ new WeakMap();
555
556
  }
556
557
  async function invokeDelegateTask(ctx, plugin, options) {
557
- var _a, _b, _c, _d, _e;
558
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
558
559
  const {
559
560
  leaderUsername,
560
561
  subAgentUsername,
@@ -573,6 +574,27 @@ async function invokeDelegateTask(ctx, plugin, options) {
573
574
  } = options;
574
575
  const ctxSnapshot = captureCtxSnapshot(ctx);
575
576
  const currentDepth = ctx[ORCHESTRATOR_DEPTH_KEY] ?? 0;
577
+ const currentPath = ctx[ORCHESTRATOR_PATH_KEY] ?? [leaderUsername];
578
+ if (currentPath.includes(subAgentUsername)) {
579
+ const loopChain = [...currentPath, subAgentUsername].join(" -> ");
580
+ await logDelegation(ctx, plugin, {
581
+ leaderUsername,
582
+ subAgentUsername,
583
+ toolName,
584
+ task,
585
+ context,
586
+ result: "",
587
+ status: "error",
588
+ depth: currentDepth,
589
+ durationMs: 0,
590
+ error: `Circular delegation detected: ${loopChain}.`,
591
+ snapshot: ctxSnapshot
592
+ });
593
+ return {
594
+ status: "error",
595
+ content: `Circular delegation detected: ${loopChain}. Execution aborted to prevent infinite reasoning loops.`
596
+ };
597
+ }
576
598
  if (currentDepth >= maxDepth) {
577
599
  await logDelegation(ctx, plugin, {
578
600
  leaderUsername,
@@ -677,7 +699,7 @@ async function invokeDelegateTask(ctx, plugin, options) {
677
699
  const entryName = toolEntry.definition.name;
678
700
  if (!entryName) continue;
679
701
  const employeeSkill = employeeSkillMap.get(entryName);
680
- if (!employeeSkill || isDelegateToolName(plugin, entryName) || employeeSkill.autoCall !== true || toolEntry.defaultPermission !== "ALLOW") {
702
+ if (!employeeSkill || isDelegateToolName(plugin, entryName) || employeeSkill.autoCall !== true) {
681
703
  continue;
682
704
  }
683
705
  langchainTools.push(
@@ -689,6 +711,12 @@ async function invokeDelegateTask(ctx, plugin, options) {
689
711
  var _a2;
690
712
  const invokeCtx = Object.create(ctx);
691
713
  invokeCtx[ORCHESTRATOR_DEPTH_KEY] = currentDepth + 1;
714
+ invokeCtx[ORCHESTRATOR_PATH_KEY] = [...currentPath, subAgentUsername];
715
+ invokeCtx._currentAIEmployee = subAgentUsername;
716
+ if (ctx.state) {
717
+ invokeCtx.state = Object.create(ctx.state);
718
+ invokeCtx.state.currentAIEmployee = subAgentUsername;
719
+ }
692
720
  const toolStartedAt = Date.now();
693
721
  const isSkillHubTool = entryName === "skill_hub_execute" || entryName.startsWith("skill_hub_");
694
722
  const toolSpan = await spanService.create({
@@ -771,7 +799,27 @@ async function invokeDelegateTask(ctx, plugin, options) {
771
799
  llm: chatModel,
772
800
  tools: langchainTools
773
801
  });
774
- const systemPrompt = ((_e = subAgentEmployee.chatSettings) == null ? void 0 : _e.systemPrompt) || subAgentEmployee.bio || `You are an AI assistant named "${subAgentEmployee.nickname || subAgentUsername}". ${subAgentEmployee.about || ""}`;
802
+ let systemPrompt = ((_e = subAgentEmployee.chatSettings) == null ? void 0 : _e.systemPrompt) || subAgentEmployee.bio || `You are an AI assistant named "${subAgentEmployee.nickname || subAgentUsername}". ${subAgentEmployee.about || ""}`;
803
+ try {
804
+ const kbPlugin = ctx.app.pm.get("plugin-knowledge-base");
805
+ if (kbPlugin == null ? void 0 : kbPlugin.sessionContext) {
806
+ const sessionId = ((_h = (_g = (_f = ctx.action) == null ? void 0 : _f.params) == null ? void 0 : _g.values) == null ? void 0 : _h.sessionId) || ((_j = (_i = ctx.action) == null ? void 0 : _i.params) == null ? void 0 : _j.sessionId) || ((_k = ctx.state) == null ? void 0 : _k.sessionId);
807
+ const contextSummary = await kbPlugin.sessionContext.buildSummary(
808
+ { rootRunId, ...sessionId ? { sessionId } : {} },
809
+ 6e3
810
+ );
811
+ if (contextSummary) {
812
+ systemPrompt += `
813
+
814
+ <shared_context>
815
+ The following context was shared by other agents in this workflow. Use it to avoid redundant work:
816
+ ${contextSummary}
817
+ </shared_context>`;
818
+ }
819
+ }
820
+ } catch (e) {
821
+ (_m = (_l = ctx.app.log) == null ? void 0 : _l.debug) == null ? void 0 : _m.call(_l, `[AgentOrchestrator] Shared context injection skipped: ${e.message}`);
822
+ }
775
823
  const combinedTask = context ? `Task: ${task}
776
824
 
777
825
  Context Provided:
@@ -867,9 +915,17 @@ ${context}` : `Task: ${task}`;
867
915
  traceCount: trace.length + 1
868
916
  }
869
917
  });
918
+ const diagnosticTrace = trace.filter((t) => t.type === "tool_error" || t.type === "error").map((t) => `[${t.toolName ? `Tool: ${t.toolName}` : "Sub-agent"}] Error: ${t.content || t.title}`).join("\n");
919
+ const formattedError = [
920
+ `Sub-agent "${subAgentUsername}" failed execution: ${e.message}`,
921
+ diagnosticTrace ? `
922
+ Diagnostic Details of internal failures:
923
+ ${diagnosticTrace}` : "",
924
+ `Suggestion: Review the tool parameters above or try dividing the task into simpler independent tasks.`
925
+ ].filter(Boolean).join("\n");
870
926
  return {
871
927
  status: "error",
872
- content: `Sub-agent "${subAgentUsername}" failed: ${e.message}`
928
+ content: formattedError
873
929
  };
874
930
  }
875
931
  }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var external_rag_search_exports = {};
28
+ __export(external_rag_search_exports, {
29
+ createExternalRagSearchTool: () => createExternalRagSearchTool
30
+ });
31
+ module.exports = __toCommonJS(external_rag_search_exports);
32
+ var import_zod = require("zod");
33
+ const TOOL_NAME = "external_rag_search";
34
+ const MAX_CONTENT_LENGTH = 4e3;
35
+ function truncate(value, max = MAX_CONTENT_LENGTH) {
36
+ const text = typeof value === "string" ? value : value == null ? "" : String(value);
37
+ return text.length > max ? `${text.slice(0, max)}...` : text;
38
+ }
39
+ function firstString(...values) {
40
+ for (const value of values) {
41
+ if (typeof value === "string" && value.trim()) {
42
+ return value.trim();
43
+ }
44
+ if (typeof value === "number" && Number.isFinite(value)) {
45
+ return String(value);
46
+ }
47
+ }
48
+ return void 0;
49
+ }
50
+ function normalizeResult(result) {
51
+ const metadata = (result == null ? void 0 : result.metadata) ?? {};
52
+ const sourceId = firstString(
53
+ result == null ? void 0 : result.id,
54
+ metadata.id,
55
+ metadata.sourceId,
56
+ metadata.documentId,
57
+ metadata.docId,
58
+ metadata.fileId,
59
+ metadata.recordId
60
+ );
61
+ const filename = firstString(metadata.filename, metadata.fileName, metadata.name, metadata.title, metadata.source);
62
+ return {
63
+ content: truncate(result == null ? void 0 : result.content),
64
+ score: Number((result == null ? void 0 : result.rerankScore) ?? (result == null ? void 0 : result.score) ?? (result == null ? void 0 : result.vectorScore) ?? 0),
65
+ knowledgeBaseId: result == null ? void 0 : result.knowledgeBaseId,
66
+ knowledgeBaseName: result == null ? void 0 : result.knowledgeBaseName,
67
+ source: {
68
+ id: sourceId,
69
+ filename,
70
+ url: firstString(metadata.url, metadata.fileUrl, metadata.sourceUrl),
71
+ collection: firstString(metadata.collection, metadata.collectionName),
72
+ recordId: firstString(metadata.recordId, metadata.rowId)
73
+ },
74
+ metadata
75
+ };
76
+ }
77
+ function createExternalRagSearchTool(plugin) {
78
+ return {
79
+ scope: "CUSTOM",
80
+ execution: "backend",
81
+ defaultPermission: "ALLOW",
82
+ introduction: {
83
+ title: "External RAG Search",
84
+ about: "Search NocoBase knowledge bases through plugin-knowledge-base, including EXTERNAL_RAG services that own chunking, embedding, and retrieval."
85
+ },
86
+ definition: {
87
+ name: TOOL_NAME,
88
+ description: `Search configured knowledge bases for relevant context. Use this before answering questions that require documents, files, or datasource-backed knowledge.
89
+
90
+ The search may be served by an external RAG service. Results include content plus source identifiers such as id, filename, collection, and recordId when the external service provides them.`,
91
+ schema: import_zod.z.object({
92
+ query: import_zod.z.string().min(1).describe("Natural-language search query."),
93
+ knowledgeBaseIds: import_zod.z.array(import_zod.z.string().min(1)).optional().describe(
94
+ "Optional list of NocoBase knowledge base IDs to search. If omitted, all accessible KBs are searched."
95
+ ),
96
+ topK: import_zod.z.number().int().min(1).max(20).optional().describe("Maximum results to return. Default 5, max 20."),
97
+ scoreThreshold: import_zod.z.number().min(0).max(1).optional().describe("Minimum relevance score. Default is controlled by plugin-knowledge-base.")
98
+ })
99
+ },
100
+ invoke: async (ctx, args) => {
101
+ var _a, _b, _c, _d, _e;
102
+ const query = typeof (args == null ? void 0 : args.query) === "string" ? args.query.trim() : "";
103
+ if (!query) {
104
+ return { status: "error", content: "Missing required field: query." };
105
+ }
106
+ const kbPlugin = (_c = (_b = (_a = ctx == null ? void 0 : ctx.app) == null ? void 0 : _a.pm) == null ? void 0 : _b.get) == null ? void 0 : _c.call(_b, "plugin-knowledge-base");
107
+ if (!(kbPlugin == null ? void 0 : kbPlugin.searchKnowledgeBases)) {
108
+ return {
109
+ status: "error",
110
+ content: "plugin-knowledge-base is not installed or does not expose searchKnowledgeBases()."
111
+ };
112
+ }
113
+ try {
114
+ const results = await kbPlugin.searchKnowledgeBases(ctx, query, {
115
+ knowledgeBaseIds: Array.isArray(args.knowledgeBaseIds) ? args.knowledgeBaseIds.map(String) : void 0,
116
+ topK: args.topK,
117
+ scoreThreshold: args.scoreThreshold,
118
+ rerank: true
119
+ });
120
+ return {
121
+ status: "success",
122
+ content: JSON.stringify({
123
+ query,
124
+ results: (results ?? []).map(normalizeResult)
125
+ })
126
+ };
127
+ } catch (error) {
128
+ (_e = (_d = plugin.app.log) == null ? void 0 : _d.error) == null ? void 0 : _e.call(_d, "[AgentOrchestrator] external_rag_search failed", error);
129
+ return {
130
+ status: "error",
131
+ content: `External RAG search failed: ${(error == null ? void 0 : error.message) || String(error)}`
132
+ };
133
+ }
134
+ }
135
+ };
136
+ }
137
+ // Annotate the CommonJS export names for ESM import in node:
138
+ 0 && (module.exports = {
139
+ createExternalRagSearchTool
140
+ });
@@ -69,9 +69,8 @@ IMPORTANT: If the skill returns file download URLs, you MUST format them as clic
69
69
  required: ["action"]
70
70
  }
71
71
  },
72
- async invoke(args, options) {
72
+ async invoke(ctx, args, _id) {
73
73
  var _a;
74
- const ctx = options == null ? void 0 : options.context;
75
74
  plugin.app.logger.info(`[skill-execute] Tool invoked with action: ${args.action}, skillName: ${args.skillName}`);
76
75
  if (args.action === "list") {
77
76
  const skills = await plugin.db.getRepository("skillDefinitions").find({
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName.zh-CN": "代理协调器",
5
5
  "displayName.vi-VN": "Điều phối Agent",
6
6
  "description": "Hierarchical Multi-Agent orchestration for NocoBase AI Employees. Enables Leader agents to delegate tasks to Sub-Agent employees without modifying core plugin-ai.",
7
- "version": "1.0.15",
7
+ "version": "1.0.17",
8
8
  "license": "Apache-2.0",
9
9
  "main": "dist/server/index.js",
10
10
  "keywords": [
@@ -42,4 +42,4 @@
42
42
  "@nocobase/ai": "2.x",
43
43
  "@nocobase/plugin-ai": "2.x"
44
44
  }
45
- }
45
+ }