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.
- package/README.md +9 -7
- package/dist/client/index.js +1 -1
- package/dist/client-v2/{214.723affb37c13bf7a.js → 214.79650a549273f163.js} +1 -1
- package/dist/client-v2/264.718a107e43fc163c.js +10 -0
- package/dist/client-v2/373.f5d5292e53c4e832.js +10 -0
- package/dist/client-v2/{41.1805b2edfaa4afe2.js → 41.ba6e080cc0488143.js} +1 -1
- package/dist/client-v2/418.29e713f79131eece.js +10 -0
- package/dist/client-v2/619.bd3c5698b40705c3.js +10 -0
- package/dist/client-v2/677.a991ce0250ff5c77.js +10 -0
- package/dist/client-v2/{70.a15d7fcec7c41768.js → 70.bda9518881c05360.js} +1 -1
- package/dist/client-v2/925.f5370de8f6632d65.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +7 -10
- package/dist/locale/en-US.json +94 -25
- package/dist/locale/vi-VN.json +94 -25
- package/dist/locale/zh-CN.json +94 -25
- package/dist/server/collections/agent-execution-spans.js +37 -0
- package/dist/server/collections/agent-harness-profiles.js +2 -2
- package/dist/server/collections/agent-memory-contexts.js +125 -0
- package/dist/server/collections/orchestrator-logs.js +2 -2
- package/dist/server/migrations/20260425000000-add-interaction-schema.js +3 -1
- package/dist/server/migrations/20260427000000-change-packages-to-text.js +3 -1
- package/dist/server/migrations/20260427000001-change-other-json-to-text.js +6 -2
- package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.js +21 -19
- package/dist/server/migrations/20260621000000-native-policy-profile-defaults.js +193 -0
- package/dist/server/plugin.js +128 -74
- package/dist/server/resources/agent-monitor.js +454 -0
- package/dist/server/services/AgentHarness.js +24 -499
- package/dist/server/services/AgentMemoryContextService.js +216 -0
- package/dist/server/services/ExecutionSpanService.js +2 -2
- package/dist/server/services/NativeSubAgentObserver.js +413 -0
- package/dist/server/skill-hub/mcp/McpController.js +16 -5
- package/dist/server/skill-hub/plugin.js +81 -5
- package/dist/server/skill-hub/tasks/SkillExecutionTask.js +9 -3
- package/dist/server/tools/delegate-task.js +11 -589
- package/dist/server/utils/skill-settings.js +18 -1
- package/package.json +47 -49
- package/src/client/AIEmployeesContext.tsx +5 -18
- package/src/client/AgentRunsTab.tsx +2 -771
- package/src/client/HarnessProfilesTab.tsx +2 -257
- package/src/client/OrchestratorSettings.tsx +97 -106
- package/src/client/RulesTab.tsx +2 -788
- package/src/client/plugin.tsx +0 -2
- package/src/client/skill-hub/components/ExecutionHistory.tsx +200 -202
- package/src/client/skill-hub/components/ExecutionProgress.tsx +51 -55
- package/src/client/skill-hub/components/LoopSettings.tsx +331 -331
- package/src/client/skill-hub/components/SkillEditor.tsx +43 -39
- package/src/client/skill-hub/components/SkillManager.tsx +194 -181
- package/src/client/skill-hub/components/SkillTestPanel.tsx +141 -145
- package/src/client/skill-hub/locale.ts +16 -16
- package/src/client/skill-hub/tools/SkillHubCard.tsx +104 -109
- package/src/client/skill-hub/tools/loopTemplates.ts +52 -52
- package/src/client/skill-hub/utils/jsonFields.ts +7 -3
- package/src/client-v2/components/AIEmployeesContext.tsx +3 -16
- package/src/client-v2/components/AgentRunsTab.tsx +182 -455
- package/src/client-v2/components/HarnessProfilesTab.tsx +34 -31
- package/src/client-v2/components/RulesTab.tsx +2 -782
- package/src/client-v2/components/TracingTab.tsx +1 -1
- package/src/client-v2/hooks/useApiRequest.ts +8 -1
- package/src/client-v2/pages/RulesPage.tsx +2 -2
- package/src/client-v2/plugin.tsx +3 -3
- package/src/locale/en-US.json +94 -25
- package/src/locale/vi-VN.json +94 -25
- package/src/locale/zh-CN.json +94 -25
- package/src/server/__tests__/native-sub-agent-observer.test.ts +246 -0
- package/src/server/__tests__/skill-settings.test.ts +6 -6
- package/src/server/__tests__/smoke.test.ts +1 -0
- package/src/server/collections/agent-execution-spans.ts +37 -0
- package/src/server/collections/agent-harness-profiles.ts +59 -59
- package/src/server/collections/agent-loop-events.ts +71 -71
- package/src/server/collections/agent-loop-steps.ts +144 -144
- package/src/server/collections/agent-memory-contexts.ts +95 -0
- package/src/server/collections/orchestrator-logs.ts +4 -4
- package/src/server/collections/skill-definitions.ts +111 -111
- package/src/server/collections/skill-executions.ts +106 -106
- package/src/server/collections/skill-loop-configs.ts +65 -65
- package/src/server/migrations/20260423000000-add-progress-fields.ts +14 -14
- package/src/server/migrations/20260425000000-add-interaction-schema.ts +3 -1
- package/src/server/migrations/20260427000000-change-packages-to-text.ts +4 -2
- package/src/server/migrations/20260427000001-change-other-json-to-text.ts +9 -5
- package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +30 -30
- package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +145 -142
- package/src/server/migrations/20260615000000-normalize-ai-employee-tool-bindings.ts +2 -2
- package/src/server/migrations/20260621000000-native-policy-profile-defaults.ts +193 -0
- package/src/server/plugin.ts +151 -94
- package/src/server/resources/agent-monitor.ts +482 -0
- package/src/server/services/AgentHarness.ts +38 -623
- package/src/server/services/AgentMemoryContextService.ts +256 -0
- package/src/server/services/AgentPlanValidator.ts +73 -73
- package/src/server/services/ExecutionSpanService.ts +6 -2
- package/src/server/services/FileManager.ts +144 -144
- package/src/server/services/NativeSubAgentObserver.ts +507 -0
- package/src/server/services/SkillManager.ts +583 -583
- package/src/server/services/SkillRepositoryService.ts +5 -7
- package/src/server/services/TokenTracker.ts +3 -3
- package/src/server/services/WorkerEnvManager.ts +1 -2
- package/src/server/skill-hub/actions/git-import.ts +5 -7
- package/src/server/skill-hub/mcp/McpController.ts +41 -14
- package/src/server/skill-hub/plugin.ts +89 -6
- package/src/server/skill-hub/tasks/SkillExecutionTask.ts +470 -460
- package/src/server/skill-hub/utils/json-fields.ts +1 -1
- package/src/server/tools/delegate-task.ts +13 -847
- package/src/server/utils/skill-settings.ts +24 -6
- package/dist/client-v2/264.0533912e6c5ea2d7.js +0 -10
- package/dist/client-v2/418.5ae055abf141820e.js +0 -10
- package/dist/client-v2/619.d99d3c9e61c99064.js +0 -10
- package/dist/client-v2/892.72db4161511c8a16.js +0 -10
- package/dist/client-v2/926.87f660b670d85bcc.js +0 -10
- package/src/client/tools/PlanApprovalCard.tsx +0 -176
- package/src/client/tools/registerOrchestratorCards.ts +0 -17
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
import { createHash } from 'crypto';
|
|
2
|
+
import { ExecutionSpanService } from './ExecutionSpanService';
|
|
3
|
+
import { AgentMemoryContextService } from './AgentMemoryContextService';
|
|
4
|
+
import { asObject, currentUserId, toPlain, trimText } from '../utils/ctx-utils';
|
|
5
|
+
|
|
6
|
+
const WRAP_STATE_KEY = Symbol.for('plugin-agent-orchestrator.nativeSubAgentObserver');
|
|
7
|
+
const NATIVE_SOURCE = 'native-plugin-ai';
|
|
8
|
+
|
|
9
|
+
type NativeWriter = (chunk: Record<string, unknown>) => unknown;
|
|
10
|
+
|
|
11
|
+
type NativeSubAgentTask = {
|
|
12
|
+
ctx: {
|
|
13
|
+
action?: { params?: { values?: Record<string, unknown> } };
|
|
14
|
+
auth?: { user?: { id?: string | number } };
|
|
15
|
+
db?: { getRepository?: (name: string) => unknown };
|
|
16
|
+
app?: unknown;
|
|
17
|
+
};
|
|
18
|
+
sessionId: string;
|
|
19
|
+
employee: unknown;
|
|
20
|
+
model?: unknown;
|
|
21
|
+
question: string;
|
|
22
|
+
skillSettings?: Record<string, unknown>;
|
|
23
|
+
writer?: NativeWriter;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
type DispatchToolMessage = {
|
|
27
|
+
id?: string | number;
|
|
28
|
+
messageId?: string | number;
|
|
29
|
+
toolCallId?: string;
|
|
30
|
+
sessionId?: string;
|
|
31
|
+
status?: string;
|
|
32
|
+
invokeStatus?: string;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
type SpanRecord = {
|
|
36
|
+
id?: string | number;
|
|
37
|
+
rootRunId?: string;
|
|
38
|
+
metadata?: Record<string, unknown>;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
type ToolSpanState = {
|
|
42
|
+
spanId?: string | number;
|
|
43
|
+
startedAt: number;
|
|
44
|
+
ready: Promise<void>;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
type RunState = {
|
|
48
|
+
rootRunId: string;
|
|
49
|
+
rootSpanId?: string | number;
|
|
50
|
+
rootStartedAt: number;
|
|
51
|
+
rootMetadata: Record<string, unknown>;
|
|
52
|
+
parentSessionId?: string;
|
|
53
|
+
subSessionId?: string;
|
|
54
|
+
toolCallId?: string;
|
|
55
|
+
leaderUsername?: string;
|
|
56
|
+
employeeUsername?: string;
|
|
57
|
+
userId?: string | number;
|
|
58
|
+
toolSpans: Map<string, ToolSpanState>;
|
|
59
|
+
pending: Set<Promise<void>>;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
type DispatcherWithRun = {
|
|
63
|
+
run: (task: NativeSubAgentTask) => Promise<string>;
|
|
64
|
+
[WRAP_STATE_KEY]?: {
|
|
65
|
+
originalRun: (task: NativeSubAgentTask) => Promise<string>;
|
|
66
|
+
wrappedRun: (task: NativeSubAgentTask) => Promise<string>;
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
function readValue(record: unknown, key: string) {
|
|
71
|
+
const model = record as { get?: (name: string) => unknown; [key: string]: unknown };
|
|
72
|
+
return typeof model?.get === 'function' ? model.get(key) : model?.[key];
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function normalizeString(value: unknown) {
|
|
76
|
+
return typeof value === 'string' ? value.trim() : '';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function modelUsername(model: unknown) {
|
|
80
|
+
return (
|
|
81
|
+
normalizeString(readValue(model, 'username')) ||
|
|
82
|
+
normalizeString(readValue(model, 'aiEmployeeUsername')) ||
|
|
83
|
+
normalizeString(readValue(model, 'name')) ||
|
|
84
|
+
undefined
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function makeNativeRunId(parts: Array<string | number | undefined>) {
|
|
89
|
+
const source = parts.map((part) => String(part || '')).join('|');
|
|
90
|
+
return `native_${createHash('sha1')
|
|
91
|
+
.update(source || String(Date.now()))
|
|
92
|
+
.digest('hex')
|
|
93
|
+
.slice(0, 24)}`;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function errorMessage(error: unknown) {
|
|
97
|
+
return error instanceof Error ? error.message : String(error || 'Unknown error');
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function chunkBody(chunk: Record<string, unknown>) {
|
|
101
|
+
return asObject(chunk.body);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function chunkCurrentConversation(chunk: Record<string, unknown>) {
|
|
105
|
+
return asObject(chunk.currentConversation);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export class NativeSubAgentObserver {
|
|
109
|
+
private readonly spanService: ExecutionSpanService;
|
|
110
|
+
private readonly memoryService: AgentMemoryContextService;
|
|
111
|
+
|
|
112
|
+
constructor(private readonly plugin: { app: any; db: any; name?: string }) {
|
|
113
|
+
this.spanService = new ExecutionSpanService(plugin);
|
|
114
|
+
this.memoryService = new AgentMemoryContextService(plugin);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
install() {
|
|
118
|
+
const aiPlugin = this.plugin.app.pm?.get?.('ai');
|
|
119
|
+
const dispatcher = aiPlugin?.subAgentsDispatcher as DispatcherWithRun | undefined;
|
|
120
|
+
if (!dispatcher?.run) {
|
|
121
|
+
this.plugin.app.logger?.warn?.(
|
|
122
|
+
'[AgentOrchestrator] plugin-ai subAgentsDispatcher not available; observer skipped.',
|
|
123
|
+
);
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const existing = dispatcher[WRAP_STATE_KEY];
|
|
128
|
+
if (existing?.wrappedRun === dispatcher.run) {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const originalRun = existing?.originalRun || dispatcher.run.bind(dispatcher);
|
|
133
|
+
const observer = this;
|
|
134
|
+
const wrappedRun = async function wrappedNativeSubAgentRun(task: NativeSubAgentTask) {
|
|
135
|
+
return observer.runObserved(originalRun, task);
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
dispatcher.run = wrappedRun;
|
|
139
|
+
dispatcher[WRAP_STATE_KEY] = {
|
|
140
|
+
originalRun,
|
|
141
|
+
wrappedRun,
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
this.plugin.app.logger?.info?.('[AgentOrchestrator] Native plugin-ai sub-agent observer installed.');
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
uninstall() {
|
|
149
|
+
const aiPlugin = this.plugin.app.pm?.get?.('ai');
|
|
150
|
+
const dispatcher = aiPlugin?.subAgentsDispatcher as DispatcherWithRun | undefined;
|
|
151
|
+
const existing = dispatcher?.[WRAP_STATE_KEY];
|
|
152
|
+
if (!dispatcher?.run || !existing || existing.wrappedRun !== dispatcher.run) {
|
|
153
|
+
return false;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
dispatcher.run = existing.originalRun;
|
|
157
|
+
delete dispatcher[WRAP_STATE_KEY];
|
|
158
|
+
this.plugin.app.logger?.info?.('[AgentOrchestrator] Native plugin-ai sub-agent observer uninstalled.');
|
|
159
|
+
return true;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private async runObserved(originalRun: (task: NativeSubAgentTask) => Promise<string>, task: NativeSubAgentTask) {
|
|
163
|
+
const settings = await this.safeResolvePolicy(task);
|
|
164
|
+
if (settings.nativeObserverEnabled === false) {
|
|
165
|
+
return originalRun(task);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const parentSessionId = this.resolveParentSessionId(task) || undefined;
|
|
169
|
+
const subSessionId = normalizeString(task.sessionId) || undefined;
|
|
170
|
+
const employeeUsername = modelUsername(task.employee);
|
|
171
|
+
const userId = currentUserId(task.ctx) || task.ctx?.auth?.user?.id;
|
|
172
|
+
const dispatchToolMessage = await this.resolveDispatchToolMessage(task.ctx, parentSessionId, subSessionId);
|
|
173
|
+
const toolCallId = dispatchToolMessage?.toolCallId;
|
|
174
|
+
const leaderUsername = await this.resolveLeaderUsername(task.ctx, parentSessionId);
|
|
175
|
+
const rootRunId = makeNativeRunId([parentSessionId, subSessionId, toolCallId, employeeUsername]);
|
|
176
|
+
const memory = await this.safeBuildMemoryContext({
|
|
177
|
+
userId,
|
|
178
|
+
aiEmployeeUsername: employeeUsername,
|
|
179
|
+
settings,
|
|
180
|
+
});
|
|
181
|
+
const observedTask = memory.context
|
|
182
|
+
? {
|
|
183
|
+
...task,
|
|
184
|
+
question: `${task.question}\n\n${memory.context}`,
|
|
185
|
+
}
|
|
186
|
+
: task;
|
|
187
|
+
|
|
188
|
+
const state: RunState = {
|
|
189
|
+
rootRunId,
|
|
190
|
+
rootStartedAt: Date.now(),
|
|
191
|
+
rootMetadata: {
|
|
192
|
+
source: NATIVE_SOURCE,
|
|
193
|
+
parentSessionId,
|
|
194
|
+
subSessionId,
|
|
195
|
+
toolCallId,
|
|
196
|
+
dispatchToolMessageId: dispatchToolMessage?.id,
|
|
197
|
+
dispatchMessageId: dispatchToolMessage?.messageId,
|
|
198
|
+
memoryContextApplied: Boolean(memory.context),
|
|
199
|
+
memoryScopes: memory.appliedScopes,
|
|
200
|
+
memoryContextChars: memory.chars,
|
|
201
|
+
harnessTag: settings.harnessTag || 'default',
|
|
202
|
+
},
|
|
203
|
+
parentSessionId,
|
|
204
|
+
subSessionId,
|
|
205
|
+
toolCallId,
|
|
206
|
+
leaderUsername,
|
|
207
|
+
employeeUsername,
|
|
208
|
+
userId,
|
|
209
|
+
toolSpans: new Map(),
|
|
210
|
+
pending: new Set(),
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
await this.safeCreateRootSpan(state, task.question);
|
|
214
|
+
|
|
215
|
+
const originalWriter = task.writer;
|
|
216
|
+
observedTask.writer = (chunk: Record<string, unknown>) => {
|
|
217
|
+
const pending = this.handleWriterChunk(state, chunk).catch((error) => {
|
|
218
|
+
this.plugin.app.logger?.warn?.('[AgentOrchestrator] Native writer observer failed', error);
|
|
219
|
+
});
|
|
220
|
+
state.pending.add(pending);
|
|
221
|
+
return originalWriter?.(chunk);
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
const result = await originalRun(observedTask);
|
|
226
|
+
await this.flushPending(state);
|
|
227
|
+
await this.spanService.finish(state.rootSpanId, 'success', state.rootStartedAt, {
|
|
228
|
+
output: trimText(result, 20000),
|
|
229
|
+
metadata: {
|
|
230
|
+
...state.rootMetadata,
|
|
231
|
+
completedAt: new Date().toISOString(),
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
return result;
|
|
235
|
+
} catch (error) {
|
|
236
|
+
await this.flushPending(state);
|
|
237
|
+
await this.spanService.finish(state.rootSpanId, 'error', state.rootStartedAt, {
|
|
238
|
+
error: trimText(errorMessage(error), 10000),
|
|
239
|
+
metadata: {
|
|
240
|
+
...state.rootMetadata,
|
|
241
|
+
failedAt: new Date().toISOString(),
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
private async safeResolvePolicy(task: NativeSubAgentTask) {
|
|
249
|
+
try {
|
|
250
|
+
return await this.memoryService.resolvePolicySettings(task);
|
|
251
|
+
} catch (error) {
|
|
252
|
+
this.plugin.app.logger?.warn?.('[AgentOrchestrator] Failed to resolve native observer policy', error);
|
|
253
|
+
return { harnessTag: 'default' };
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private async safeBuildMemoryContext(options: {
|
|
258
|
+
userId?: string | number;
|
|
259
|
+
aiEmployeeUsername?: string;
|
|
260
|
+
settings: Record<string, unknown>;
|
|
261
|
+
}) {
|
|
262
|
+
try {
|
|
263
|
+
return await this.memoryService.buildContext(options);
|
|
264
|
+
} catch (error) {
|
|
265
|
+
this.plugin.app.logger?.warn?.('[AgentOrchestrator] Failed to build agent memory context', error);
|
|
266
|
+
return { context: '', appliedScopes: [] as string[], chars: 0 };
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
private async safeCreateRootSpan(state: RunState, question: string) {
|
|
271
|
+
const span = (await this.spanService.create({
|
|
272
|
+
rootRunId: state.rootRunId,
|
|
273
|
+
parentSpanId: undefined,
|
|
274
|
+
source: NATIVE_SOURCE,
|
|
275
|
+
parentSessionId: state.parentSessionId,
|
|
276
|
+
subSessionId: state.subSessionId,
|
|
277
|
+
toolCallId: state.toolCallId,
|
|
278
|
+
type: 'sub_agent',
|
|
279
|
+
status: 'running',
|
|
280
|
+
leaderUsername: state.leaderUsername,
|
|
281
|
+
employeeUsername: state.employeeUsername,
|
|
282
|
+
toolName: 'dispatch-sub-agent-task',
|
|
283
|
+
title: `${state.leaderUsername || 'main'} -> ${state.employeeUsername || 'sub-agent'}`,
|
|
284
|
+
input: {
|
|
285
|
+
question,
|
|
286
|
+
parentSessionId: state.parentSessionId,
|
|
287
|
+
subSessionId: state.subSessionId,
|
|
288
|
+
},
|
|
289
|
+
metadata: state.rootMetadata,
|
|
290
|
+
userId: state.userId,
|
|
291
|
+
})) as SpanRecord | null;
|
|
292
|
+
|
|
293
|
+
state.rootSpanId = span?.id;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
private async handleWriterChunk(state: RunState, chunk: Record<string, unknown>) {
|
|
297
|
+
const action = chunk.action;
|
|
298
|
+
if (action === 'beforeToolCall') {
|
|
299
|
+
await this.handleBeforeToolCall(state, chunk);
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (action === 'afterToolCall') {
|
|
303
|
+
await this.handleAfterToolCall(state, chunk, false);
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (action === 'afterToolCallError') {
|
|
307
|
+
await this.handleAfterToolCall(state, chunk, true);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
if (action === 'afterSubAgentInvoke') {
|
|
311
|
+
state.rootMetadata = {
|
|
312
|
+
...state.rootMetadata,
|
|
313
|
+
afterSubAgentInvokeAt: new Date().toISOString(),
|
|
314
|
+
};
|
|
315
|
+
await this.spanService.update(state.rootSpanId, { metadata: state.rootMetadata });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private async handleBeforeToolCall(state: RunState, chunk: Record<string, unknown>) {
|
|
320
|
+
const body = chunkBody(chunk);
|
|
321
|
+
const toolCall = asObject(body.toolCall);
|
|
322
|
+
const toolCallId = normalizeString(toolCall.id);
|
|
323
|
+
if (!toolCallId || state.toolSpans.has(toolCallId)) return;
|
|
324
|
+
|
|
325
|
+
const conversation = chunkCurrentConversation(chunk);
|
|
326
|
+
const startedAt = Date.now();
|
|
327
|
+
const toolSpan: ToolSpanState = {
|
|
328
|
+
startedAt,
|
|
329
|
+
ready: Promise.resolve(),
|
|
330
|
+
};
|
|
331
|
+
state.toolSpans.set(toolCallId, toolSpan);
|
|
332
|
+
|
|
333
|
+
toolSpan.ready = this.spanService
|
|
334
|
+
.create({
|
|
335
|
+
rootRunId: state.rootRunId,
|
|
336
|
+
parentSpanId: state.rootSpanId ? String(state.rootSpanId) : undefined,
|
|
337
|
+
source: NATIVE_SOURCE,
|
|
338
|
+
parentSessionId: state.parentSessionId || undefined,
|
|
339
|
+
subSessionId: normalizeString(conversation.sessionId) || state.subSessionId || undefined,
|
|
340
|
+
toolCallId,
|
|
341
|
+
type: normalizeString(toolCall.name) === 'dispatch-sub-agent-task' ? 'dispatch' : 'tool',
|
|
342
|
+
status: 'running',
|
|
343
|
+
leaderUsername: state.leaderUsername,
|
|
344
|
+
employeeUsername: normalizeString(conversation.username) || state.employeeUsername,
|
|
345
|
+
toolName: normalizeString(toolCall.name),
|
|
346
|
+
title: normalizeString(toolCall.name) || 'tool call',
|
|
347
|
+
input: asObject(toolCall.args),
|
|
348
|
+
metadata: {
|
|
349
|
+
source: NATIVE_SOURCE,
|
|
350
|
+
currentConversation: conversation,
|
|
351
|
+
messageId: toolCall.messageId,
|
|
352
|
+
},
|
|
353
|
+
userId: state.userId,
|
|
354
|
+
})
|
|
355
|
+
.then((span) => {
|
|
356
|
+
toolSpan.spanId = (span as SpanRecord | null)?.id;
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
await toolSpan.ready;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private async handleAfterToolCall(state: RunState, chunk: Record<string, unknown>, forceError: boolean) {
|
|
363
|
+
const body = chunkBody(chunk);
|
|
364
|
+
const toolCall = asObject(body.toolCall);
|
|
365
|
+
const toolCallId = normalizeString(toolCall.id);
|
|
366
|
+
const existing = toolCallId ? state.toolSpans.get(toolCallId) : undefined;
|
|
367
|
+
if (!existing) return;
|
|
368
|
+
await existing.ready;
|
|
369
|
+
|
|
370
|
+
const result = asObject(toPlain(body.toolCallResult));
|
|
371
|
+
const error = body.error;
|
|
372
|
+
const status = forceError || result.status === 'error' ? 'error' : 'success';
|
|
373
|
+
const output = result.content ?? result.result ?? result;
|
|
374
|
+
const invokeStart = Number(result.invokeStartTime);
|
|
375
|
+
const invokeEnd = Number(result.invokeEndTime);
|
|
376
|
+
const durationMs =
|
|
377
|
+
Number.isFinite(invokeStart) && Number.isFinite(invokeEnd) && invokeEnd >= invokeStart
|
|
378
|
+
? invokeEnd - invokeStart
|
|
379
|
+
: Date.now() - existing.startedAt;
|
|
380
|
+
|
|
381
|
+
await this.spanService.update(existing.spanId, {
|
|
382
|
+
status,
|
|
383
|
+
endedAt: new Date(),
|
|
384
|
+
durationMs,
|
|
385
|
+
output: forceError ? undefined : trimText(output, 20000),
|
|
386
|
+
error: forceError ? trimText(errorMessage(error), 10000) : undefined,
|
|
387
|
+
metadata: {
|
|
388
|
+
source: NATIVE_SOURCE,
|
|
389
|
+
toolCallResultStatus: result.status,
|
|
390
|
+
invokeStatus: result.invokeStatus,
|
|
391
|
+
messageId: toolCall.messageId,
|
|
392
|
+
},
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
private resolveParentSessionId(task: NativeSubAgentTask) {
|
|
397
|
+
const values = task.ctx?.action?.params?.values || {};
|
|
398
|
+
return normalizeString(values.sessionId) || undefined;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
private async resolveLeaderUsername(ctx: NativeSubAgentTask['ctx'], parentSessionId?: string) {
|
|
402
|
+
const values = ctx?.action?.params?.values || {};
|
|
403
|
+
const direct =
|
|
404
|
+
normalizeString(values.aiEmployeeUsername) ||
|
|
405
|
+
normalizeString((asObject(values.aiEmployee) as Record<string, unknown>).username);
|
|
406
|
+
if (direct) return direct;
|
|
407
|
+
if (!parentSessionId) return undefined;
|
|
408
|
+
|
|
409
|
+
try {
|
|
410
|
+
const repo = ctx.db?.getRepository?.('aiConversations') as
|
|
411
|
+
| { findOne?: (options: Record<string, unknown>) => Promise<unknown> }
|
|
412
|
+
| undefined;
|
|
413
|
+
const conversation = await repo?.findOne?.({
|
|
414
|
+
filter: { sessionId: parentSessionId },
|
|
415
|
+
});
|
|
416
|
+
return normalizeString(readValue(conversation, 'aiEmployeeUsername')) || undefined;
|
|
417
|
+
} catch {
|
|
418
|
+
return undefined;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
private async resolveDispatchToolMessage(
|
|
423
|
+
ctx: NativeSubAgentTask['ctx'],
|
|
424
|
+
parentSessionId?: string,
|
|
425
|
+
subSessionId?: string,
|
|
426
|
+
) {
|
|
427
|
+
if (!parentSessionId) return null;
|
|
428
|
+
try {
|
|
429
|
+
const fromMetadata = await this.resolveDispatchToolMessageFromMetadata(ctx, parentSessionId, subSessionId);
|
|
430
|
+
if (fromMetadata) {
|
|
431
|
+
return fromMetadata;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
const repo = ctx.db?.getRepository?.('aiToolMessages') as
|
|
435
|
+
| { findOne?: (options: Record<string, unknown>) => Promise<unknown> }
|
|
436
|
+
| undefined;
|
|
437
|
+
const record = await repo?.findOne?.({
|
|
438
|
+
filter: {
|
|
439
|
+
sessionId: parentSessionId,
|
|
440
|
+
toolName: 'dispatch-sub-agent-task',
|
|
441
|
+
invokeStatus: {
|
|
442
|
+
$ne: 'confirmed',
|
|
443
|
+
},
|
|
444
|
+
},
|
|
445
|
+
sort: ['-id'],
|
|
446
|
+
});
|
|
447
|
+
return toPlain(record) as DispatchToolMessage | null;
|
|
448
|
+
} catch {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private async resolveDispatchToolMessageFromMetadata(
|
|
454
|
+
ctx: NativeSubAgentTask['ctx'],
|
|
455
|
+
parentSessionId?: string,
|
|
456
|
+
subSessionId?: string,
|
|
457
|
+
) {
|
|
458
|
+
if (!parentSessionId || !subSessionId) return null;
|
|
459
|
+
|
|
460
|
+
const messageRepo = ctx.db?.getRepository?.('aiMessages') as
|
|
461
|
+
| { find?: (options: Record<string, unknown>) => Promise<unknown[]> }
|
|
462
|
+
| undefined;
|
|
463
|
+
const toolRepo = ctx.db?.getRepository?.('aiToolMessages') as
|
|
464
|
+
| { findOne?: (options: Record<string, unknown>) => Promise<unknown> }
|
|
465
|
+
| undefined;
|
|
466
|
+
const messages = await messageRepo?.find?.({
|
|
467
|
+
filter: { sessionId: parentSessionId },
|
|
468
|
+
sort: ['-messageId'],
|
|
469
|
+
limit: 20,
|
|
470
|
+
});
|
|
471
|
+
if (!Array.isArray(messages)) return null;
|
|
472
|
+
|
|
473
|
+
for (const rawMessage of messages) {
|
|
474
|
+
const message = toPlain(rawMessage);
|
|
475
|
+
const conversations = asObject(message?.metadata).subAgentConversations;
|
|
476
|
+
if (!Array.isArray(conversations)) continue;
|
|
477
|
+
|
|
478
|
+
const matched = conversations.find((item) => normalizeString(item?.sessionId) === subSessionId);
|
|
479
|
+
const toolCallId = normalizeString(matched?.toolCallId);
|
|
480
|
+
if (!toolCallId) continue;
|
|
481
|
+
|
|
482
|
+
const toolMessage = await toolRepo?.findOne?.({
|
|
483
|
+
filter: {
|
|
484
|
+
sessionId: parentSessionId,
|
|
485
|
+
toolCallId,
|
|
486
|
+
},
|
|
487
|
+
});
|
|
488
|
+
return {
|
|
489
|
+
...(toPlain(toolMessage) || {}),
|
|
490
|
+
toolCallId,
|
|
491
|
+
messageId: readValue(toolMessage, 'messageId') || message?.messageId,
|
|
492
|
+
sessionId: parentSessionId,
|
|
493
|
+
status: matched?.status,
|
|
494
|
+
} as DispatchToolMessage;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
private async flushPending(state: RunState) {
|
|
501
|
+
const pending = Array.from(state.pending);
|
|
502
|
+
if (!pending.length) return;
|
|
503
|
+
await Promise.allSettled(pending);
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export { NATIVE_SOURCE, makeNativeRunId };
|