plugin-agent-orchestrator 1.2.0 → 1.2.1
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/LICENSE +201 -0
- package/dist/client/{117.2e4cb0477da3db1f.js → 117.6c69b6a87751dd18.js} +1 -1
- package/dist/client/{253.93deb9e0192e76a5.js → 253.52f62e1bc0e9520a.js} +1 -1
- package/dist/client/{404.498d2d9516dd1dce.js → 404.86593f98c9768ed5.js} +1 -1
- package/dist/client/{627.fdd60bcc0f3a9cf6.js → 453.fa2d169576262213.js} +1 -1
- package/dist/client/{53.774ff07505d521fa.js → 53.567db3ae078650c6.js} +1 -1
- package/dist/client/{619.e342b0fa467d39ca.js → 619.01713281e5e951d3.js} +1 -1
- package/dist/client/652.69da1598312b3a3f.js +10 -0
- package/dist/client/773.648965568ff476f9.js +10 -0
- package/dist/client/{981.e0546ffc34afedcd.js → 981.37e7aeecdb1ef6fa.js} +1 -1
- package/dist/client/{993.5d04b510835ab0d2.js → 993.ac89f3852990918d.js} +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client-v2/{117.ccf43ae8631f7d74.js → 117.c982d79ff68738f5.js} +1 -1
- package/dist/client-v2/{214.cdf76752053a8990.js → 214.94c4257bf2838577.js} +1 -1
- package/dist/client-v2/{253.1198df22f5baf304.js → 253.8e19956d2a44dfb8.js} +1 -1
- package/dist/client-v2/{264.78887ff88f969467.js → 264.80e8e358c8c6c2e5.js} +1 -1
- package/dist/client-v2/{404.9ba964c28a151c81.js → 404.ab032b79c95dab6f.js} +1 -1
- package/dist/client-v2/{41.b28cf7a675a603d1.js → 41.cd5610fcf7446127.js} +1 -1
- package/dist/client-v2/{627.e16f4a0dd596c3e6.js → 453.42c6d70628d56cc2.js} +1 -1
- package/dist/client-v2/{53.282081f97e4308c6.js → 53.37c08089a648f89a.js} +1 -1
- package/dist/client-v2/{619.8c03913873785fb6.js → 619.6e9618550101e819.js} +1 -1
- package/dist/client-v2/652.eeba4e0c38367321.js +10 -0
- package/dist/client-v2/{70.9166ed70906d041f.js → 70.332698e53eb59677.js} +1 -1
- package/dist/client-v2/773.4de2ba5acb07318c.js +10 -0
- package/dist/client-v2/981.76060f466e6f7c11.js +10 -0
- package/dist/client-v2/{993.ca5b28f1e2b4c1ef.js → 993.f8cdb5172566ce75.js} +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +4 -1
- package/dist/locale/en-US.json +80 -1
- package/dist/locale/vi-VN.json +5 -1
- package/dist/locale/zh-CN.json +80 -1
- package/dist/node_modules/acorn/LICENSE +21 -0
- package/dist/node_modules/acorn/bin/acorn +4 -0
- package/dist/node_modules/acorn/dist/acorn.d.mts +857 -0
- package/dist/node_modules/acorn/dist/acorn.d.ts +857 -0
- package/dist/node_modules/acorn/dist/acorn.js +1 -0
- package/dist/node_modules/acorn/dist/bin.js +90 -0
- package/dist/node_modules/acorn/package.json +1 -0
- package/dist/node_modules/acorn-walk/LICENSE +21 -0
- package/dist/node_modules/acorn-walk/dist/walk.d.mts +177 -0
- package/dist/node_modules/acorn-walk/dist/walk.d.ts +177 -0
- package/dist/node_modules/acorn-walk/dist/walk.js +1 -0
- package/dist/node_modules/acorn-walk/node_modules/.bin/acorn +15 -0
- package/dist/node_modules/acorn-walk/node_modules/.bin/acorn.cmd +7 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/bin/acorn +4 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/dist/acorn.d.mts +866 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/dist/acorn.d.ts +866 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/dist/acorn.js +6174 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/dist/bin.js +90 -0
- package/dist/node_modules/acorn-walk/node_modules/acorn/package.json +50 -0
- package/dist/node_modules/acorn-walk/package.json +1 -0
- package/dist/node_modules/adm-zip/package.json +1 -1
- package/dist/node_modules/ajv/package.json +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/collections/agent-auto-approval-checkpoints.js +47 -0
- package/dist/server/collections/agent-execution-spans.js +3 -3
- package/dist/server/collections/agent-hierarchy-invocations.js +59 -0
- package/dist/server/collections/agent-routing-graph-locks.js +40 -0
- package/dist/server/collections/agent-session-auto-approvals.js +45 -0
- package/dist/server/collections/orchestrator-config.js +17 -0
- package/dist/server/migrations/20261119000000-widen-native-employee-identifiers.js +59 -0
- package/dist/server/plugin.js +55 -0
- package/dist/server/resources/agent-auto-approval.js +80 -0
- package/dist/server/resources/hierarchical-routing.js +60 -0
- package/dist/server/services/AutoApprovalCheckpoint.js +133 -0
- package/dist/server/services/CodeValidator.js +8 -4
- package/dist/server/services/GovernanceAdmission.js +60 -0
- package/dist/server/services/HarnessCompiler.js +3 -0
- package/dist/server/services/HarnessSchema.js +13 -1
- package/dist/server/services/HierarchicalAgentRuntime.js +925 -0
- package/dist/server/services/HierarchyEnrollmentGuard.js +216 -0
- package/dist/server/services/HierarchyInvocationJournal.js +157 -0
- package/dist/server/services/HierarchyRequestCancellation.js +150 -0
- package/dist/server/services/LoopRunRepository.js +1 -1
- package/dist/server/services/LoopRunStateMachine.js +2 -2
- package/dist/server/services/LoopWorkerService.js +7 -7
- package/dist/server/services/PluginAiRuntimeAdapter.js +107 -9
- package/dist/server/services/RoutingBindingRepository.js +156 -0
- package/dist/server/services/RoutingBindingValidation.js +161 -0
- package/dist/server/services/SandboxRunner.js +19 -0
- package/dist/server/services/SessionAutoApproval.js +173 -0
- package/dist/server/services/VerificationService.js +2 -2
- package/dist/server/skill-hub/plugin.js +17 -0
- package/dist/server/skill-hub/services/RegistrySkillInstallationService.js +2 -2
- package/dist/server/skill-hub/services/registry-node-package.js +191 -0
- package/dist/server/skill-hub/tasks/SkillExecutionTask.js +21 -6
- package/dist/server/tools/skill-execute.js +1 -0
- package/dist/server/utils/ensure-indexes.js +1 -0
- package/package.json +5 -2
- package/src/client/SkillPages.tsx +1 -8
- package/src/client/__tests__/embedded-settings.test.tsx +1 -8
- package/src/client/plugin.tsx +3 -8
- package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +21 -6
- package/src/client/skill-hub/tools/SkillHubCard.tsx +22 -16
- package/src/client/skill-hub/tools/__tests__/skill-hub-card.test.tsx +255 -0
- package/src/client/skill-hub/tools/registerSkillLoopCards.ts +12 -3
- package/src/client-v2/__tests__/embedded-settings.test.tsx +20 -11
- package/src/client-v2/__tests__/hierarchical-routing-settings.test.tsx +350 -0
- package/src/client-v2/auto-approval/AutoApprovalBridge.tsx +513 -0
- package/src/client-v2/auto-approval/AutoApprovalProvider.tsx +399 -0
- package/src/client-v2/auto-approval/__tests__/session-auto-approval.test.tsx +1676 -0
- package/src/client-v2/components/AgentBindingsTab.tsx +275 -3
- package/src/client-v2/components/AgentRunsTab.tsx +1 -8
- package/src/client-v2/components/EmployeeGovernanceTab.tsx +1 -8
- package/src/client-v2/components/HarnessProfilesTab.tsx +4 -8
- package/src/client-v2/components/HarnessSettingsForm.tsx +221 -0
- package/src/client-v2/components/UsageGovernanceTab.tsx +1 -8
- package/src/client-v2/pages/AgentBindingsPage.tsx +1 -8
- package/src/client-v2/pages/ApprovalsPage.tsx +1 -8
- package/src/client-v2/pages/EmployeeGovernancePage.tsx +1 -8
- package/src/client-v2/pages/ExecutionHistoryPage.tsx +1 -8
- package/src/client-v2/pages/HarnessProfilesPage.tsx +1 -8
- package/src/client-v2/pages/KnowledgeAccessPage.tsx +1 -8
- package/src/client-v2/pages/LoopSettingsPage.tsx +1 -8
- package/src/client-v2/pages/MemoryInspectorPage.tsx +1 -8
- package/src/client-v2/pages/RetrievalTracePage.tsx +1 -8
- package/src/client-v2/pages/RulesPage.tsx +1 -8
- package/src/client-v2/pages/SkillDefinitionsPage.tsx +1 -8
- package/src/client-v2/pages/SkillMetricsPage.tsx +1 -8
- package/src/client-v2/pages/TracingPage.tsx +1 -8
- package/src/client-v2/pages/UsageGovernancePage.tsx +1 -8
- package/src/client-v2/plugin.tsx +3 -8
- package/src/client-v2/skill-hub/tools/__tests__/interactions.test.ts +17 -1
- package/src/client-v2/skill-hub/tools/interactions.ts +12 -3
- package/src/locale/en-US.json +80 -1
- package/src/locale/vi-VN.json +5 -1
- package/src/locale/zh-CN.json +80 -1
- package/src/server/__tests__/agent-governance.integration.test.ts +1 -8
- package/src/server/__tests__/agent-monitor-acl.integration.test.ts +1 -8
- package/src/server/__tests__/agent-usage-report.integration.test.ts +1 -8
- package/src/server/__tests__/auto-approval-checkpoint.integration.test.ts +295 -0
- package/src/server/__tests__/harness-capabilities.test.ts +1 -8
- package/src/server/__tests__/harness-compiler.test.ts +64 -0
- package/src/server/__tests__/harness-tool-plan.test.ts +1 -8
- package/src/server/__tests__/hierarchical-routing.integration.test.ts +2318 -0
- package/src/server/__tests__/hierarchy-invocation-journal.integration.test.ts +119 -0
- package/src/server/__tests__/loop-approval-decision.test.ts +59 -12
- package/src/server/__tests__/loop-budget-service.test.ts +1 -8
- package/src/server/__tests__/loop-run-repository.test.ts +1 -8
- package/src/server/__tests__/loop-trigger-service.test.ts +1 -8
- package/src/server/__tests__/loop-worker-claim.test.ts +46 -9
- package/src/server/__tests__/loop-worker-execution.test.ts +1 -8
- package/src/server/__tests__/native-agent-monitor-sync.test.ts +1 -8
- package/src/server/__tests__/native-hierarchy-probe.integration.test.ts +527 -0
- package/src/server/__tests__/native-sub-agent-observer.test.ts +1 -8
- package/src/server/__tests__/native-usage-attribution.integration.test.ts +1 -8
- package/src/server/__tests__/plugin-ai-runtime-adapter.test.ts +403 -0
- package/src/server/__tests__/registry-node-package.test.ts +299 -0
- package/src/server/__tests__/routing-binding-graph.integration.test.ts +217 -0
- package/src/server/__tests__/routing-binding-validation.test.ts +256 -0
- package/src/server/__tests__/session-auto-approval.integration.test.ts +329 -0
- package/src/server/__tests__/skill-execute.test.ts +11 -0
- package/src/server/__tests__/skill-review-guard.test.ts +171 -0
- package/src/server/__tests__/token-tracker.test.ts +1 -8
- package/src/server/__tests__/tracing-retention-policy.test.ts +1 -8
- package/src/server/__tests__/usage-ledger.integration.test.ts +1 -8
- package/src/server/collections/agent-auto-approval-checkpoints.ts +18 -0
- package/src/server/collections/agent-execution-spans.ts +4 -11
- package/src/server/collections/agent-governance-audit-events.ts +1 -8
- package/src/server/collections/agent-governance-policies.ts +1 -8
- package/src/server/collections/agent-governance-policy-versions.ts +1 -8
- package/src/server/collections/agent-governance-prompt-bindings.ts +1 -8
- package/src/server/collections/agent-hierarchy-invocations.ts +30 -0
- package/src/server/collections/agent-loop-runs.ts +1 -8
- package/src/server/collections/agent-routing-graph-locks.ts +11 -0
- package/src/server/collections/agent-session-auto-approvals.ts +16 -0
- package/src/server/collections/orchestrator-config.ts +26 -0
- package/src/server/migrations/20261110000000-add-usage-pricing-snapshots.ts +1 -8
- package/src/server/migrations/20261110010000-add-usage-department-attribution.ts +1 -8
- package/src/server/migrations/20261119000000-widen-native-employee-identifiers.ts +37 -0
- package/src/server/plugin.ts +58 -8
- package/src/server/resources/agent-auto-approval.ts +51 -0
- package/src/server/resources/agent-governance.ts +1 -8
- package/src/server/resources/agent-harness-profile.ts +1 -8
- package/src/server/resources/agent-monitor.ts +1 -8
- package/src/server/resources/agent-usage.ts +1 -8
- package/src/server/resources/hierarchical-routing.ts +39 -0
- package/src/server/resources/native-monitor-format.ts +1 -8
- package/src/server/resources/tracing.ts +1 -8
- package/src/server/services/AgentGovernanceService.ts +1 -8
- package/src/server/services/AutoApprovalCheckpoint.ts +140 -0
- package/src/server/services/CodeValidator.ts +23 -4
- package/src/server/services/DepartmentAttribution.ts +1 -8
- package/src/server/services/ExecutionSpanService.ts +1 -8
- package/src/server/services/GovernanceAdmission.ts +83 -8
- package/src/server/services/HarnessCapabilities.ts +1 -8
- package/src/server/services/HarnessCompiler.ts +12 -0
- package/src/server/services/HarnessSchema.ts +30 -0
- package/src/server/services/HierarchicalAgentRuntime.ts +1052 -0
- package/src/server/services/HierarchyEnrollmentGuard.ts +211 -0
- package/src/server/services/HierarchyInvocationJournal.ts +172 -0
- package/src/server/services/HierarchyRequestCancellation.ts +132 -0
- package/src/server/services/LoopBudgetService.ts +1 -8
- package/src/server/services/LoopRunRepository.ts +2 -9
- package/src/server/services/LoopRunStateMachine.ts +3 -10
- package/src/server/services/LoopTriggerService.ts +1 -8
- package/src/server/services/LoopWorkerService.ts +8 -19
- package/src/server/services/ManagedPromptProtection.ts +1 -8
- package/src/server/services/NativeAgentMonitorSyncService.ts +1 -8
- package/src/server/services/NativeSubAgentObserver.ts +1 -8
- package/src/server/services/NativeUsageAttribution.ts +1 -8
- package/src/server/services/PluginAiRuntimeAdapter.ts +140 -9
- package/src/server/services/RoutingBindingRepository.ts +146 -0
- package/src/server/services/RoutingBindingValidation.ts +161 -0
- package/src/server/services/SandboxRunner.ts +35 -1
- package/src/server/services/SessionAutoApproval.ts +167 -0
- package/src/server/services/TokenTracker.ts +1 -8
- package/src/server/services/TracingRetentionPolicy.ts +1 -8
- package/src/server/services/VerificationService.ts +3 -10
- package/src/server/skill-hub/plugin.ts +40 -0
- package/src/server/skill-hub/services/RegistrySkillInstallationService.ts +11 -1
- package/src/server/skill-hub/services/registry-node-package.ts +191 -0
- package/src/server/skill-hub/tasks/SkillExecutionTask.ts +34 -5
- package/src/server/tools/skill-execute.ts +10 -0
- package/src/server/utils/ensure-indexes.ts +2 -8
- package/dist/client/418.6f01da17774a5a25.js +0 -10
- package/dist/client/652.477e21bfff67bc1c.js +0 -10
- package/dist/client-v2/418.55b6b28cda8bb5f3.js +0 -10
- package/dist/client-v2/652.1a48364774d5383a.js +0 -10
- package/dist/client-v2/981.a81521f0296c7db8.js +0 -10
|
@@ -0,0 +1,925 @@
|
|
|
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 HierarchicalAgentRuntime_exports = {};
|
|
28
|
+
__export(HierarchicalAgentRuntime_exports, {
|
|
29
|
+
HIERARCHY_DISPATCH_TOOL: () => HIERARCHY_DISPATCH_TOOL,
|
|
30
|
+
HIERARCHY_LIST_TOOL: () => HIERARCHY_LIST_TOOL,
|
|
31
|
+
HierarchicalAgentRuntime: () => HierarchicalAgentRuntime,
|
|
32
|
+
createHierarchicalAgentTools: () => createHierarchicalAgentTools
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(HierarchicalAgentRuntime_exports);
|
|
35
|
+
var import_node_util = require("node:util");
|
|
36
|
+
var import_server = require("@nocobase/plugin-ai/server");
|
|
37
|
+
var import_ai = require("@nocobase/ai");
|
|
38
|
+
var import_langchain = require("langchain");
|
|
39
|
+
var import_zod = require("zod");
|
|
40
|
+
var import_HarnessProfileService = require("./HarnessProfileService");
|
|
41
|
+
var import_HarnessCompiler = require("./HarnessCompiler");
|
|
42
|
+
var import_GovernanceAdmission = require("./GovernanceAdmission");
|
|
43
|
+
var import_NativeUsageAttribution = require("./NativeUsageAttribution");
|
|
44
|
+
var import_HierarchyInvocationJournal = require("./HierarchyInvocationJournal");
|
|
45
|
+
var import_ExecutionSpanService = require("./ExecutionSpanService");
|
|
46
|
+
var import_HierarchyEnrollmentGuard = require("./HierarchyEnrollmentGuard");
|
|
47
|
+
var import_HierarchyRequestCancellation = require("./HierarchyRequestCancellation");
|
|
48
|
+
var import_SessionAutoApproval = require("./SessionAutoApproval");
|
|
49
|
+
var import_ai_manager = require("../utils/ai-manager");
|
|
50
|
+
var import_record_utils = require("../utils/record-utils");
|
|
51
|
+
const HIERARCHY_LIST_TOOL = "orchestrator_list_agents";
|
|
52
|
+
const HIERARCHY_DISPATCH_TOOL = "orchestrator_delegate_task";
|
|
53
|
+
const scopes = /* @__PURE__ */ new WeakMap();
|
|
54
|
+
const pendingRootScopes = /* @__PURE__ */ new WeakMap();
|
|
55
|
+
function stringValue(value) {
|
|
56
|
+
return typeof value === "string" ? value.trim() : "";
|
|
57
|
+
}
|
|
58
|
+
function toolName(value) {
|
|
59
|
+
const item = (0, import_record_utils.asRecord)(value);
|
|
60
|
+
return stringValue(item.name) || stringValue((0, import_record_utils.asRecord)(item.function).name);
|
|
61
|
+
}
|
|
62
|
+
function toolCallKey(sessionId, messageId, toolCallId, name) {
|
|
63
|
+
return JSON.stringify([sessionId, messageId, toolCallId, name]);
|
|
64
|
+
}
|
|
65
|
+
function abortError() {
|
|
66
|
+
return new Error("The delegation was cancelled or timed out.");
|
|
67
|
+
}
|
|
68
|
+
async function withAbort(signal, run) {
|
|
69
|
+
if (signal.aborted) throw abortError();
|
|
70
|
+
let onAbort = () => void 0;
|
|
71
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
72
|
+
onAbort = () => reject(abortError());
|
|
73
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
74
|
+
});
|
|
75
|
+
try {
|
|
76
|
+
if (signal.aborted) throw abortError();
|
|
77
|
+
return await Promise.race([Promise.resolve().then(run), aborted]);
|
|
78
|
+
} finally {
|
|
79
|
+
signal.removeEventListener("abort", onAbort);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function bindingLimits(binding) {
|
|
83
|
+
const rawDepth = (0, import_record_utils.read)(binding, "maxDepth");
|
|
84
|
+
const rawTimeout = (0, import_record_utils.read)(binding, "timeout");
|
|
85
|
+
const maxDepth = rawDepth == null ? 1 : Number(rawDepth);
|
|
86
|
+
const timeout = rawTimeout == null ? 12e4 : Number(rawTimeout);
|
|
87
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 1 || maxDepth > 10) {
|
|
88
|
+
throw new Error("The delegation depth is invalid.");
|
|
89
|
+
}
|
|
90
|
+
if (!Number.isSafeInteger(timeout) || timeout < 1e3 || timeout > 6e5) {
|
|
91
|
+
throw new Error("The delegation timeout is invalid.");
|
|
92
|
+
}
|
|
93
|
+
return { maxDepth, timeout };
|
|
94
|
+
}
|
|
95
|
+
class RestrictedAIEmployee extends import_server.AIEmployee {
|
|
96
|
+
allowedToolNames = /* @__PURE__ */ new Set();
|
|
97
|
+
autoApprovedToolNames = /* @__PURE__ */ new Set();
|
|
98
|
+
recursionLimit = 200;
|
|
99
|
+
guardTool;
|
|
100
|
+
signal;
|
|
101
|
+
isAutoCall(tools) {
|
|
102
|
+
var _a;
|
|
103
|
+
if (((_a = tools == null ? void 0 : tools.definition) == null ? void 0 : _a.name) && this.autoApprovedToolNames.has(tools.definition.name)) return true;
|
|
104
|
+
return super.isAutoCall(tools);
|
|
105
|
+
}
|
|
106
|
+
async createAgent(options) {
|
|
107
|
+
var _a;
|
|
108
|
+
const tools = (_a = options.tools) == null ? void 0 : _a.filter((item) => this.allowedToolNames.has(toolName(item)));
|
|
109
|
+
const signal = this.signal;
|
|
110
|
+
const guardTool = this.guardTool;
|
|
111
|
+
const guard = (0, import_langchain.createMiddleware)({
|
|
112
|
+
name: "HierarchyLiveAuthorization",
|
|
113
|
+
wrapToolCall: async (request, handler) => {
|
|
114
|
+
if (!signal || !guardTool) throw new Error("The hierarchy tool guard is unavailable.");
|
|
115
|
+
await withAbort(signal, () => guardTool(request.toolCall.name, request.toolCall.id));
|
|
116
|
+
return withAbort(signal, () => handler(request));
|
|
117
|
+
},
|
|
118
|
+
wrapModelCall: async (request, handler) => {
|
|
119
|
+
if (!signal) throw new Error("The hierarchy model guard is unavailable.");
|
|
120
|
+
return withAbort(signal, () => handler(request));
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
return super.createAgent({ ...options, tools, middleware: [...options.middleware ?? [], guard] });
|
|
124
|
+
}
|
|
125
|
+
async agentInvoke(...args) {
|
|
126
|
+
const [provider, context, config, state] = args;
|
|
127
|
+
return super.agentInvoke(provider, context, { ...config, recursionLimit: this.recursionLimit }, state);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
class HierarchicalAgentRuntime {
|
|
131
|
+
constructor(plugin) {
|
|
132
|
+
this.plugin = plugin;
|
|
133
|
+
}
|
|
134
|
+
get ai() {
|
|
135
|
+
const ai = this.plugin.app.pm.get("ai");
|
|
136
|
+
if (!ai) throw new Error("AI Employee is unavailable.");
|
|
137
|
+
return ai;
|
|
138
|
+
}
|
|
139
|
+
async getScope(ctx, toolCallId, expectedTool) {
|
|
140
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
141
|
+
const userId = (_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id;
|
|
142
|
+
if (!userId) throw new Error("Authentication is required.");
|
|
143
|
+
const local = scopes.get(ctx);
|
|
144
|
+
if (local) {
|
|
145
|
+
if ((_c = local.signal) == null ? void 0 : _c.aborted) throw new Error("The request was cancelled.");
|
|
146
|
+
await this.accessibleEmployee(ctx, local.username);
|
|
147
|
+
if (toolCallId) await this.assertCallingTool(ctx, local, toolCallId, expectedTool);
|
|
148
|
+
if (toolCallId) await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(local.rootContext, async () => void 0);
|
|
149
|
+
if ((_d = local.signal) == null ? void 0 : _d.aborted) throw new Error("The request was cancelled.");
|
|
150
|
+
return local;
|
|
151
|
+
}
|
|
152
|
+
if (toolCallId && (((_e = ctx.action) == null ? void 0 : _e.resourceName) !== "aiConversations" || !["sendMessages", "resendMessages", "resumeToolCall"].includes((_f = ctx.action) == null ? void 0 : _f.actionName))) {
|
|
153
|
+
throw new Error("Hierarchy routing is not available in this execution context.");
|
|
154
|
+
}
|
|
155
|
+
if (toolCallId && !(0, import_HierarchyRequestCancellation.hasHierarchyRequest)(ctx)) {
|
|
156
|
+
throw new Error("The managed request is unavailable.");
|
|
157
|
+
}
|
|
158
|
+
let pending = pendingRootScopes.get(ctx);
|
|
159
|
+
if (!pending) {
|
|
160
|
+
pending = this.createRootScope(ctx);
|
|
161
|
+
pendingRootScopes.set(ctx, pending);
|
|
162
|
+
}
|
|
163
|
+
let scope;
|
|
164
|
+
try {
|
|
165
|
+
scope = await pending;
|
|
166
|
+
} catch (error) {
|
|
167
|
+
pendingRootScopes.delete(ctx);
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
if ((_g = scope.signal) == null ? void 0 : _g.aborted) throw new Error("The request was cancelled.");
|
|
171
|
+
if (toolCallId) {
|
|
172
|
+
await this.assertCallingTool(ctx, scope, toolCallId, expectedTool);
|
|
173
|
+
await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(ctx, async () => void 0);
|
|
174
|
+
if ((_h = scope.signal) == null ? void 0 : _h.aborted) throw new Error("The request was cancelled.");
|
|
175
|
+
scopes.set(ctx, scope);
|
|
176
|
+
}
|
|
177
|
+
return scope;
|
|
178
|
+
}
|
|
179
|
+
async createRootScope(ctx) {
|
|
180
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
181
|
+
const userId = (_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id;
|
|
182
|
+
const sessionId = stringValue((_e = (_d = (_c = ctx.action) == null ? void 0 : _c.params) == null ? void 0 : _d.values) == null ? void 0 : _e.sessionId);
|
|
183
|
+
if (!sessionId) throw new Error("A conversation is required.");
|
|
184
|
+
const conversation = await ctx.db.getRepository("aiConversations").findOne({ filter: { sessionId, userId } });
|
|
185
|
+
const username = stringValue((0, import_record_utils.read)(conversation, "aiEmployeeUsername"));
|
|
186
|
+
if (!conversation || !username || (0, import_record_utils.read)(conversation, "from") === "sub-agent") {
|
|
187
|
+
throw new Error("The current conversation is unavailable.");
|
|
188
|
+
}
|
|
189
|
+
const requested = stringValue((_h = (_g = (_f = ctx.action) == null ? void 0 : _f.params) == null ? void 0 : _g.values) == null ? void 0 : _h.aiEmployee);
|
|
190
|
+
if (requested && requested !== username) throw new Error("The employee does not match the conversation.");
|
|
191
|
+
await this.accessibleEmployee(ctx, username);
|
|
192
|
+
const controller = this.ai.aiEmployeesManager.conversationController.get(sessionId);
|
|
193
|
+
return {
|
|
194
|
+
rootSessionId: sessionId,
|
|
195
|
+
sessionId,
|
|
196
|
+
username,
|
|
197
|
+
role: "orchestrator",
|
|
198
|
+
ancestors: [username],
|
|
199
|
+
signal: (0, import_HierarchyRequestCancellation.hierarchyRequestSignal)(ctx, controller == null ? void 0 : controller.signal),
|
|
200
|
+
budget: { count: 0, max: null },
|
|
201
|
+
delegationCount: 0,
|
|
202
|
+
rootContext: ctx,
|
|
203
|
+
evidence: [],
|
|
204
|
+
evidenceOmitted: 0,
|
|
205
|
+
approvedToolCalls: /* @__PURE__ */ new Set(),
|
|
206
|
+
completed: /* @__PURE__ */ new Map(),
|
|
207
|
+
recordedChildren: /* @__PURE__ */ new Set(),
|
|
208
|
+
remainingDepth: null
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
async assertCallingTool(ctx, scope, toolCallId, toolName2) {
|
|
212
|
+
const toolCall = await ctx.db.getRepository("aiToolMessages").findOne({
|
|
213
|
+
filter: { sessionId: scope.sessionId, toolCallId, toolName: toolName2 }
|
|
214
|
+
});
|
|
215
|
+
const messageId = (0, import_record_utils.read)(toolCall, "messageId");
|
|
216
|
+
if (!messageId) throw new Error("The invoking tool call is unavailable.");
|
|
217
|
+
const message = await ctx.db.getRepository("aiMessages").findOne({
|
|
218
|
+
filter: { sessionId: scope.sessionId, messageId, role: scope.username }
|
|
219
|
+
});
|
|
220
|
+
if (!message) throw new Error("The invoking employee could not be verified.");
|
|
221
|
+
return String(messageId);
|
|
222
|
+
}
|
|
223
|
+
async accessibleEmployee(ctx, username) {
|
|
224
|
+
const filter = { username, enabled: true, category: "business", deprecated: false };
|
|
225
|
+
const roles = await this.currentRoles(ctx);
|
|
226
|
+
if (!roles.includes("root")) {
|
|
227
|
+
const mappings = await ctx.db.getRepository("rolesAiEmployees").find({ filter: { roleName: roles } });
|
|
228
|
+
if (!mappings.some((row) => (0, import_record_utils.read)(row, "aiEmployee") === username)) {
|
|
229
|
+
throw new Error("The requested AI employee is unavailable.");
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const employee = await ctx.db.getRepository("aiEmployees").findOne({ filter });
|
|
233
|
+
if (!employee) throw new Error("The requested AI employee is unavailable.");
|
|
234
|
+
return employee;
|
|
235
|
+
}
|
|
236
|
+
async currentRoles(ctx) {
|
|
237
|
+
var _a, _b;
|
|
238
|
+
const requestedRoles = ctx.state.currentRoles;
|
|
239
|
+
if (!Array.isArray(requestedRoles)) throw new Error("Current roles are unavailable.");
|
|
240
|
+
const memberships = await ctx.db.getRepository("rolesUsers").find({ filter: { userId: (_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id } });
|
|
241
|
+
const currentRoles = new Set(memberships.map((row) => (0, import_record_utils.read)(row, "roleName")));
|
|
242
|
+
const roles = requestedRoles.filter((role) => currentRoles.has(role));
|
|
243
|
+
if (!roles.length) throw new Error("The requested AI employee is unavailable.");
|
|
244
|
+
const selectedRole = ctx.state.currentRole;
|
|
245
|
+
if (typeof selectedRole === "string" && selectedRole !== "__union__" && !roles.includes(selectedRole)) {
|
|
246
|
+
throw new Error("The selected role is no longer available.");
|
|
247
|
+
}
|
|
248
|
+
return roles;
|
|
249
|
+
}
|
|
250
|
+
async authorizeTool(ctx, scope, name, toolCallId) {
|
|
251
|
+
var _a, _b;
|
|
252
|
+
if ((_a = scope.signal) == null ? void 0 : _a.aborted) throw abortError();
|
|
253
|
+
const messageId = await this.assertCallingTool(ctx, scope, toolCallId, name);
|
|
254
|
+
await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(scope.rootContext, async () => void 0);
|
|
255
|
+
for (const ancestor of scope.ancestors) await this.accessibleEmployee(ctx, ancestor);
|
|
256
|
+
let current = scope;
|
|
257
|
+
while ((current == null ? void 0 : current.parentScope) && current.bindingSnapshot) {
|
|
258
|
+
const target = await this.resolveTarget(scope.rootContext, current.parentScope, current.username);
|
|
259
|
+
const snapshot = current.bindingSnapshot;
|
|
260
|
+
if (target.profile.id !== snapshot.profileVersionId || !(0, import_node_util.isDeepStrictEqual)(target.model, snapshot.model) || !(0, import_node_util.isDeepStrictEqual)(target.bindingLimits, { timeout: snapshot.timeout, maxDepth: snapshot.maxDepth }))
|
|
261
|
+
throw new Error("The delegation policy changed while the request was running.");
|
|
262
|
+
current = current.parentScope;
|
|
263
|
+
}
|
|
264
|
+
const employee = await this.accessibleEmployee(ctx, scope.username);
|
|
265
|
+
const settings = (0, import_record_utils.asRecord)((0, import_record_utils.read)(employee, "skillSettings"));
|
|
266
|
+
const originalTools = Array.isArray(settings.tools) ? settings.tools : [];
|
|
267
|
+
if (!scope.harness) throw new Error("The delegation policy is unavailable.");
|
|
268
|
+
const autoApprove = await (0, import_SessionAutoApproval.sessionAutoApprovalEnabled)(ctx, scope.rootSessionId);
|
|
269
|
+
const approvalRequired = /* @__PURE__ */ new Set();
|
|
270
|
+
const allowed = await this.allowedTools(
|
|
271
|
+
ctx,
|
|
272
|
+
scope.sessionId,
|
|
273
|
+
scope.role,
|
|
274
|
+
originalTools,
|
|
275
|
+
scope.harness,
|
|
276
|
+
autoApprove,
|
|
277
|
+
approvalRequired
|
|
278
|
+
);
|
|
279
|
+
if (!allowed.includes(name)) throw new Error("The requested tool is no longer permitted.");
|
|
280
|
+
const roles = await this.currentRoles(ctx);
|
|
281
|
+
if ((_b = scope.signal) == null ? void 0 : _b.aborted) throw abortError();
|
|
282
|
+
ctx.state = { ...ctx.state, currentRoles: roles };
|
|
283
|
+
if (scope.role === "worker" && autoApprove && approvalRequired.has(name)) {
|
|
284
|
+
scope.approvedToolCalls.add(toolCallKey(scope.sessionId, messageId, toolCallId, name));
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async bindings(ctx, scope) {
|
|
288
|
+
var _a;
|
|
289
|
+
if (scope.role === "worker") return [];
|
|
290
|
+
if (scope.remainingDepth === 0) return [];
|
|
291
|
+
if (((_a = scope.harness) == null ? void 0 : _a.delegation.maxDepth) === 0) return [];
|
|
292
|
+
const expectedRole = scope.role === "orchestrator" ? "specialist" : "worker";
|
|
293
|
+
return ctx.db.getRepository("orchestratorConfig").find({
|
|
294
|
+
filter: { leaderUsername: scope.username, routingEnabled: true, enabled: true, routingRole: expectedRole },
|
|
295
|
+
sort: ["subAgentUsername"]
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
async list(ctx, toolCallId) {
|
|
299
|
+
var _a, _b;
|
|
300
|
+
const scope = await this.getScope(ctx, toolCallId, HIERARCHY_LIST_TOOL);
|
|
301
|
+
const result = [];
|
|
302
|
+
for (const binding of await this.bindings(ctx, scope)) {
|
|
303
|
+
const username = stringValue((0, import_record_utils.read)(binding, "subAgentUsername"));
|
|
304
|
+
if (!username || scope.ancestors.includes(username)) continue;
|
|
305
|
+
const allowed = ((_a = scope.harness) == null ? void 0 : _a.delegation.allowedEmployees) ?? [];
|
|
306
|
+
if (allowed.length && !allowed.includes(username)) continue;
|
|
307
|
+
try {
|
|
308
|
+
await this.accessibleEmployee(ctx, username);
|
|
309
|
+
result.push({
|
|
310
|
+
username,
|
|
311
|
+
description: stringValue((0, import_record_utils.read)(binding, "routingPrompt")),
|
|
312
|
+
role: stringValue((0, import_record_utils.read)(binding, "routingRole"))
|
|
313
|
+
});
|
|
314
|
+
} catch {
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
if ((_b = scope.signal) == null ? void 0 : _b.aborted) throw abortError();
|
|
318
|
+
return result;
|
|
319
|
+
}
|
|
320
|
+
async resolveTarget(ctx, scope, username) {
|
|
321
|
+
var _a, _b;
|
|
322
|
+
if (!username || scope.ancestors.includes(username)) throw new Error("Invalid delegation request.");
|
|
323
|
+
const allowed = ((_a = scope.harness) == null ? void 0 : _a.delegation.allowedEmployees) ?? [];
|
|
324
|
+
if (allowed.length && !allowed.includes(username)) throw new Error("The requested delegation is unavailable.");
|
|
325
|
+
const binding = (await this.bindings(ctx, scope)).find((row) => (0, import_record_utils.read)(row, "subAgentUsername") === username);
|
|
326
|
+
if (!binding) throw new Error("The requested delegation is unavailable.");
|
|
327
|
+
const employee = await this.accessibleEmployee(ctx, username);
|
|
328
|
+
const role = stringValue((0, import_record_utils.read)(binding, "routingRole"));
|
|
329
|
+
const limits = bindingLimits(binding);
|
|
330
|
+
const profileTag = stringValue((0, import_record_utils.read)(binding, "harnessTag")) || "default";
|
|
331
|
+
const profile = await new import_HarnessProfileService.HarnessProfileService(ctx.db).getPublishedByTag(profileTag);
|
|
332
|
+
if (!profile) throw new Error("The delegation policy profile is unavailable.");
|
|
333
|
+
const harness = (0, import_HarnessCompiler.compileHarness)([{ source: `${profileTag}@${profile.version}`, settings: profile.settings }]);
|
|
334
|
+
if (harness.limits.maxToolCalls != null || harness.limits.maxInputTokens != null || harness.limits.maxOutputTokens != null || harness.limits.maxTotalTokens != null || harness.limits.maxCost != null || harness.isolation.requireWorktree || harness.isolation.mode === "worktree") {
|
|
335
|
+
throw new Error("This delegation policy contains limits or isolation not supported by the chat runtime.");
|
|
336
|
+
}
|
|
337
|
+
const modelService = stringValue((0, import_record_utils.read)(binding, "llmService"));
|
|
338
|
+
const modelName = stringValue((0, import_record_utils.read)(binding, "model"));
|
|
339
|
+
if (Boolean(modelService) !== Boolean(modelName)) throw new Error("The delegation model is incomplete.");
|
|
340
|
+
const override = modelService && modelName ? { llmService: modelService, model: modelName } : void 0;
|
|
341
|
+
const routing = (_b = profile.settings.routing) == null ? void 0 : _b.models;
|
|
342
|
+
const primary = override || (routing == null ? void 0 : routing.primary) || await this.ai.aiEmployeesManager.resolveModel(employee);
|
|
343
|
+
const candidates = [primary, ...(routing == null ? void 0 : routing.fallback) ?? []];
|
|
344
|
+
const services = await this.ai.aiManager.listAllEnabledModels();
|
|
345
|
+
const seen = /* @__PURE__ */ new Set();
|
|
346
|
+
for (const [index, option] of candidates.entries()) {
|
|
347
|
+
if (typeof option.llmService !== "string" || !option.llmService || typeof option.model !== "string" || !option.model) {
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const candidate = { llmService: option.llmService, model: option.model };
|
|
351
|
+
const key = `${candidate.llmService}\0${candidate.model}`;
|
|
352
|
+
if (seen.has(key)) continue;
|
|
353
|
+
seen.add(key);
|
|
354
|
+
const resolved = await this.ai.aiEmployeesManager.resolveModel(employee, candidate);
|
|
355
|
+
if (resolved.llmService !== candidate.llmService || resolved.model !== candidate.model) {
|
|
356
|
+
throw new Error("The delegation model is not enabled for this employee.");
|
|
357
|
+
}
|
|
358
|
+
const service = services.find(
|
|
359
|
+
(item) => item.llmService === candidate.llmService && item.enabledModels.some((m) => m.value === candidate.model)
|
|
360
|
+
);
|
|
361
|
+
if (!service) continue;
|
|
362
|
+
const attribution = await (0, import_GovernanceAdmission.authorizeDelegatedEmployee)(ctx, employee, candidate);
|
|
363
|
+
return {
|
|
364
|
+
binding,
|
|
365
|
+
bindingLimits: limits,
|
|
366
|
+
employee,
|
|
367
|
+
role,
|
|
368
|
+
profile,
|
|
369
|
+
profileTag,
|
|
370
|
+
harness,
|
|
371
|
+
model: candidate,
|
|
372
|
+
attribution,
|
|
373
|
+
provider: service.provider,
|
|
374
|
+
fallback: index > 0
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
throw new Error("The delegation model is unavailable.");
|
|
378
|
+
}
|
|
379
|
+
async preview(ctx, username, specialistUsername) {
|
|
380
|
+
const scope = await this.getScope(ctx);
|
|
381
|
+
const rootCtx = Object.create(ctx);
|
|
382
|
+
const action = Object.create(ctx.action);
|
|
383
|
+
action.resourceName = "aiConversations";
|
|
384
|
+
action.actionName = "sendMessages";
|
|
385
|
+
action.params = { ...ctx.action.params, values: { ...ctx.action.params.values, aiEmployee: scope.username } };
|
|
386
|
+
rootCtx.action = action;
|
|
387
|
+
await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(rootCtx, async () => void 0);
|
|
388
|
+
const checkInvocation = (parent, harness) => {
|
|
389
|
+
var _a;
|
|
390
|
+
const maxChildren = (_a = parent.harness) == null ? void 0 : _a.delegation.maxCount;
|
|
391
|
+
if (maxChildren != null && parent.delegationCount >= maxChildren) {
|
|
392
|
+
throw new Error("The delegation limit has been reached.");
|
|
393
|
+
}
|
|
394
|
+
const limits = [parent.budget.max, harness.limits.maxInvocations].filter(
|
|
395
|
+
(limit) => limit != null
|
|
396
|
+
);
|
|
397
|
+
if (limits.length && parent.budget.count >= Math.min(...limits)) {
|
|
398
|
+
throw new Error("The delegation limit has been reached.");
|
|
399
|
+
}
|
|
400
|
+
};
|
|
401
|
+
const checkSpecialistTools = async (employee, harness) => {
|
|
402
|
+
const settings = (0, import_record_utils.asRecord)((0, import_record_utils.read)(employee, "skillSettings"));
|
|
403
|
+
const configured = Array.isArray(settings.tools) ? settings.tools : [];
|
|
404
|
+
const autoApprove = await (0, import_SessionAutoApproval.sessionAutoApprovalEnabled)(ctx, scope.rootSessionId);
|
|
405
|
+
const allowed = await this.allowedTools(rootCtx, scope.sessionId, "specialist", configured, harness, autoApprove);
|
|
406
|
+
if (!allowed.includes(HIERARCHY_LIST_TOOL) || !allowed.includes(HIERARCHY_DISPATCH_TOOL)) {
|
|
407
|
+
throw new Error("The delegation profile does not provide the required allowed tools.");
|
|
408
|
+
}
|
|
409
|
+
};
|
|
410
|
+
let parentScope = scope;
|
|
411
|
+
let specialist;
|
|
412
|
+
if (specialistUsername) {
|
|
413
|
+
const selected = stringValue(specialistUsername);
|
|
414
|
+
const parent = await this.resolveTarget(ctx, scope, selected);
|
|
415
|
+
if (parent.role !== "specialist") throw new Error("The intermediate employee is not a specialist.");
|
|
416
|
+
checkInvocation(scope, parent.harness);
|
|
417
|
+
await checkSpecialistTools(parent.employee, parent.harness);
|
|
418
|
+
parentScope = {
|
|
419
|
+
...scope,
|
|
420
|
+
username: selected,
|
|
421
|
+
role: "specialist",
|
|
422
|
+
ancestors: [...scope.ancestors, selected],
|
|
423
|
+
harness: parent.harness,
|
|
424
|
+
budget: { count: 1, max: parent.harness.limits.maxInvocations },
|
|
425
|
+
delegationCount: 0,
|
|
426
|
+
remainingDepth: parent.bindingLimits.maxDepth - 1,
|
|
427
|
+
parentScope: scope
|
|
428
|
+
};
|
|
429
|
+
specialist = {
|
|
430
|
+
username: selected,
|
|
431
|
+
model: parent.model,
|
|
432
|
+
fallback: parent.fallback,
|
|
433
|
+
profile: { tag: parent.profileTag, version: parent.profile.version }
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
const resolved = await this.resolveTarget(ctx, parentScope, stringValue(username));
|
|
437
|
+
checkInvocation(parentScope, resolved.harness);
|
|
438
|
+
if (resolved.role === "specialist") await checkSpecialistTools(resolved.employee, resolved.harness);
|
|
439
|
+
return {
|
|
440
|
+
username,
|
|
441
|
+
role: resolved.role,
|
|
442
|
+
model: resolved.model,
|
|
443
|
+
fallback: resolved.fallback,
|
|
444
|
+
profile: { tag: resolved.profileTag, version: resolved.profile.version },
|
|
445
|
+
...specialist ? { specialist } : {}
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
async readEvidence(ctx, rootSessionId, refs, approvedToolCalls) {
|
|
449
|
+
var _a, _b;
|
|
450
|
+
const evidence = [];
|
|
451
|
+
let remaining = 12e3;
|
|
452
|
+
let omitted = 0;
|
|
453
|
+
for (const ref of refs) {
|
|
454
|
+
if (evidence.length >= 10 || remaining <= 0) {
|
|
455
|
+
omitted += 1;
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
const userId = (_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id;
|
|
459
|
+
const parent = await ctx.db.getRepository("aiConversations").findOne({
|
|
460
|
+
filter: { sessionId: ref.parentSessionId, userId, aiEmployeeUsername: ref.parentUsername }
|
|
461
|
+
});
|
|
462
|
+
const conversation = await ctx.db.getRepository("aiConversations").findOne({
|
|
463
|
+
filter: { sessionId: ref.sessionId, userId, aiEmployeeUsername: ref.username, from: "sub-agent" }
|
|
464
|
+
});
|
|
465
|
+
const options = (0, import_record_utils.asRecord)((0, import_record_utils.read)(conversation, "options"));
|
|
466
|
+
if (!parent || !conversation || options.hierarchyRootSessionId !== rootSessionId || options.hierarchyParentSessionId !== ref.parentSessionId)
|
|
467
|
+
throw new Error("The evidence conversation is unavailable.");
|
|
468
|
+
await this.accessibleEmployee(ctx, ref.parentUsername);
|
|
469
|
+
const worker = await this.accessibleEmployee(ctx, ref.username);
|
|
470
|
+
const binding = await ctx.db.getRepository("orchestratorConfig").findOne({
|
|
471
|
+
filter: {
|
|
472
|
+
leaderUsername: ref.parentUsername,
|
|
473
|
+
subAgentUsername: ref.username,
|
|
474
|
+
routingRole: "worker",
|
|
475
|
+
routingEnabled: true,
|
|
476
|
+
enabled: true
|
|
477
|
+
}
|
|
478
|
+
});
|
|
479
|
+
if (!binding || (stringValue((0, import_record_utils.read)(binding, "harnessTag")) || "default") !== ref.profileTag) {
|
|
480
|
+
throw new Error("The evidence delegation is unavailable.");
|
|
481
|
+
}
|
|
482
|
+
const profile = await new import_HarnessProfileService.HarnessProfileService(ctx.db).getPublishedByTag(ref.profileTag);
|
|
483
|
+
if (!profile || profile.id !== ref.profileVersionId) throw new Error("The evidence policy changed.");
|
|
484
|
+
const harness = (0, import_HarnessCompiler.compileHarness)([{ source: ref.profileTag, settings: profile.settings }]);
|
|
485
|
+
const settings = (0, import_record_utils.asRecord)((0, import_record_utils.read)(worker, "skillSettings"));
|
|
486
|
+
const originalTools = Array.isArray(settings.tools) ? settings.tools : [];
|
|
487
|
+
const workerCtx = Object.create(ctx);
|
|
488
|
+
const action = Object.create(ctx.action);
|
|
489
|
+
action.params = {
|
|
490
|
+
...ctx.action.params,
|
|
491
|
+
values: { ...ctx.action.params.values, sessionId: ref.sessionId, aiEmployee: ref.username, model: ref.model }
|
|
492
|
+
};
|
|
493
|
+
workerCtx.action = action;
|
|
494
|
+
workerCtx.state = { ...ctx.state, currentAIEmployee: { username: ref.username } };
|
|
495
|
+
const autoApprove = await (0, import_SessionAutoApproval.sessionAutoApprovalEnabled)(ctx, rootSessionId) || approvedToolCalls.has(toolCallKey(ref.sessionId, ref.messageId, ref.toolCallId, ref.toolName));
|
|
496
|
+
const allowed = await this.allowedTools(workerCtx, ref.sessionId, "worker", originalTools, harness, autoApprove);
|
|
497
|
+
if (!allowed.includes(ref.toolName)) throw new Error("The evidence tool is no longer permitted.");
|
|
498
|
+
await (0, import_GovernanceAdmission.authorizeDelegatedEmployee)(ctx, worker, ref.model);
|
|
499
|
+
const message = await ctx.db.getRepository("aiMessages").findOne({
|
|
500
|
+
filter: { sessionId: ref.sessionId, messageId: ref.messageId, role: ref.username }
|
|
501
|
+
});
|
|
502
|
+
const tool = await ctx.db.getRepository("aiToolMessages").findOne({
|
|
503
|
+
filter: {
|
|
504
|
+
sessionId: ref.sessionId,
|
|
505
|
+
messageId: ref.messageId,
|
|
506
|
+
toolCallId: ref.toolCallId,
|
|
507
|
+
toolName: ref.toolName,
|
|
508
|
+
status: "success"
|
|
509
|
+
}
|
|
510
|
+
});
|
|
511
|
+
if (!message || !tool || !["done", "confirmed"].includes(String((0, import_record_utils.read)(tool, "invokeStatus")))) {
|
|
512
|
+
throw new Error("The evidence is unavailable.");
|
|
513
|
+
}
|
|
514
|
+
const content = (0, import_record_utils.read)(tool, "content");
|
|
515
|
+
const raw = typeof content === "string" ? content : JSON.stringify(content ?? null);
|
|
516
|
+
const bytes = Buffer.from(raw, "utf8");
|
|
517
|
+
const allowedBytes = Math.min(2e3, remaining);
|
|
518
|
+
const excerpt = bytes.subarray(0, allowedBytes).toString("utf8");
|
|
519
|
+
remaining -= Math.min(bytes.length, allowedBytes);
|
|
520
|
+
evidence.push({
|
|
521
|
+
sessionId: ref.sessionId,
|
|
522
|
+
messageId: ref.messageId,
|
|
523
|
+
toolCallId: ref.toolCallId,
|
|
524
|
+
toolName: ref.toolName,
|
|
525
|
+
excerpt,
|
|
526
|
+
truncated: bytes.length > allowedBytes
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
return { items: evidence, omitted };
|
|
530
|
+
}
|
|
531
|
+
async dispatch(ctx, input, runtime) {
|
|
532
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
|
|
533
|
+
const dispatchStartedAt = Date.now();
|
|
534
|
+
if (!(runtime == null ? void 0 : runtime.toolCallId)) throw new Error("The invoking tool call is required.");
|
|
535
|
+
const scope = await this.getScope(ctx, runtime.toolCallId, HIERARCHY_DISPATCH_TOOL);
|
|
536
|
+
const username = stringValue(input.username);
|
|
537
|
+
const question = stringValue(input.question);
|
|
538
|
+
if (!question || question.length > 5e4) throw new Error("Invalid delegation request.");
|
|
539
|
+
const {
|
|
540
|
+
employee,
|
|
541
|
+
role,
|
|
542
|
+
harness,
|
|
543
|
+
model,
|
|
544
|
+
attribution,
|
|
545
|
+
profile,
|
|
546
|
+
profileTag,
|
|
547
|
+
provider,
|
|
548
|
+
fallback,
|
|
549
|
+
bindingLimits: limitsForBinding
|
|
550
|
+
} = await this.resolveTarget(ctx, scope, username);
|
|
551
|
+
if ((_a = scope.signal) == null ? void 0 : _a.aborted) throw new Error("The request was cancelled.");
|
|
552
|
+
if (Date.now() - dispatchStartedAt >= Math.min(limitsForBinding.timeout, harness.limits.timeoutMs ?? 12e4)) {
|
|
553
|
+
throw abortError();
|
|
554
|
+
}
|
|
555
|
+
if (role !== "specialist" && role !== "worker") throw new Error("Invalid delegation role.");
|
|
556
|
+
const journal = new import_HierarchyInvocationJournal.HierarchyInvocationJournal(ctx.db);
|
|
557
|
+
const key = {
|
|
558
|
+
ownerId: attribution.userId,
|
|
559
|
+
parentSessionId: scope.sessionId,
|
|
560
|
+
parentToolCallId: runtime.toolCallId
|
|
561
|
+
};
|
|
562
|
+
const snapshot = {
|
|
563
|
+
profileTag,
|
|
564
|
+
profileVersion: profile.version,
|
|
565
|
+
profileVersionId: profile.id,
|
|
566
|
+
policy: profile.settings,
|
|
567
|
+
model,
|
|
568
|
+
provider,
|
|
569
|
+
ancestors: [...scope.ancestors],
|
|
570
|
+
bindingTimeout: limitsForBinding.timeout,
|
|
571
|
+
bindingMaxDepth: limitsForBinding.maxDepth
|
|
572
|
+
};
|
|
573
|
+
const stored = await journal.reserve({
|
|
574
|
+
...key,
|
|
575
|
+
rootSessionId: scope.rootSessionId,
|
|
576
|
+
parentEmployee: scope.username,
|
|
577
|
+
employeeUsername: username,
|
|
578
|
+
role,
|
|
579
|
+
question,
|
|
580
|
+
snapshot
|
|
581
|
+
});
|
|
582
|
+
if ((_b = scope.signal) == null ? void 0 : _b.aborted) throw abortError();
|
|
583
|
+
if (!(0, import_node_util.isDeepStrictEqual)((0, import_record_utils.read)(stored, "snapshot"), snapshot)) {
|
|
584
|
+
throw new Error("The delegation policy changed after the request was created.");
|
|
585
|
+
}
|
|
586
|
+
if ((0, import_record_utils.read)(stored, "status") === "succeeded") {
|
|
587
|
+
const saved = (0, import_record_utils.asRecord)((0, import_record_utils.read)(stored, "result"));
|
|
588
|
+
const childSessionId = stringValue(saved.sessionId);
|
|
589
|
+
if (childSessionId !== (0, import_record_utils.read)(stored, "childSessionId") || saved.username !== username || saved.role !== role || !(0, import_node_util.isDeepStrictEqual)(saved.model, model)) {
|
|
590
|
+
throw new Error("The stored delegation result is invalid.");
|
|
591
|
+
}
|
|
592
|
+
for (const ancestor of scope.ancestors) await this.accessibleEmployee(ctx, ancestor);
|
|
593
|
+
await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(scope.rootContext, async () => void 0);
|
|
594
|
+
const cached = scope.completed.get(runtime.toolCallId);
|
|
595
|
+
if (!cached) return { status: "already_completed", sessionId: childSessionId };
|
|
596
|
+
const { answer, evidenceRefs, evidenceOmitted } = cached;
|
|
597
|
+
const evidence = await this.readEvidence(ctx, scope.rootSessionId, evidenceRefs, scope.approvedToolCalls);
|
|
598
|
+
if ((_c = scope.signal) == null ? void 0 : _c.aborted) throw abortError();
|
|
599
|
+
this.recordEvidence(scope, runtime.toolCallId, evidenceRefs, evidenceOmitted);
|
|
600
|
+
return {
|
|
601
|
+
sessionId: childSessionId,
|
|
602
|
+
username,
|
|
603
|
+
role,
|
|
604
|
+
model: saved.model,
|
|
605
|
+
answer,
|
|
606
|
+
evidence: { ...evidence, omitted: evidence.omitted + evidenceOmitted }
|
|
607
|
+
};
|
|
608
|
+
}
|
|
609
|
+
if ((0, import_record_utils.read)(stored, "status") !== "reserved") {
|
|
610
|
+
throw new Error("The delegation has an unfinished or uncertain outcome and cannot be replayed.");
|
|
611
|
+
}
|
|
612
|
+
const maxChildren = (_d = scope.harness) == null ? void 0 : _d.delegation.maxCount;
|
|
613
|
+
if (maxChildren != null && scope.delegationCount >= maxChildren) {
|
|
614
|
+
throw new Error("The delegation limit has been reached.");
|
|
615
|
+
}
|
|
616
|
+
const limits = [scope.budget.max, harness.limits.maxInvocations].filter((limit) => limit != null);
|
|
617
|
+
const max = limits.length ? Math.min(...limits) : null;
|
|
618
|
+
if (max != null && scope.budget.count >= max) throw new Error("The delegation limit has been reached.");
|
|
619
|
+
scope.budget.max = max;
|
|
620
|
+
scope.budget.count += 1;
|
|
621
|
+
scope.delegationCount += 1;
|
|
622
|
+
const { token } = await journal.claim(key);
|
|
623
|
+
if ((_e = scope.signal) == null ? void 0 : _e.aborted) {
|
|
624
|
+
await journal.markUncertain(key, token);
|
|
625
|
+
throw abortError();
|
|
626
|
+
}
|
|
627
|
+
const startedAt = Date.now();
|
|
628
|
+
const trace = new import_ExecutionSpanService.ExecutionSpanService(this.plugin);
|
|
629
|
+
const span = harness.observability.enabled && harness.observability.sharing !== "disabled" ? await trace.create({
|
|
630
|
+
rootRunId: `hierarchy:${scope.rootSessionId}`,
|
|
631
|
+
parentSpanId: scope.spanId,
|
|
632
|
+
depth: scope.ancestors.length,
|
|
633
|
+
source: "hierarchy",
|
|
634
|
+
parentSessionId: scope.sessionId,
|
|
635
|
+
toolCallId: runtime.toolCallId,
|
|
636
|
+
type: "sub_agent",
|
|
637
|
+
status: "running",
|
|
638
|
+
leaderUsername: scope.username,
|
|
639
|
+
employeeUsername: username,
|
|
640
|
+
toolName: HIERARCHY_DISPATCH_TOOL,
|
|
641
|
+
userId: attribution.userId,
|
|
642
|
+
metadata: { model, provider, fallback, profileTag, profileVersion: profile.version }
|
|
643
|
+
}) : null;
|
|
644
|
+
const spanId = span && (typeof span.id === "number" || typeof span.id === "string") ? String(span.id) : void 0;
|
|
645
|
+
let invocationSignal;
|
|
646
|
+
try {
|
|
647
|
+
if ((_f = scope.signal) == null ? void 0 : _f.aborted) throw abortError();
|
|
648
|
+
const conversation = await this.ai.aiConversationsManager.create({
|
|
649
|
+
userId: ctx.auth.user.id,
|
|
650
|
+
aiEmployee: { username },
|
|
651
|
+
title: question.slice(0, 30),
|
|
652
|
+
from: "sub-agent",
|
|
653
|
+
options: { hierarchyRootSessionId: scope.rootSessionId, hierarchyParentSessionId: scope.sessionId }
|
|
654
|
+
});
|
|
655
|
+
const sessionId = stringValue((0, import_record_utils.read)(conversation, "sessionId"));
|
|
656
|
+
if (!sessionId) throw new Error("The delegated conversation could not be created.");
|
|
657
|
+
await journal.attachChild(key, token, sessionId);
|
|
658
|
+
const child = Object.create(ctx);
|
|
659
|
+
const action = Object.create(ctx.action);
|
|
660
|
+
action.resourceName = "aiConversations";
|
|
661
|
+
action.actionName = "sendMessages";
|
|
662
|
+
action.params = {
|
|
663
|
+
...ctx.action.params,
|
|
664
|
+
values: { ...ctx.action.params.values, sessionId, aiEmployee: username, model }
|
|
665
|
+
};
|
|
666
|
+
child.action = action;
|
|
667
|
+
child.state = { ...ctx.state, currentAIEmployee: { username } };
|
|
668
|
+
const controller = new AbortController();
|
|
669
|
+
invocationSignal = controller.signal;
|
|
670
|
+
const abort = () => controller.abort();
|
|
671
|
+
(_g = scope.signal) == null ? void 0 : _g.addEventListener("abort", abort, { once: true });
|
|
672
|
+
if ((_h = scope.signal) == null ? void 0 : _h.aborted) controller.abort();
|
|
673
|
+
const timeoutMs = Math.min(limitsForBinding.timeout, harness.limits.timeoutMs ?? 12e4);
|
|
674
|
+
const remaining = timeoutMs - (Date.now() - dispatchStartedAt);
|
|
675
|
+
if (remaining <= 0) controller.abort();
|
|
676
|
+
const timeout = setTimeout(abort, Math.max(0, remaining));
|
|
677
|
+
const childScope = {
|
|
678
|
+
rootSessionId: scope.rootSessionId,
|
|
679
|
+
sessionId,
|
|
680
|
+
username,
|
|
681
|
+
role,
|
|
682
|
+
ancestors: [...scope.ancestors, username],
|
|
683
|
+
signal: controller.signal,
|
|
684
|
+
harness,
|
|
685
|
+
budget: scope.budget,
|
|
686
|
+
delegationCount: 0,
|
|
687
|
+
spanId,
|
|
688
|
+
rootContext: scope.rootContext,
|
|
689
|
+
evidence: [],
|
|
690
|
+
evidenceOmitted: 0,
|
|
691
|
+
approvedToolCalls: scope.approvedToolCalls,
|
|
692
|
+
completed: /* @__PURE__ */ new Map(),
|
|
693
|
+
recordedChildren: /* @__PURE__ */ new Set(),
|
|
694
|
+
remainingDepth: Math.min(
|
|
695
|
+
limitsForBinding.maxDepth - 1,
|
|
696
|
+
scope.remainingDepth == null ? limitsForBinding.maxDepth - 1 : Math.max(0, scope.remainingDepth - 1)
|
|
697
|
+
),
|
|
698
|
+
parentScope: scope,
|
|
699
|
+
bindingSnapshot: { ...limitsForBinding, profileVersionId: profile.id, model }
|
|
700
|
+
};
|
|
701
|
+
scopes.set(child, childScope);
|
|
702
|
+
try {
|
|
703
|
+
const execute = async () => {
|
|
704
|
+
var _a2, _b2;
|
|
705
|
+
const originalSettings = (0, import_record_utils.asRecord)((0, import_record_utils.read)(employee, "skillSettings"));
|
|
706
|
+
const originalTools = Array.isArray(originalSettings.tools) ? originalSettings.tools : [];
|
|
707
|
+
const autoApprove = await (0, import_SessionAutoApproval.sessionAutoApprovalEnabled)(child, scope.rootSessionId);
|
|
708
|
+
const tools = await this.allowedTools(child, sessionId, role, originalTools, harness, autoApprove);
|
|
709
|
+
if (role === "specialist" && (!tools.includes(HIERARCHY_LIST_TOOL) || !tools.includes(HIERARCHY_DISPATCH_TOOL)) || role === "worker" && tools.length === 0) {
|
|
710
|
+
throw new Error("The delegation profile does not provide the required allowed tools.");
|
|
711
|
+
}
|
|
712
|
+
employee.set("skillSettings", {
|
|
713
|
+
...originalSettings,
|
|
714
|
+
tools: tools.map((name) => ({ name, autoCall: true }))
|
|
715
|
+
});
|
|
716
|
+
employee.set("chatSettings", { ...(0, import_record_utils.asRecord)((0, import_record_utils.read)(employee, "chatSettings")), enableSkills: false });
|
|
717
|
+
employee.set("enableKnowledgeBase", false);
|
|
718
|
+
const agent = new RestrictedAIEmployee({
|
|
719
|
+
ctx: child,
|
|
720
|
+
employee,
|
|
721
|
+
sessionId,
|
|
722
|
+
model,
|
|
723
|
+
webSearch: false,
|
|
724
|
+
skillSettings: { skillsVersion: 2, toolsVersion: 2, skills: [], tools },
|
|
725
|
+
// A dedicated checkpoint lets us detect interruptions without passing them off as results.
|
|
726
|
+
from: "main-agent"
|
|
727
|
+
});
|
|
728
|
+
agent.allowedToolNames = new Set(tools);
|
|
729
|
+
if (autoApprove) agent.autoApprovedToolNames = new Set(tools);
|
|
730
|
+
agent.recursionLimit = harness.limits.recursionLimit ?? 200;
|
|
731
|
+
agent.signal = controller.signal;
|
|
732
|
+
agent.guardTool = async (name, toolCallId) => this.authorizeTool(child, childScope, name, toolCallId);
|
|
733
|
+
const writer = runtime.writer ? (chunk) => {
|
|
734
|
+
var _a3;
|
|
735
|
+
if (controller.signal.aborted) return;
|
|
736
|
+
const event = (0, import_record_utils.asRecord)(chunk);
|
|
737
|
+
const current2 = (0, import_record_utils.asRecord)(event.currentConversation);
|
|
738
|
+
(_a3 = runtime.writer) == null ? void 0 : _a3.call(runtime, {
|
|
739
|
+
...event,
|
|
740
|
+
currentConversation: Object.keys(current2).length ? { ...current2, from: "sub-agent" } : current2
|
|
741
|
+
});
|
|
742
|
+
} : void 0;
|
|
743
|
+
const result = await agent.invoke({
|
|
744
|
+
userMessages: [{ role: "user", content: { type: "text", content: question } }],
|
|
745
|
+
signal: controller.signal,
|
|
746
|
+
writer
|
|
747
|
+
});
|
|
748
|
+
if (controller.signal.aborted) throw new Error("The delegation was cancelled.");
|
|
749
|
+
if (result.__interrupt__ != null && (!Array.isArray(result.__interrupt__) || result.__interrupt__.length > 0)) {
|
|
750
|
+
throw new Error("A delegated tool requires approval and cannot be completed here.");
|
|
751
|
+
}
|
|
752
|
+
const content = (_b2 = (_a2 = result.messages) == null ? void 0 : _a2.at(-1)) == null ? void 0 : _b2.content;
|
|
753
|
+
const answer = typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => stringValue((0, import_record_utils.asRecord)(part).text)).join("") : "";
|
|
754
|
+
if (!answer) throw new Error("The delegated employee returned no answer.");
|
|
755
|
+
const message = await ctx.db.getRepository("aiMessages").findOne({
|
|
756
|
+
filter: { sessionId, role: username },
|
|
757
|
+
sort: ["-messageId"]
|
|
758
|
+
});
|
|
759
|
+
const messageId = stringValue(String((0, import_record_utils.read)(message, "messageId") || ""));
|
|
760
|
+
const persistedAnswer = stringValue((0, import_record_utils.asRecord)((0, import_record_utils.read)(message, "content")).content);
|
|
761
|
+
if (!messageId || !persistedAnswer || persistedAnswer !== answer.trim()) {
|
|
762
|
+
throw new Error("The delegated answer could not be persisted.");
|
|
763
|
+
}
|
|
764
|
+
for (const ancestor of scope.ancestors) await this.accessibleEmployee(ctx, ancestor);
|
|
765
|
+
await (0, import_HierarchyEnrollmentGuard.guardHierarchyEnrollment)(scope.rootContext, async () => void 0);
|
|
766
|
+
const current = await this.resolveTarget(ctx, scope, username);
|
|
767
|
+
if (current.profile.id !== profile.id || current.profile.version !== profile.version || !(0, import_node_util.isDeepStrictEqual)(current.model, model)) {
|
|
768
|
+
throw new Error("The delegation policy changed while the request was running.");
|
|
769
|
+
}
|
|
770
|
+
if (role === "worker") {
|
|
771
|
+
const toolRepo = ctx.db.getRepository("aiToolMessages");
|
|
772
|
+
const filter = { sessionId, status: "success", invokeStatus: { $in: ["done", "confirmed"] } };
|
|
773
|
+
const [calls, count] = await Promise.all([
|
|
774
|
+
toolRepo.find({ filter, sort: ["id"], limit: 10 }),
|
|
775
|
+
toolRepo.count({ filter })
|
|
776
|
+
]);
|
|
777
|
+
childScope.evidenceOmitted += Math.max(0, count - calls.length);
|
|
778
|
+
for (const call of calls) {
|
|
779
|
+
const name = stringValue((0, import_record_utils.read)(call, "toolName"));
|
|
780
|
+
if (!tools.includes(name)) throw new Error("An unapproved evidence tool was recorded.");
|
|
781
|
+
childScope.evidence.push({
|
|
782
|
+
sessionId,
|
|
783
|
+
messageId: String((0, import_record_utils.read)(call, "messageId") || ""),
|
|
784
|
+
toolCallId: stringValue((0, import_record_utils.read)(call, "toolCallId")),
|
|
785
|
+
toolName: name,
|
|
786
|
+
username,
|
|
787
|
+
parentUsername: scope.username,
|
|
788
|
+
parentSessionId: scope.sessionId,
|
|
789
|
+
profileTag,
|
|
790
|
+
profileVersionId: profile.id,
|
|
791
|
+
model
|
|
792
|
+
});
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
const evidenceRefs = childScope.evidence.slice(0, 10);
|
|
796
|
+
const evidenceOmitted = childScope.evidenceOmitted + Math.max(0, childScope.evidence.length - evidenceRefs.length);
|
|
797
|
+
const evidence = await this.readEvidence(ctx, scope.rootSessionId, evidenceRefs, scope.approvedToolCalls);
|
|
798
|
+
if (controller.signal.aborted) throw abortError();
|
|
799
|
+
await journal.complete(
|
|
800
|
+
key,
|
|
801
|
+
token,
|
|
802
|
+
{ sessionId, username, role, model, messageId, evidenceRefs, evidenceOmitted },
|
|
803
|
+
controller.signal
|
|
804
|
+
);
|
|
805
|
+
if (controller.signal.aborted) throw abortError();
|
|
806
|
+
scope.completed.set(runtime.toolCallId, {
|
|
807
|
+
sessionId,
|
|
808
|
+
username,
|
|
809
|
+
role,
|
|
810
|
+
model,
|
|
811
|
+
answer: persistedAnswer,
|
|
812
|
+
evidenceRefs,
|
|
813
|
+
evidenceOmitted
|
|
814
|
+
});
|
|
815
|
+
this.recordEvidence(scope, runtime.toolCallId, evidenceRefs, evidenceOmitted);
|
|
816
|
+
await trace.finish(spanId, "success", startedAt, { subSessionId: sessionId });
|
|
817
|
+
return {
|
|
818
|
+
sessionId,
|
|
819
|
+
username,
|
|
820
|
+
role,
|
|
821
|
+
model,
|
|
822
|
+
answer: persistedAnswer,
|
|
823
|
+
evidence: { ...evidence, omitted: evidence.omitted + evidenceOmitted }
|
|
824
|
+
};
|
|
825
|
+
};
|
|
826
|
+
await (0, import_GovernanceAdmission.authorizeDelegatedEmployee)(child, employee, model);
|
|
827
|
+
return await withAbort(
|
|
828
|
+
controller.signal,
|
|
829
|
+
() => (0, import_NativeUsageAttribution.runWithNativeUsageAttribution)(
|
|
830
|
+
{
|
|
831
|
+
db: child.db,
|
|
832
|
+
userId: attribution.userId,
|
|
833
|
+
sessionId,
|
|
834
|
+
...attribution.departmentId == null ? {} : { departmentId: attribution.departmentId }
|
|
835
|
+
},
|
|
836
|
+
execute
|
|
837
|
+
)
|
|
838
|
+
);
|
|
839
|
+
} finally {
|
|
840
|
+
clearTimeout(timeout);
|
|
841
|
+
(_i = scope.signal) == null ? void 0 : _i.removeEventListener("abort", abort);
|
|
842
|
+
scopes.delete(child);
|
|
843
|
+
}
|
|
844
|
+
} catch (error) {
|
|
845
|
+
await journal.markUncertain(key, token).catch(() => void 0);
|
|
846
|
+
if (invocationSignal == null ? void 0 : invocationSignal.aborted) await journal.invalidateCompleted(key);
|
|
847
|
+
await trace.finish(spanId, ((_j = scope.signal) == null ? void 0 : _j.aborted) ? "canceled" : "error", startedAt);
|
|
848
|
+
throw error;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
async allowedTools(ctx, sessionId, role, originalTools, harness, autoApprove = false, approvalRequired) {
|
|
852
|
+
var _a;
|
|
853
|
+
const manager = (0, import_ai_manager.getAIToolsManager)(this.plugin.app);
|
|
854
|
+
const configured = new Map(originalTools.map((item) => [stringValue((0, import_record_utils.asRecord)(item).name), (0, import_record_utils.asRecord)(item)]));
|
|
855
|
+
const candidates = role === "specialist" ? [HIERARCHY_LIST_TOOL, HIERARCHY_DISPATCH_TOOL] : [.../* @__PURE__ */ new Set([...harness.tools.allow, ...autoApprove ? harness.tools.ask : []])];
|
|
856
|
+
const result = [];
|
|
857
|
+
for (const name of candidates) {
|
|
858
|
+
if (!name) continue;
|
|
859
|
+
if (role === "specialist" && !harness.tools.allow.includes(name) && !harness.tools.ask.includes(name)) continue;
|
|
860
|
+
const decision = (0, import_HarnessCompiler.decideTool)(harness, name, "read");
|
|
861
|
+
if (decision === "deny" || decision === "ask" && !autoApprove) continue;
|
|
862
|
+
if (role === "worker" && harness.tools.effects[name] !== "read") continue;
|
|
863
|
+
if (role === "worker" && (0, import_ai.listSystemTools)().includes(name)) continue;
|
|
864
|
+
if (role === "worker" && [HIERARCHY_LIST_TOOL, HIERARCHY_DISPATCH_TOOL, "dispatch-sub-agent-task"].includes(name))
|
|
865
|
+
continue;
|
|
866
|
+
const entry = await manager.getTools(name, { ctx, sessionId });
|
|
867
|
+
if (!entry || entry.execution === "frontend") continue;
|
|
868
|
+
const requiresApproval = decision === "ask" || entry.defaultPermission !== "ALLOW" || ((_a = configured.get(name)) == null ? void 0 : _a.autoCall) === false;
|
|
869
|
+
if (requiresApproval && (!autoApprove || entry.from === "mcp")) continue;
|
|
870
|
+
if (requiresApproval && await (0, import_SessionAutoApproval.skillRequiresUserInput)(ctx, name, {})) continue;
|
|
871
|
+
if (role === "worker" && entry.scope !== "GENERAL" && !configured.has(name)) continue;
|
|
872
|
+
if (requiresApproval) approvalRequired == null ? void 0 : approvalRequired.add(name);
|
|
873
|
+
result.push(name);
|
|
874
|
+
}
|
|
875
|
+
return result;
|
|
876
|
+
}
|
|
877
|
+
recordEvidence(scope, toolCallId, refs, omitted) {
|
|
878
|
+
if (scope.recordedChildren.has(toolCallId)) return;
|
|
879
|
+
scope.recordedChildren.add(toolCallId);
|
|
880
|
+
scope.evidence.push(...refs);
|
|
881
|
+
scope.evidenceOmitted += omitted;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
function createHierarchicalAgentTools(plugin) {
|
|
885
|
+
const service = new HierarchicalAgentRuntime(plugin);
|
|
886
|
+
return [
|
|
887
|
+
{
|
|
888
|
+
scope: "CUSTOM",
|
|
889
|
+
execution: "backend",
|
|
890
|
+
defaultPermission: "ALLOW",
|
|
891
|
+
introduction: { title: '{{t("List delegated AI employees", { ns: "plugin-agent-orchestrator" })}}' },
|
|
892
|
+
definition: {
|
|
893
|
+
name: HIERARCHY_LIST_TOOL,
|
|
894
|
+
description: "List AI employees available for delegation in the current conversation.",
|
|
895
|
+
schema: import_zod.z.object({})
|
|
896
|
+
},
|
|
897
|
+
invoke: async (ctx, _input, runtime) => {
|
|
898
|
+
if (!(runtime == null ? void 0 : runtime.toolCallId)) throw new Error("The invoking tool call is required.");
|
|
899
|
+
return service.list(ctx, runtime.toolCallId);
|
|
900
|
+
}
|
|
901
|
+
},
|
|
902
|
+
{
|
|
903
|
+
scope: "CUSTOM",
|
|
904
|
+
execution: "backend",
|
|
905
|
+
defaultPermission: "ALLOW",
|
|
906
|
+
introduction: { title: '{{t("Delegate to an AI employee", { ns: "plugin-agent-orchestrator" })}}' },
|
|
907
|
+
definition: {
|
|
908
|
+
name: HIERARCHY_DISPATCH_TOOL,
|
|
909
|
+
description: "Delegate one bounded task to an available AI employee. Use orchestrator_list_agents to discover candidates.",
|
|
910
|
+
schema: import_zod.z.object({
|
|
911
|
+
username: import_zod.z.string().min(1).max(200),
|
|
912
|
+
question: import_zod.z.string().min(1).max(5e4)
|
|
913
|
+
})
|
|
914
|
+
},
|
|
915
|
+
invoke: async (ctx, input, runtime) => service.dispatch(ctx, input, runtime)
|
|
916
|
+
}
|
|
917
|
+
];
|
|
918
|
+
}
|
|
919
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
920
|
+
0 && (module.exports = {
|
|
921
|
+
HIERARCHY_DISPATCH_TOOL,
|
|
922
|
+
HIERARCHY_LIST_TOOL,
|
|
923
|
+
HierarchicalAgentRuntime,
|
|
924
|
+
createHierarchicalAgentTools
|
|
925
|
+
});
|