plugin-agent-orchestrator 1.0.17 → 1.0.18

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 (139) hide show
  1. package/dist/client/AIEmployeeSelect.d.ts +11 -0
  2. package/dist/client/AIEmployeesContext.d.ts +30 -0
  3. package/dist/client/AgentRunsTab.d.ts +2 -0
  4. package/dist/client/HarnessProfilesTab.d.ts +2 -0
  5. package/dist/client/OrchestratorSettings.d.ts +3 -0
  6. package/dist/client/RulesTab.d.ts +2 -0
  7. package/dist/client/TracingTab.d.ts +2 -0
  8. package/dist/client/index.d.ts +1 -0
  9. package/dist/client/index.js +1 -1
  10. package/dist/client/plugin.d.ts +6 -0
  11. package/dist/client/skill-hub/components/ExecutionHistory.d.ts +2 -0
  12. package/dist/client/skill-hub/components/ExecutionProgress.d.ts +20 -0
  13. package/dist/client/skill-hub/components/GitSkillImport.d.ts +7 -0
  14. package/dist/client/skill-hub/components/LoopSettings.d.ts +2 -0
  15. package/dist/client/skill-hub/components/SkillEditor.d.ts +7 -0
  16. package/dist/client/skill-hub/components/SkillManager.d.ts +2 -0
  17. package/dist/client/skill-hub/components/SkillMetrics.d.ts +2 -0
  18. package/dist/client/skill-hub/components/SkillTestPanel.d.ts +7 -0
  19. package/dist/client/skill-hub/index.d.ts +11 -0
  20. package/dist/client/skill-hub/locale.d.ts +3 -0
  21. package/dist/client/skill-hub/tools/InteractionSchemasProvider.d.ts +6 -0
  22. package/dist/client/skill-hub/tools/SkillHubCard.d.ts +3 -0
  23. package/dist/client/skill-hub/tools/loopTemplates.d.ts +22 -0
  24. package/dist/client/skill-hub/tools/registerSkillLoopCards.d.ts +1 -0
  25. package/dist/client/skill-hub/utils/jsonFields.d.ts +3 -0
  26. package/dist/client/tools/PlanApprovalCard.d.ts +3 -0
  27. package/dist/client/tools/registerOrchestratorCards.d.ts +1 -0
  28. package/dist/externalVersion.js +6 -6
  29. package/dist/index.d.ts +2 -0
  30. package/dist/server/collections/agent-execution-spans.d.ts +9 -0
  31. package/dist/server/collections/agent-harness-profiles.d.ts +2 -0
  32. package/dist/server/collections/agent-harness-profiles.js +89 -0
  33. package/dist/server/collections/agent-loop-events.d.ts +2 -0
  34. package/dist/server/collections/agent-loop-events.js +101 -0
  35. package/dist/server/collections/agent-loop-runs.d.ts +2 -0
  36. package/dist/server/collections/agent-loop-runs.js +188 -0
  37. package/dist/server/collections/agent-loop-steps.d.ts +2 -0
  38. package/dist/server/collections/agent-loop-steps.js +174 -0
  39. package/dist/server/collections/orchestrator-config.d.ts +2 -0
  40. package/dist/server/collections/orchestrator-config.js +7 -0
  41. package/dist/server/collections/orchestrator-logs.d.ts +8 -0
  42. package/dist/server/collections/skill-definitions.d.ts +3 -0
  43. package/dist/server/collections/skill-executions.d.ts +3 -0
  44. package/dist/server/collections/skill-executions.js +12 -0
  45. package/dist/server/collections/skill-loop-configs.d.ts +3 -0
  46. package/dist/server/collections/skill-loop-configs.js +94 -0
  47. package/dist/server/collections/skill-worker-configs.d.ts +3 -0
  48. package/dist/server/index.d.ts +1 -0
  49. package/dist/server/migrations/20260423000000-add-progress-fields.d.ts +4 -0
  50. package/dist/server/migrations/20260425000000-add-interaction-schema.d.ts +4 -0
  51. package/dist/server/migrations/20260427000000-add-tracing-detail-fields.d.ts +7 -0
  52. package/dist/server/migrations/20260427000000-change-packages-to-text.d.ts +4 -0
  53. package/dist/server/migrations/20260427000001-change-other-json-to-text.d.ts +4 -0
  54. package/dist/server/migrations/20260429000000-add-llm-fields.d.ts +7 -0
  55. package/dist/server/migrations/20260429000000-fix-inputargs-json-to-text.d.ts +16 -0
  56. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.d.ts +7 -0
  57. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.d.ts +7 -0
  58. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +55 -0
  59. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.d.ts +12 -0
  60. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.js +162 -0
  61. package/dist/server/plugin.d.ts +16 -0
  62. package/dist/server/plugin.js +13 -0
  63. package/dist/server/resources/agent-loop.d.ts +3 -0
  64. package/dist/server/resources/agent-loop.js +205 -0
  65. package/dist/server/resources/tracing.d.ts +7 -0
  66. package/dist/server/services/AgentHarness.d.ts +42 -0
  67. package/dist/server/services/AgentHarness.js +565 -0
  68. package/dist/server/services/AgentLoopController.d.ts +205 -0
  69. package/dist/server/services/AgentLoopController.js +940 -0
  70. package/dist/server/services/AgentLoopRepository.d.ts +20 -0
  71. package/dist/server/services/AgentLoopRepository.js +210 -0
  72. package/dist/server/services/AgentLoopService.d.ts +149 -0
  73. package/dist/server/services/AgentLoopService.js +133 -0
  74. package/dist/server/services/AgentPlanValidator.d.ts +4 -0
  75. package/dist/server/services/AgentPlanValidator.js +99 -0
  76. package/dist/server/services/AgentPlannerService.d.ts +8 -0
  77. package/dist/server/services/AgentPlannerService.js +119 -0
  78. package/dist/server/services/AgentRegistryService.d.ts +13 -0
  79. package/dist/server/services/AgentRegistryService.js +178 -0
  80. package/dist/server/services/CodeValidator.d.ts +32 -0
  81. package/dist/server/services/ExecutionSpanService.d.ts +46 -0
  82. package/dist/server/services/FileManager.d.ts +28 -0
  83. package/dist/server/services/SandboxRunner.d.ts +41 -0
  84. package/dist/server/services/SkillManager.d.ts +6 -0
  85. package/dist/server/services/SkillRepositoryService.d.ts +22 -0
  86. package/dist/server/services/WorkerEnvManager.d.ts +26 -0
  87. package/dist/server/skill-hub/actions/git-import.d.ts +21 -0
  88. package/dist/server/skill-hub/mcp/McpController.d.ts +15 -0
  89. package/dist/server/skill-hub/plugin.d.ts +61 -0
  90. package/dist/server/skill-hub/plugin.js +137 -54
  91. package/dist/server/skill-hub/tasks/SkillExecutionTask.d.ts +16 -0
  92. package/dist/server/skill-hub/utils/json-fields.d.ts +7 -0
  93. package/dist/server/tools/agent-loop.d.ts +235 -0
  94. package/dist/server/tools/agent-loop.js +406 -0
  95. package/dist/server/tools/delegate-task.d.ts +19 -0
  96. package/dist/server/tools/delegate-task.js +19 -368
  97. package/dist/server/tools/external-rag-search.d.ts +42 -0
  98. package/dist/server/tools/orchestrator-plan.d.ts +205 -0
  99. package/dist/server/tools/orchestrator-plan.js +291 -0
  100. package/dist/server/tools/skill-execute.d.ts +36 -0
  101. package/dist/server/tools/skill-execute.js +2 -0
  102. package/package.json +1 -1
  103. package/src/client/AgentRunsTab.tsx +764 -0
  104. package/src/client/HarnessProfilesTab.tsx +247 -0
  105. package/src/client/OrchestratorSettings.tsx +40 -2
  106. package/src/client/RulesTab.tsx +103 -6
  107. package/src/client/plugin.tsx +27 -54
  108. package/src/client/skill-hub/components/LoopSettings.tsx +331 -0
  109. package/src/client/skill-hub/index.tsx +51 -75
  110. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +56 -16
  111. package/src/client/skill-hub/tools/SkillHubCard.tsx +35 -4
  112. package/src/client/skill-hub/tools/loopTemplates.ts +52 -0
  113. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +58 -0
  114. package/src/client/tools/PlanApprovalCard.tsx +175 -0
  115. package/src/client/tools/registerOrchestratorCards.ts +7 -0
  116. package/src/server/collections/agent-harness-profiles.ts +59 -0
  117. package/src/server/collections/agent-loop-events.ts +71 -0
  118. package/src/server/collections/agent-loop-runs.ts +158 -0
  119. package/src/server/collections/agent-loop-steps.ts +144 -0
  120. package/src/server/collections/orchestrator-config.ts +7 -0
  121. package/src/server/collections/skill-executions.ts +63 -51
  122. package/src/server/collections/skill-loop-configs.ts +65 -0
  123. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +30 -0
  124. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +142 -0
  125. package/src/server/plugin.ts +15 -0
  126. package/src/server/resources/agent-loop.ts +183 -0
  127. package/src/server/services/AgentHarness.ts +663 -0
  128. package/src/server/services/AgentLoopController.ts +1128 -0
  129. package/src/server/services/AgentLoopRepository.ts +194 -0
  130. package/src/server/services/AgentLoopService.ts +161 -0
  131. package/src/server/services/AgentPlanValidator.ts +73 -0
  132. package/src/server/services/AgentPlannerService.ts +93 -0
  133. package/src/server/services/AgentRegistryService.ts +169 -0
  134. package/src/server/services/ExecutionSpanService.ts +2 -0
  135. package/src/server/skill-hub/plugin.ts +881 -771
  136. package/src/server/tools/agent-loop.ts +399 -0
  137. package/src/server/tools/delegate-task.ts +23 -485
  138. package/src/server/tools/orchestrator-plan.ts +279 -0
  139. package/src/server/tools/skill-execute.ts +68 -64
