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