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