@@ -0,0 +1,565 @@
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 AgentHarness_exports = {};
28
+ __export(AgentHarness_exports, {
29
+ AgentHarness: () => AgentHarness
30
+ });
31
+ module.exports = __toCommonJS(AgentHarness_exports);
32
+ var import_zod = require("zod");
33
+ var import_prebuilt = require("@langchain/langgraph/prebuilt");
34
+ var import_tools = require("@langchain/core/tools");
35
+ var import_messages = require("@langchain/core/messages");
36
+ var import_ExecutionSpanService = require("./ExecutionSpanService");
37
+ const ORCHESTRATOR_DEPTH_KEY = "__orchestratorDepth";
38
+ const ORCHESTRATOR_PATH_KEY = "__orchestratorPath";
39
+ function toPlain(record) {
40
+ var _a;
41
+ return ((_a = record == null ? void 0 : record.toJSON) == null ? void 0 : _a.call(record)) || record;
42
+ }
43
+ function asObject(value) {
44
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
45
+ if (typeof value === "string" && value.trim()) {
46
+ try {
47
+ const parsed = JSON.parse(value);
48
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+ return {};
54
+ }
55
+ function trimText(value, max = 5e4) {
56
+ let text = "";
57
+ if (typeof value === "string") {
58
+ text = value;
59
+ } else if (value != null) {
60
+ try {
61
+ text = JSON.stringify(value);
62
+ } catch {
63
+ text = String(value);
64
+ }
65
+ }
66
+ return text.length > max ? `${text.slice(0, max)}
67
+ ...[truncated]` : text;
68
+ }
69
+ function sanitizeToolPart(value) {
70
+ return (value || "").replace(/[^a-zA-Z0-9_-]/g, "_");
71
+ }
72
+ function buildDelegateToolName(leaderUsername, subAgentUsername) {
73
+ return `delegate_${sanitizeToolPart(leaderUsername)}_to_${sanitizeToolPart(subAgentUsername)}`;
74
+ }
75
+ function nowIso() {
76
+ return (/* @__PURE__ */ new Date()).toISOString();
77
+ }
78
+ class AgentHarness {
79
+ constructor(plugin, registryService) {
80
+ this.plugin = plugin;
81
+ this.registryService = registryService;
82
+ this.spanService = new import_ExecutionSpanService.ExecutionSpanService(plugin);
83
+ }
84
+ spanService;
85
+ get db() {
86
+ return this.plugin.db;
87
+ }
88
+ get app() {
89
+ return this.plugin.app;
90
+ }
91
+ async executeStep(run, step, options = {}) {
92
+ const harnessTag = asObject(run.metadata).harnessTag || asObject(step.metadata).harnessTag || "default";
93
+ const profile = await this.registryService.getHarnessProfile(harnessTag);
94
+ const settings = asObject(profile == null ? void 0 : profile.settings);
95
+ if (step.type === "sub_agent") {
96
+ if (settings.allowSubAgents === false) {
97
+ throw new Error(`Harness profile "${harnessTag}" does not allow sub-agent execution.`);
98
+ }
99
+ return this.invokeSubAgentStep(run, step, settings, options);
100
+ }
101
+ if ((step.type === "tool" || step.type === "skill") && step.target) {
102
+ if (settings.allowToolCalls === false) {
103
+ throw new Error(`Harness profile "${harnessTag}" does not allow tool/skill execution.`);
104
+ }
105
+ return this.invokeNamedTool(run, step, step.target, step.input || {}, settings, options);
106
+ }
107
+ if (step.type === "verification") {
108
+ return {
109
+ passed: true,
110
+ summary: "Verification completed by orchestrator controller.",
111
+ checkedDependencies: Array.isArray(step.dependsOn) ? step.dependsOn.map(String) : [],
112
+ harnessTag
113
+ };
114
+ }
115
+ return {
116
+ summary: `${step.title || step.planKey} completed by orchestrator controller.`,
117
+ description: step.description || "",
118
+ input: step.input || {},
119
+ harnessTag
120
+ };
121
+ }
122
+ async invokeSubAgentStep(run, step, settings, options) {
123
+ var _a;
124
+ const target = step.target || asObject(step.metadata).subAgentUsername || ((_a = step.input) == null ? void 0 : _a.subAgentUsername);
125
+ if (!target) {
126
+ throw new Error(`Sub-agent step "${step.planKey}" is missing target sub-agent username.`);
127
+ }
128
+ if (!run.leaderUsername) {
129
+ throw new Error(`Sub-agent step "${step.planKey}" requires a leader AI employee username.`);
130
+ }
131
+ const toolName = String(target).startsWith("delegate_") ? String(target) : buildDelegateToolName(run.leaderUsername, target);
132
+ const task = step.description || step.title || run.goal;
133
+ const context = trimText(
134
+ {
135
+ goal: run.goal,
136
+ input: step.input || {},
137
+ harnessTag: asObject(run.metadata).harnessTag || asObject(step.metadata).harnessTag || "default",
138
+ agentLoopRunId: String(run.id),
139
+ agentLoopStepId: String(step.id)
140
+ },
141
+ 2e4
142
+ );
143
+ return this.invokeNamedTool(run, step, toolName, { task, context }, settings, options);
144
+ }
145
+ async invokeNamedTool(run, step, toolName, args, settings, options) {
146
+ var _a, _b, _c, _d, _e;
147
+ if (String(toolName).startsWith("orchestrator_")) {
148
+ throw new Error(`Tool step "${step.planKey}" cannot call internal orchestrator control tool "${toolName}".`);
149
+ }
150
+ if (Array.isArray(settings.allowTools) && settings.allowTools.length > 0) {
151
+ if (!settings.allowTools.includes(toolName)) {
152
+ throw new Error(`Tool "${toolName}" is not on the allowed list for harness profile.`);
153
+ }
154
+ }
155
+ if (Array.isArray(settings.denyTools) && settings.denyTools.length > 0) {
156
+ if (settings.denyTools.includes(toolName)) {
157
+ throw new Error(`Tool "${toolName}" is on the denied list for harness profile.`);
158
+ }
159
+ }
160
+ const toolsManager = (_b = (_a = this.app) == null ? void 0 : _a.aiManager) == null ? void 0 : _b.toolsManager;
161
+ const tool = await ((_c = toolsManager == null ? void 0 : toolsManager.getTools) == null ? void 0 : _c.call(toolsManager, toolName));
162
+ if (!(tool == null ? void 0 : tool.invoke)) {
163
+ throw new Error(`Tool "${toolName}" was not found or is missing standard invoke handler.`);
164
+ }
165
+ const isDelegationTool = await this.registryService.isRegisteredDelegationTool(toolName);
166
+ const isStepAlreadyApproved = ((_d = step == null ? void 0 : step.approval) == null ? void 0 : _d.approved) === true;
167
+ if (!isDelegationTool && !isStepAlreadyApproved && (tool.defaultPermission === "ASK" || settings.requireApprovalRiskLevel && tool.riskLevel && tool.riskLevel >= settings.requireApprovalRiskLevel)) {
168
+ throw new Error("requires_approval");
169
+ }
170
+ const ctx = options.ctx || {};
171
+ const previousEmployee = ctx._currentAIEmployee;
172
+ const previousStateEmployee = (_e = ctx.state) == null ? void 0 : _e.currentAIEmployee;
173
+ if (run.leaderUsername) {
174
+ ctx._currentAIEmployee = run.leaderUsername;
175
+ ctx.state = { ...ctx.state || {}, currentAIEmployee: run.leaderUsername };
176
+ }
177
+ try {
178
+ const result = await tool.invoke(ctx, args, `agent-loop-${run.id}-${step.id}`);
179
+ if ((result == null ? void 0 : result.status) === "error") {
180
+ throw new Error(result.content || `Tool "${toolName}" returned an error.`);
181
+ }
182
+ return {
183
+ toolName,
184
+ args,
185
+ result
186
+ };
187
+ } finally {
188
+ if (previousEmployee === void 0) {
189
+ delete ctx._currentAIEmployee;
190
+ } else {
191
+ ctx._currentAIEmployee = previousEmployee;
192
+ }
193
+ if (ctx.state) {
194
+ if (previousStateEmployee === void 0) {
195
+ delete ctx.state.currentAIEmployee;
196
+ } else {
197
+ ctx.state.currentAIEmployee = previousStateEmployee;
198
+ }
199
+ }
200
+ }
201
+ }
202
+ async runSubAgent(ctx, options) {
203
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
204
+ const {
205
+ leaderUsername,
206
+ subAgentUsername,
207
+ subAgentEmployee,
208
+ task,
209
+ context,
210
+ maxDepth,
211
+ timeout,
212
+ toolCallId,
213
+ toolName,
214
+ llmService,
215
+ model,
216
+ recursionLimit,
217
+ rootRunId,
218
+ parentSpanId,
219
+ agentLoopRunId,
220
+ agentLoopStepId
221
+ } = options;
222
+ const startTime = Date.now();
223
+ const currentDepth = options.currentDepth ?? 0;
224
+ const currentPath = options.currentPath ?? [leaderUsername];
225
+ const trace = [
226
+ {
227
+ type: "start",
228
+ at: nowIso(),
229
+ title: `Delegation started: ${leaderUsername} -> ${subAgentUsername}`,
230
+ content: task
231
+ }
232
+ ];
233
+ const executionSpan = await this.spanService.create({
234
+ rootRunId: rootRunId || `run_${Date.now()}`,
235
+ parentSpanId,
236
+ type: "sub_agent",
237
+ status: "running",
238
+ leaderUsername,
239
+ employeeUsername: subAgentUsername,
240
+ title: `Delegation: ${leaderUsername} -> ${subAgentUsername}`,
241
+ input: { task, context },
242
+ metadata: {
243
+ depth: maxDepth,
244
+ toolName,
245
+ recursionLimit,
246
+ agentLoopRunId,
247
+ agentLoopStepId
248
+ },
249
+ userId: ((_b = (_a = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) || ((_d = (_c = ctx == null ? void 0 : ctx.state) == null ? void 0 : _c.currentUser) == null ? void 0 : _d.id)
250
+ });
251
+ const executionSpanId = (executionSpan == null ? void 0 : executionSpan.id) ? String(executionSpan.id) : void 0;
252
+ const logRecord = await this.logDelegation(ctx, {
253
+ leaderUsername,
254
+ subAgentUsername,
255
+ toolName,
256
+ task,
257
+ context,
258
+ result: "",
259
+ status: "running",
260
+ depth: maxDepth,
261
+ durationMs: 0,
262
+ trace
263
+ });
264
+ if (executionSpanId && (logRecord == null ? void 0 : logRecord.id)) {
265
+ await this.spanService.update(executionSpanId, { orchestratorLogId: logRecord.id });
266
+ }
267
+ try {
268
+ const aiPlugin = ctx.app.pm.get("ai");
269
+ if (!aiPlugin) {
270
+ throw new Error("Plugin AI is not enabled.");
271
+ }
272
+ const modelSettings = await this.registryService.resolveModelSettings(
273
+ subAgentUsername,
274
+ leaderUsername,
275
+ llmService && model ? { llmService, model } : void 0
276
+ );
277
+ if (!modelSettings) {
278
+ throw new Error(`Sub-agent "${subAgentUsername}" has no LLM model configured.`);
279
+ }
280
+ const { provider } = await aiPlugin.aiManager.getLLMService({
281
+ llmService: modelSettings.llmService,
282
+ model: modelSettings.model
283
+ });
284
+ const chatModel = provider.createModel();
285
+ const coreToolsManager = ctx.app.aiManager.toolsManager;
286
+ const allTools = await coreToolsManager.listTools();
287
+ const employeeSkills = (((_e = subAgentEmployee.skillSettings) == null ? void 0 : _e.skills) ?? []).map(
288
+ (s) => typeof s === "string" ? { name: s, autoCall: false } : { name: s == null ? void 0 : s.name, autoCall: (s == null ? void 0 : s.autoCall) === true }
289
+ ).filter((s) => Boolean(s.name));
290
+ const employeeSkillMap = new Map(employeeSkills.map((s) => [s.name, s]));
291
+ const langchainTools = [];
292
+ for (const toolEntry of allTools) {
293
+ const entryName = toolEntry.definition.name;
294
+ if (!entryName) continue;
295
+ const employeeSkill = employeeSkillMap.get(entryName);
296
+ if (!employeeSkill || employeeSkill.autoCall !== true || toolEntry.defaultPermission !== "ALLOW") {
297
+ continue;
298
+ }
299
+ langchainTools.push(
300
+ new import_tools.DynamicStructuredTool({
301
+ name: entryName.replace(/[^a-zA-Z0-9_-]/g, "_"),
302
+ description: toolEntry.definition.description || entryName,
303
+ schema: toolEntry.definition.schema || import_zod.z.object({}),
304
+ func: async (toolArgs) => {
305
+ var _a2, _b2, _c2, _d2, _e2;
306
+ const invokeCtx = Object.create(ctx);
307
+ invokeCtx._currentAIEmployee = subAgentUsername;
308
+ invokeCtx[ORCHESTRATOR_DEPTH_KEY] = currentDepth + 1;
309
+ invokeCtx[ORCHESTRATOR_PATH_KEY] = [...currentPath, subAgentUsername];
310
+ if (ctx.state) {
311
+ invokeCtx.state = Object.create(ctx.state);
312
+ invokeCtx.state.currentAIEmployee = subAgentUsername;
313
+ }
314
+ const toolStartedAt = Date.now();
315
+ const isSkillHubTool = entryName === "skill_hub_execute" || entryName.startsWith("skill_hub_");
316
+ const toolSpan = await this.spanService.create({
317
+ rootRunId: rootRunId || `run_${Date.now()}`,
318
+ parentSpanId: executionSpanId,
319
+ type: isSkillHubTool ? "skill" : "tool",
320
+ status: "running",
321
+ leaderUsername,
322
+ employeeUsername: subAgentUsername,
323
+ toolName: toolEntry.definition.name,
324
+ title: isSkillHubTool ? `Skill: ${toolEntry.definition.name}` : `Tool: ${toolEntry.definition.name}`,
325
+ input: toolArgs,
326
+ metadata: {
327
+ depth: currentDepth + 1,
328
+ toolCallId: `orch-${toolCallId}`,
329
+ agentLoopRunId,
330
+ agentLoopStepId
331
+ },
332
+ userId: ((_b2 = (_a2 = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _a2.user) == null ? void 0 : _b2.id) || ((_d2 = (_c2 = ctx == null ? void 0 : ctx.state) == null ? void 0 : _c2.currentUser) == null ? void 0 : _d2.id)
333
+ });
334
+ const toolSpanId = (toolSpan == null ? void 0 : toolSpan.id) ? String(toolSpan.id) : void 0;
335
+ (0, import_ExecutionSpanService.setOrchestratorTraceContext)(invokeCtx, {
336
+ rootRunId,
337
+ spanId: toolSpanId,
338
+ parentSpanId: executionSpanId,
339
+ toolCallId: `orch-${toolCallId}`,
340
+ leaderUsername,
341
+ employeeUsername: subAgentUsername,
342
+ toolName: toolEntry.definition.name,
343
+ agentLoopRunId,
344
+ agentLoopStepId
345
+ });
346
+ trace.push({
347
+ type: "tool_call",
348
+ at: nowIso(),
349
+ title: `Calling tool: ${toolEntry.definition.name}`,
350
+ toolName: toolEntry.definition.name,
351
+ args: toolArgs
352
+ });
353
+ try {
354
+ const res = await toolEntry.invoke(invokeCtx, toolArgs, `orch-${toolCallId}`);
355
+ const output = trimText((res == null ? void 0 : res.content) ?? (res == null ? void 0 : res.result) ?? res, 5e4);
356
+ trace.push({
357
+ type: "tool_result",
358
+ at: nowIso(),
359
+ title: `Tool finished: ${toolEntry.definition.name}`,
360
+ toolName: toolEntry.definition.name,
361
+ status: (res == null ? void 0 : res.status) || "success",
362
+ content: trimText(output, 2e3)
363
+ });
364
+ if ((res == null ? void 0 : res.status) === "error") {
365
+ await this.spanService.finish(toolSpanId, "error", toolStartedAt, {
366
+ output,
367
+ error: trimText(res.content || output, 1e4)
368
+ });
369
+ throw new Error(`Tool <${toolEntry.definition.name}> failed: ${res.content}`);
370
+ }
371
+ await this.spanService.finish(toolSpanId, "success", toolStartedAt, {
372
+ output,
373
+ skillExecutionId: ((_e2 = res == null ? void 0 : res.result) == null ? void 0 : _e2.execId) || (res == null ? void 0 : res.execId)
374
+ });
375
+ return typeof (res == null ? void 0 : res.content) === "string" ? res.content : JSON.stringify(res);
376
+ } catch (e) {
377
+ trace.push({
378
+ type: "tool_error",
379
+ at: nowIso(),
380
+ title: `Tool failed: ${toolEntry.definition.name}`,
381
+ toolName: toolEntry.definition.name,
382
+ status: "error",
383
+ content: e.message
384
+ });
385
+ await this.spanService.finish(toolSpanId, "error", toolStartedAt, {
386
+ error: trimText(e.message, 1e4)
387
+ });
388
+ throw e;
389
+ }
390
+ }
391
+ })
392
+ );
393
+ }
394
+ const abortController = new AbortController();
395
+ const executor = (0, import_prebuilt.createReactAgent)({
396
+ llm: chatModel,
397
+ tools: langchainTools
398
+ });
399
+ let systemPrompt = ((_f = subAgentEmployee.chatSettings) == null ? void 0 : _f.systemPrompt) || subAgentEmployee.bio || `You are an AI assistant named "${subAgentEmployee.nickname || subAgentUsername}". ${subAgentEmployee.about || ""}`;
400
+ try {
401
+ const kbPlugin = ctx.app.pm.get("plugin-knowledge-base");
402
+ if (kbPlugin == null ? void 0 : kbPlugin.sessionContext) {
403
+ const sessionId = ((_i = (_h = (_g = ctx.action) == null ? void 0 : _g.params) == null ? void 0 : _h.values) == null ? void 0 : _i.sessionId) || ((_k = (_j = ctx.action) == null ? void 0 : _j.params) == null ? void 0 : _k.sessionId) || ((_l = ctx.state) == null ? void 0 : _l.sessionId);
404
+ const contextSummary = await kbPlugin.sessionContext.buildSummary(
405
+ { rootRunId, ...sessionId ? { sessionId } : {} },
406
+ 6e3
407
+ );
408
+ if (contextSummary) {
409
+ systemPrompt += `
410
+
411
+ <shared_context>
412
+ The following context was shared by other agents in this workflow:
413
+ ${contextSummary}
414
+ </shared_context>`;
415
+ }
416
+ }
417
+ } catch {
418
+ }
419
+ const combinedTask = context ? `Task: ${task}
420
+
421
+ Context:
422
+ ${context}` : `Task: ${task}`;
423
+ const effectiveLimit = recursionLimit && recursionLimit > 0 ? recursionLimit : 50;
424
+ let timeoutId;
425
+ const timeoutMs = Number(timeout) > 0 ? Number(timeout) : 12e4;
426
+ const timeoutPromise = new Promise((_, reject) => {
427
+ timeoutId = setTimeout(() => {
428
+ abortController.abort();
429
+ reject(new Error(`Sub-agent execution timed out after ${timeoutMs}ms.`));
430
+ }, timeoutMs);
431
+ });
432
+ const invokePromise = executor.invoke(
433
+ {
434
+ messages: [new import_messages.SystemMessage(systemPrompt), new import_messages.HumanMessage(combinedTask)]
435
+ },
436
+ { recursionLimit: effectiveLimit, signal: abortController.signal }
437
+ );
438
+ let finalState;
439
+ try {
440
+ finalState = await Promise.race([invokePromise, timeoutPromise]);
441
+ } finally {
442
+ if (timeoutId) clearTimeout(timeoutId);
443
+ }
444
+ const messages = (finalState == null ? void 0 : finalState.messages) || [];
445
+ const lastAIMessage = [...messages].reverse().find((m) => m.getType() === "ai");
446
+ let content = "";
447
+ if (lastAIMessage) {
448
+ content = typeof lastAIMessage.content === "string" ? lastAIMessage.content : Array.isArray(lastAIMessage.content) ? lastAIMessage.content.map((c) => c.text || JSON.stringify(c)).join("\n") : String(lastAIMessage.content);
449
+ }
450
+ trace.push({
451
+ type: "finish",
452
+ at: nowIso(),
453
+ title: `Delegation finished: ${subAgentUsername}`,
454
+ status: "success",
455
+ content: trimText(content, 2e3)
456
+ });
457
+ await this.logDelegation(ctx, {
458
+ id: logRecord == null ? void 0 : logRecord.id,
459
+ leaderUsername,
460
+ subAgentUsername,
461
+ toolName,
462
+ task,
463
+ context,
464
+ result: content,
465
+ status: "success",
466
+ depth: maxDepth,
467
+ durationMs: Date.now() - startTime,
468
+ trace
469
+ });
470
+ await this.spanService.finish(executionSpanId, "success", startTime, {
471
+ output: content,
472
+ metadata: {
473
+ depth: currentDepth,
474
+ toolName,
475
+ recursionLimit,
476
+ agentLoopRunId,
477
+ agentLoopStepId
478
+ }
479
+ });
480
+ return {
481
+ status: "success",
482
+ content
483
+ };
484
+ } catch (e) {
485
+ trace.push({
486
+ type: "error",
487
+ at: nowIso(),
488
+ title: `Delegation failed: ${subAgentUsername}`,
489
+ status: "error",
490
+ content: e.message
491
+ });
492
+ await this.logDelegation(ctx, {
493
+ id: logRecord == null ? void 0 : logRecord.id,
494
+ leaderUsername,
495
+ subAgentUsername,
496
+ toolName,
497
+ task,
498
+ context,
499
+ result: "",
500
+ status: "error",
501
+ depth: maxDepth,
502
+ durationMs: Date.now() - startTime,
503
+ error: e.message,
504
+ trace
505
+ });
506
+ await this.spanService.finish(executionSpanId, "error", startTime, {
507
+ error: trimText(e.message, 1e4),
508
+ metadata: {
509
+ depth: currentDepth,
510
+ toolName,
511
+ recursionLimit,
512
+ agentLoopRunId,
513
+ agentLoopStepId
514
+ }
515
+ });
516
+ return {
517
+ status: "error",
518
+ content: e.message
519
+ };
520
+ }
521
+ }
522
+ async logDelegation(ctx, data) {
523
+ var _a, _b, _c, _d;
524
+ try {
525
+ const logsRepo = this.db.getRepository("orchestratorLogs");
526
+ if (!logsRepo) return null;
527
+ const userId = ((_b = (_a = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) || ((_d = (_c = ctx == null ? void 0 : ctx.state) == null ? void 0 : _c.currentUser) == null ? void 0 : _d.id);
528
+ const values = {
529
+ leaderUsername: data.leaderUsername,
530
+ subAgentUsername: data.subAgentUsername,
531
+ toolName: data.toolName,
532
+ task: trimText(data.task, 1e4),
533
+ context: trimText(data.context || "", 1e4),
534
+ result: trimText(data.result || "", 5e4),
535
+ status: data.status,
536
+ depth: data.depth,
537
+ durationMs: data.durationMs,
538
+ error: trimText(data.error || "", 1e4),
539
+ trace: data.trace || [],
540
+ userId,
541
+ updatedAt: /* @__PURE__ */ new Date()
542
+ };
543
+ if (data.id) {
544
+ await logsRepo.update({
545
+ filterByTk: data.id,
546
+ values
547
+ });
548
+ return { id: data.id };
549
+ }
550
+ const record = await logsRepo.create({
551
+ values: {
552
+ ...values,
553
+ createdAt: /* @__PURE__ */ new Date()
554
+ }
555
+ });
556
+ return toPlain(record);
557
+ } catch {
558
+ return null;
559
+ }
560
+ }
561
+ }
562
+ // Annotate the CommonJS export names for ESM import in node:
563
+ 0 && (module.exports = {
564
+ AgentHarness
565
+ });