plugin-agent-orchestrator 1.1.3 → 1.1.5
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 +204 -114
- package/dist/client/index.js +1 -1
- package/dist/client-v2/117.7565cff57c39318a.js +10 -0
- package/dist/client-v2/214.106635011859dede.js +10 -0
- package/dist/client-v2/253.59577b40d9875be0.js +10 -0
- package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
- package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
- package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
- package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
- package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
- package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
- package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
- package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
- package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +8 -7
- package/dist/locale/en-US.json +199 -123
- package/dist/locale/vi-VN.json +199 -123
- package/dist/locale/zh-CN.json +199 -123
- package/dist/server/collections/agent-execution-spans.js +55 -0
- package/dist/server/collections/agent-harness-profile-versions.js +56 -0
- package/dist/server/collections/agent-harness-profiles.js +12 -0
- package/dist/server/collections/agent-loop-action-approvals.js +69 -0
- package/dist/server/collections/agent-loop-artifacts.js +55 -0
- package/dist/server/collections/agent-loop-circuit-states.js +53 -0
- package/dist/server/collections/agent-loop-control-settings.js +51 -0
- package/dist/server/collections/agent-loop-events.js +27 -0
- package/dist/server/collections/agent-loop-path-locks.js +57 -0
- package/dist/server/collections/agent-loop-patterns.js +72 -0
- package/dist/server/collections/agent-loop-runs.js +170 -3
- package/dist/server/collections/agent-loop-steps.js +76 -0
- package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
- package/dist/server/collections/agent-loop-worktrees.js +55 -0
- package/dist/server/collections/skill-executions.js +8 -0
- package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
- package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
- package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
- package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
- package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
- package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
- package/dist/server/plugin.js +54 -150
- package/dist/server/resources/agent-harness-profile.js +117 -0
- package/dist/server/resources/agent-knowledge-insights.js +1 -3
- package/dist/server/resources/agent-loop-approval.js +108 -0
- package/dist/server/resources/agent-loop-artifact.js +86 -0
- package/dist/server/resources/agent-loop-events-stream.js +130 -0
- package/dist/server/resources/agent-loop.js +183 -139
- package/dist/server/resources/resource-helpers.js +63 -0
- package/dist/server/resources/tracing.js +121 -107
- package/dist/server/services/AgentMemoryContextService.js +34 -0
- package/dist/server/services/DurableCircuitBreakerService.js +229 -0
- package/dist/server/services/HarnessCompiler.js +175 -0
- package/dist/server/services/HarnessProfileService.js +233 -0
- package/dist/server/services/HarnessSchema.js +194 -0
- package/dist/server/services/LoopBudgetService.js +269 -0
- package/dist/server/services/LoopControlService.js +139 -0
- package/dist/server/services/LoopPatternSchema.js +195 -0
- package/dist/server/services/LoopPatternService.js +132 -0
- package/dist/server/services/LoopRunRepository.js +285 -0
- package/dist/server/services/LoopRunStateMachine.js +478 -0
- package/dist/server/services/LoopSchedulerService.js +193 -0
- package/dist/server/services/LoopTriggerService.js +165 -0
- package/dist/server/services/LoopWorkerService.js +699 -0
- package/dist/server/services/NativeSubAgentObserver.js +165 -23
- package/dist/server/services/PathLockService.js +288 -0
- package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
- package/dist/server/services/ToolLoopDetectionService.js +210 -0
- package/dist/server/services/VerificationSchema.js +59 -0
- package/dist/server/services/VerificationService.js +235 -0
- package/dist/server/services/harness-runtime-policy.js +139 -0
- package/dist/server/skill-hub/actions/git-import.js +13 -7
- package/dist/server/skill-hub/plugin.js +36 -3
- package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
- package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
- package/dist/server/utils/ensure-indexes.js +111 -0
- package/dist/server/utils/loop-pattern-context.js +56 -0
- package/package.json +53 -53
- package/src/client/ApprovalsTab.tsx +2 -0
- package/src/client/OrchestratorSettings.tsx +55 -0
- package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
- package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
- package/src/client/skill-hub/index.tsx +0 -52
- package/src/client-v2/components/AgentRunsTab.tsx +100 -18
- package/src/client-v2/components/ApprovalsTab.tsx +337 -0
- package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
- package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
- package/src/client-v2/components/TracingTab.tsx +160 -77
- package/src/client-v2/hooks/useApiRequest.ts +28 -8
- package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
- package/src/client-v2/plugin.tsx +6 -6
- package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
- package/src/locale/en-US.json +199 -123
- package/src/locale/vi-VN.json +199 -123
- package/src/locale/zh-CN.json +199 -123
- package/src/server/__tests__/circuit-breaker.test.ts +248 -169
- package/src/server/__tests__/harness-compiler.test.ts +214 -0
- package/src/server/__tests__/harness-profile-service.test.ts +167 -0
- package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
- package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
- package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
- package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
- package/src/server/__tests__/loop-budget-service.test.ts +255 -0
- package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
- package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
- package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
- package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
- package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
- package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
- package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
- package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
- package/src/server/__tests__/path-lock-service.test.ts +254 -0
- package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
- package/src/server/__tests__/smoke.test.ts +162 -121
- package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
- package/src/server/collections/agent-execution-spans.ts +55 -0
- package/src/server/collections/agent-harness-profile-versions.ts +26 -0
- package/src/server/collections/agent-harness-profiles.ts +71 -59
- package/src/server/collections/agent-loop-action-approvals.ts +39 -0
- package/src/server/collections/agent-loop-artifacts.ts +25 -0
- package/src/server/collections/agent-loop-circuit-states.ts +23 -0
- package/src/server/collections/agent-loop-control-settings.ts +21 -0
- package/src/server/collections/agent-loop-events.ts +98 -71
- package/src/server/collections/agent-loop-path-locks.ts +27 -0
- package/src/server/collections/agent-loop-patterns.ts +42 -0
- package/src/server/collections/agent-loop-runs.ts +170 -3
- package/src/server/collections/agent-loop-steps.ts +76 -0
- package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
- package/src/server/collections/agent-loop-worktrees.ts +25 -0
- package/src/server/collections/skill-executions.ts +8 -0
- package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
- package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
- package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
- package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
- package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
- package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
- package/src/server/plugin.ts +55 -167
- package/src/server/resources/agent-harness-profile.ts +94 -0
- package/src/server/resources/agent-knowledge-insights.ts +5 -3
- package/src/server/resources/agent-loop-approval.ts +84 -0
- package/src/server/resources/agent-loop-artifact.ts +56 -0
- package/src/server/resources/agent-loop-events-stream.ts +105 -0
- package/src/server/resources/agent-loop.ts +204 -143
- package/src/server/resources/agent-monitor.ts +482 -482
- package/src/server/resources/resource-helpers.ts +33 -0
- package/src/server/resources/tracing.ts +266 -258
- package/src/server/services/AgentMemoryContextService.ts +44 -0
- package/src/server/services/DurableCircuitBreakerService.ts +239 -0
- package/src/server/services/ExecutionSpanService.ts +2 -0
- package/src/server/services/HarnessCompiler.ts +170 -0
- package/src/server/services/HarnessProfileService.ts +239 -0
- package/src/server/services/HarnessSchema.ts +194 -0
- package/src/server/services/LoopBudgetService.ts +275 -0
- package/src/server/services/LoopControlService.ts +124 -0
- package/src/server/services/LoopPatternSchema.ts +185 -0
- package/src/server/services/LoopPatternService.ts +143 -0
- package/src/server/services/LoopRunRepository.ts +336 -0
- package/src/server/services/LoopRunStateMachine.ts +529 -0
- package/src/server/services/LoopSchedulerService.ts +199 -0
- package/src/server/services/LoopTriggerService.ts +157 -0
- package/src/server/services/LoopWorkerService.ts +822 -0
- package/src/server/services/NativeSubAgentObserver.ts +186 -21
- package/src/server/services/PathLockService.ts +321 -0
- package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
- package/src/server/services/ToolLoopDetectionService.ts +213 -0
- package/src/server/services/VerificationSchema.ts +31 -0
- package/src/server/services/VerificationService.ts +264 -0
- package/src/server/services/harness-runtime-policy.ts +141 -0
- package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
- package/src/server/skill-hub/actions/git-import.ts +9 -3
- package/src/server/skill-hub/plugin.ts +41 -3
- package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
- package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
- package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
- package/src/server/utils/ensure-indexes.ts +96 -0
- package/src/server/utils/logging.ts +62 -63
- package/src/server/utils/loop-pattern-context.ts +20 -0
- package/dist/client-v2/214.79650a549273f163.js +0 -10
- package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
- package/dist/client-v2/264.718a107e43fc163c.js +0 -10
- package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
- package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
- package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
- package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
- package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
- package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
- package/dist/server/services/AgentHarness.js +0 -81
- package/dist/server/services/AgentLoopController.js +0 -1023
- package/dist/server/services/AgentLoopRepository.js +0 -192
- package/dist/server/services/AgentLoopService.js +0 -142
- package/dist/server/services/AgentPlanValidator.js +0 -99
- package/dist/server/services/AgentPlannerService.js +0 -99
- package/dist/server/services/CircuitBreaker.js +0 -125
- package/dist/server/services/ContextAggregator.js +0 -201
- package/dist/server/services/PlanningPromptService.js +0 -95
- package/dist/server/tools/agent-loop.js +0 -373
- package/dist/server/tools/orchestrator-plan.js +0 -254
- package/src/client/AIEmployeeSelect.tsx +0 -47
- package/src/client/AIEmployeesContext.tsx +0 -102
- package/src/client/RulesTab.tsx +0 -2
- package/src/client/TracingTab.tsx +0 -436
- package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
- package/src/client-v2/components/RulesTab.tsx +0 -2
- package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
- package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
- package/src/server/__tests__/context-aggregator.test.ts +0 -222
- package/src/server/__tests__/parallel-execution.test.ts +0 -318
- package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
- package/src/server/services/AgentHarness.ts +0 -67
- package/src/server/services/AgentLoopController.ts +0 -1263
- package/src/server/services/AgentLoopRepository.ts +0 -178
- package/src/server/services/AgentLoopService.ts +0 -177
- package/src/server/services/AgentPlanValidator.ts +0 -73
- package/src/server/services/AgentPlannerService.ts +0 -80
- package/src/server/services/CircuitBreaker.ts +0 -126
- package/src/server/services/ContextAggregator.ts +0 -239
- package/src/server/services/PlanningPromptService.ts +0 -72
- package/src/server/tools/agent-loop.ts +0 -360
- package/src/server/tools/orchestrator-plan.ts +0 -255
|
@@ -0,0 +1,226 @@
|
|
|
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 PluginAiRuntimeAdapter_exports = {};
|
|
28
|
+
__export(PluginAiRuntimeAdapter_exports, {
|
|
29
|
+
PluginAiRuntimeAdapter: () => PluginAiRuntimeAdapter,
|
|
30
|
+
planHarnessTools: () => planHarnessTools
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(PluginAiRuntimeAdapter_exports);
|
|
33
|
+
var import_server = require("@nocobase/plugin-ai/server");
|
|
34
|
+
var import_ai = require("@nocobase/ai");
|
|
35
|
+
var import_ai_manager = require("../utils/ai-manager");
|
|
36
|
+
var import_HarnessCompiler = require("./HarnessCompiler");
|
|
37
|
+
const SYSTEM_TOOL_WEB_SEARCH = "subAgentWebSearch";
|
|
38
|
+
const SYSTEM_TOOL_KNOWLEDGE_BASE = "knowledge-base-retrieve";
|
|
39
|
+
function read(record, key) {
|
|
40
|
+
const model = record;
|
|
41
|
+
return typeof model.get === "function" ? model.get(key) : record[key];
|
|
42
|
+
}
|
|
43
|
+
function textContent(messages) {
|
|
44
|
+
if (!Array.isArray(messages)) return "";
|
|
45
|
+
const last = messages[messages.length - 1];
|
|
46
|
+
if (typeof (last == null ? void 0 : last.content) === "string") return last.content;
|
|
47
|
+
if (Array.isArray(last == null ? void 0 : last.content)) {
|
|
48
|
+
return last.content.map(
|
|
49
|
+
(part) => typeof part === "object" && part && "text" in part ? String(part.text) : ""
|
|
50
|
+
).join("");
|
|
51
|
+
}
|
|
52
|
+
return "";
|
|
53
|
+
}
|
|
54
|
+
function interruptedFrom(result) {
|
|
55
|
+
const interrupts = result.__interrupt__;
|
|
56
|
+
if (!Array.isArray(interrupts)) return [];
|
|
57
|
+
const calls = [];
|
|
58
|
+
for (const interrupt of interrupts) {
|
|
59
|
+
const value = interrupt.value ?? interrupt;
|
|
60
|
+
const record = value;
|
|
61
|
+
const toolCallId = String(record.toolCallId || record.tool_call_id || "");
|
|
62
|
+
if (!toolCallId) continue;
|
|
63
|
+
calls.push({
|
|
64
|
+
toolCallId,
|
|
65
|
+
toolName: String(record.name || record.toolName || ""),
|
|
66
|
+
args: record.args ?? record.input ?? {},
|
|
67
|
+
interruptId: String(interrupt.id || record.interruptId || "")
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
return calls;
|
|
71
|
+
}
|
|
72
|
+
function askIsEnforceable(entry) {
|
|
73
|
+
return (entry == null ? void 0 : entry.scope) === "CUSTOM" || (entry == null ? void 0 : entry.defaultPermission) !== "ALLOW";
|
|
74
|
+
}
|
|
75
|
+
async function planHarnessTools(app, harness, discovery) {
|
|
76
|
+
const toolsManager = (0, import_ai_manager.getAIToolsManager)(app);
|
|
77
|
+
const candidates = Array.from(/* @__PURE__ */ new Set([...harness.tools.allow, ...harness.tools.ask, ...harness.tools.escalate]));
|
|
78
|
+
const plan = { filter: [], employeeTools: [], withheld: [], blockedSystemTools: [] };
|
|
79
|
+
const filter = discovery ? { ctx: discovery.ctx, sessionId: discovery.sessionId } : void 0;
|
|
80
|
+
for (const name of candidates.sort()) {
|
|
81
|
+
const decision = (0, import_HarnessCompiler.decideTool)(harness, name);
|
|
82
|
+
if (decision === "deny") {
|
|
83
|
+
plan.withheld.push({ name, reason: "denied by harness" });
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const entry = await toolsManager.getTools(name, filter);
|
|
87
|
+
if (!entry) {
|
|
88
|
+
plan.withheld.push({ name, reason: "not registered with plugin-ai" });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (decision === "ask" && !askIsEnforceable(entry)) {
|
|
92
|
+
plan.withheld.push({ name, reason: "approval cannot be enforced for this tool" });
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
plan.filter.push(name);
|
|
96
|
+
plan.employeeTools.push({ name, autoCall: decision === "allow" });
|
|
97
|
+
}
|
|
98
|
+
const granted = new Set(plan.filter);
|
|
99
|
+
plan.blockedSystemTools = (0, import_ai.listSystemTools)().filter((name) => !granted.has(name)).sort();
|
|
100
|
+
return plan;
|
|
101
|
+
}
|
|
102
|
+
class PluginAiRuntimeAdapter {
|
|
103
|
+
constructor(app) {
|
|
104
|
+
this.app = app;
|
|
105
|
+
}
|
|
106
|
+
plugin() {
|
|
107
|
+
const plugin = this.app.pm.get("ai");
|
|
108
|
+
if (!(plugin == null ? void 0 : plugin.aiEmployeesManager) || !(plugin == null ? void 0 : plugin.aiConversationsManager)) {
|
|
109
|
+
throw new Error("The official @nocobase/plugin-ai plugin is required to execute Loop Control Plane runs.");
|
|
110
|
+
}
|
|
111
|
+
return plugin;
|
|
112
|
+
}
|
|
113
|
+
async createConversation(input) {
|
|
114
|
+
const conversation = await this.plugin().aiConversationsManager.create({
|
|
115
|
+
userId: input.userId,
|
|
116
|
+
aiEmployee: { username: input.username },
|
|
117
|
+
title: input.title,
|
|
118
|
+
category: "task",
|
|
119
|
+
options: { controlPlaneRunId: input.runId }
|
|
120
|
+
});
|
|
121
|
+
const sessionId = String(read(conversation, "sessionId") || "");
|
|
122
|
+
if (!sessionId) throw new Error("The AI conversation was created without a session identifier.");
|
|
123
|
+
return sessionId;
|
|
124
|
+
}
|
|
125
|
+
async invoke(input) {
|
|
126
|
+
const { aiEmployee } = await this.buildEmployee(input);
|
|
127
|
+
const result = await aiEmployee.invoke({
|
|
128
|
+
userMessages: [{ role: "user", content: input.prompt }],
|
|
129
|
+
signal: input.signal
|
|
130
|
+
});
|
|
131
|
+
return {
|
|
132
|
+
sessionId: input.sessionId,
|
|
133
|
+
messageId: String(result.messageId || ""),
|
|
134
|
+
interrupted: interruptedFrom(result),
|
|
135
|
+
content: textContent(result.messages)
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
// Resume mirrors the official workflow employee node: flip the persisted tool call to
|
|
139
|
+
// `waiting` with a decision, then re-invoke so plugin-ai resumes its own checkpoint.
|
|
140
|
+
// Decisions are per tool call: plugin-ai stores one `userDecision` per interrupted row and
|
|
141
|
+
// `getUserDecisions` only unblocks once every interrupted call of the message has one.
|
|
142
|
+
async resume(input) {
|
|
143
|
+
const plugin = this.plugin();
|
|
144
|
+
for (const entry of input.decisions) {
|
|
145
|
+
await this.app.db.getModel("aiToolMessages").update(
|
|
146
|
+
{ userDecision: entry.decision, invokeStatus: "waiting" },
|
|
147
|
+
{
|
|
148
|
+
where: {
|
|
149
|
+
sessionId: input.sessionId,
|
|
150
|
+
messageId: input.messageId,
|
|
151
|
+
toolCallId: entry.toolCallId,
|
|
152
|
+
invokeStatus: "interrupted"
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
const userDecisions = await plugin.aiConversationsManager.getUserDecisions(input.messageId);
|
|
158
|
+
if (!userDecisions) throw new Error("The interrupted tool calls are not all ready to resume.");
|
|
159
|
+
const { aiEmployee } = await this.buildEmployee(input);
|
|
160
|
+
const result = await aiEmployee.invoke({
|
|
161
|
+
messageId: input.messageId,
|
|
162
|
+
userDecisions,
|
|
163
|
+
signal: input.signal
|
|
164
|
+
});
|
|
165
|
+
return {
|
|
166
|
+
sessionId: input.sessionId,
|
|
167
|
+
messageId: String(result.messageId || input.messageId),
|
|
168
|
+
interrupted: interruptedFrom(result),
|
|
169
|
+
content: textContent(result.messages)
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
// The employee model is re-read per invocation and mutated only in memory. `isAutoCall` reads
|
|
173
|
+
// `employee.skillSettings` off the Sequelize dataValues, so `set()` without `save()` gates this
|
|
174
|
+
// run's tool calls without touching the shared employee configuration.
|
|
175
|
+
async buildEmployee(input) {
|
|
176
|
+
const plugin = this.plugin();
|
|
177
|
+
const employee = await plugin.aiEmployeesManager.getEmployee(input.username);
|
|
178
|
+
if (!employee) throw new Error(`AI employee "${input.username}" was not found.`);
|
|
179
|
+
const model = await plugin.aiEmployeesManager.resolveModel(employee);
|
|
180
|
+
const currentRoles = await this.rolesFor(input.userId);
|
|
181
|
+
const ctx = {
|
|
182
|
+
app: this.app,
|
|
183
|
+
db: this.app.db,
|
|
184
|
+
log: this.app.log,
|
|
185
|
+
logger: this.app.log,
|
|
186
|
+
state: { currentRoles },
|
|
187
|
+
auth: { user: { id: input.userId } },
|
|
188
|
+
action: { params: { values: { sessionId: input.sessionId, model } } }
|
|
189
|
+
};
|
|
190
|
+
const plan = await planHarnessTools(this.app, input.harness, { ctx, sessionId: input.sessionId });
|
|
191
|
+
if (plan.withheld.length) {
|
|
192
|
+
this.app.logger.info(
|
|
193
|
+
`[AgentOrchestrator] Harness withheld ${plan.withheld.length} tool(s) from ${input.username}.`,
|
|
194
|
+
{ withheld: plan.withheld }
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
const persisted = employee.get("skillSettings") || {};
|
|
198
|
+
employee.set("skillSettings", { ...persisted, tools: plan.employeeTools });
|
|
199
|
+
const blockedSystemTools = new Set(plan.blockedSystemTools);
|
|
200
|
+
if (blockedSystemTools.has(SYSTEM_TOOL_KNOWLEDGE_BASE)) {
|
|
201
|
+
employee.set("enableKnowledgeBase", false);
|
|
202
|
+
}
|
|
203
|
+
const aiEmployee = new import_server.AIEmployee({
|
|
204
|
+
ctx,
|
|
205
|
+
employee,
|
|
206
|
+
sessionId: input.sessionId,
|
|
207
|
+
systemMessage: input.systemMessage,
|
|
208
|
+
skillSettings: { skillsVersion: 2, toolsVersion: 2, skills: [], tools: plan.filter },
|
|
209
|
+
// Same reasoning for web search: the flag is what injects the system tool, so it is only
|
|
210
|
+
// ever enabled when the harness explicitly granted it.
|
|
211
|
+
webSearch: !blockedSystemTools.has(SYSTEM_TOOL_WEB_SEARCH),
|
|
212
|
+
model
|
|
213
|
+
});
|
|
214
|
+
return { aiEmployee, plan };
|
|
215
|
+
}
|
|
216
|
+
async rolesFor(userId) {
|
|
217
|
+
if (!userId) return [];
|
|
218
|
+
const rows = await this.app.db.getRepository("rolesUsers").find({ filter: { userId } });
|
|
219
|
+
return rows.map((row) => String(read(row, "roleName") || "")).filter(Boolean);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
223
|
+
0 && (module.exports = {
|
|
224
|
+
PluginAiRuntimeAdapter,
|
|
225
|
+
planHarnessTools
|
|
226
|
+
});
|
|
@@ -0,0 +1,210 @@
|
|
|
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 ToolLoopDetectionService_exports = {};
|
|
28
|
+
__export(ToolLoopDetectionService_exports, {
|
|
29
|
+
ToolLoopDetectionService: () => ToolLoopDetectionService,
|
|
30
|
+
countToolRepetitions: () => countToolRepetitions,
|
|
31
|
+
toolCallSignature: () => toolCallSignature,
|
|
32
|
+
toolLoopLevel: () => toolLoopLevel,
|
|
33
|
+
toolLoopNotice: () => toolLoopNotice,
|
|
34
|
+
toolLoopReason: () => toolLoopReason
|
|
35
|
+
});
|
|
36
|
+
module.exports = __toCommonJS(ToolLoopDetectionService_exports);
|
|
37
|
+
var import_node_crypto = require("node:crypto");
|
|
38
|
+
var import_RunEventBus = require("./RunEventBus");
|
|
39
|
+
function read(record, key) {
|
|
40
|
+
const model = record;
|
|
41
|
+
return typeof model.get === "function" ? model.get(key) : record[key];
|
|
42
|
+
}
|
|
43
|
+
function asObject(value) {
|
|
44
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
45
|
+
}
|
|
46
|
+
function canonicalize(value) {
|
|
47
|
+
if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
|
|
48
|
+
if (value && typeof value === "object") {
|
|
49
|
+
const source = value;
|
|
50
|
+
const ordered = {};
|
|
51
|
+
for (const key of Object.keys(source).sort()) ordered[key] = canonicalize(source[key]);
|
|
52
|
+
return ordered;
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
const NAME_ARGS_SEPARATOR = String.fromCharCode(0);
|
|
57
|
+
function toolCallSignature(name, args) {
|
|
58
|
+
return (0, import_node_crypto.createHash)("sha256").update(name + NAME_ARGS_SEPARATOR + JSON.stringify(canonicalize(args ?? null))).digest("hex");
|
|
59
|
+
}
|
|
60
|
+
function countToolRepetitions(calls) {
|
|
61
|
+
const counts = /* @__PURE__ */ new Map();
|
|
62
|
+
for (const call of calls) {
|
|
63
|
+
if (!call.name) continue;
|
|
64
|
+
const signature = toolCallSignature(call.name, call.args);
|
|
65
|
+
const entry = counts.get(signature) ?? {
|
|
66
|
+
toolName: call.name,
|
|
67
|
+
signature,
|
|
68
|
+
count: 0,
|
|
69
|
+
sampleArgs: asObject(call.args)
|
|
70
|
+
};
|
|
71
|
+
entry.count += 1;
|
|
72
|
+
counts.set(signature, entry);
|
|
73
|
+
}
|
|
74
|
+
return counts;
|
|
75
|
+
}
|
|
76
|
+
function toolLoopLevel(count, detection) {
|
|
77
|
+
if (!detection.enabled) return "none";
|
|
78
|
+
if (count >= detection.escalateAt) return "escalate";
|
|
79
|
+
if (count >= detection.blockAt) return "block";
|
|
80
|
+
if (count >= detection.warnAt) return "warn";
|
|
81
|
+
return "none";
|
|
82
|
+
}
|
|
83
|
+
function toolLoopReason(finding) {
|
|
84
|
+
return `Tool loop detected: "${finding.toolName}" was invoked ${finding.count} times with identical arguments.`;
|
|
85
|
+
}
|
|
86
|
+
function toolLoopNotice(toolName, count) {
|
|
87
|
+
return [
|
|
88
|
+
"<tool_loop_warning>",
|
|
89
|
+
`An earlier pass of this run invoked the tool "${toolName}" with identical arguments ${count} times.`,
|
|
90
|
+
"Do not repeat this pattern. If the tool did not return what you expected, change your approach or report the blocker explicitly instead of retrying the same call.",
|
|
91
|
+
"</tool_loop_warning>"
|
|
92
|
+
].join("\n");
|
|
93
|
+
}
|
|
94
|
+
class ToolLoopDetectionService {
|
|
95
|
+
constructor(database) {
|
|
96
|
+
this.database = database;
|
|
97
|
+
}
|
|
98
|
+
// Scans every tool call the run has issued so far (across all pass sessions, which are linked
|
|
99
|
+
// through agentLoopSteps.sessionId) and returns the most repeated signature once it crosses the
|
|
100
|
+
// policy's warn threshold. Returns null while the run stays under every threshold.
|
|
101
|
+
async scanRun(runId, policy) {
|
|
102
|
+
const detection = policy.loopDetection;
|
|
103
|
+
if (!detection.enabled) return null;
|
|
104
|
+
const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
|
|
105
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
106
|
+
for (const step of steps) {
|
|
107
|
+
const sessionId = read(step, "sessionId");
|
|
108
|
+
if (typeof sessionId === "string" && sessionId) sessionIds.add(sessionId);
|
|
109
|
+
}
|
|
110
|
+
if (!sessionIds.size) return null;
|
|
111
|
+
const messages = await this.database.getRepository("aiMessages").find({
|
|
112
|
+
filter: { sessionId: { $in: [...sessionIds] } }
|
|
113
|
+
});
|
|
114
|
+
const calls = [];
|
|
115
|
+
for (const message of messages) {
|
|
116
|
+
const toolCalls = read(message, "toolCalls");
|
|
117
|
+
if (!Array.isArray(toolCalls)) continue;
|
|
118
|
+
for (const toolCall of toolCalls) {
|
|
119
|
+
const entry = asObject(toolCall);
|
|
120
|
+
if (typeof entry.name === "string" && entry.name) calls.push({ name: entry.name, args: entry.args });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (!calls.length) return null;
|
|
124
|
+
let worst = null;
|
|
125
|
+
for (const entry of countToolRepetitions(calls).values()) {
|
|
126
|
+
const level = toolLoopLevel(entry.count, detection);
|
|
127
|
+
if (level === "none") continue;
|
|
128
|
+
if (!worst || entry.count > worst.count) worst = { level, ...entry };
|
|
129
|
+
}
|
|
130
|
+
return worst;
|
|
131
|
+
}
|
|
132
|
+
// Persists the guard step and event for a finding, deduplicated by signature so a run records
|
|
133
|
+
// each loop once no matter how many subsequent passes observe it. Returns true when a new
|
|
134
|
+
// record was created.
|
|
135
|
+
async recordFinding(context, finding) {
|
|
136
|
+
const steps = this.database.getRepository("agentLoopSteps");
|
|
137
|
+
const existing = await steps.findOne({
|
|
138
|
+
filter: { runId: context.runId, kind: "guard", inputHash: finding.signature }
|
|
139
|
+
});
|
|
140
|
+
if (existing) return false;
|
|
141
|
+
const now = /* @__PURE__ */ new Date();
|
|
142
|
+
const runSteps = await steps.find({ filter: { runId: context.runId } });
|
|
143
|
+
const step = await steps.create({
|
|
144
|
+
values: {
|
|
145
|
+
runId: context.runId,
|
|
146
|
+
runtimeVersion: "control-plane-v2",
|
|
147
|
+
sequence: runSteps.length,
|
|
148
|
+
role: context.role,
|
|
149
|
+
kind: "guard",
|
|
150
|
+
type: "tool_loop",
|
|
151
|
+
employeeUsername: context.username,
|
|
152
|
+
toolName: finding.toolName,
|
|
153
|
+
inputHash: finding.signature,
|
|
154
|
+
title: `Tool loop ${finding.level}: ${finding.toolName} x${finding.count}`,
|
|
155
|
+
description: toolLoopReason(finding),
|
|
156
|
+
status: "succeeded",
|
|
157
|
+
metadata: { level: finding.level, count: finding.count, sampleArgs: finding.sampleArgs },
|
|
158
|
+
startedAt: now,
|
|
159
|
+
endedAt: now,
|
|
160
|
+
createdAt: now
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
const event = await this.database.getRepository("agentLoopEvents").create({
|
|
164
|
+
values: {
|
|
165
|
+
runId: context.runId,
|
|
166
|
+
stepId: read(step, "id"),
|
|
167
|
+
type: "tool_loop_detected",
|
|
168
|
+
title: `Tool loop ${finding.level}: ${finding.toolName}`,
|
|
169
|
+
content: toolLoopReason(finding),
|
|
170
|
+
status: context.runStatus,
|
|
171
|
+
payload: {
|
|
172
|
+
level: finding.level,
|
|
173
|
+
toolName: finding.toolName,
|
|
174
|
+
count: finding.count,
|
|
175
|
+
signature: finding.signature
|
|
176
|
+
},
|
|
177
|
+
actorType: context.actorType,
|
|
178
|
+
actorIdentity: context.actorIdentity,
|
|
179
|
+
correlationKey: `tool-loop:${finding.signature}`,
|
|
180
|
+
createdAt: now
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
(0, import_RunEventBus.getRunEventBus)().emit(context.runId, typeof event.toJSON === "function" ? event.toJSON() : event);
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
// Rebuilds the model-facing notices from guard steps recorded before the current worker claim,
|
|
187
|
+
// so a run that parked and resumed keeps warning later roles about an earlier loop.
|
|
188
|
+
async existingNotices(runId) {
|
|
189
|
+
const steps = await this.database.getRepository("agentLoopSteps").find({
|
|
190
|
+
filter: { runId, kind: "guard" }
|
|
191
|
+
});
|
|
192
|
+
const notices = [];
|
|
193
|
+
for (const step of steps) {
|
|
194
|
+
const toolName = String(read(step, "toolName") || "");
|
|
195
|
+
const count = Number(asObject(read(step, "metadata")).count) || 0;
|
|
196
|
+
if (!toolName || !count) continue;
|
|
197
|
+
notices.push(toolLoopNotice(toolName, count));
|
|
198
|
+
}
|
|
199
|
+
return notices;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
203
|
+
0 && (module.exports = {
|
|
204
|
+
ToolLoopDetectionService,
|
|
205
|
+
countToolRepetitions,
|
|
206
|
+
toolCallSignature,
|
|
207
|
+
toolLoopLevel,
|
|
208
|
+
toolLoopNotice,
|
|
209
|
+
toolLoopReason
|
|
210
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
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 VerificationSchema_exports = {};
|
|
28
|
+
__export(VerificationSchema_exports, {
|
|
29
|
+
isPassingVerification: () => isPassingVerification,
|
|
30
|
+
parseVerificationVerdict: () => parseVerificationVerdict,
|
|
31
|
+
verificationVerdictSchema: () => verificationVerdictSchema
|
|
32
|
+
});
|
|
33
|
+
module.exports = __toCommonJS(VerificationSchema_exports);
|
|
34
|
+
var import_zod = require("zod");
|
|
35
|
+
const verificationVerdictSchema = import_zod.z.object({
|
|
36
|
+
verdict: import_zod.z.enum(["pass", "reject", "escalate"]),
|
|
37
|
+
summary: import_zod.z.string().min(1),
|
|
38
|
+
checks: import_zod.z.array(
|
|
39
|
+
import_zod.z.object({
|
|
40
|
+
name: import_zod.z.string().min(1),
|
|
41
|
+
status: import_zod.z.enum(["pass", "fail", "skipped"]),
|
|
42
|
+
evidenceArtifactIds: import_zod.z.array(import_zod.z.number().int().positive()).default([])
|
|
43
|
+
})
|
|
44
|
+
).min(1),
|
|
45
|
+
residualRisks: import_zod.z.array(import_zod.z.string()).default([])
|
|
46
|
+
});
|
|
47
|
+
function parseVerificationVerdict(value) {
|
|
48
|
+
return verificationVerdictSchema.parse(value);
|
|
49
|
+
}
|
|
50
|
+
function isPassingVerification(value) {
|
|
51
|
+
const parsed = verificationVerdictSchema.safeParse(value);
|
|
52
|
+
return parsed.success && parsed.data.verdict === "pass" && parsed.data.checks.every((check) => check.status === "pass" && check.evidenceArtifactIds.length > 0);
|
|
53
|
+
}
|
|
54
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
55
|
+
0 && (module.exports = {
|
|
56
|
+
isPassingVerification,
|
|
57
|
+
parseVerificationVerdict,
|
|
58
|
+
verificationVerdictSchema
|
|
59
|
+
});
|