plugin-agent-orchestrator 1.0.27 → 1.0.32

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